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