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