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