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