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