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