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