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$")
34 #include "asterisk/_private.h" /* declare ast_file_init() */
35 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
36 #include "asterisk/mod_format.h"
37 #include "asterisk/cli.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/sched.h"
40 #include "asterisk/translate.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/app.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/linkedlists.h"
46 #include "asterisk/module.h"
47 #include "asterisk/astobj2.h"
48 #include "asterisk/test.h"
51 * The following variable controls the layout of localized sound files.
52 * If 0, use the historical layout with prefix just before the filename
53 * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
54 * if 1 put the prefix at the beginning of the filename
55 * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
56 * The latter permits a language to be entirely in one directory.
58 * This is settable in asterisk.conf.
60 int ast_language_is_prefix = 1;
62 static AST_RWLIST_HEAD_STATIC(formats, ast_format);
64 int __ast_format_register(const struct ast_format *f, struct ast_module *mod)
66 struct ast_format *tmp;
68 AST_RWLIST_WRLOCK(&formats);
69 AST_RWLIST_TRAVERSE(&formats, tmp, list) {
70 if (!strcasecmp(f->name, tmp->name)) {
71 AST_RWLIST_UNLOCK(&formats);
72 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
76 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
77 AST_RWLIST_UNLOCK(&formats);
84 * Align buf_size properly, rounding up to the machine-specific
85 * alignment for pointers.
87 struct _test_align { void *a, *b; } p;
88 int align = (char *)&p.b - (char *)&p.a;
89 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
92 memset(&tmp->list, 0, sizeof(tmp->list));
94 AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
95 AST_RWLIST_UNLOCK(&formats);
96 ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
101 int ast_format_unregister(const char *name)
103 struct ast_format *tmp;
106 AST_RWLIST_WRLOCK(&formats);
107 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
108 if (!strcasecmp(name, tmp->name)) {
109 AST_RWLIST_REMOVE_CURRENT(list);
114 AST_RWLIST_TRAVERSE_SAFE_END;
115 AST_RWLIST_UNLOCK(&formats);
118 ast_verb(2, "Unregistered format %s\n", name);
120 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
125 int ast_stopstream(struct ast_channel *tmp)
127 ast_channel_lock(tmp);
129 /* Stop a running stream if there is one */
131 ast_closestream(tmp->stream);
133 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
134 ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(tmp->oldwriteformat));
136 /* Stop the video stream too */
137 if (tmp->vstream != NULL) {
138 ast_closestream(tmp->vstream);
142 ast_channel_unlock(tmp);
147 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
151 if (f->frametype == AST_FRAME_VIDEO) {
152 if (fs->fmt->format & AST_FORMAT_AUDIO_MASK) {
153 /* This is the audio portion. Call the video one... */
154 if (!fs->vfs && fs->filename) {
155 const char *type = ast_getformatname(f->subclass.codec & ~0x1);
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 /* Might / might not have mark set */
167 } else if (f->frametype != AST_FRAME_VOICE) {
168 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
171 if (((fs->fmt->format | alt) & f->subclass.codec) == f->subclass.codec) {
172 res = fs->fmt->write(fs, f);
174 ast_log(LOG_WARNING, "Natural write failed\n");
176 ast_log(LOG_WARNING, "Huh??\n");
178 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
179 the one we've setup a translator for, we do the "wrong thing" XXX */
180 if (fs->trans && f->subclass.codec != fs->lastwriteformat) {
181 ast_translator_free_path(fs->trans);
185 fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass.codec);
187 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
188 fs->fmt->name, ast_getformatname(f->subclass.codec));
190 struct ast_frame *trf;
191 fs->lastwriteformat = f->subclass.codec;
192 /* Get the translated frame but don't consume the original in case they're using it on another stream */
193 if ((trf = ast_translate(fs->trans, f, 0))) {
194 struct ast_frame *cur;
196 /* the translator may have returned multiple frames, so process them */
197 for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
198 if ((res = fs->fmt->write(fs, trf))) {
199 ast_log(LOG_WARNING, "Translated frame write failed\n");
212 static int copy(const char *infile, const char *outfile)
215 char buf[4096]; /* XXX make it lerger. */
217 if ((ifd = open(infile, O_RDONLY)) < 0) {
218 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
221 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
222 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
226 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
229 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
232 /* XXX handle partial writes */
233 res = write(ofd, buf, len);
235 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
236 len = -1; /* error marker */
244 return -1; /* error */
246 return 0; /* success */
250 * \brief construct a filename. Absolute pathnames are preserved,
251 * relative names are prefixed by the sounds/ directory.
252 * The wav49 suffix is replaced by 'WAV'.
253 * Returns a malloc'ed string to be freed by the caller.
255 static char *build_filename(const char *filename, const char *ext)
259 if (!strcmp(ext, "wav49"))
262 if (filename[0] == '/') {
263 if (asprintf(&fn, "%s.%s", filename, ext) < 0) {
264 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
268 if (asprintf(&fn, "%s/sounds/%s.%s",
269 ast_config_AST_DATA_DIR, filename, ext) < 0) {
270 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
277 /* compare type against the list 'exts' */
278 /* XXX need a better algorithm */
279 static int exts_compare(const char *exts, const char *type)
282 char *stringp = tmp, *ext;
284 ast_copy_string(tmp, exts, sizeof(tmp));
285 while ((ext = strsep(&stringp, "|"))) {
286 if (!strcmp(ext, type))
293 static void filestream_destructor(void *arg)
297 struct ast_filestream *f = arg;
299 /* Stop a running stream if there is one */
301 if (f->fmt->format < AST_FORMAT_AUDIO_MASK) {
302 f->owner->stream = NULL;
303 AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
304 ast_settimeout(f->owner, 0, NULL, NULL);
306 f->owner->vstream = NULL;
307 AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
310 /* destroy the translator on exit */
312 ast_translator_free_path(f->trans);
314 if (f->realfilename && f->filename) {
315 size = strlen(f->filename) + strlen(f->realfilename) + 15;
318 snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
319 ast_safe_system(cmd);
325 free(f->realfilename);
327 void (*closefn)(struct ast_filestream *) = f->fmt->close;
333 ast_closestream(f->vfs);
334 if (f->write_buffer) {
335 ast_free(f->write_buffer);
337 if (f->orig_chan_name)
338 free((void *) f->orig_chan_name);
339 ast_module_unref(f->fmt->module);
342 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
344 struct ast_filestream *s;
346 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
347 if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
353 s->_private = ((char *)(s + 1)) + fmt->buf_size;
355 s->buf = (char *)(s + 1);
356 s->fr.src = fmt->name;
361 * Default implementations of open and rewrite.
362 * Only use them if you don't have expensive stuff to do.
364 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
366 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
368 struct ast_format *f = s->fmt;
370 int (*openfn)(struct ast_filestream *s);
372 if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
373 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
374 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
375 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
377 /* preliminary checks succeed. update usecount */
378 ast_module_ref(f->module);
384 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
386 return fn_wrapper(s, comment, WRAP_REWRITE);
389 static int open_wrapper(struct ast_filestream *s)
391 return fn_wrapper(s, NULL, WRAP_OPEN);
395 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
396 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
397 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
399 ACTION_COPY /* copy file. return 0 on success, -1 on error */
403 * \brief perform various actions on a file. Second argument
404 * arg2 depends on the command:
405 * unused for EXISTS and DELETE
406 * destination file name (const char *) for COPY and RENAME
407 * struct ast_channel * for OPEN
408 * if fmt is NULL, OPEN will return the first matching entry,
409 * whereas other functions will run on all matching entries.
411 static format_t ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
413 struct ast_format *f;
414 format_t res = (action == ACTION_EXISTS) ? 0 : -1;
416 AST_RWLIST_RDLOCK(&formats);
417 /* Check for a specific format */
418 AST_RWLIST_TRAVERSE(&formats, f, list) {
419 char *stringp, *ext = NULL;
421 if (fmt && !exts_compare(f->exts, fmt))
424 /* Look for a file matching the supported extensions.
425 * The file must exist, and for OPEN, must match
426 * one of the formats supported by the channel.
428 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
429 while ( (ext = strsep(&stringp, "|")) ) {
431 char *fn = build_filename(filename, ext);
436 if ( stat(fn, &st) ) { /* file not existent */
440 /* for 'OPEN' we need to be sure that the format matches
441 * what the channel can process
443 if (action == ACTION_OPEN) {
444 struct ast_channel *chan = (struct ast_channel *)arg2;
446 struct ast_filestream *s;
448 if ( !(chan->writeformat & f->format) &&
449 !((f->format & AST_FORMAT_AUDIO_MASK && fmt) ||
450 (f->format & AST_FORMAT_VIDEO_MASK && fmt))) {
452 continue; /* not a supported format */
454 if ( (bfile = fopen(fn, "r")) == NULL) {
456 continue; /* cannot open file */
458 s = get_filestream(f, bfile);
461 ast_free(fn); /* cannot allocate descriptor */
464 if (open_wrapper(s)) {
467 continue; /* cannot run open on file */
469 if (st.st_size == 0) {
470 ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
472 /* ok this is good for OPEN */
478 if (s->fmt->format & AST_FORMAT_AUDIO_MASK) {
480 ast_closestream(chan->stream);
484 ast_closestream(chan->vstream);
492 break; /* will never get here */
494 case ACTION_EXISTS: /* return the matching format */
499 if ( (res = unlink(fn)) )
500 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
505 char *nfn = build_filename((const char *)arg2, ext);
507 ast_log(LOG_WARNING, "Out of memory\n");
509 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
511 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
512 action == ACTION_COPY ? "copy" : "rename",
513 fn, nfn, strerror(errno));
520 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
525 AST_RWLIST_UNLOCK(&formats);
529 static int is_absolute_path(const char *filename)
531 return filename[0] == '/';
534 static format_t fileexists_test(const char *filename, const char *fmt, const char *lang,
535 char *buf, int buflen)
541 if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
543 snprintf(buf, buflen, "%s/%s", lang, filename);
545 snprintf(buf, buflen, "%s", filename);
547 } else { /* old layout */
548 strcpy(buf, filename); /* first copy the full string */
550 /* insert the language and suffix if needed */
551 const char *c = strrchr(filename, '/');
552 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
553 snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
557 return ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
561 * \brief helper routine to locate a file with a given format
562 * and language preference.
563 * Try preflang, preflang with stripped '_' suffices, or NULL.
565 * The last parameter(s) point to a buffer of sufficient size,
566 * which on success is filled with the matching filename.
568 static format_t fileexists_core(const char *filename, const char *fmt, const char *preflang,
569 char *buf, int buflen)
578 /* We try languages in the following order:
579 * preflang (may include dialect and style codes)
580 * lang (preflang without dialect - if any)
582 * default (unless the same as preflang or lang without dialect)
585 lang = ast_strdupa(preflang);
587 /* Try preferred language, including removing any style or dialect codes */
588 while (!ast_strlen_zero(lang)) {
591 if ((res = fileexists_test(filename, fmt, lang, buf, buflen)) > 0) {
595 if ((end = strrchr(lang, '_')) != NULL) {
603 /* Try without any language */
604 if ((res = fileexists_test(filename, fmt, NULL, buf, buflen)) > 0) {
608 /* Finally try the default language unless it was already tried before */
609 if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
610 if ((res = fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen)) > 0) {
618 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
620 return ast_openstream_full(chan, filename, preflang, 0);
623 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
626 * Use fileexists_core() to find a file in a compatible
627 * language and format, set up a suitable translator,
628 * and open the stream.
635 /* do this first, otherwise we detect the wrong writeformat */
636 ast_stopstream(chan);
638 ast_deactivate_generator(chan);
640 if (preflang == NULL)
642 buflen = strlen(preflang) + strlen(filename) + 4;
643 buf = alloca(buflen);
646 fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
648 fmts &= AST_FORMAT_AUDIO_MASK;
650 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
653 chan->oldwriteformat = chan->writeformat;
654 /* Set the channel to a format we can work with */
655 res = ast_set_write_format(chan, fmts);
656 if (res == -1) { /* No format available that works with this channel */
659 res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
665 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
667 /* As above, but for video. But here we don't have translators
668 * so we must enforce a format.
674 if (preflang == NULL)
676 buflen = strlen(preflang) + strlen(filename) + 4;
677 buf = alloca(buflen);
681 for (format = AST_FORMAT_AUDIO_MASK + 1; format <= AST_FORMAT_VIDEO_MASK; format = format << 1) {
685 if (!(chan->nativeformats & format))
687 fmt = ast_getformatname(format);
688 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
690 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
692 return chan->vstream;
693 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
698 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
700 struct ast_frame *fr, *new_fr;
706 if (!(fr = s->fmt->read(s, whennext))) {
710 if (!(new_fr = ast_frisolate(fr))) {
723 struct ast_frame *ast_readframe(struct ast_filestream *s)
727 return read_frame(s, &whennext);
732 FSREAD_SUCCESS_SCHED,
733 FSREAD_SUCCESS_NOSCHED,
736 static int ast_fsread_audio(const void *data);
738 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
743 struct ast_frame *fr;
745 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name)) {
749 fr = read_frame(s, &whennext);
751 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
753 ast_log(LOG_WARNING, "Failed to write frame\n");
764 if (whennext != s->lasttimeout) {
765 if (s->owner->timingfd > -1) {
766 float samp_rate = (float) ast_format_rate(s->fmt->format);
769 rate = (unsigned int) roundf(samp_rate / ((float) whennext));
771 ast_settimeout(s->owner, rate, ast_fsread_audio, s);
773 s->owner->streamid = ast_sched_add(s->owner->sched,
774 whennext / (ast_format_rate(s->fmt->format) / 1000), ast_fsread_audio, s);
776 s->lasttimeout = whennext;
777 return FSREAD_SUCCESS_NOSCHED;
779 return FSREAD_SUCCESS_SCHED;
782 s->owner->streamid = -1;
783 ast_settimeout(s->owner, 0, NULL, NULL);
784 return FSREAD_FAILURE;
787 static int ast_fsread_audio(const void *data)
789 struct ast_filestream *fs = (struct ast_filestream *)data;
792 res = ast_readaudio_callback(fs);
794 if (res == FSREAD_SUCCESS_SCHED)
800 static int ast_fsread_video(const void *data);
802 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
807 struct ast_frame *fr = read_frame(s, &whennext);
809 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
811 ast_log(LOG_WARNING, "Failed to write frame\n");
814 s->owner->vstreamid = -1;
815 return FSREAD_FAILURE;
823 if (whennext != s->lasttimeout) {
824 s->owner->vstreamid = ast_sched_add(s->owner->sched,
825 whennext / (ast_format_rate(s->fmt->format) / 1000),
826 ast_fsread_video, s);
827 s->lasttimeout = whennext;
828 return FSREAD_SUCCESS_NOSCHED;
831 return FSREAD_SUCCESS_SCHED;
834 static int ast_fsread_video(const void *data)
836 struct ast_filestream *fs = (struct ast_filestream *)data;
839 res = ast_readvideo_callback(fs);
841 if (res == FSREAD_SUCCESS_SCHED)
847 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
853 int ast_playstream(struct ast_filestream *s)
857 if (s->fmt->format & AST_FORMAT_AUDIO_MASK)
858 res = ast_readaudio_callback(s);
860 res = ast_readvideo_callback(s);
862 return (res == FSREAD_FAILURE) ? -1 : 0;
865 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
867 return fs->fmt->seek(fs, sample_offset, whence);
870 int ast_truncstream(struct ast_filestream *fs)
872 return fs->fmt->trunc(fs);
875 off_t ast_tellstream(struct ast_filestream *fs)
877 return fs->fmt->tell(fs);
880 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
882 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
885 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
887 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
890 int ast_closestream(struct ast_filestream *f)
892 /* This used to destroy the filestream, but it now just decrements a refcount.
893 * We need to force the stream to quit queuing frames now, because we might
894 * change the writeformat, which could result in a subsequent write error, if
895 * the format is different. */
897 /* Stop a running stream if there is one */
899 if (f->fmt->format < AST_FORMAT_AUDIO_MASK) {
900 f->owner->stream = NULL;
901 AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
902 ast_settimeout(f->owner, 0, NULL, NULL);
904 f->owner->vstream = NULL;
905 AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
915 * Look the various language-specific places where a file could exist.
917 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
922 if (preflang == NULL)
924 buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
925 buf = alloca(buflen);
928 return fileexists_core(filename, fmt, preflang, buf, buflen);
931 int ast_filedelete(const char *filename, const char *fmt)
933 return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
936 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
938 return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
941 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
943 return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
946 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
948 struct ast_filestream *fs;
949 struct ast_filestream *vfs=NULL;
954 fs = ast_openstream(chan, filename, preflang);
956 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
960 /* check to see if there is any data present (not a zero length file),
961 * done this way because there is no where for ast_openstream_full to
962 * return the file had no data. */
963 seekattempt = fseek(fs->f, -1, SEEK_END);
965 ast_seekstream(fs, 0, SEEK_SET);
969 vfs = ast_openvstream(chan, filename, preflang);
971 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
974 if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
975 fs->orig_chan_name = ast_strdup(chan->name);
976 if (ast_applystream(chan, fs))
978 if (vfs && ast_applystream(chan, vfs))
980 res = ast_playstream(fs);
982 res = ast_playstream(vfs);
983 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", chan->name, filename, ast_getformatname(chan->writeformat), preflang ? preflang : "default");
988 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
991 struct ast_format *f;
992 struct ast_filestream *fs = NULL;
994 int format_found = 0;
996 AST_RWLIST_RDLOCK(&formats);
998 AST_RWLIST_TRAVERSE(&formats, f, list) {
1000 if (!exts_compare(f->exts, type))
1005 fn = build_filename(filename, type);
1007 bfile = fopen(fn, "r");
1009 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
1010 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
1012 ast_closestream(fs);
1024 fs->filename = ast_strdup(filename);
1029 AST_RWLIST_UNLOCK(&formats);
1031 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1036 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1038 int fd, myflags = 0;
1039 /* compiler claims this variable can be used before initialization... */
1041 struct ast_format *f;
1042 struct ast_filestream *fs = NULL;
1045 int format_found = 0;
1047 AST_RWLIST_RDLOCK(&formats);
1049 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
1050 /* We really can't use O_APPEND as it will break WAV header updates */
1051 if (flags & O_APPEND) {
1057 myflags |= O_WRONLY | O_CREAT;
1059 /* XXX need to fix this - we should just do the fopen,
1060 * not open followed by fdopen()
1062 AST_RWLIST_TRAVERSE(&formats, f, list) {
1063 char *fn, *orig_fn = NULL;
1067 if (!exts_compare(f->exts, type))
1072 fn = build_filename(filename, type);
1073 fd = open(fn, flags | myflags, mode);
1075 /* fdopen() the resulting file stream */
1076 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1078 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1084 if (ast_opt_cache_record_files && (fd > -1)) {
1087 fclose(bfile); /* this also closes fd */
1089 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1090 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1092 orig_fn = ast_strdupa(fn);
1093 for (c = fn; *c; c++)
1097 size = strlen(fn) + strlen(record_cache_dir) + 2;
1099 strcpy(buf, record_cache_dir);
1104 fd = open(fn, flags | myflags, mode);
1106 /* fdopen() the resulting file stream */
1107 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1109 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1117 fs = get_filestream(f, bfile);
1118 if (!fs || rewrite_wrapper(fs, comment)) {
1119 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1126 ast_closestream(fs);
1136 fs->realfilename = ast_strdup(orig_fn);
1137 fs->filename = ast_strdup(fn);
1139 fs->realfilename = NULL;
1140 fs->filename = ast_strdup(filename);
1143 /* If truncated, we'll be at the beginning; if not truncated, then append */
1145 if ((fs->write_buffer = ast_malloc(32768))){
1146 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1149 f->seek(fs, 0, SEEK_END);
1150 } else if (errno != EEXIST) {
1151 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1155 /* if buf != NULL then fn is already free and pointing to it */
1160 AST_RWLIST_UNLOCK(&formats);
1163 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1169 * \brief the core of all waitstream() functions
1171 static int waitstream_core(struct ast_channel *c, const char *breakon,
1172 const char *forward, const char *reverse, int skip_ms,
1173 int audiofd, int cmdfd, const char *context)
1175 const char *orig_chan_name = NULL;
1185 /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1186 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1188 if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1189 orig_chan_name = ast_strdupa(c->name);
1195 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1201 ms = ast_sched_wait(c->sched);
1203 if (ms < 0 && !c->timingfunc) {
1210 res = ast_waitfor(c, ms);
1212 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1213 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1218 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1219 if (!rchan && (outfd < 0) && (ms)) {
1223 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1224 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1226 } else if (outfd > -1) { /* this requires cmdfd set */
1227 /* The FD we were watching has something waiting */
1228 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1231 /* if rchan is set, it is 'c' */
1232 res = rchan ? 1 : 0; /* map into 'res' values */
1235 struct ast_frame *fr = ast_read(c);
1237 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1240 switch (fr->frametype) {
1241 case AST_FRAME_DTMF_END:
1243 const char exten[2] = { fr->subclass.integer, '\0' };
1244 if (ast_exists_extension(c, context, exten, 1,
1245 S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
1246 res = fr->subclass.integer;
1248 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1252 res = fr->subclass.integer;
1253 if (strchr(forward, res)) {
1255 ast_stream_fastforward(c->stream, skip_ms);
1256 eoftest = fgetc(c->stream->f);
1257 if (feof(c->stream->f)) {
1258 ast_stream_rewind(c->stream, skip_ms);
1260 ungetc(eoftest, c->stream->f);
1262 } else if (strchr(reverse, res)) {
1263 ast_stream_rewind(c->stream, skip_ms);
1264 } else if (strchr(breakon, res)) {
1266 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1271 case AST_FRAME_CONTROL:
1272 switch (fr->subclass.integer) {
1273 case AST_CONTROL_HANGUP:
1274 case AST_CONTROL_BUSY:
1275 case AST_CONTROL_CONGESTION:
1277 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1279 case AST_CONTROL_RINGING:
1280 case AST_CONTROL_ANSWER:
1281 case AST_CONTROL_VIDUPDATE:
1282 case AST_CONTROL_SRCUPDATE:
1283 case AST_CONTROL_SRCCHANGE:
1284 case AST_CONTROL_HOLD:
1285 case AST_CONTROL_UNHOLD:
1286 case AST_CONTROL_CONNECTED_LINE:
1287 case AST_CONTROL_REDIRECTING:
1288 case AST_CONTROL_AOC:
1293 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
1296 case AST_FRAME_VOICE:
1297 /* Write audio if appropriate */
1299 if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
1300 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
1304 /* Ignore all others */
1309 ast_sched_runq(c->sched);
1312 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1314 return (err || c->_softhangup) ? -1 : 0;
1317 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1319 return waitstream_core(c, breakon, forward, reverse, ms,
1320 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1323 int ast_waitstream(struct ast_channel *c, const char *breakon)
1325 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1328 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1330 return waitstream_core(c, breakon, NULL, NULL, 0,
1331 audiofd, cmdfd, NULL /* no context */);
1334 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1336 /* Waitstream, with return in the case of a valid 1 digit extension */
1337 /* in the current or specified context being pressed */
1340 context = c->context;
1341 return waitstream_core(c, NULL, NULL, NULL, 0,
1346 * if the file name is non-empty, try to play it.
1347 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1348 * If digits == "" then we can simply check for non-zero.
1350 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1353 if (!ast_strlen_zero(file)) {
1354 res = ast_streamfile(chan, file, chan->language);
1356 res = ast_waitstream(chan, digits);
1362 char *ast_format_str_reduce(char *fmts)
1364 struct ast_format *f;
1365 struct ast_format *fmts_ptr[AST_MAX_FORMATS];
1366 char *fmts_str[AST_MAX_FORMATS];
1367 char *stringp, *type;
1369 int i, j, x, first, found = 0;
1370 int len = strlen(fmts) + 1;
1373 if (AST_RWLIST_RDLOCK(&formats)) {
1374 ast_log(LOG_WARNING, "Unable to lock format list\n");
1378 stringp = ast_strdupa(fmts);
1380 for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
1381 AST_RWLIST_TRAVERSE(&formats, f, list) {
1382 if (exts_compare(f->exts, type)) {
1395 AST_RWLIST_UNLOCK(&formats);
1398 for (i = 0; i < x; i++) {
1399 /* ignore invalid entries */
1401 ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
1405 /* special handling for the first entry */
1407 res = snprintf(fmts, len, "%s", fmts_str[i]);
1415 for (j = 0; j < i; j++) {
1416 /* this is a duplicate */
1417 if (fmts_ptr[j] == fmts_ptr[i]) {
1424 res = snprintf(fmts, len, "|%s", fmts_str[i]);
1431 ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
1438 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1440 #define FORMAT "%-10s %-10s %-20s\n"
1441 #define FORMAT2 "%-10s %-10s %-20s\n"
1442 struct ast_format *f;
1447 e->command = "core show file formats";
1449 "Usage: core show file formats\n"
1450 " Displays currently registered file formats (if any).\n";
1457 return CLI_SHOWUSAGE;
1459 ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1460 ast_cli(a->fd, FORMAT, "------", "----", "----------");
1462 AST_RWLIST_RDLOCK(&formats);
1463 AST_RWLIST_TRAVERSE(&formats, f, list) {
1464 ast_cli(a->fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1467 AST_RWLIST_UNLOCK(&formats);
1468 ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1474 static struct ast_cli_entry cli_file[] = {
1475 AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1478 int ast_file_init(void)
1480 ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));