2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief Generic File Format Support.
23 * \author Mark Spencer <markster@digium.com>
27 <support_level>core</support_level>
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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"
56 * The following variable controls the layout of localized sound files.
57 * If 0, use the historical layout with prefix just before the filename
58 * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
59 * if 1 put the prefix at the beginning of the filename
60 * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
61 * The latter permits a language to be entirely in one directory.
63 * This is settable in asterisk.conf.
65 int ast_language_is_prefix = 1;
67 static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
69 int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
71 struct ast_format_def *tmp;
73 AST_RWLIST_WRLOCK(&formats);
74 AST_RWLIST_TRAVERSE(&formats, tmp, list) {
75 if (!strcasecmp(f->name, tmp->name)) {
76 AST_RWLIST_UNLOCK(&formats);
77 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
81 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
82 AST_RWLIST_UNLOCK(&formats);
89 * Align buf_size properly, rounding up to the machine-specific
90 * alignment for pointers.
92 struct _test_align { void *a, *b; } p;
93 int align = (char *)&p.b - (char *)&p.a;
94 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
97 memset(&tmp->list, 0, sizeof(tmp->list));
99 AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
100 AST_RWLIST_UNLOCK(&formats);
101 ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
106 int ast_format_def_unregister(const char *name)
108 struct ast_format_def *tmp;
111 AST_RWLIST_WRLOCK(&formats);
112 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
113 if (!strcasecmp(name, tmp->name)) {
114 AST_RWLIST_REMOVE_CURRENT(list);
119 AST_RWLIST_TRAVERSE_SAFE_END;
120 AST_RWLIST_UNLOCK(&formats);
123 ast_verb(2, "Unregistered format %s\n", name);
125 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
130 int ast_stopstream(struct ast_channel *tmp)
132 ast_channel_lock(tmp);
134 /* Stop a running stream if there is one */
135 if (ast_channel_stream(tmp)) {
136 ast_closestream(ast_channel_stream(tmp));
137 ast_channel_stream_set(tmp, NULL);
138 if (ast_channel_oldwriteformat(tmp)->id && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
139 ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(ast_channel_oldwriteformat(tmp)));
141 /* Stop the video stream too */
142 if (ast_channel_vstream(tmp) != NULL) {
143 ast_closestream(ast_channel_vstream(tmp));
144 ast_channel_vstream_set(tmp, NULL);
147 ast_channel_unlock(tmp);
152 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
155 if (f->frametype == AST_FRAME_VIDEO) {
156 if (AST_FORMAT_GET_TYPE(fs->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
157 /* This is the audio portion. Call the video one... */
158 if (!fs->vfs && fs->filename) {
159 const char *type = ast_getformatname(&f->subclass.format);
160 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
161 ast_debug(1, "Opened video output file\n");
164 return ast_writestream(fs->vfs, f);
168 } else if (f->frametype != AST_FRAME_VOICE) {
169 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
172 if (ast_format_cmp(&f->subclass.format, &fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
173 res = fs->fmt->write(fs, f);
175 ast_log(LOG_WARNING, "Natural write failed\n");
177 ast_log(LOG_WARNING, "Huh??\n");
179 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
180 the one we've setup a translator for, we do the "wrong thing" XXX */
181 if (fs->trans && (ast_format_cmp(&f->subclass.format, &fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
182 ast_translator_free_path(fs->trans);
186 fs->trans = ast_translator_build_path(&fs->fmt->format, &f->subclass.format);
188 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
189 fs->fmt->name, ast_getformatname(&f->subclass.format));
191 struct ast_frame *trf;
192 ast_format_copy(&fs->lastwriteformat, &f->subclass.format);
193 /* Get the translated frame but don't consume the original in case they're using it on another stream */
194 if ((trf = ast_translate(fs->trans, f, 0))) {
195 struct ast_frame *cur;
197 /* the translator may have returned multiple frames, so process them */
198 for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
199 if ((res = fs->fmt->write(fs, trf))) {
200 ast_log(LOG_WARNING, "Translated frame write failed\n");
213 static int copy(const char *infile, const char *outfile)
216 char buf[4096]; /* XXX make it lerger. */
218 if ((ifd = open(infile, O_RDONLY)) < 0) {
219 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
222 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
223 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
227 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
230 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
233 /* XXX handle partial writes */
234 res = write(ofd, buf, len);
236 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
237 len = -1; /* error marker */
245 return -1; /* error */
247 return 0; /* success */
251 * \brief construct a filename. Absolute pathnames are preserved,
252 * relative names are prefixed by the sounds/ directory.
253 * The wav49 suffix is replaced by 'WAV'.
254 * Returns a malloc'ed string to be freed by the caller.
256 static char *build_filename(const char *filename, const char *ext)
260 if (!strcmp(ext, "wav49"))
263 if (filename[0] == '/') {
264 if (ast_asprintf(&fn, "%s.%s", filename, ext) < 0) {
268 if (ast_asprintf(&fn, "%s/sounds/%s.%s",
269 ast_config_AST_DATA_DIR, filename, ext) < 0) {
276 /* compare type against the list 'exts' */
277 /* XXX need a better algorithm */
278 static int exts_compare(const char *exts, const char *type)
281 char *stringp = tmp, *ext;
283 ast_copy_string(tmp, exts, sizeof(tmp));
284 while ((ext = strsep(&stringp, "|"))) {
285 if (!strcmp(ext, type))
292 /*! \internal \brief Close the file stream by canceling any pending read / write callbacks */
293 static void filestream_close(struct ast_filestream *f)
295 enum ast_format_type format_type = AST_FORMAT_GET_TYPE(f->fmt->format.id);
301 /* Stop a running stream if there is one */
304 case AST_FORMAT_TYPE_AUDIO:
305 ast_channel_stream_set(f->owner, NULL);
306 AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
307 ast_settimeout(f->owner, 0, NULL, NULL);
309 case AST_FORMAT_TYPE_VIDEO:
310 ast_channel_vstream_set(f->owner, NULL);
311 AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
314 ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
319 static void filestream_destructor(void *arg)
321 struct ast_filestream *f = arg;
325 /* Stop a running stream if there is one */
328 /* destroy the translator on exit */
330 ast_translator_free_path(f->trans);
332 if (f->realfilename && f->filename) {
333 pid = ast_safe_fork(0);
335 execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
339 /* Block the parent until the move is complete.*/
340 waitpid(pid, &status, 0);
347 free(f->realfilename);
349 void (*closefn)(struct ast_filestream *) = f->fmt->close;
355 ast_closestream(f->vfs);
356 if (f->write_buffer) {
357 ast_free(f->write_buffer);
359 if (f->orig_chan_name)
360 free((void *) f->orig_chan_name);
361 ast_module_unref(f->fmt->module);
364 static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
366 struct ast_filestream *s;
368 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
369 if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
375 s->_private = ((char *)(s + 1)) + fmt->buf_size;
377 s->buf = (char *)(s + 1);
378 s->fr.src = fmt->name;
383 * Default implementations of open and rewrite.
384 * Only use them if you don't have expensive stuff to do.
386 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
388 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
390 struct ast_format_def *f = s->fmt;
392 int (*openfn)(struct ast_filestream *s);
394 if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
395 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
396 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
397 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
399 /* preliminary checks succeed. update usecount */
400 ast_module_ref(f->module);
406 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
408 return fn_wrapper(s, comment, WRAP_REWRITE);
411 static int open_wrapper(struct ast_filestream *s)
413 return fn_wrapper(s, NULL, WRAP_OPEN);
417 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
418 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
419 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
421 ACTION_COPY /* copy file. return 0 on success, -1 on error */
426 * \brief perform various actions on a file. Second argument
427 * \note arg2 depends on the command:
429 * optional ast_format_cap holding all the formats found for a file, for EXISTS.
430 * destination file name (const char *) for COPY and RENAME
431 * struct ast_channel * for OPEN
432 * if fmt is NULL, OPEN will return the first matching entry,
433 * whereas other functions will run on all matching entries.
435 static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
437 struct ast_format_def *f;
438 int res = (action == ACTION_EXISTS) ? 0 : -1;
440 AST_RWLIST_RDLOCK(&formats);
441 /* Check for a specific format */
442 AST_RWLIST_TRAVERSE(&formats, f, list) {
443 char *stringp, *ext = NULL;
445 if (fmt && !exts_compare(f->exts, fmt))
448 /* Look for a file matching the supported extensions.
449 * The file must exist, and for OPEN, must match
450 * one of the formats supported by the channel.
452 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
453 while ( (ext = strsep(&stringp, "|")) ) {
455 char *fn = build_filename(filename, ext);
460 if ( stat(fn, &st) ) { /* file not existent */
464 /* for 'OPEN' we need to be sure that the format matches
465 * what the channel can process
467 if (action == ACTION_OPEN) {
468 struct ast_channel *chan = (struct ast_channel *)arg2;
470 struct ast_filestream *s;
472 if ((ast_format_cmp(ast_channel_writeformat(chan), &f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
473 !(((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_AUDIO) && fmt) ||
474 ((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_VIDEO) && fmt))) {
476 continue; /* not a supported format */
478 if ( (bfile = fopen(fn, "r")) == NULL) {
480 continue; /* cannot open file */
482 s = get_filestream(f, bfile);
485 ast_free(fn); /* cannot allocate descriptor */
488 if (open_wrapper(s)) {
491 continue; /* cannot run open on file */
493 if (st.st_size == 0) {
494 ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
496 /* ok this is good for OPEN */
502 if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
503 if (ast_channel_stream(chan))
504 ast_closestream(ast_channel_stream(chan));
505 ast_channel_stream_set(chan, s);
507 if (ast_channel_vstream(chan))
508 ast_closestream(ast_channel_vstream(chan));
509 ast_channel_vstream_set(chan, s);
516 break; /* will never get here */
518 case ACTION_EXISTS: /* return the matching format */
519 /* if arg2 is present, it is a format capabilities structure.
520 * Add this format to the set of formats this file can be played in */
522 ast_format_cap_add((struct ast_format_cap *) arg2, &f->format);
524 res = 1; /* file does exist and format it exists in is returned in arg2 */
528 if ( (res = unlink(fn)) )
529 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
534 char *nfn = build_filename((const char *)arg2, ext);
536 ast_log(LOG_WARNING, "Out of memory\n");
538 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
540 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
541 action == ACTION_COPY ? "copy" : "rename",
542 fn, nfn, strerror(errno));
549 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
554 AST_RWLIST_UNLOCK(&formats);
558 static int is_absolute_path(const char *filename)
560 return filename[0] == '/';
564 * \brief test if a file exists for a given format.
565 * \note result_cap is OPTIONAL
566 * \retval 1, true and result_cap represents format capabilities file exists in.
569 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
570 char *buf, int buflen, struct ast_format_cap *result_cap)
576 if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
578 snprintf(buf, buflen, "%s/%s", lang, filename);
580 snprintf(buf, buflen, "%s", filename);
582 } else { /* old layout */
583 strcpy(buf, filename); /* first copy the full string */
585 /* insert the language and suffix if needed */
586 const char *c = strrchr(filename, '/');
587 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
588 snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
592 return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
596 * \brief helper routine to locate a file with a given format
597 * and language preference.
599 * \note Try preflang, preflang with stripped '_' suffices, or NULL.
601 * \note The last parameter(s) point to a buffer of sufficient size,
602 * which on success is filled with the matching filename.
604 * \param filename Name of the file.
605 * \param fmt Format to look for the file in. OPTIONAL
606 * \param preflang The perfered language
607 * \param buf Returns the matching filename
608 * \param buflen Size of the buf
609 * \param result_cap OPTIONAL format capabilities result structure
610 * returns what formats the file was found in.
612 * \retval 1, true. file exists and result format is set
613 * \retval 0, false. file does not exist.
615 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
616 char *buf, int buflen, struct ast_format_cap *result_cap)
624 /* We try languages in the following order:
625 * preflang (may include dialect and style codes)
626 * lang (preflang without dialect - if any)
628 * default (unless the same as preflang or lang without dialect)
631 lang = ast_strdupa(preflang);
633 /* Try preferred language, including removing any style or dialect codes */
634 while (!ast_strlen_zero(lang)) {
637 if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
641 if ((end = strrchr(lang, '_')) != NULL) {
649 /* Try without any language */
650 if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
654 /* Finally try the default language unless it was already tried before */
655 if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
656 if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
664 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
666 return ast_openstream_full(chan, filename, preflang, 0);
669 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
672 * Use fileexists_core() to find a file in a compatible
673 * language and format, set up a suitable translator,
674 * and open the stream.
676 struct ast_format_cap *file_fmt_cap;
682 /* do this first, otherwise we detect the wrong writeformat */
683 ast_stopstream(chan);
684 if (ast_channel_generator(chan))
685 ast_deactivate_generator(chan);
687 if (preflang == NULL)
689 buflen = strlen(preflang) + strlen(filename) + 4;
690 buf = ast_alloca(buflen);
692 if (!(file_fmt_cap = ast_format_cap_alloc_nolock())) {
695 if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
696 !ast_format_cap_has_type(file_fmt_cap, AST_FORMAT_TYPE_AUDIO)) {
698 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
699 file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
703 /* Set the channel to a format we can work with and save off the previous format. */
704 ast_format_copy(ast_channel_oldwriteformat(chan), ast_channel_writeformat(chan));
705 /* Set the channel to the best format that exists for the file. */
706 res = ast_set_write_format_from_cap(chan, file_fmt_cap);
707 /* don't need this anymore now that the channel's write format is set. */
708 file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
710 if (res == -1) { /* No format available that works with this channel */
713 res = filehelper(buf, chan, NULL, ACTION_OPEN);
715 return ast_channel_stream(chan);
719 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
721 /* As above, but for video. But here we don't have translators
722 * so we must enforce a format.
724 struct ast_format tmp_fmt;
725 struct ast_format_cap *tmp_cap;
731 if (preflang == NULL)
733 buflen = strlen(preflang) + strlen(filename) + 4;
734 buf = ast_alloca(buflen);
736 /* is the channel capable of video without translation ?*/
737 if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_FORMAT_TYPE_VIDEO)) {
740 if (!(tmp_cap = ast_format_cap_alloc_nolock())) {
743 /* Video is supported, so see what video formats exist for this file */
744 if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
745 tmp_cap = ast_format_cap_destroy(tmp_cap);
749 /* iterate over file formats and pick the first one compatible with the channel's native formats */
750 ast_format_cap_iter_start(tmp_cap);
751 while (!ast_format_cap_iter_next(tmp_cap, &tmp_fmt)) {
752 fmt = ast_getformatname(&tmp_fmt);
753 if ((AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_VIDEO) ||
754 !ast_format_cap_iscompatible(ast_channel_nativeformats(chan), &tmp_fmt)) {
758 fd = filehelper(buf, chan, fmt, ACTION_OPEN);
760 ast_format_cap_iter_end(tmp_cap);
761 tmp_cap = ast_format_cap_destroy(tmp_cap);
762 return ast_channel_vstream(chan);
764 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
766 ast_format_cap_iter_end(tmp_cap);
767 tmp_cap = ast_format_cap_destroy(tmp_cap);
772 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
774 struct ast_frame *fr, *new_fr;
780 if (!(fr = s->fmt->read(s, whennext))) {
784 if (!(new_fr = ast_frisolate(fr))) {
797 struct ast_frame *ast_readframe(struct ast_filestream *s)
801 return read_frame(s, &whennext);
806 FSREAD_SUCCESS_SCHED,
807 FSREAD_SUCCESS_NOSCHED,
810 static int ast_fsread_audio(const void *data);
812 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
817 struct ast_frame *fr;
819 if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
823 fr = read_frame(s, &whennext);
825 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
827 ast_log(LOG_WARNING, "Failed to write frame\n");
838 if (whennext != s->lasttimeout) {
839 if (ast_channel_timingfd(s->owner) > -1) {
840 float samp_rate = (float) ast_format_rate(&s->fmt->format);
843 rate = (unsigned int) roundf(samp_rate / ((float) whennext));
845 ast_settimeout(s->owner, rate, ast_fsread_audio, s);
847 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));
849 s->lasttimeout = whennext;
850 return FSREAD_SUCCESS_NOSCHED;
852 return FSREAD_SUCCESS_SCHED;
855 ast_channel_streamid_set(s->owner, -1);
856 ast_settimeout(s->owner, 0, NULL, NULL);
857 return FSREAD_FAILURE;
860 static int ast_fsread_audio(const void *data)
862 struct ast_filestream *fs = (struct ast_filestream *)data;
865 res = ast_readaudio_callback(fs);
867 if (res == FSREAD_SUCCESS_SCHED)
873 static int ast_fsread_video(const void *data);
875 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
880 struct ast_frame *fr = read_frame(s, &whennext);
882 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
884 ast_log(LOG_WARNING, "Failed to write frame\n");
887 ast_channel_vstreamid_set(s->owner, -1);
888 return FSREAD_FAILURE;
896 if (whennext != s->lasttimeout) {
897 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));
898 s->lasttimeout = whennext;
899 return FSREAD_SUCCESS_NOSCHED;
902 return FSREAD_SUCCESS_SCHED;
905 static int ast_fsread_video(const void *data)
907 struct ast_filestream *fs = (struct ast_filestream *)data;
910 res = ast_readvideo_callback(fs);
912 if (res == FSREAD_SUCCESS_SCHED)
918 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
924 int ast_playstream(struct ast_filestream *s)
928 if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO)
929 res = ast_readaudio_callback(s);
931 res = ast_readvideo_callback(s);
933 return (res == FSREAD_FAILURE) ? -1 : 0;
936 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
938 return fs->fmt->seek(fs, sample_offset, whence);
941 int ast_truncstream(struct ast_filestream *fs)
943 return fs->fmt->trunc(fs);
946 off_t ast_tellstream(struct ast_filestream *fs)
948 return fs->fmt->tell(fs);
951 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
953 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
956 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
958 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
961 int ast_closestream(struct ast_filestream *f)
963 /* This used to destroy the filestream, but it now just decrements a refcount.
964 * We close the stream in order to quit queuing frames now, because we might
965 * change the writeformat, which could result in a subsequent write error, if
966 * the format is different. */
974 * Look the various language-specific places where a file could exist.
976 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
981 if (preflang == NULL)
983 buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
984 buf = ast_alloca(buflen);
985 return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
988 int ast_filedelete(const char *filename, const char *fmt)
990 return filehelper(filename, NULL, fmt, ACTION_DELETE);
993 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
995 return filehelper(filename, filename2, fmt, ACTION_RENAME);
998 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
1000 return filehelper(filename, filename2, fmt, ACTION_COPY);
1003 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
1005 struct ast_filestream *fs;
1006 struct ast_filestream *vfs=NULL;
1012 fs = ast_openstream(chan, filename, preflang);
1014 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));
1018 /* check to see if there is any data present (not a zero length file),
1019 * done this way because there is no where for ast_openstream_full to
1020 * return the file had no data. */
1021 pos = ftello(fs->f);
1022 seekattempt = fseeko(fs->f, -1, SEEK_END);
1024 if (errno == EINVAL) {
1025 /* Zero-length file, as opposed to a pipe */
1028 ast_seekstream(fs, 0, SEEK_SET);
1031 fseeko(fs->f, pos, SEEK_SET);
1034 vfs = ast_openvstream(chan, filename, preflang);
1036 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(&vfs->fmt->format));
1039 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
1040 fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
1041 if (ast_applystream(chan, fs))
1043 if (vfs && ast_applystream(chan, vfs))
1045 res = ast_playstream(fs);
1047 res = ast_playstream(vfs);
1048 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", ast_channel_name(chan), filename, ast_getformatname(ast_channel_writeformat(chan)), preflang ? preflang : "default");
1053 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1056 struct ast_format_def *f;
1057 struct ast_filestream *fs = NULL;
1059 int format_found = 0;
1061 AST_RWLIST_RDLOCK(&formats);
1063 AST_RWLIST_TRAVERSE(&formats, f, list) {
1065 if (!exts_compare(f->exts, type))
1070 fn = build_filename(filename, type);
1075 bfile = fopen(fn, "r");
1077 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
1078 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
1080 ast_closestream(fs);
1092 fs->filename = ast_strdup(filename);
1098 AST_RWLIST_UNLOCK(&formats);
1100 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1105 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1107 int fd, myflags = 0;
1108 /* compiler claims this variable can be used before initialization... */
1110 struct ast_format_def *f;
1111 struct ast_filestream *fs = NULL;
1114 int format_found = 0;
1116 AST_RWLIST_RDLOCK(&formats);
1118 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
1119 /* We really can't use O_APPEND as it will break WAV header updates */
1120 if (flags & O_APPEND) {
1126 myflags |= O_WRONLY | O_CREAT;
1128 /* XXX need to fix this - we should just do the fopen,
1129 * not open followed by fdopen()
1131 AST_RWLIST_TRAVERSE(&formats, f, list) {
1132 char *fn, *orig_fn = NULL;
1136 if (!exts_compare(f->exts, type))
1141 fn = build_filename(filename, type);
1145 fd = open(fn, flags | myflags, mode);
1147 /* fdopen() the resulting file stream */
1148 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1150 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1156 if (ast_opt_cache_record_files && (fd > -1)) {
1159 fclose(bfile); /* this also closes fd */
1161 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1162 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1164 orig_fn = ast_strdupa(fn);
1165 for (c = fn; *c; c++)
1169 size = strlen(fn) + strlen(record_cache_dir) + 2;
1170 buf = ast_alloca(size);
1171 strcpy(buf, record_cache_dir);
1176 fd = open(fn, flags | myflags, mode);
1178 /* fdopen() the resulting file stream */
1179 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1181 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1189 fs = get_filestream(f, bfile);
1191 if ((fs->write_buffer = ast_malloc(32768))) {
1192 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1195 if (!fs || rewrite_wrapper(fs, comment)) {
1196 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1203 ast_closestream(fs);
1216 fs->realfilename = ast_strdup(orig_fn);
1217 fs->filename = ast_strdup(fn);
1219 fs->realfilename = NULL;
1220 fs->filename = ast_strdup(filename);
1223 /* If truncated, we'll be at the beginning; if not truncated, then append */
1224 f->seek(fs, 0, SEEK_END);
1225 } else if (errno != EEXIST) {
1226 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1230 /* if buf != NULL then fn is already free and pointing to it */
1235 AST_RWLIST_UNLOCK(&formats);
1238 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1244 * \brief the core of all waitstream() functions
1246 static int waitstream_core(struct ast_channel *c,
1247 const char *breakon,
1248 const char *forward,
1249 const char *reverse,
1253 const char *context,
1254 ast_waitstream_fr_cb cb)
1256 const char *orig_chan_name = NULL;
1267 /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1268 ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1270 if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
1271 orig_chan_name = ast_strdupa(ast_channel_name(c));
1273 if (ast_channel_stream(c) && cb) {
1274 long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_rate(&ast_channel_stream(c)->fmt->format) / 1000);
1275 cb(c, ms_len, AST_WAITSTREAM_CB_START);
1278 while (ast_channel_stream(c)) {
1282 if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
1288 ms = ast_sched_wait(ast_channel_sched(c));
1290 if (ms < 0 && !ast_channel_timingfunc(c)) {
1297 res = ast_waitfor(c, ms);
1299 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1300 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1305 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1306 if (!rchan && (outfd < 0) && (ms)) {
1310 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1311 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1313 } else if (outfd > -1) { /* this requires cmdfd set */
1314 /* The FD we were watching has something waiting */
1315 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1318 /* if rchan is set, it is 'c' */
1319 res = rchan ? 1 : 0; /* map into 'res' values */
1322 struct ast_frame *fr = ast_read(c);
1324 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1327 switch (fr->frametype) {
1328 case AST_FRAME_DTMF_END:
1330 const char exten[2] = { fr->subclass.integer, '\0' };
1331 if (ast_exists_extension(c, context, exten, 1,
1332 S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
1333 res = fr->subclass.integer;
1335 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1339 enum ast_waitstream_fr_cb_values cb_val = 0;
1340 res = fr->subclass.integer;
1341 if (strchr(forward, res)) {
1343 ast_stream_fastforward(ast_channel_stream(c), skip_ms);
1344 eoftest = fgetc(ast_channel_stream(c)->f);
1345 if (feof(ast_channel_stream(c)->f)) {
1346 ast_stream_rewind(ast_channel_stream(c), skip_ms);
1348 ungetc(eoftest, ast_channel_stream(c)->f);
1350 cb_val = AST_WAITSTREAM_CB_FASTFORWARD;
1351 } else if (strchr(reverse, res)) {
1352 ast_stream_rewind(ast_channel_stream(c), skip_ms);
1353 cb_val = AST_WAITSTREAM_CB_REWIND;
1354 } else if (strchr(breakon, res)) {
1356 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1360 long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_rate(&ast_channel_stream(c)->fmt->format) / 1000);
1361 cb(c, ms_len, cb_val);
1365 case AST_FRAME_CONTROL:
1366 switch (fr->subclass.integer) {
1367 case AST_CONTROL_HANGUP:
1368 case AST_CONTROL_BUSY:
1369 case AST_CONTROL_CONGESTION:
1371 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1373 case AST_CONTROL_RINGING:
1374 case AST_CONTROL_ANSWER:
1375 case AST_CONTROL_VIDUPDATE:
1376 case AST_CONTROL_SRCUPDATE:
1377 case AST_CONTROL_SRCCHANGE:
1378 case AST_CONTROL_HOLD:
1379 case AST_CONTROL_UNHOLD:
1380 case AST_CONTROL_CONNECTED_LINE:
1381 case AST_CONTROL_REDIRECTING:
1382 case AST_CONTROL_AOC:
1383 case AST_CONTROL_UPDATE_RTP_PEER:
1384 case AST_CONTROL_PVT_CAUSE_CODE:
1389 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
1392 case AST_FRAME_VOICE:
1393 /* Write audio if appropriate */
1395 if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
1396 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
1400 /* Ignore all others */
1405 ast_sched_runq(ast_channel_sched(c));
1408 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1410 return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
1413 int ast_waitstream_fr_w_cb(struct ast_channel *c,
1414 const char *breakon,
1415 const char *forward,
1416 const char *reverse,
1418 ast_waitstream_fr_cb cb)
1420 return waitstream_core(c, breakon, forward, reverse, ms,
1421 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, cb);
1424 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1426 return waitstream_core(c, breakon, forward, reverse, ms,
1427 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, NULL /* no callback */);
1430 int ast_waitstream(struct ast_channel *c, const char *breakon)
1432 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL, NULL /* no callback */);
1435 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1437 return waitstream_core(c, breakon, NULL, NULL, 0,
1438 audiofd, cmdfd, NULL /* no context */, NULL /* no callback */);
1441 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1443 /* Waitstream, with return in the case of a valid 1 digit extension */
1444 /* in the current or specified context being pressed */
1447 context = ast_channel_context(c);
1448 return waitstream_core(c, NULL, NULL, NULL, 0,
1449 -1, -1, context, NULL /* no callback */);
1453 * if the file name is non-empty, try to play it.
1454 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1455 * If digits == "" then we can simply check for non-zero.
1457 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1460 if (!ast_strlen_zero(file)) {
1461 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", file, ast_channel_name(chan));
1462 res = ast_streamfile(chan, file, ast_channel_language(chan));
1464 res = ast_waitstream(chan, digits);
1470 char *ast_format_str_reduce(char *fmts)
1472 struct ast_format_def *f;
1473 struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
1474 char *fmts_str[AST_MAX_FORMATS];
1475 char *stringp, *type;
1477 int i, j, x, first, found = 0;
1478 int len = strlen(fmts) + 1;
1481 if (AST_RWLIST_RDLOCK(&formats)) {
1482 ast_log(LOG_WARNING, "Unable to lock format list\n");
1486 stringp = ast_strdupa(fmts);
1488 for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
1489 AST_RWLIST_TRAVERSE(&formats, f, list) {
1490 if (exts_compare(f->exts, type)) {
1503 AST_RWLIST_UNLOCK(&formats);
1506 for (i = 0; i < x; i++) {
1507 /* ignore invalid entries */
1509 ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
1513 /* special handling for the first entry */
1515 res = snprintf(fmts, len, "%s", fmts_str[i]);
1523 for (j = 0; j < i; j++) {
1524 /* this is a duplicate */
1525 if (fmts_ptr[j] == fmts_ptr[i]) {
1532 res = snprintf(fmts, len, "|%s", fmts_str[i]);
1539 ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
1546 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1548 #define FORMAT "%-10s %-10s %-20s\n"
1549 #define FORMAT2 "%-10s %-10s %-20s\n"
1550 struct ast_format_def *f;
1555 e->command = "core show file formats";
1557 "Usage: core show file formats\n"
1558 " Displays currently registered file formats (if any).\n";
1565 return CLI_SHOWUSAGE;
1567 ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1568 ast_cli(a->fd, FORMAT, "------", "----", "----------");
1570 AST_RWLIST_RDLOCK(&formats);
1571 AST_RWLIST_TRAVERSE(&formats, f, list) {
1572 ast_cli(a->fd, FORMAT2, ast_getformatname(&f->format), f->name, f->exts);
1575 AST_RWLIST_UNLOCK(&formats);
1576 ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1582 static struct ast_cli_entry cli_file[] = {
1583 AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1586 int ast_file_init(void)
1588 ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));