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