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