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