Remove status_response callbacks where they are not needed.
[asterisk/asterisk.git] / main / file.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Generic File Format Support.
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <dirent.h>
31 #include <sys/stat.h>
32 #include <math.h>
33
34 #include "asterisk/_private.h"  /* declare ast_file_init() */
35 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
36 #include "asterisk/mod_format.h"
37 #include "asterisk/cli.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/sched.h"
40 #include "asterisk/translate.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/app.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/linkedlists.h"
46 #include "asterisk/module.h"
47 #include "asterisk/astobj2.h"
48 #include "asterisk/test.h"
49
50 /*
51  * The following variable controls the layout of localized sound files.
52  * If 0, use the historical layout with prefix just before the filename
53  * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
54  * if 1 put the prefix at the beginning of the filename
55  * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
56  * The latter permits a language to be entirely in one directory.
57  */
58 int ast_language_is_prefix = 1;
59
60 static AST_RWLIST_HEAD_STATIC(formats, ast_format);
61
62 int __ast_format_register(const struct ast_format *f, struct ast_module *mod)
63 {
64         struct ast_format *tmp;
65
66         AST_RWLIST_WRLOCK(&formats);
67         AST_RWLIST_TRAVERSE(&formats, tmp, list) {
68                 if (!strcasecmp(f->name, tmp->name)) {
69                         AST_RWLIST_UNLOCK(&formats);
70                         ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
71                         return -1;
72                 }
73         }
74         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
75                 AST_RWLIST_UNLOCK(&formats);
76                 return -1;
77         }
78         *tmp = *f;
79         tmp->module = mod;
80         if (tmp->buf_size) {
81                 /*
82                  * Align buf_size properly, rounding up to the machine-specific
83                  * alignment for pointers.
84                  */
85                 struct _test_align { void *a, *b; } p;
86                 int align = (char *)&p.b - (char *)&p.a;
87                 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
88         }
89         
90         memset(&tmp->list, 0, sizeof(tmp->list));
91
92         AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
93         AST_RWLIST_UNLOCK(&formats);
94         ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
95
96         return 0;
97 }
98
99 int ast_format_unregister(const char *name)
100 {
101         struct ast_format *tmp;
102         int res = -1;
103
104         AST_RWLIST_WRLOCK(&formats);
105         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
106                 if (!strcasecmp(name, tmp->name)) {
107                         AST_RWLIST_REMOVE_CURRENT(list);
108                         ast_free(tmp);
109                         res = 0;
110                 }
111         }
112         AST_RWLIST_TRAVERSE_SAFE_END;
113         AST_RWLIST_UNLOCK(&formats);
114
115         if (!res)
116                 ast_verb(2, "Unregistered format %s\n", name);
117         else
118                 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
119
120         return res;
121 }
122
123 int ast_stopstream(struct ast_channel *tmp)
124 {
125         ast_channel_lock(tmp);
126
127         /* Stop a running stream if there is one */
128         if (tmp->stream) {
129                 ast_closestream(tmp->stream);
130                 tmp->stream = NULL;
131                 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
132                         ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(tmp->oldwriteformat));
133         }
134         /* Stop the video stream too */
135         if (tmp->vstream != NULL) {
136                 ast_closestream(tmp->vstream);
137                 tmp->vstream = NULL;
138         }
139
140         ast_channel_unlock(tmp);
141
142         return 0;
143 }
144
145 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
146 {
147         int res = -1;
148         int alt = 0;
149         if (f->frametype == AST_FRAME_VIDEO) {
150                 if (fs->fmt->format & AST_FORMAT_AUDIO_MASK) {
151                         /* This is the audio portion.  Call the video one... */
152                         if (!fs->vfs && fs->filename) {
153                                 const char *type = ast_getformatname(f->subclass.codec & ~0x1);
154                                 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
155                                 ast_debug(1, "Opened video output file\n");
156                         }
157                         if (fs->vfs)
158                                 return ast_writestream(fs->vfs, f);
159                         /* else ignore */
160                         return 0;                               
161                 } else {
162                         /* Might / might not have mark set */
163                         alt = 1;
164                 }
165         } else if (f->frametype != AST_FRAME_VOICE) {
166                 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
167                 return -1;
168         }
169         if (((fs->fmt->format | alt) & f->subclass.codec) == f->subclass.codec) {
170                 res =  fs->fmt->write(fs, f);
171                 if (res < 0) 
172                         ast_log(LOG_WARNING, "Natural write failed\n");
173                 else if (res > 0)
174                         ast_log(LOG_WARNING, "Huh??\n");
175         } else {
176                 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
177                        the one we've setup a translator for, we do the "wrong thing" XXX */
178                 if (fs->trans && f->subclass.codec != fs->lastwriteformat) {
179                         ast_translator_free_path(fs->trans);
180                         fs->trans = NULL;
181                 }
182                 if (!fs->trans) 
183                         fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass.codec);
184                 if (!fs->trans)
185                         ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
186                                 fs->fmt->name, ast_getformatname(f->subclass.codec));
187                 else {
188                         struct ast_frame *trf;
189                         fs->lastwriteformat = f->subclass.codec;
190                         /* Get the translated frame but don't consume the original in case they're using it on another stream */
191                         if ((trf = ast_translate(fs->trans, f, 0))) {
192                                 struct ast_frame *cur;
193
194                                 /* the translator may have returned multiple frames, so process them */
195                                 for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
196                                         if ((res = fs->fmt->write(fs, trf))) {
197                                                 ast_log(LOG_WARNING, "Translated frame write failed\n");
198                                                 break;
199                                         }
200                                 }
201                                 ast_frfree(trf);
202                         } else {
203                                 res = 0;
204                         }
205                 }
206         }
207         return res;
208 }
209
210 static int copy(const char *infile, const char *outfile)
211 {
212         int ifd, ofd, len;
213         char buf[4096]; /* XXX make it lerger. */
214
215         if ((ifd = open(infile, O_RDONLY)) < 0) {
216                 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
217                 return -1;
218         }
219         if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
220                 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
221                 close(ifd);
222                 return -1;
223         }
224         while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
225                 int res;
226                 if (len < 0) {
227                         ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
228                         break;
229                 }
230                 /* XXX handle partial writes */
231                 res = write(ofd, buf, len);
232                 if (res != len) {
233                         ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
234                         len = -1; /* error marker */
235                         break;
236                 }
237         }
238         close(ifd);
239         close(ofd);
240         if (len < 0) {
241                 unlink(outfile);
242                 return -1; /* error */
243         }
244         return 0;       /* success */
245 }
246
247 /*!
248  * \brief construct a filename. Absolute pathnames are preserved,
249  * relative names are prefixed by the sounds/ directory.
250  * The wav49 suffix is replaced by 'WAV'.
251  * Returns a malloc'ed string to be freed by the caller.
252  */
253 static char *build_filename(const char *filename, const char *ext)
254 {
255         char *fn = NULL;
256
257         if (!strcmp(ext, "wav49"))
258                 ext = "WAV";
259
260         if (filename[0] == '/') {
261                 if (asprintf(&fn, "%s.%s", filename, ext) < 0) {
262                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
263                         fn = NULL;
264                 }
265         } else {
266                 if (asprintf(&fn, "%s/sounds/%s.%s",
267                              ast_config_AST_DATA_DIR, filename, ext) < 0) {
268                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
269                         fn = NULL;
270                 }
271         }
272         return fn;
273 }
274
275 /* compare type against the list 'exts' */
276 /* XXX need a better algorithm */
277 static int exts_compare(const char *exts, const char *type)
278 {
279         char tmp[256];
280         char *stringp = tmp, *ext;
281
282         ast_copy_string(tmp, exts, sizeof(tmp));
283         while ((ext = strsep(&stringp, "|"))) {
284                 if (!strcmp(ext, type))
285                         return 1;
286         }
287
288         return 0;
289 }
290
291 static void filestream_destructor(void *arg)
292 {
293         char *cmd = NULL;
294         size_t size = 0;
295         struct ast_filestream *f = arg;
296
297         /* Stop a running stream if there is one */
298         if (f->owner) {
299                 if (f->fmt->format < AST_FORMAT_AUDIO_MASK) {
300                         f->owner->stream = NULL;
301                         AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
302                         ast_settimeout(f->owner, 0, NULL, NULL);
303                 } else {
304                         f->owner->vstream = NULL;
305                         AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
306                 }
307         }
308         /* destroy the translator on exit */
309         if (f->trans)
310                 ast_translator_free_path(f->trans);
311
312         if (f->realfilename && f->filename) {
313                         size = strlen(f->filename) + strlen(f->realfilename) + 15;
314                         cmd = alloca(size);
315                         memset(cmd,0,size);
316                         snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
317                         ast_safe_system(cmd);
318         }
319
320         if (f->filename)
321                 free(f->filename);
322         if (f->realfilename)
323                 free(f->realfilename);
324         if (f->fmt->close) {
325                 void (*closefn)(struct ast_filestream *) = f->fmt->close;
326                 closefn(f);
327         }
328         if (f->f)
329                 fclose(f->f);
330         if (f->vfs)
331                 ast_closestream(f->vfs);
332         if (f->write_buffer) {
333                 ast_free(f->write_buffer);
334         }
335         if (f->orig_chan_name)
336                 free((void *) f->orig_chan_name);
337         ast_module_unref(f->fmt->module);
338 }
339
340 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
341 {
342         struct ast_filestream *s;
343
344         int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;    /* total allocation size */
345         if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
346                 return NULL;
347         s->fmt = fmt;
348         s->f = bfile;
349
350         if (fmt->desc_size)
351                 s->_private = ((char *)(s + 1)) + fmt->buf_size;
352         if (fmt->buf_size)
353                 s->buf = (char *)(s + 1);
354         s->fr.src = fmt->name;
355         return s;
356 }
357
358 /*
359  * Default implementations of open and rewrite.
360  * Only use them if you don't have expensive stuff to do.
361  */
362 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
363
364 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
365 {
366         struct ast_format *f = s->fmt;
367         int ret = -1;
368         int (*openfn)(struct ast_filestream *s);
369
370         if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
371                 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
372         else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
373                 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
374         else {
375                 /* preliminary checks succeed. update usecount */
376                 ast_module_ref(f->module);
377                 ret = 0;
378         }
379         return ret;
380 }
381
382 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
383 {
384         return fn_wrapper(s, comment, WRAP_REWRITE);
385 }
386
387 static int open_wrapper(struct ast_filestream *s)
388 {
389         return fn_wrapper(s, NULL, WRAP_OPEN);
390 }
391
392 enum file_action {
393         ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
394         ACTION_DELETE,  /* delete file, return 0 on success, -1 on error */
395         ACTION_RENAME,  /* rename file. return 0 on success, -1 on error */
396         ACTION_OPEN,
397         ACTION_COPY     /* copy file. return 0 on success, -1 on error */
398 };
399
400 /*!
401  * \brief perform various actions on a file. Second argument
402  * arg2 depends on the command:
403  *      unused for EXISTS and DELETE
404  *      destination file name (const char *) for COPY and RENAME
405  *      struct ast_channel * for OPEN
406  * if fmt is NULL, OPEN will return the first matching entry,
407  * whereas other functions will run on all matching entries.
408  */
409 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
410 {
411         struct ast_format *f;
412         int res = (action == ACTION_EXISTS) ? 0 : -1;
413
414         AST_RWLIST_RDLOCK(&formats);
415         /* Check for a specific format */
416         AST_RWLIST_TRAVERSE(&formats, f, list) {
417                 char *stringp, *ext = NULL;
418
419                 if (fmt && !exts_compare(f->exts, fmt))
420                         continue;
421
422                 /* Look for a file matching the supported extensions.
423                  * The file must exist, and for OPEN, must match
424                  * one of the formats supported by the channel.
425                  */
426                 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
427                 while ( (ext = strsep(&stringp, "|")) ) {
428                         struct stat st;
429                         char *fn = build_filename(filename, ext);
430
431                         if (fn == NULL)
432                                 continue;
433
434                         if ( stat(fn, &st) ) { /* file not existent */
435                                 ast_free(fn);
436                                 continue;
437                         }
438                         /* for 'OPEN' we need to be sure that the format matches
439                          * what the channel can process
440                          */
441                         if (action == ACTION_OPEN) {
442                                 struct ast_channel *chan = (struct ast_channel *)arg2;
443                                 FILE *bfile;
444                                 struct ast_filestream *s;
445
446                                 if ( !(chan->writeformat & f->format) &&
447                                      !((f->format & AST_FORMAT_AUDIO_MASK && fmt) ||
448                                           (f->format & AST_FORMAT_VIDEO_MASK && fmt))) {
449                                         ast_free(fn);
450                                         continue;       /* not a supported format */
451                                 }
452                                 if ( (bfile = fopen(fn, "r")) == NULL) {
453                                         ast_free(fn);
454                                         continue;       /* cannot open file */
455                                 }
456                                 s = get_filestream(f, bfile);
457                                 if (!s) {
458                                         fclose(bfile);
459                                         ast_free(fn);   /* cannot allocate descriptor */
460                                         continue;
461                                 }
462                                 if (open_wrapper(s)) {
463                                         ast_free(fn);
464                                         ast_closestream(s);
465                                         continue;       /* cannot run open on file */
466                                 }
467                                 if (st.st_size == 0) {
468                                         ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
469                                 }
470                                 /* ok this is good for OPEN */
471                                 res = 1;        /* found */
472                                 s->lasttimeout = -1;
473                                 s->fmt = f;
474                                 s->trans = NULL;
475                                 s->filename = NULL;
476                                 if (s->fmt->format & AST_FORMAT_AUDIO_MASK) {
477                                         if (chan->stream)
478                                                 ast_closestream(chan->stream);
479                                         chan->stream = s;
480                                 } else {
481                                         if (chan->vstream)
482                                                 ast_closestream(chan->vstream);
483                                         chan->vstream = s;
484                                 }
485                                 ast_free(fn);
486                                 break;
487                         }
488                         switch (action) {
489                         case ACTION_OPEN:
490                                 break;  /* will never get here */
491
492                         case ACTION_EXISTS:     /* return the matching format */
493                                 res |= f->format;
494                                 break;
495
496                         case ACTION_DELETE:
497                                 if ( (res = unlink(fn)) )
498                                         ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
499                                 break;
500
501                         case ACTION_RENAME:
502                         case ACTION_COPY: {
503                                 char *nfn = build_filename((const char *)arg2, ext);
504                                 if (!nfn)
505                                         ast_log(LOG_WARNING, "Out of memory\n");
506                                 else {
507                                         res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
508                                         if (res)
509                                                 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
510                                                         action == ACTION_COPY ? "copy" : "rename",
511                                                          fn, nfn, strerror(errno));
512                                         ast_free(nfn);
513                                 }
514                             }
515                                 break;
516
517                         default:
518                                 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
519                         }
520                         ast_free(fn);
521                 }
522         }
523         AST_RWLIST_UNLOCK(&formats);
524         return res;
525 }
526
527 static int is_absolute_path(const char *filename)
528 {
529         return filename[0] == '/';
530 }
531
532 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
533                            char *buf, int buflen)
534 {
535         if (buf == NULL) {
536                 return -1;
537         }
538
539         if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
540                 if (lang) {
541                         snprintf(buf, buflen, "%s/%s", lang, filename);
542                 } else {
543                         snprintf(buf, buflen, "%s", filename);
544                 }
545         } else { /* old layout */
546                 strcpy(buf, filename);  /* first copy the full string */
547                 if (lang) {
548                         /* insert the language and suffix if needed */
549                         const char *c = strrchr(filename, '/');
550                         int offset = c ? c - filename + 1 : 0;  /* points right after the last '/' */
551                         snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
552                 }
553         }
554
555         return ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
556 }
557
558 /*!
559  * \brief helper routine to locate a file with a given format
560  * and language preference.
561  * Try preflang, preflang with stripped '_' suffices, or NULL.
562  *
563  * The last parameter(s) point to a buffer of sufficient size,
564  * which on success is filled with the matching filename.
565  */
566 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
567                            char *buf, int buflen)
568 {
569         int res = -1;
570         char *lang;
571
572         if (buf == NULL) {
573                 return -1;
574         }
575
576         /* We try languages in the following order:
577          *    preflang (may include dialect and style codes)
578          *    lang (preflang without dialect - if any)
579          *    <none>
580          *    default (unless the same as preflang or lang without dialect)
581          */
582
583         lang = ast_strdupa(preflang);
584
585         /* Try preferred language, including removing any style or dialect codes */
586         while (!ast_strlen_zero(lang)) {
587                 char *end;
588
589                 if ((res = fileexists_test(filename, fmt, lang, buf, buflen)) > 0) {
590                         return res;
591                 }
592
593                 if ((end = strrchr(lang, '_')) != NULL) {
594                         *end = '\0';
595                         continue;
596                 }
597
598                 break;
599         }
600
601         /* Try without any language */
602         if ((res = fileexists_test(filename, fmt, NULL, buf, buflen)) > 0) {
603                 return res;
604         }
605
606         /* Finally try the default language unless it was already tried before */
607         if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
608                 if ((res = fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen)) > 0) {
609                         return res;
610                 }
611         }
612
613         return 0;
614 }
615
616 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
617 {
618         return ast_openstream_full(chan, filename, preflang, 0);
619 }
620
621 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
622 {
623         /* 
624          * Use fileexists_core() to find a file in a compatible
625          * language and format, set up a suitable translator,
626          * and open the stream.
627          */
628         int fmts, res, buflen;
629         char *buf;
630
631         if (!asis) {
632                 /* do this first, otherwise we detect the wrong writeformat */
633                 ast_stopstream(chan);
634                 if (chan->generator)
635                         ast_deactivate_generator(chan);
636         }
637         if (preflang == NULL)
638                 preflang = "";
639         buflen = strlen(preflang) + strlen(filename) + 4;
640         buf = alloca(buflen);
641         if (buf == NULL)
642                 return NULL;
643         fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
644         if (fmts > 0)
645                 fmts &= AST_FORMAT_AUDIO_MASK;
646         if (fmts < 1) {
647                 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
648                 return NULL;
649         }
650         chan->oldwriteformat = chan->writeformat;
651         /* Set the channel to a format we can work with */
652         res = ast_set_write_format(chan, fmts);
653         res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
654         if (res >= 0)
655                 return chan->stream;
656         return NULL;
657 }
658
659 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
660 {
661         /* As above, but for video. But here we don't have translators
662          * so we must enforce a format.
663          */
664         format_t format;
665         char *buf;
666         int buflen;
667
668         if (preflang == NULL)
669                 preflang = "";
670         buflen = strlen(preflang) + strlen(filename) + 4;
671         buf = alloca(buflen);
672         if (buf == NULL)
673                 return NULL;
674
675         for (format = AST_FORMAT_AUDIO_MASK + 1; format <= AST_FORMAT_VIDEO_MASK; format = format << 1) {
676                 int fd;
677                 const char *fmt;
678
679                 if (!(chan->nativeformats & format))
680                         continue;
681                 fmt = ast_getformatname(format);
682                 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
683                         continue;
684                 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
685                 if (fd >= 0)
686                         return chan->vstream;
687                 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
688         }
689         return NULL;
690 }
691
692 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
693 {
694         struct ast_frame *fr, *new_fr;
695
696         if (!s || !s->fmt) {
697                 return NULL;
698         }
699
700         if (!(fr = s->fmt->read(s, whennext))) {
701                 return NULL;
702         }
703
704         if (!(new_fr = ast_frisolate(fr))) {
705                 ast_frfree(fr);
706                 return NULL;
707         }
708
709         if (new_fr != fr) {
710                 ast_frfree(fr);
711                 fr = new_fr;
712         }
713
714         return fr;
715 }
716
717 struct ast_frame *ast_readframe(struct ast_filestream *s)
718 {
719         int whennext = 0;
720
721         return read_frame(s, &whennext);
722 }
723
724 enum fsread_res {
725         FSREAD_FAILURE,
726         FSREAD_SUCCESS_SCHED,
727         FSREAD_SUCCESS_NOSCHED,
728 };
729
730 static int ast_fsread_audio(const void *data);
731
732 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
733 {
734         int whennext = 0;
735
736         while (!whennext) {
737                 struct ast_frame *fr;
738
739                 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name)) {
740                         goto return_failure;
741                 }
742
743                 fr = read_frame(s, &whennext);
744
745                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
746                         if (fr) {
747                                 ast_log(LOG_WARNING, "Failed to write frame\n");
748                                 ast_frfree(fr);
749                         }
750                         goto return_failure;
751                 } 
752
753                 if (fr) {
754                         ast_frfree(fr);
755                 }
756         }
757
758         if (whennext != s->lasttimeout) {
759                 if (s->owner->timingfd > -1) {
760                         float samp_rate = (float) ast_format_rate(s->fmt->format);
761                         unsigned int rate;
762
763                         rate = (unsigned int) roundf(samp_rate / ((float) whennext));
764
765                         ast_settimeout(s->owner, rate, ast_fsread_audio, s);
766                 } else {
767                         s->owner->streamid = ast_sched_add(s->owner->sched, 
768                                 whennext / (ast_format_rate(s->fmt->format) / 1000), ast_fsread_audio, s);
769                 }
770                 s->lasttimeout = whennext;
771                 return FSREAD_SUCCESS_NOSCHED;
772         }
773         return FSREAD_SUCCESS_SCHED;
774
775 return_failure:
776         s->owner->streamid = -1;
777         ast_settimeout(s->owner, 0, NULL, NULL);
778         return FSREAD_FAILURE;
779 }
780
781 static int ast_fsread_audio(const void *data)
782 {
783         struct ast_filestream *fs = (struct ast_filestream *)data;
784         enum fsread_res res;
785
786         res = ast_readaudio_callback(fs);
787
788         if (res == FSREAD_SUCCESS_SCHED)
789                 return 1;
790         
791         return 0;
792 }
793
794 static int ast_fsread_video(const void *data);
795
796 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
797 {
798         int whennext = 0;
799
800         while (!whennext) {
801                 struct ast_frame *fr = read_frame(s, &whennext);
802
803                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
804                         if (fr) {
805                                 ast_log(LOG_WARNING, "Failed to write frame\n");
806                                 ast_frfree(fr);
807                         }
808                         s->owner->vstreamid = -1;
809                         return FSREAD_FAILURE;
810                 }
811
812                 if (fr) {
813                         ast_frfree(fr);
814                 }
815         }
816
817         if (whennext != s->lasttimeout) {
818                 s->owner->vstreamid = ast_sched_add(s->owner->sched, 
819                         whennext / (ast_format_rate(s->fmt->format) / 1000), 
820                         ast_fsread_video, s);
821                 s->lasttimeout = whennext;
822                 return FSREAD_SUCCESS_NOSCHED;
823         }
824
825         return FSREAD_SUCCESS_SCHED;
826 }
827
828 static int ast_fsread_video(const void *data)
829 {
830         struct ast_filestream *fs = (struct ast_filestream *)data;
831         enum fsread_res res;
832
833         res = ast_readvideo_callback(fs);
834
835         if (res == FSREAD_SUCCESS_SCHED)
836                 return 1;
837         
838         return 0;
839 }
840
841 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
842 {
843         s->owner = chan;
844         return 0;
845 }
846
847 int ast_playstream(struct ast_filestream *s)
848 {
849         enum fsread_res res;
850
851         if (s->fmt->format & AST_FORMAT_AUDIO_MASK)
852                 res = ast_readaudio_callback(s);
853         else
854                 res = ast_readvideo_callback(s);
855
856         return (res == FSREAD_FAILURE) ? -1 : 0;
857 }
858
859 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
860 {
861         return fs->fmt->seek(fs, sample_offset, whence);
862 }
863
864 int ast_truncstream(struct ast_filestream *fs)
865 {
866         return fs->fmt->trunc(fs);
867 }
868
869 off_t ast_tellstream(struct ast_filestream *fs)
870 {
871         return fs->fmt->tell(fs);
872 }
873
874 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
875 {
876         return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
877 }
878
879 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
880 {
881         return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
882 }
883
884 int ast_closestream(struct ast_filestream *f)
885 {
886         /* This used to destroy the filestream, but it now just decrements a refcount.
887          * We need to force the stream to quit queuing frames now, because we might
888          * change the writeformat, which could result in a subsequent write error, if
889          * the format is different. */
890
891         /* Stop a running stream if there is one */
892         if (f->owner) {
893                 if (f->fmt->format < AST_FORMAT_AUDIO_MASK) {
894                         f->owner->stream = NULL;
895                         AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
896                         ast_settimeout(f->owner, 0, NULL, NULL);
897                 } else {
898                         f->owner->vstream = NULL;
899                         AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
900                 }
901         }
902
903         ao2_ref(f, -1);
904         return 0;
905 }
906
907
908 /*
909  * Look the various language-specific places where a file could exist.
910  */
911 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
912 {
913         char *buf;
914         int buflen;
915
916         if (preflang == NULL)
917                 preflang = "";
918         buflen = strlen(preflang) + strlen(filename) + 4;       /* room for everything */
919         buf = alloca(buflen);
920         if (buf == NULL)
921                 return 0;
922         return fileexists_core(filename, fmt, preflang, buf, buflen);
923 }
924
925 int ast_filedelete(const char *filename, const char *fmt)
926 {
927         return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
928 }
929
930 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
931 {
932         return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
933 }
934
935 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
936 {
937         return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
938 }
939
940 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
941 {
942         struct ast_filestream *fs;
943         struct ast_filestream *vfs=NULL;
944         char fmt[256];
945         int seekattempt;
946         int res;
947
948         fs = ast_openstream(chan, filename, preflang);
949         if (!fs) {
950                 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
951                 return -1;
952         }
953
954         /* check to see if there is any data present (not a zero length file),
955          * done this way because there is no where for ast_openstream_full to
956          * return the file had no data. */
957         seekattempt = fseek(fs->f, -1, SEEK_END);
958         if (!seekattempt)
959                 ast_seekstream(fs, 0, SEEK_SET);
960         else
961                 return 0;
962
963         vfs = ast_openvstream(chan, filename, preflang);
964         if (vfs) {
965                 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
966         }
967
968         if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
969                 fs->orig_chan_name = ast_strdup(chan->name);
970         if (ast_applystream(chan, fs))
971                 return -1;
972         if (vfs && ast_applystream(chan, vfs))
973                 return -1;
974         res = ast_playstream(fs);
975         if (!res && vfs)
976                 res = ast_playstream(vfs);
977         ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", chan->name, filename, ast_getformatname(chan->writeformat), preflang ? preflang : "default");
978
979         return res;
980 }
981
982 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
983 {
984         FILE *bfile;
985         struct ast_format *f;
986         struct ast_filestream *fs = NULL;
987         char *fn;
988         int format_found = 0;   
989
990         AST_RWLIST_RDLOCK(&formats);
991
992         AST_RWLIST_TRAVERSE(&formats, f, list) {
993                 fs = NULL;
994                 if (!exts_compare(f->exts, type))
995                         continue;
996                 else 
997                         format_found = 1;
998
999                 fn = build_filename(filename, type);
1000                 errno = 0;
1001                 bfile = fopen(fn, "r");
1002
1003                 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
1004                         ast_log(LOG_WARNING, "Unable to open %s\n", fn);
1005                         if (fs) {
1006                                 ast_closestream(fs);
1007                         }
1008                         fs = NULL;
1009                         bfile = NULL;
1010                         ast_free(fn);
1011                         break;                          
1012                 }
1013                 /* found it */
1014                 fs->trans = NULL;
1015                 fs->fmt = f;
1016                 fs->flags = flags;
1017                 fs->mode = mode;
1018                 fs->filename = ast_strdup(filename);
1019                 fs->vfs = NULL;
1020                 break;
1021         }
1022
1023         AST_RWLIST_UNLOCK(&formats);
1024         if (!format_found)
1025                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1026
1027         return fs;
1028 }
1029
1030 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1031 {
1032         int fd, myflags = 0;
1033         /* compiler claims this variable can be used before initialization... */
1034         FILE *bfile = NULL;
1035         struct ast_format *f;
1036         struct ast_filestream *fs = NULL;
1037         char *buf = NULL;
1038         size_t size = 0;
1039         int format_found = 0;
1040
1041         AST_RWLIST_RDLOCK(&formats);
1042
1043         /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
1044         /* We really can't use O_APPEND as it will break WAV header updates */
1045         if (flags & O_APPEND) { 
1046                 flags &= ~O_APPEND;
1047         } else {
1048                 myflags = O_TRUNC;
1049         }
1050         
1051         myflags |= O_WRONLY | O_CREAT;
1052
1053         /* XXX need to fix this - we should just do the fopen,
1054          * not open followed by fdopen()
1055          */
1056         AST_RWLIST_TRAVERSE(&formats, f, list) {
1057                 char *fn, *orig_fn = NULL;
1058                 if (fs)
1059                         break;
1060
1061                 if (!exts_compare(f->exts, type))
1062                         continue;
1063                 else
1064                         format_found = 1;
1065
1066                 fn = build_filename(filename, type);
1067                 fd = open(fn, flags | myflags, mode);
1068                 if (fd > -1) {
1069                         /* fdopen() the resulting file stream */
1070                         bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1071                         if (!bfile) {
1072                                 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1073                                 close(fd);
1074                                 fd = -1;
1075                         }
1076                 }
1077                 
1078                 if (ast_opt_cache_record_files && (fd > -1)) {
1079                         char *c;
1080
1081                         fclose(bfile);  /* this also closes fd */
1082                         /*
1083                           We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1084                           What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1085                         */
1086                         orig_fn = ast_strdupa(fn);
1087                         for (c = fn; *c; c++)
1088                                 if (*c == '/')
1089                                         *c = '_';
1090
1091                         size = strlen(fn) + strlen(record_cache_dir) + 2;
1092                         buf = alloca(size);
1093                         strcpy(buf, record_cache_dir);
1094                         strcat(buf, "/");
1095                         strcat(buf, fn);
1096                         ast_free(fn);
1097                         fn = buf;
1098                         fd = open(fn, flags | myflags, mode);
1099                         if (fd > -1) {
1100                                 /* fdopen() the resulting file stream */
1101                                 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1102                                 if (!bfile) {
1103                                         ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1104                                         close(fd);
1105                                         fd = -1;
1106                                 }
1107                         }
1108                 }
1109                 if (fd > -1) {
1110                         errno = 0;
1111                         fs = get_filestream(f, bfile);
1112                         if (!fs || rewrite_wrapper(fs, comment)) {
1113                                 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1114                                 close(fd);
1115                                 if (orig_fn) {
1116                                         unlink(fn);
1117                                         unlink(orig_fn);
1118                                 }
1119                                 if (fs) {
1120                                         ast_closestream(fs);
1121                                         fs = NULL;
1122                                 }
1123                                 continue;
1124                         }
1125                         fs->trans = NULL;
1126                         fs->fmt = f;
1127                         fs->flags = flags;
1128                         fs->mode = mode;
1129                         if (orig_fn) {
1130                                 fs->realfilename = ast_strdup(orig_fn);
1131                                 fs->filename = ast_strdup(fn);
1132                         } else {
1133                                 fs->realfilename = NULL;
1134                                 fs->filename = ast_strdup(filename);
1135                         }
1136                         fs->vfs = NULL;
1137                         /* If truncated, we'll be at the beginning; if not truncated, then append */
1138
1139                         if ((fs->write_buffer = ast_malloc(32768))){
1140                                 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1141                         }
1142
1143                         f->seek(fs, 0, SEEK_END);
1144                 } else if (errno != EEXIST) {
1145                         ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1146                         if (orig_fn)
1147                                 unlink(orig_fn);
1148                 }
1149                 /* if buf != NULL then fn is already free and pointing to it */
1150                 if (!buf)
1151                         ast_free(fn);
1152         }
1153
1154         AST_RWLIST_UNLOCK(&formats);
1155
1156         if (!format_found)
1157                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1158
1159         return fs;
1160 }
1161
1162 /*!
1163  * \brief the core of all waitstream() functions
1164  */
1165 static int waitstream_core(struct ast_channel *c, const char *breakon,
1166         const char *forward, const char *reverse, int skip_ms,
1167         int audiofd, int cmdfd,  const char *context)
1168 {
1169         const char *orig_chan_name = NULL;
1170         int err = 0;
1171
1172         if (!breakon)
1173                 breakon = "";
1174         if (!forward)
1175                 forward = "";
1176         if (!reverse)
1177                 reverse = "";
1178
1179         /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1180         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1181
1182         if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1183                 orig_chan_name = ast_strdupa(c->name);
1184
1185         while (c->stream) {
1186                 int res;
1187                 int ms;
1188
1189                 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1190                         ast_stopstream(c);
1191                         err = 1;
1192                         break;
1193                 }
1194
1195                 ms = ast_sched_wait(c->sched);
1196
1197                 if (ms < 0 && !c->timingfunc) {
1198                         ast_stopstream(c);
1199                         break;
1200                 }
1201                 if (ms < 0)
1202                         ms = 1000;
1203                 if (cmdfd < 0) {
1204                         res = ast_waitfor(c, ms);
1205                         if (res < 0) {
1206                                 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1207                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1208                                 return res;
1209                         }
1210                 } else {
1211                         int outfd;
1212                         struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1213                         if (!rchan && (outfd < 0) && (ms)) {
1214                                 /* Continue */
1215                                 if (errno == EINTR)
1216                                         continue;
1217                                 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1218                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1219                                 return -1;
1220                         } else if (outfd > -1) { /* this requires cmdfd set */
1221                                 /* The FD we were watching has something waiting */
1222                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1223                                 return 1;
1224                         }
1225                         /* if rchan is set, it is 'c' */
1226                         res = rchan ? 1 : 0; /* map into 'res' values */
1227                 }
1228                 if (res > 0) {
1229                         struct ast_frame *fr = ast_read(c);
1230                         if (!fr) {
1231                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1232                                 return -1;
1233                         }
1234                         switch (fr->frametype) {
1235                         case AST_FRAME_DTMF_END:
1236                                 if (context) {
1237                                         const char exten[2] = { fr->subclass.integer, '\0' };
1238                                         if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1239                                                 res = fr->subclass.integer;
1240                                                 ast_frfree(fr);
1241                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1242                                                 return res;
1243                                         }
1244                                 } else {
1245                                         res = fr->subclass.integer;
1246                                         if (strchr(forward, res)) {
1247                                                 int eoftest;
1248                                                 ast_stream_fastforward(c->stream, skip_ms);
1249                                                 eoftest = fgetc(c->stream->f);
1250                                                 if (feof(c->stream->f)) {
1251                                                         ast_stream_rewind(c->stream, skip_ms);
1252                                                 } else {
1253                                                         ungetc(eoftest, c->stream->f);
1254                                                 }
1255                                         } else if (strchr(reverse, res)) {
1256                                                 ast_stream_rewind(c->stream, skip_ms);
1257                                         } else if (strchr(breakon, res)) {
1258                                                 ast_frfree(fr);
1259                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1260                                                 return res;
1261                                         }                                       
1262                                 }
1263                                 break;
1264                         case AST_FRAME_CONTROL:
1265                                 switch (fr->subclass.integer) {
1266                                 case AST_CONTROL_HANGUP:
1267                                 case AST_CONTROL_BUSY:
1268                                 case AST_CONTROL_CONGESTION:
1269                                         ast_frfree(fr);
1270                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1271                                         return -1;
1272                                 case AST_CONTROL_RINGING:
1273                                 case AST_CONTROL_ANSWER:
1274                                 case AST_CONTROL_VIDUPDATE:
1275                                 case AST_CONTROL_SRCUPDATE:
1276                                 case AST_CONTROL_SRCCHANGE:
1277                                 case AST_CONTROL_HOLD:
1278                                 case AST_CONTROL_UNHOLD:
1279                                 case -1:
1280                                         /* Unimportant */
1281                                         break;
1282                                 default:
1283                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
1284                                 }
1285                                 break;
1286                         case AST_FRAME_VOICE:
1287                                 /* Write audio if appropriate */
1288                                 if (audiofd > -1) {
1289                                         if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
1290                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
1291                                         }
1292                                 }
1293                         default:
1294                                 /* Ignore all others */
1295                                 break;
1296                         }
1297                         ast_frfree(fr);
1298                 }
1299                 ast_sched_runq(c->sched);
1300         }
1301
1302         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1303
1304         return (err || c->_softhangup) ? -1 : 0;
1305 }
1306
1307 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1308 {
1309         return waitstream_core(c, breakon, forward, reverse, ms,
1310                 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1311 }
1312
1313 int ast_waitstream(struct ast_channel *c, const char *breakon)
1314 {
1315         return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1316 }
1317
1318 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1319 {
1320         return waitstream_core(c, breakon, NULL, NULL, 0,
1321                 audiofd, cmdfd, NULL /* no context */);
1322 }
1323
1324 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1325 {
1326         /* Waitstream, with return in the case of a valid 1 digit extension */
1327         /* in the current or specified context being pressed */
1328
1329         if (!context)
1330                 context = c->context;
1331         return waitstream_core(c, NULL, NULL, NULL, 0,
1332                 -1, -1, context);
1333 }
1334
1335 /*
1336  * if the file name is non-empty, try to play it.
1337  * Return 0 if success, -1 if error, digit if interrupted by a digit.
1338  * If digits == "" then we can simply check for non-zero.
1339  */
1340 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1341 {
1342         int res = 0;
1343         if (!ast_strlen_zero(file)) {
1344                 res = ast_streamfile(chan, file, chan->language);
1345                 if (!res) {
1346                         res = ast_waitstream(chan, digits);
1347                 }
1348         }
1349         return res;
1350
1351
1352 char *ast_format_str_reduce(char *fmts)
1353 {
1354         struct ast_format *f;
1355         struct ast_format *fmts_ptr[AST_MAX_FORMATS];
1356         char *fmts_str[AST_MAX_FORMATS];
1357         char *stringp, *type;
1358         char *orig = fmts;
1359         int i, j, x, first, found = 0;
1360         int len = strlen(fmts) + 1;
1361         int res;
1362
1363         if (AST_RWLIST_RDLOCK(&formats)) {
1364                 ast_log(LOG_WARNING, "Unable to lock format list\n");
1365                 return NULL;
1366         }
1367
1368         stringp = ast_strdupa(fmts);
1369
1370         for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
1371                 AST_RWLIST_TRAVERSE(&formats, f, list) {
1372                         if (exts_compare(f->exts, type)) {
1373                                 found = 1;
1374                                 break;
1375                         }
1376                 }
1377
1378                 fmts_str[x] = type;
1379                 if (found) {
1380                         fmts_ptr[x] = f;
1381                 } else {
1382                         fmts_ptr[x] = NULL;
1383                 }
1384         }
1385         AST_RWLIST_UNLOCK(&formats);
1386
1387         first = 1;
1388         for (i = 0; i < x; i++) {
1389                 /* ignore invalid entries */
1390                 if (!fmts_ptr[i]) {
1391                         ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
1392                         continue;
1393                 }
1394
1395                 /* special handling for the first entry */
1396                 if (first) {
1397                         res = snprintf(fmts, len, "%s", fmts_str[i]);
1398                         fmts += res;
1399                         len -= res;
1400                         first = 0;
1401                         continue;
1402                 }
1403
1404                 found = 0;
1405                 for (j = 0; j < i; j++) {
1406                         /* this is a duplicate */
1407                         if (fmts_ptr[j] == fmts_ptr[i]) {
1408                                 found = 1;
1409                                 break;
1410                         }
1411                 }
1412
1413                 if (!found) {
1414                         res = snprintf(fmts, len, "|%s", fmts_str[i]);
1415                         fmts += res;
1416                         len -= res;
1417                 }
1418         }
1419
1420         if (first) {
1421                 ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
1422                 return NULL;
1423         }
1424
1425         return orig;
1426 }
1427
1428 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1429 {
1430 #define FORMAT "%-10s %-10s %-20s\n"
1431 #define FORMAT2 "%-10s %-10s %-20s\n"
1432         struct ast_format *f;
1433         int count_fmt = 0;
1434
1435         switch (cmd) {
1436         case CLI_INIT:
1437                 e->command = "core show file formats";
1438                 e->usage =
1439                         "Usage: core show file formats\n"
1440                         "       Displays currently registered file formats (if any).\n";
1441                 return NULL;
1442         case CLI_GENERATE:
1443                 return NULL;
1444         }
1445
1446         if (a->argc != 4)
1447                 return CLI_SHOWUSAGE;
1448
1449         ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1450         ast_cli(a->fd, FORMAT, "------", "----", "----------");
1451
1452         AST_RWLIST_RDLOCK(&formats);
1453         AST_RWLIST_TRAVERSE(&formats, f, list) {
1454                 ast_cli(a->fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1455                 count_fmt++;
1456         }
1457         AST_RWLIST_UNLOCK(&formats);
1458         ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1459         return CLI_SUCCESS;
1460 #undef FORMAT
1461 #undef FORMAT2
1462 }
1463
1464 static struct ast_cli_entry cli_file[] = {
1465         AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1466 };
1467
1468 int ast_file_init(void)
1469 {
1470         ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
1471         return 0;
1472 }