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>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35 #include "asterisk/_private.h" /* declare ast_file_init() */
36 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
37 #include "asterisk/mod_format.h"
38 #include "asterisk/cli.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/sched.h"
41 #include "asterisk/translate.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/app.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/linkedlists.h"
47 #include "asterisk/module.h"
48 #include "asterisk/astobj2.h"
49 #include "asterisk/test.h"
52 * The following variable controls the layout of localized sound files.
53 * If 0, use the historical layout with prefix just before the filename
54 * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
55 * if 1 put the prefix at the beginning of the filename
56 * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
57 * The latter permits a language to be entirely in one directory.
59 * This is settable in asterisk.conf.
61 int ast_language_is_prefix = 1;
63 static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
65 int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
67 struct ast_format_def *tmp;
69 AST_RWLIST_WRLOCK(&formats);
70 AST_RWLIST_TRAVERSE(&formats, tmp, list) {
71 if (!strcasecmp(f->name, tmp->name)) {
72 AST_RWLIST_UNLOCK(&formats);
73 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
77 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
78 AST_RWLIST_UNLOCK(&formats);
85 * Align buf_size properly, rounding up to the machine-specific
86 * alignment for pointers.
88 struct _test_align { void *a, *b; } p;
89 int align = (char *)&p.b - (char *)&p.a;
90 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
93 memset(&tmp->list, 0, sizeof(tmp->list));
95 AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
96 AST_RWLIST_UNLOCK(&formats);
97 ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
102 int ast_format_def_unregister(const char *name)
104 struct ast_format_def *tmp;
107 AST_RWLIST_WRLOCK(&formats);
108 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
109 if (!strcasecmp(name, tmp->name)) {
110 AST_RWLIST_REMOVE_CURRENT(list);
115 AST_RWLIST_TRAVERSE_SAFE_END;
116 AST_RWLIST_UNLOCK(&formats);
119 ast_verb(2, "Unregistered format %s\n", name);
121 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
126 int ast_stopstream(struct ast_channel *tmp)
128 ast_channel_lock(tmp);
130 /* Stop a running stream if there is one */
132 ast_closestream(tmp->stream);
134 if (tmp->oldwriteformat.id && ast_set_write_format(tmp, &tmp->oldwriteformat))
135 ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(&tmp->oldwriteformat));
137 /* Stop the video stream too */
138 if (tmp->vstream != NULL) {
139 ast_closestream(tmp->vstream);
143 ast_channel_unlock(tmp);
148 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
151 if (f->frametype == AST_FRAME_VIDEO) {
152 if (AST_FORMAT_GET_TYPE(fs->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
153 /* This is the audio portion. Call the video one... */
154 if (!fs->vfs && fs->filename) {
155 const char *type = ast_getformatname(&f->subclass.format);
156 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
157 ast_debug(1, "Opened video output file\n");
160 return ast_writestream(fs->vfs, f);
164 } else if (f->frametype != AST_FRAME_VOICE) {
165 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
168 if (ast_format_cmp(&f->subclass.format, &fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
169 res = fs->fmt->write(fs, f);
171 ast_log(LOG_WARNING, "Natural write failed\n");
173 ast_log(LOG_WARNING, "Huh??\n");
175 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
176 the one we've setup a translator for, we do the "wrong thing" XXX */
177 if (fs->trans && (ast_format_cmp(&f->subclass.format, &fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
178 ast_translator_free_path(fs->trans);
182 fs->trans = ast_translator_build_path(&fs->fmt->format, &f->subclass.format);
184 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
185 fs->fmt->name, ast_getformatname(&f->subclass.format));
187 struct ast_frame *trf;
188 ast_format_copy(&fs->lastwriteformat, &f->subclass.format);
189 /* Get the translated frame but don't consume the original in case they're using it on another stream */
190 if ((trf = ast_translate(fs->trans, f, 0))) {
191 struct ast_frame *cur;
193 /* the translator may have returned multiple frames, so process them */
194 for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
195 if ((res = fs->fmt->write(fs, trf))) {
196 ast_log(LOG_WARNING, "Translated frame write failed\n");
209 static int copy(const char *infile, const char *outfile)
212 char buf[4096]; /* XXX make it lerger. */
214 if ((ifd = open(infile, O_RDONLY)) < 0) {
215 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
218 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
219 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
223 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
226 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
229 /* XXX handle partial writes */
230 res = write(ofd, buf, len);
232 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
233 len = -1; /* error marker */
241 return -1; /* error */
243 return 0; /* success */
247 * \brief construct a filename. Absolute pathnames are preserved,
248 * relative names are prefixed by the sounds/ directory.
249 * The wav49 suffix is replaced by 'WAV'.
250 * Returns a malloc'ed string to be freed by the caller.
252 static char *build_filename(const char *filename, const char *ext)
256 if (!strcmp(ext, "wav49"))
259 if (filename[0] == '/') {
260 if (asprintf(&fn, "%s.%s", filename, ext) < 0) {
261 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
265 if (asprintf(&fn, "%s/sounds/%s.%s",
266 ast_config_AST_DATA_DIR, filename, ext) < 0) {
267 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
274 /* compare type against the list 'exts' */
275 /* XXX need a better algorithm */
276 static int exts_compare(const char *exts, const char *type)
279 char *stringp = tmp, *ext;
281 ast_copy_string(tmp, exts, sizeof(tmp));
282 while ((ext = strsep(&stringp, "|"))) {
283 if (!strcmp(ext, type))
290 static void filestream_destructor(void *arg)
292 struct ast_filestream *f = arg;
296 /* Stop a running stream if there is one */
298 if (AST_FORMAT_GET_TYPE(f->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
299 f->owner->stream = NULL;
300 AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
301 ast_settimeout(f->owner, 0, NULL, NULL);
303 f->owner->vstream = NULL;
304 AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
307 /* destroy the translator on exit */
309 ast_translator_free_path(f->trans);
311 if (f->realfilename && f->filename) {
312 pid = ast_safe_fork(0);
314 execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
318 /* Block the parent until the move is complete.*/
319 waitpid(pid, &status, 0);
326 free(f->realfilename);
328 void (*closefn)(struct ast_filestream *) = f->fmt->close;
334 ast_closestream(f->vfs);
335 if (f->write_buffer) {
336 ast_free(f->write_buffer);
338 if (f->orig_chan_name)
339 free((void *) f->orig_chan_name);
340 ast_module_unref(f->fmt->module);
343 static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
345 struct ast_filestream *s;
347 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
348 if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
354 s->_private = ((char *)(s + 1)) + fmt->buf_size;
356 s->buf = (char *)(s + 1);
357 s->fr.src = fmt->name;
362 * Default implementations of open and rewrite.
363 * Only use them if you don't have expensive stuff to do.
365 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
367 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
369 struct ast_format_def *f = s->fmt;
371 int (*openfn)(struct ast_filestream *s);
373 if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
374 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
375 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
376 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
378 /* preliminary checks succeed. update usecount */
379 ast_module_ref(f->module);
385 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
387 return fn_wrapper(s, comment, WRAP_REWRITE);
390 static int open_wrapper(struct ast_filestream *s)
392 return fn_wrapper(s, NULL, WRAP_OPEN);
396 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
397 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
398 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
400 ACTION_COPY /* copy file. return 0 on success, -1 on error */
405 * \brief perform various actions on a file. Second argument
406 * \note arg2 depends on the command:
408 * optional ast_format_cap holding all the formats found for a file, for EXISTS.
409 * destination file name (const char *) for COPY and RENAME
410 * struct ast_channel * for OPEN
411 * if fmt is NULL, OPEN will return the first matching entry,
412 * whereas other functions will run on all matching entries.
414 static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
416 struct ast_format_def *f;
417 int res = (action == ACTION_EXISTS) ? 0 : -1;
419 AST_RWLIST_RDLOCK(&formats);
420 /* Check for a specific format */
421 AST_RWLIST_TRAVERSE(&formats, f, list) {
422 char *stringp, *ext = NULL;
424 if (fmt && !exts_compare(f->exts, fmt))
427 /* Look for a file matching the supported extensions.
428 * The file must exist, and for OPEN, must match
429 * one of the formats supported by the channel.
431 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
432 while ( (ext = strsep(&stringp, "|")) ) {
434 char *fn = build_filename(filename, ext);
439 if ( stat(fn, &st) ) { /* file not existent */
443 /* for 'OPEN' we need to be sure that the format matches
444 * what the channel can process
446 if (action == ACTION_OPEN) {
447 struct ast_channel *chan = (struct ast_channel *)arg2;
449 struct ast_filestream *s;
451 if ((ast_format_cmp(&chan->writeformat, &f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
452 !(((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_AUDIO) && fmt) ||
453 ((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_VIDEO) && fmt))) {
455 continue; /* not a supported format */
457 if ( (bfile = fopen(fn, "r")) == NULL) {
459 continue; /* cannot open file */
461 s = get_filestream(f, bfile);
464 ast_free(fn); /* cannot allocate descriptor */
467 if (open_wrapper(s)) {
470 continue; /* cannot run open on file */
472 if (st.st_size == 0) {
473 ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
475 /* ok this is good for OPEN */
481 if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
483 ast_closestream(chan->stream);
487 ast_closestream(chan->vstream);
495 break; /* will never get here */
497 case ACTION_EXISTS: /* return the matching format */
498 /* if arg2 is present, it is a format capabilities structure.
499 * Add this format to the set of formats this file can be played in */
501 ast_format_cap_add((struct ast_format_cap *) arg2, &f->format);
503 res = 1; /* file does exist and format it exists in is returned in arg2 */
507 if ( (res = unlink(fn)) )
508 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
513 char *nfn = build_filename((const char *)arg2, ext);
515 ast_log(LOG_WARNING, "Out of memory\n");
517 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
519 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
520 action == ACTION_COPY ? "copy" : "rename",
521 fn, nfn, strerror(errno));
528 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
533 AST_RWLIST_UNLOCK(&formats);
537 static int is_absolute_path(const char *filename)
539 return filename[0] == '/';
543 * \brief test if a file exists for a given format.
544 * \note result_cap is OPTIONAL
545 * \retval 1, true and result_cap represents format capabilities file exists in.
548 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
549 char *buf, int buflen, struct ast_format_cap *result_cap)
555 if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
557 snprintf(buf, buflen, "%s/%s", lang, filename);
559 snprintf(buf, buflen, "%s", filename);
561 } else { /* old layout */
562 strcpy(buf, filename); /* first copy the full string */
564 /* insert the language and suffix if needed */
565 const char *c = strrchr(filename, '/');
566 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
567 snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
571 return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
575 * \brief helper routine to locate a file with a given format
576 * and language preference.
578 * \note Try preflang, preflang with stripped '_' suffices, or NULL.
580 * \note The last parameter(s) point to a buffer of sufficient size,
581 * which on success is filled with the matching filename.
583 * \param filename, name of the file.
584 * \param fmt, format to look for the file in. OPTIONAL
585 * \param preflang, the perfered language
586 * \param buf, returns the matching filename
587 * \param buflen, size of the buf
588 * \param result_cap, OPTIONAL format capabilities result structure
589 * returns what formats the file was found in.
591 * \retval 1, true. file exists and result format is set
592 * \retval 0, false. file does not exist.
594 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
595 char *buf, int buflen, struct ast_format_cap *result_cap)
603 /* We try languages in the following order:
604 * preflang (may include dialect and style codes)
605 * lang (preflang without dialect - if any)
607 * default (unless the same as preflang or lang without dialect)
610 lang = ast_strdupa(preflang);
612 /* Try preferred language, including removing any style or dialect codes */
613 while (!ast_strlen_zero(lang)) {
616 if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
620 if ((end = strrchr(lang, '_')) != NULL) {
628 /* Try without any language */
629 if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
633 /* Finally try the default language unless it was already tried before */
634 if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
635 if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
643 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
645 return ast_openstream_full(chan, filename, preflang, 0);
648 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
651 * Use fileexists_core() to find a file in a compatible
652 * language and format, set up a suitable translator,
653 * and open the stream.
655 struct ast_format_cap *file_fmt_cap;
661 /* do this first, otherwise we detect the wrong writeformat */
662 ast_stopstream(chan);
664 ast_deactivate_generator(chan);
666 if (preflang == NULL)
668 buflen = strlen(preflang) + strlen(filename) + 4;
669 buf = alloca(buflen);
673 if (!(file_fmt_cap = ast_format_cap_alloc_nolock())) {
676 if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
677 !ast_format_cap_has_type(file_fmt_cap, AST_FORMAT_TYPE_AUDIO)) {
679 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
680 file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
684 /* Set the channel to a format we can work with and save off the previous format. */
685 ast_format_copy(&chan->oldwriteformat, &chan->writeformat);
686 /* Set the channel to the best format that exists for the file. */
687 res = ast_set_write_format_from_cap(chan, file_fmt_cap);
688 /* don't need this anymore now that the channel's write format is set. */
689 file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
691 if (res == -1) { /* No format available that works with this channel */
694 res = filehelper(buf, chan, NULL, ACTION_OPEN);
700 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
702 /* As above, but for video. But here we don't have translators
703 * so we must enforce a format.
705 struct ast_format tmp_fmt;
706 struct ast_format_cap *tmp_cap;
712 if (preflang == NULL)
714 buflen = strlen(preflang) + strlen(filename) + 4;
715 buf = alloca(buflen);
719 /* is the channel capable of video without translation ?*/
720 if (!ast_format_cap_has_type(chan->nativeformats, AST_FORMAT_TYPE_VIDEO)) {
723 if (!(tmp_cap = ast_format_cap_alloc_nolock())) {
726 /* Video is supported, so see what video formats exist for this file */
727 if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
728 tmp_cap = ast_format_cap_destroy(tmp_cap);
732 /* iterate over file formats and pick the first one compatible with the channel's native formats */
733 ast_format_cap_iter_start(tmp_cap);
734 while (!ast_format_cap_iter_next(tmp_cap, &tmp_fmt)) {
735 fmt = ast_getformatname(&tmp_fmt);
736 if ((AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_VIDEO) ||
737 !ast_format_cap_iscompatible(chan->nativeformats, &tmp_fmt)) {
741 fd = filehelper(buf, chan, fmt, ACTION_OPEN);
743 ast_format_cap_iter_end(tmp_cap);
744 tmp_cap = ast_format_cap_destroy(tmp_cap);
745 return chan->vstream;
747 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
749 ast_format_cap_iter_end(tmp_cap);
750 tmp_cap = ast_format_cap_destroy(tmp_cap);
755 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
757 struct ast_frame *fr, *new_fr;
763 if (!(fr = s->fmt->read(s, whennext))) {
767 if (!(new_fr = ast_frisolate(fr))) {
780 struct ast_frame *ast_readframe(struct ast_filestream *s)
784 return read_frame(s, &whennext);
789 FSREAD_SUCCESS_SCHED,
790 FSREAD_SUCCESS_NOSCHED,
793 static int ast_fsread_audio(const void *data);
795 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
800 struct ast_frame *fr;
802 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name)) {
806 fr = read_frame(s, &whennext);
808 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
810 ast_log(LOG_WARNING, "Failed to write frame\n");
821 if (whennext != s->lasttimeout) {
822 if (s->owner->timingfd > -1) {
823 float samp_rate = (float) ast_format_rate(&s->fmt->format);
826 rate = (unsigned int) roundf(samp_rate / ((float) whennext));
828 ast_settimeout(s->owner, rate, ast_fsread_audio, s);
830 s->owner->streamid = ast_sched_add(s->owner->sched,
831 whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_audio, s);
833 s->lasttimeout = whennext;
834 return FSREAD_SUCCESS_NOSCHED;
836 return FSREAD_SUCCESS_SCHED;
839 s->owner->streamid = -1;
840 ast_settimeout(s->owner, 0, NULL, NULL);
841 return FSREAD_FAILURE;
844 static int ast_fsread_audio(const void *data)
846 struct ast_filestream *fs = (struct ast_filestream *)data;
849 res = ast_readaudio_callback(fs);
851 if (res == FSREAD_SUCCESS_SCHED)
857 static int ast_fsread_video(const void *data);
859 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
864 struct ast_frame *fr = read_frame(s, &whennext);
866 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
868 ast_log(LOG_WARNING, "Failed to write frame\n");
871 s->owner->vstreamid = -1;
872 return FSREAD_FAILURE;
880 if (whennext != s->lasttimeout) {
881 s->owner->vstreamid = ast_sched_add(s->owner->sched,
882 whennext / (ast_format_rate(&s->fmt->format) / 1000),
883 ast_fsread_video, s);
884 s->lasttimeout = whennext;
885 return FSREAD_SUCCESS_NOSCHED;
888 return FSREAD_SUCCESS_SCHED;
891 static int ast_fsread_video(const void *data)
893 struct ast_filestream *fs = (struct ast_filestream *)data;
896 res = ast_readvideo_callback(fs);
898 if (res == FSREAD_SUCCESS_SCHED)
904 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
910 int ast_playstream(struct ast_filestream *s)
914 if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO)
915 res = ast_readaudio_callback(s);
917 res = ast_readvideo_callback(s);
919 return (res == FSREAD_FAILURE) ? -1 : 0;
922 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
924 return fs->fmt->seek(fs, sample_offset, whence);
927 int ast_truncstream(struct ast_filestream *fs)
929 return fs->fmt->trunc(fs);
932 off_t ast_tellstream(struct ast_filestream *fs)
934 return fs->fmt->tell(fs);
937 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
939 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
942 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
944 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
947 int ast_closestream(struct ast_filestream *f)
949 /* This used to destroy the filestream, but it now just decrements a refcount.
950 * We need to force the stream to quit queuing frames now, because we might
951 * change the writeformat, which could result in a subsequent write error, if
952 * the format is different. */
954 /* Stop a running stream if there is one */
956 if (AST_FORMAT_GET_TYPE(f->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
957 f->owner->stream = NULL;
958 AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
959 ast_settimeout(f->owner, 0, NULL, NULL);
961 f->owner->vstream = NULL;
962 AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
972 * Look the various language-specific places where a file could exist.
974 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
979 if (preflang == NULL)
981 buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
982 buf = 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;
1011 fs = ast_openstream(chan, filename, preflang);
1013 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
1017 /* check to see if there is any data present (not a zero length file),
1018 * done this way because there is no where for ast_openstream_full to
1019 * return the file had no data. */
1020 seekattempt = fseek(fs->f, -1, SEEK_END);
1021 if (seekattempt && errno == EINVAL) {
1022 /* Zero-length file, as opposed to a pipe */
1025 ast_seekstream(fs, 0, SEEK_SET);
1028 vfs = ast_openvstream(chan, filename, preflang);
1030 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(&vfs->fmt->format));
1033 if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
1034 fs->orig_chan_name = ast_strdup(chan->name);
1035 if (ast_applystream(chan, fs))
1037 if (vfs && ast_applystream(chan, vfs))
1039 res = ast_playstream(fs);
1041 res = ast_playstream(vfs);
1042 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", chan->name, filename, ast_getformatname(&chan->writeformat), preflang ? preflang : "default");
1047 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1050 struct ast_format_def *f;
1051 struct ast_filestream *fs = NULL;
1053 int format_found = 0;
1055 AST_RWLIST_RDLOCK(&formats);
1057 AST_RWLIST_TRAVERSE(&formats, f, list) {
1059 if (!exts_compare(f->exts, type))
1064 fn = build_filename(filename, type);
1066 bfile = fopen(fn, "r");
1068 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
1069 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
1071 ast_closestream(fs);
1083 fs->filename = ast_strdup(filename);
1088 AST_RWLIST_UNLOCK(&formats);
1090 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1095 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1097 int fd, myflags = 0;
1098 /* compiler claims this variable can be used before initialization... */
1100 struct ast_format_def *f;
1101 struct ast_filestream *fs = NULL;
1104 int format_found = 0;
1106 AST_RWLIST_RDLOCK(&formats);
1108 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
1109 /* We really can't use O_APPEND as it will break WAV header updates */
1110 if (flags & O_APPEND) {
1116 myflags |= O_WRONLY | O_CREAT;
1118 /* XXX need to fix this - we should just do the fopen,
1119 * not open followed by fdopen()
1121 AST_RWLIST_TRAVERSE(&formats, f, list) {
1122 char *fn, *orig_fn = NULL;
1126 if (!exts_compare(f->exts, type))
1131 fn = build_filename(filename, type);
1132 fd = open(fn, flags | myflags, mode);
1134 /* fdopen() the resulting file stream */
1135 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1137 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1143 if (ast_opt_cache_record_files && (fd > -1)) {
1146 fclose(bfile); /* this also closes fd */
1148 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1149 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1151 orig_fn = ast_strdupa(fn);
1152 for (c = fn; *c; c++)
1156 size = strlen(fn) + strlen(record_cache_dir) + 2;
1158 strcpy(buf, record_cache_dir);
1163 fd = open(fn, flags | myflags, mode);
1165 /* fdopen() the resulting file stream */
1166 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1168 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1176 fs = get_filestream(f, bfile);
1178 if ((fs->write_buffer = ast_malloc(32768))) {
1179 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1182 if (!fs || rewrite_wrapper(fs, comment)) {
1183 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1190 ast_closestream(fs);
1200 fs->realfilename = ast_strdup(orig_fn);
1201 fs->filename = ast_strdup(fn);
1203 fs->realfilename = NULL;
1204 fs->filename = ast_strdup(filename);
1207 /* If truncated, we'll be at the beginning; if not truncated, then append */
1208 f->seek(fs, 0, SEEK_END);
1209 } else if (errno != EEXIST) {
1210 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1214 /* if buf != NULL then fn is already free and pointing to it */
1219 AST_RWLIST_UNLOCK(&formats);
1222 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1228 * \brief the core of all waitstream() functions
1230 static int waitstream_core(struct ast_channel *c, const char *breakon,
1231 const char *forward, const char *reverse, int skip_ms,
1232 int audiofd, int cmdfd, const char *context)
1234 const char *orig_chan_name = NULL;
1244 /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1245 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1247 if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1248 orig_chan_name = ast_strdupa(c->name);
1254 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1260 ms = ast_sched_wait(c->sched);
1262 if (ms < 0 && !c->timingfunc) {
1269 res = ast_waitfor(c, ms);
1271 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1272 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1277 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1278 if (!rchan && (outfd < 0) && (ms)) {
1282 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1283 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1285 } else if (outfd > -1) { /* this requires cmdfd set */
1286 /* The FD we were watching has something waiting */
1287 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1290 /* if rchan is set, it is 'c' */
1291 res = rchan ? 1 : 0; /* map into 'res' values */
1294 struct ast_frame *fr = ast_read(c);
1296 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1299 switch (fr->frametype) {
1300 case AST_FRAME_DTMF_END:
1302 const char exten[2] = { fr->subclass.integer, '\0' };
1303 if (ast_exists_extension(c, context, exten, 1,
1304 S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
1305 res = fr->subclass.integer;
1307 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1311 res = fr->subclass.integer;
1312 if (strchr(forward, res)) {
1314 ast_stream_fastforward(c->stream, skip_ms);
1315 eoftest = fgetc(c->stream->f);
1316 if (feof(c->stream->f)) {
1317 ast_stream_rewind(c->stream, skip_ms);
1319 ungetc(eoftest, c->stream->f);
1321 } else if (strchr(reverse, res)) {
1322 ast_stream_rewind(c->stream, skip_ms);
1323 } else if (strchr(breakon, res)) {
1325 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1330 case AST_FRAME_CONTROL:
1331 switch (fr->subclass.integer) {
1332 case AST_CONTROL_HANGUP:
1333 case AST_CONTROL_BUSY:
1334 case AST_CONTROL_CONGESTION:
1336 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1338 case AST_CONTROL_RINGING:
1339 case AST_CONTROL_ANSWER:
1340 case AST_CONTROL_VIDUPDATE:
1341 case AST_CONTROL_SRCUPDATE:
1342 case AST_CONTROL_SRCCHANGE:
1343 case AST_CONTROL_HOLD:
1344 case AST_CONTROL_UNHOLD:
1345 case AST_CONTROL_CONNECTED_LINE:
1346 case AST_CONTROL_REDIRECTING:
1347 case AST_CONTROL_AOC:
1348 case AST_CONTROL_UPDATE_RTP_PEER:
1353 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
1356 case AST_FRAME_VOICE:
1357 /* Write audio if appropriate */
1359 if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
1360 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
1364 /* Ignore all others */
1369 ast_sched_runq(c->sched);
1372 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1374 return (err || c->_softhangup) ? -1 : 0;
1377 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1379 return waitstream_core(c, breakon, forward, reverse, ms,
1380 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1383 int ast_waitstream(struct ast_channel *c, const char *breakon)
1385 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1388 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1390 return waitstream_core(c, breakon, NULL, NULL, 0,
1391 audiofd, cmdfd, NULL /* no context */);
1394 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1396 /* Waitstream, with return in the case of a valid 1 digit extension */
1397 /* in the current or specified context being pressed */
1400 context = c->context;
1401 return waitstream_core(c, NULL, NULL, NULL, 0,
1406 * if the file name is non-empty, try to play it.
1407 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1408 * If digits == "" then we can simply check for non-zero.
1410 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1413 if (!ast_strlen_zero(file)) {
1414 ast_test_suite_event_notify("PLAYBACK", "Message: %s", file);
1415 res = ast_streamfile(chan, file, chan->language);
1417 res = ast_waitstream(chan, digits);
1423 char *ast_format_str_reduce(char *fmts)
1425 struct ast_format_def *f;
1426 struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
1427 char *fmts_str[AST_MAX_FORMATS];
1428 char *stringp, *type;
1430 int i, j, x, first, found = 0;
1431 int len = strlen(fmts) + 1;
1434 if (AST_RWLIST_RDLOCK(&formats)) {
1435 ast_log(LOG_WARNING, "Unable to lock format list\n");
1439 stringp = ast_strdupa(fmts);
1441 for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
1442 AST_RWLIST_TRAVERSE(&formats, f, list) {
1443 if (exts_compare(f->exts, type)) {
1456 AST_RWLIST_UNLOCK(&formats);
1459 for (i = 0; i < x; i++) {
1460 /* ignore invalid entries */
1462 ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
1466 /* special handling for the first entry */
1468 res = snprintf(fmts, len, "%s", fmts_str[i]);
1476 for (j = 0; j < i; j++) {
1477 /* this is a duplicate */
1478 if (fmts_ptr[j] == fmts_ptr[i]) {
1485 res = snprintf(fmts, len, "|%s", fmts_str[i]);
1492 ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
1499 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1501 #define FORMAT "%-10s %-10s %-20s\n"
1502 #define FORMAT2 "%-10s %-10s %-20s\n"
1503 struct ast_format_def *f;
1508 e->command = "core show file formats";
1510 "Usage: core show file formats\n"
1511 " Displays currently registered file formats (if any).\n";
1518 return CLI_SHOWUSAGE;
1520 ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1521 ast_cli(a->fd, FORMAT, "------", "----", "----------");
1523 AST_RWLIST_RDLOCK(&formats);
1524 AST_RWLIST_TRAVERSE(&formats, f, list) {
1525 ast_cli(a->fd, FORMAT2, ast_getformatname(&f->format), f->name, f->exts);
1528 AST_RWLIST_UNLOCK(&formats);
1529 ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1535 static struct ast_cli_entry cli_file[] = {
1536 AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1539 int ast_file_init(void)
1541 ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));