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_REGISTER_FILE()
39 #include "asterisk/_private.h" /* declare ast_file_init() */
40 #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
41 #include "asterisk/mod_format.h"
42 #include "asterisk/cli.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/translate.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/app.h"
49 #include "asterisk/pbx.h"
50 #include "asterisk/linkedlists.h"
51 #include "asterisk/module.h"
52 #include "asterisk/astobj2.h"
53 #include "asterisk/test.h"
54 #include "asterisk/stasis.h"
55 #include "asterisk/json.h"
56 #include "asterisk/stasis_system.h"
59 * The following variable controls the layout of localized sound files.
60 * If 0, use the historical layout with prefix just before the filename
61 * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
62 * if 1 put the prefix at the beginning of the filename
63 * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
64 * The latter permits a language to be entirely in one directory.
66 * This is settable in asterisk.conf.
68 int ast_language_is_prefix = 1;
70 static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
72 STASIS_MESSAGE_TYPE_DEFN(ast_format_register_type);
73 STASIS_MESSAGE_TYPE_DEFN(ast_format_unregister_type);
75 static struct ast_json *json_array_from_list(const char *list, const char *sep)
77 RAII_VAR(struct ast_json *, array, ast_json_array_create(), ast_json_unref);
80 stringp = ast_strdupa(list); /* this is in the stack so does not need to be freed */
81 if (!array || !stringp) {
85 while ((ext = strsep(&stringp, sep))) {
86 if (ast_json_array_append(array, ast_json_string_create(ext))) {
91 return ast_json_ref(array);
94 static int publish_format_update(const struct ast_format_def *f, struct stasis_message_type *type)
96 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
97 RAII_VAR(struct ast_json_payload *, json_payload, NULL, ao2_cleanup);
98 RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
104 json_object = ast_json_pack("{s: s, s: o}",
106 "extensions", json_array_from_list(f->exts, "|"));
111 json_payload = ast_json_payload_create(json_object);
116 msg = stasis_message_create(type, json_payload);
121 stasis_publish(ast_system_topic(), msg);
125 int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
127 struct ast_format_def *tmp;
129 AST_RWLIST_WRLOCK(&formats);
130 AST_RWLIST_TRAVERSE(&formats, tmp, list) {
131 if (!strcasecmp(f->name, tmp->name)) {
132 AST_RWLIST_UNLOCK(&formats);
133 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
137 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
138 AST_RWLIST_UNLOCK(&formats);
145 * Align buf_size properly, rounding up to the machine-specific
146 * alignment for pointers.
148 struct _test_align { void *a, *b; } p;
149 int align = (char *)&p.b - (char *)&p.a;
150 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
153 memset(&tmp->list, 0, sizeof(tmp->list));
155 AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
156 AST_RWLIST_UNLOCK(&formats);
157 ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
158 publish_format_update(f, ast_format_register_type());
163 int ast_format_def_unregister(const char *name)
165 struct ast_format_def *tmp;
168 AST_RWLIST_WRLOCK(&formats);
169 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
170 if (!strcasecmp(name, tmp->name)) {
171 AST_RWLIST_REMOVE_CURRENT(list);
172 publish_format_update(tmp, ast_format_unregister_type());
177 AST_RWLIST_TRAVERSE_SAFE_END;
178 AST_RWLIST_UNLOCK(&formats);
181 ast_verb(2, "Unregistered format %s\n", name);
183 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
188 int ast_stopstream(struct ast_channel *tmp)
190 ast_channel_lock(tmp);
192 /* Stop a running stream if there is one */
193 if (ast_channel_stream(tmp)) {
194 ast_closestream(ast_channel_stream(tmp));
195 ast_channel_stream_set(tmp, NULL);
196 if (ast_channel_oldwriteformat(tmp) && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
197 ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_format_get_name(ast_channel_oldwriteformat(tmp)));
199 /* Stop the video stream too */
200 if (ast_channel_vstream(tmp) != NULL) {
201 ast_closestream(ast_channel_vstream(tmp));
202 ast_channel_vstream_set(tmp, NULL);
205 ast_channel_unlock(tmp);
210 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
213 if (f->frametype == AST_FRAME_VIDEO) {
214 if (ast_format_get_type(fs->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
215 /* This is the audio portion. Call the video one... */
216 if (!fs->vfs && fs->filename) {
217 const char *type = ast_format_get_name(f->subclass.format);
218 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
219 ast_debug(1, "Opened video output file\n");
222 return ast_writestream(fs->vfs, f);
226 } else if (f->frametype != AST_FRAME_VOICE) {
227 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
230 if (ast_format_cmp(f->subclass.format, fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
231 res = fs->fmt->write(fs, f);
233 ast_log(LOG_WARNING, "Natural write failed\n");
235 ast_log(LOG_WARNING, "Huh??\n");
237 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
238 the one we've setup a translator for, we do the "wrong thing" XXX */
239 if (fs->trans && (ast_format_cmp(f->subclass.format, fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
240 ast_translator_free_path(fs->trans);
244 fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass.format);
247 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
248 fs->fmt->name, ast_format_get_name(f->subclass.format));
250 struct ast_frame *trf;
251 ao2_replace(fs->lastwriteformat, f->subclass.format);
252 /* Get the translated frame but don't consume the original in case they're using it on another stream */
253 if ((trf = ast_translate(fs->trans, f, 0))) {
254 struct ast_frame *cur;
256 /* the translator may have returned multiple frames, so process them */
257 for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
258 if ((res = fs->fmt->write(fs, trf))) {
259 ast_log(LOG_WARNING, "Translated frame write failed\n");
272 static int copy(const char *infile, const char *outfile)
275 char buf[4096]; /* XXX make it lerger. */
277 if ((ifd = open(infile, O_RDONLY)) < 0) {
278 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
281 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
282 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
286 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
289 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
292 /* XXX handle partial writes */
293 res = write(ofd, buf, len);
295 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
296 len = -1; /* error marker */
304 return -1; /* error */
306 return 0; /* success */
310 * \brief construct a filename. Absolute pathnames are preserved,
311 * relative names are prefixed by the sounds/ directory.
312 * The wav49 suffix is replaced by 'WAV'.
313 * Returns a malloc'ed string to be freed by the caller.
315 static char *build_filename(const char *filename, const char *ext)
319 if (!strcmp(ext, "wav49"))
322 if (filename[0] == '/') {
323 if (ast_asprintf(&fn, "%s.%s", filename, ext) < 0) {
327 if (ast_asprintf(&fn, "%s/sounds/%s.%s",
328 ast_config_AST_DATA_DIR, filename, ext) < 0) {
335 /* compare type against the list 'exts' */
336 /* XXX need a better algorithm */
337 static int exts_compare(const char *exts, const char *type)
340 char *stringp = tmp, *ext;
342 ast_copy_string(tmp, exts, sizeof(tmp));
343 while ((ext = strsep(&stringp, "|"))) {
344 if (!strcmp(ext, type))
353 * \brief Close the file stream by canceling any pending read / write callbacks
355 static void filestream_close(struct ast_filestream *f)
357 enum ast_media_type format_type = ast_format_get_type(f->fmt->format);
363 /* Stop a running stream if there is one */
366 case AST_MEDIA_TYPE_AUDIO:
367 ast_channel_stream_set(f->owner, NULL);
368 AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
369 ast_settimeout(f->owner, 0, NULL, NULL);
371 case AST_MEDIA_TYPE_VIDEO:
372 ast_channel_vstream_set(f->owner, NULL);
373 AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
376 ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
381 static void filestream_destructor(void *arg)
383 struct ast_filestream *f = arg;
387 /* Stop a running stream if there is one */
390 /* destroy the translator on exit */
392 ast_translator_free_path(f->trans);
395 void (*closefn)(struct ast_filestream *) = f->fmt->close;
403 if (f->realfilename && f->filename) {
404 pid = ast_safe_fork(0);
406 execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
410 /* Block the parent until the move is complete.*/
411 waitpid(pid, &status, 0);
415 ast_free(f->filename);
416 ast_free(f->realfilename);
418 ast_closestream(f->vfs);
419 ast_free(f->write_buffer);
420 ast_free((void *)f->orig_chan_name);
421 ao2_cleanup(f->lastwriteformat);
422 ao2_cleanup(f->fr.subclass.format);
423 ast_module_unref(f->fmt->module);
426 static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
428 struct ast_filestream *s;
430 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
431 if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
433 ast_module_ref(fmt->module);
438 s->_private = ((char *)(s + 1)) + fmt->buf_size;
440 s->buf = (char *)(s + 1);
441 s->fr.src = fmt->name;
443 if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_AUDIO) {
444 s->fr.frametype = AST_FRAME_VOICE;
445 } else if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_VIDEO) {
446 s->fr.frametype = AST_FRAME_VIDEO;
449 s->fr.subclass.format = ao2_bump(fmt->format);
455 * Default implementations of open and rewrite.
456 * Only use them if you don't have expensive stuff to do.
458 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
460 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
462 struct ast_format_def *f = s->fmt;
464 int (*openfn)(struct ast_filestream *s);
466 if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
467 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
468 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
469 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
471 /* preliminary checks succeed. */
477 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
479 return fn_wrapper(s, comment, WRAP_REWRITE);
482 static int open_wrapper(struct ast_filestream *s)
484 return fn_wrapper(s, NULL, WRAP_OPEN);
488 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
489 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
490 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
492 ACTION_COPY /* copy file. return 0 on success, -1 on error */
497 * \brief perform various actions on a file. Second argument
498 * \note arg2 depends on the command:
500 * optional ast_format_cap holding all the formats found for a file, for EXISTS.
501 * destination file name (const char *) for COPY and RENAME
502 * struct ast_channel * for OPEN
503 * if fmt is NULL, OPEN will return the first matching entry,
504 * whereas other functions will run on all matching entries.
506 static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
508 struct ast_format_def *f;
509 int res = (action == ACTION_EXISTS) ? 0 : -1;
511 AST_RWLIST_RDLOCK(&formats);
512 /* Check for a specific format */
513 AST_RWLIST_TRAVERSE(&formats, f, list) {
514 char *stringp, *ext = NULL;
516 if (fmt && !exts_compare(f->exts, fmt))
519 /* Look for a file matching the supported extensions.
520 * The file must exist, and for OPEN, must match
521 * one of the formats supported by the channel.
523 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
524 while ( (ext = strsep(&stringp, "|")) ) {
526 char *fn = build_filename(filename, ext);
531 if ( stat(fn, &st) ) { /* file not existent */
535 /* for 'OPEN' we need to be sure that the format matches
536 * what the channel can process
538 if (action == ACTION_OPEN) {
539 struct ast_channel *chan = (struct ast_channel *)arg2;
541 struct ast_filestream *s;
543 if ((ast_format_cmp(ast_channel_writeformat(chan), f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
544 !(((ast_format_get_type(f->format) == AST_MEDIA_TYPE_AUDIO) && fmt) ||
545 ((ast_format_get_type(f->format) == AST_MEDIA_TYPE_VIDEO) && fmt))) {
547 continue; /* not a supported format */
549 if ( (bfile = fopen(fn, "r")) == NULL) {
551 continue; /* cannot open file */
553 s = get_filestream(f, bfile);
556 ast_free(fn); /* cannot allocate descriptor */
559 if (open_wrapper(s)) {
562 continue; /* cannot run open on file */
564 if (st.st_size == 0) {
565 ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
567 /* ok this is good for OPEN */
573 if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
574 if (ast_channel_stream(chan))
575 ast_closestream(ast_channel_stream(chan));
576 ast_channel_stream_set(chan, s);
578 if (ast_channel_vstream(chan))
579 ast_closestream(ast_channel_vstream(chan));
580 ast_channel_vstream_set(chan, s);
587 break; /* will never get here */
589 case ACTION_EXISTS: /* return the matching format */
590 /* if arg2 is present, it is a format capabilities structure.
591 * Add this format to the set of formats this file can be played in */
593 ast_format_cap_append((struct ast_format_cap *) arg2, f->format, 0);
595 res = 1; /* file does exist and format it exists in is returned in arg2 */
599 if ( (res = unlink(fn)) )
600 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
605 char *nfn = build_filename((const char *)arg2, ext);
607 ast_log(LOG_WARNING, "Out of memory\n");
609 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
611 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
612 action == ACTION_COPY ? "copy" : "rename",
613 fn, nfn, strerror(errno));
620 ast_log(LOG_WARNING, "Unknown helper %u\n", action);
625 AST_RWLIST_UNLOCK(&formats);
629 static int is_absolute_path(const char *filename)
631 return filename[0] == '/';
635 * \brief test if a file exists for a given format.
636 * \note result_cap is OPTIONAL
637 * \retval 1, true and result_cap represents format capabilities file exists in.
640 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
641 char *buf, int buflen, struct ast_format_cap *result_cap)
647 if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
649 snprintf(buf, buflen, "%s/%s", lang, filename);
651 snprintf(buf, buflen, "%s", filename);
653 } else { /* old layout */
654 strcpy(buf, filename); /* first copy the full string */
656 /* insert the language and suffix if needed */
657 const char *c = strrchr(filename, '/');
658 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
659 snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
663 return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
667 * \brief helper routine to locate a file with a given format
668 * and language preference.
670 * \note Try preflang, preflang with stripped '_' suffices, or NULL.
672 * \note The last parameter(s) point to a buffer of sufficient size,
673 * which on success is filled with the matching filename.
675 * \param filename Name of the file.
676 * \param fmt Format to look for the file in. OPTIONAL
677 * \param preflang The perfered language
678 * \param buf Returns the matching filename
679 * \param buflen Size of the buf
680 * \param result_cap OPTIONAL format capabilities result structure
681 * returns what formats the file was found in.
683 * \retval 1, true. file exists and result format is set
684 * \retval 0, false. file does not exist.
686 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
687 char *buf, int buflen, struct ast_format_cap *result_cap)
695 /* We try languages in the following order:
696 * preflang (may include dialect and style codes)
697 * lang (preflang without dialect - if any)
699 * default (unless the same as preflang or lang without dialect)
702 lang = ast_strdupa(preflang);
704 /* Try preferred language, including removing any style or dialect codes */
705 while (!ast_strlen_zero(lang)) {
708 if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
712 if ((end = strrchr(lang, '_')) != NULL) {
720 /* Try without any language */
721 if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
725 /* Finally try the default language unless it was already tried before */
726 if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
727 if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
735 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
737 return ast_openstream_full(chan, filename, preflang, 0);
740 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
743 * Use fileexists_core() to find a file in a compatible
744 * language and format, set up a suitable translator,
745 * and open the stream.
747 struct ast_format_cap *file_fmt_cap;
753 /* do this first, otherwise we detect the wrong writeformat */
754 ast_stopstream(chan);
755 if (ast_channel_generator(chan))
756 ast_deactivate_generator(chan);
758 if (preflang == NULL)
760 buflen = strlen(preflang) + strlen(filename) + 4;
761 buf = ast_alloca(buflen);
763 if (!(file_fmt_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
766 if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
767 !ast_format_cap_has_type(file_fmt_cap, AST_MEDIA_TYPE_AUDIO)) {
769 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
770 ao2_ref(file_fmt_cap, -1);
774 /* Set the channel to a format we can work with and save off the previous format. */
775 ast_channel_lock(chan);
776 ast_channel_set_oldwriteformat(chan, ast_channel_writeformat(chan));
777 /* Set the channel to the best format that exists for the file. */
778 res = ast_set_write_format_from_cap(chan, file_fmt_cap);
779 ast_channel_unlock(chan);
780 /* don't need this anymore now that the channel's write format is set. */
781 ao2_ref(file_fmt_cap, -1);
783 if (res == -1) { /* No format available that works with this channel */
786 res = filehelper(buf, chan, NULL, ACTION_OPEN);
788 return ast_channel_stream(chan);
792 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
794 /* As above, but for video. But here we don't have translators
795 * so we must enforce a format.
797 struct ast_format_cap *tmp_cap;
802 if (preflang == NULL) {
805 buflen = strlen(preflang) + strlen(filename) + 4;
806 buf = ast_alloca(buflen);
808 /* is the channel capable of video without translation ?*/
809 if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_VIDEO)) {
812 if (!(tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
815 /* Video is supported, so see what video formats exist for this file */
816 if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
817 ao2_ref(tmp_cap, -1);
821 /* iterate over file formats and pick the first one compatible with the channel's native formats */
822 for (i = 0; i < ast_format_cap_count(tmp_cap); ++i) {
823 struct ast_format *format = ast_format_cap_get_format(tmp_cap, i);
825 if ((ast_format_get_type(format) != AST_MEDIA_TYPE_VIDEO) ||
826 !ast_format_cap_iscompatible(ast_channel_nativeformats(chan), tmp_cap)) {
831 fd = filehelper(buf, chan, ast_format_get_name(format), ACTION_OPEN);
834 ao2_ref(tmp_cap, -1);
835 return ast_channel_vstream(chan);
837 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
840 ao2_ref(tmp_cap, -1);
845 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
847 struct ast_frame *fr, *new_fr;
853 if (!(fr = s->fmt->read(s, whennext))) {
857 if (!(new_fr = ast_frisolate(fr))) {
870 struct ast_frame *ast_readframe(struct ast_filestream *s)
874 return read_frame(s, &whennext);
879 FSREAD_SUCCESS_SCHED,
880 FSREAD_SUCCESS_NOSCHED,
883 static int ast_fsread_audio(const void *data);
885 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
890 struct ast_frame *fr;
892 if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
896 fr = read_frame(s, &whennext);
898 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
900 ast_debug(2, "Failed to write frame\n");
911 if (whennext != s->lasttimeout) {
912 if (ast_channel_timingfd(s->owner) > -1) {
913 float samp_rate = (float) ast_format_get_sample_rate(s->fmt->format);
916 rate = (unsigned int) roundf(samp_rate / ((float) whennext));
918 ast_settimeout_full(s->owner, rate, ast_fsread_audio, s, 1);
920 ast_channel_streamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_get_sample_rate(s->fmt->format) / 1000), ast_fsread_audio, s));
922 s->lasttimeout = whennext;
923 return FSREAD_SUCCESS_NOSCHED;
925 return FSREAD_SUCCESS_SCHED;
928 ast_channel_streamid_set(s->owner, -1);
929 ast_settimeout(s->owner, 0, NULL, NULL);
930 return FSREAD_FAILURE;
933 static int ast_fsread_audio(const void *data)
935 struct ast_filestream *fs = (struct ast_filestream *)data;
938 res = ast_readaudio_callback(fs);
940 if (res == FSREAD_SUCCESS_SCHED)
946 static int ast_fsread_video(const void *data);
948 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
953 struct ast_frame *fr = read_frame(s, &whennext);
955 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
957 ast_debug(2, "Failed to write frame\n");
960 ast_channel_vstreamid_set(s->owner, -1);
961 return FSREAD_FAILURE;
969 if (whennext != s->lasttimeout) {
970 ast_channel_vstreamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_get_sample_rate(s->fmt->format) / 1000), ast_fsread_video, s));
971 s->lasttimeout = whennext;
972 return FSREAD_SUCCESS_NOSCHED;
975 return FSREAD_SUCCESS_SCHED;
978 static int ast_fsread_video(const void *data)
980 struct ast_filestream *fs = (struct ast_filestream *)data;
983 res = ast_readvideo_callback(fs);
985 if (res == FSREAD_SUCCESS_SCHED)
991 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
997 int ast_playstream(struct ast_filestream *s)
1001 if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO)
1002 res = ast_readaudio_callback(s);
1004 res = ast_readvideo_callback(s);
1006 return (res == FSREAD_FAILURE) ? -1 : 0;
1009 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
1011 return fs->fmt->seek(fs, sample_offset, whence);
1014 int ast_truncstream(struct ast_filestream *fs)
1016 return fs->fmt->trunc(fs);
1019 off_t ast_tellstream(struct ast_filestream *fs)
1021 return fs->fmt->tell(fs);
1024 int ast_ratestream(struct ast_filestream *fs)
1026 return ast_format_get_sample_rate(fs->fmt->format);
1029 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
1031 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
1034 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
1036 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
1039 int ast_closestream(struct ast_filestream *f)
1041 /* This used to destroy the filestream, but it now just decrements a refcount.
1042 * We close the stream in order to quit queuing frames now, because we might
1043 * change the writeformat, which could result in a subsequent write error, if
1044 * the format is different. */
1048 filestream_close(f);
1055 * Look the various language-specific places where a file could exist.
1057 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
1062 if (preflang == NULL)
1064 buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
1065 buf = ast_alloca(buflen);
1066 return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
1069 int ast_filedelete(const char *filename, const char *fmt)
1071 return filehelper(filename, NULL, fmt, ACTION_DELETE);
1074 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
1076 return filehelper(filename, filename2, fmt, ACTION_RENAME);
1079 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
1081 return filehelper(filename, filename2, fmt, ACTION_COPY);
1084 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
1086 struct ast_filestream *fs;
1087 struct ast_filestream *vfs=NULL;
1092 fs = ast_openstream(chan, filename, preflang);
1094 struct ast_str *codec_buf = ast_str_alloca(64);
1095 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n",
1096 filename, ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf), strerror(errno));
1100 /* check to see if there is any data present (not a zero length file),
1101 * done this way because there is no where for ast_openstream_full to
1102 * return the file had no data. */
1103 pos = ftello(fs->f);
1104 seekattempt = fseeko(fs->f, -1, SEEK_END);
1106 if (errno == EINVAL) {
1107 /* Zero-length file, as opposed to a pipe */
1110 ast_seekstream(fs, 0, SEEK_SET);
1113 fseeko(fs->f, pos, SEEK_SET);
1116 vfs = ast_openvstream(chan, filename, preflang);
1118 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_format_get_name(vfs->fmt->format));
1121 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
1122 fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
1123 if (ast_applystream(chan, fs))
1125 if (vfs && ast_applystream(chan, vfs))
1127 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", filename, ast_channel_name(chan));
1128 res = ast_playstream(fs);
1130 res = ast_playstream(vfs);
1131 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", ast_channel_name(chan), filename, ast_format_get_name(ast_channel_writeformat(chan)), preflang ? preflang : "default");
1136 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1139 struct ast_format_def *f;
1140 struct ast_filestream *fs = NULL;
1142 int format_found = 0;
1144 AST_RWLIST_RDLOCK(&formats);
1146 AST_RWLIST_TRAVERSE(&formats, f, list) {
1148 if (!exts_compare(f->exts, type))
1153 fn = build_filename(filename, type);
1158 bfile = fopen(fn, "r");
1160 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
1161 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
1163 ast_closestream(fs);
1175 fs->filename = ast_strdup(filename);
1181 AST_RWLIST_UNLOCK(&formats);
1183 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1188 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
1190 int fd, myflags = 0;
1191 /* compiler claims this variable can be used before initialization... */
1193 struct ast_format_def *f;
1194 struct ast_filestream *fs = NULL;
1197 int format_found = 0;
1199 AST_RWLIST_RDLOCK(&formats);
1201 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
1202 /* We really can't use O_APPEND as it will break WAV header updates */
1203 if (flags & O_APPEND) {
1209 myflags |= O_WRONLY | O_CREAT;
1211 /* XXX need to fix this - we should just do the fopen,
1212 * not open followed by fdopen()
1214 AST_RWLIST_TRAVERSE(&formats, f, list) {
1215 char *fn, *orig_fn = NULL;
1219 if (!exts_compare(f->exts, type))
1224 fn = build_filename(filename, type);
1228 fd = open(fn, flags | myflags, mode);
1230 /* fdopen() the resulting file stream */
1231 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1233 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1239 if (ast_opt_cache_record_files && (fd > -1)) {
1242 fclose(bfile); /* this also closes fd */
1244 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1245 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1247 orig_fn = ast_strdupa(fn);
1248 for (c = fn; *c; c++)
1252 size = strlen(fn) + strlen(record_cache_dir) + 2;
1253 buf = ast_alloca(size);
1254 strcpy(buf, record_cache_dir);
1259 fd = open(fn, flags | myflags, mode);
1261 /* fdopen() the resulting file stream */
1262 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1264 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1272 fs = get_filestream(f, bfile);
1274 if ((fs->write_buffer = ast_malloc(32768))) {
1275 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1278 if (!fs || rewrite_wrapper(fs, comment)) {
1279 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1286 ast_closestream(fs);
1299 fs->realfilename = ast_strdup(orig_fn);
1300 fs->filename = ast_strdup(fn);
1302 fs->realfilename = NULL;
1303 fs->filename = ast_strdup(filename);
1306 /* If truncated, we'll be at the beginning; if not truncated, then append */
1307 f->seek(fs, 0, SEEK_END);
1308 } else if (errno != EEXIST) {
1309 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1313 /* if buf != NULL then fn is already free and pointing to it */
1318 AST_RWLIST_UNLOCK(&formats);
1321 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1326 static void waitstream_control(struct ast_channel *c,
1327 enum ast_waitstream_fr_cb_values type,
1328 ast_waitstream_fr_cb cb,
1333 case AST_WAITSTREAM_CB_FASTFORWARD:
1336 ast_stream_fastforward(ast_channel_stream(c), skip_ms);
1337 eoftest = fgetc(ast_channel_stream(c)->f);
1338 if (feof(ast_channel_stream(c)->f)) {
1339 ast_stream_rewind(ast_channel_stream(c), skip_ms);
1341 ungetc(eoftest, ast_channel_stream(c)->f);
1345 case AST_WAITSTREAM_CB_REWIND:
1346 ast_stream_rewind(ast_channel_stream(c), skip_ms);
1353 long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_get_sample_rate(ast_channel_stream(c)->fmt->format) / 1000);
1354 cb(c, ms_len, type);
1357 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1360 ast_channel_name(c),
1361 (type == AST_WAITSTREAM_CB_FASTFORWARD) ? "FastForward" : "Rewind",
1366 * \brief the core of all waitstream() functions
1368 static int waitstream_core(struct ast_channel *c,
1369 const char *breakon,
1370 const char *forward,
1371 const char *reverse,
1375 const char *context,
1376 ast_waitstream_fr_cb cb)
1378 const char *orig_chan_name = NULL;
1389 /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1390 ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1392 if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
1393 orig_chan_name = ast_strdupa(ast_channel_name(c));
1395 if (ast_channel_stream(c) && cb) {
1396 long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_get_sample_rate(ast_channel_stream(c)->fmt->format) / 1000);
1397 cb(c, ms_len, AST_WAITSTREAM_CB_START);
1400 while (ast_channel_stream(c)) {
1404 if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
1410 ms = ast_sched_wait(ast_channel_sched(c));
1412 if (ms < 0 && !ast_channel_timingfunc(c)) {
1419 res = ast_waitfor(c, ms);
1421 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1422 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1427 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1428 if (!rchan && (outfd < 0) && (ms)) {
1432 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1433 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1435 } else if (outfd > -1) { /* this requires cmdfd set */
1436 /* The FD we were watching has something waiting */
1437 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1440 /* if rchan is set, it is 'c' */
1441 res = rchan ? 1 : 0; /* map into 'res' values */
1444 struct ast_frame *fr = ast_read(c);
1446 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1449 switch (fr->frametype) {
1450 case AST_FRAME_DTMF_END:
1452 const char exten[2] = { fr->subclass.integer, '\0' };
1453 if (ast_exists_extension(c, context, exten, 1,
1454 S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
1455 res = fr->subclass.integer;
1457 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1461 res = fr->subclass.integer;
1462 if (strchr(forward, res)) {
1463 waitstream_control(c, AST_WAITSTREAM_CB_FASTFORWARD, cb, skip_ms);
1464 } else if (strchr(reverse, res)) {
1465 waitstream_control(c, AST_WAITSTREAM_CB_REWIND, cb, skip_ms);
1466 } else if (strchr(breakon, res)) {
1467 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1469 ast_channel_name(c),
1473 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1478 case AST_FRAME_CONTROL:
1479 switch (fr->subclass.integer) {
1480 case AST_CONTROL_STREAM_STOP:
1481 case AST_CONTROL_STREAM_SUSPEND:
1482 case AST_CONTROL_STREAM_RESTART:
1483 /* Fall-through and break out */
1484 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1486 ast_channel_name(c),
1488 res = fr->subclass.integer;
1490 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1492 case AST_CONTROL_STREAM_REVERSE:
1496 waitstream_control(c, AST_WAITSTREAM_CB_REWIND, cb, skip_ms);
1498 case AST_CONTROL_STREAM_FORWARD:
1502 waitstream_control(c, AST_WAITSTREAM_CB_FASTFORWARD, cb, skip_ms);
1504 case AST_CONTROL_HANGUP:
1505 case AST_CONTROL_BUSY:
1506 case AST_CONTROL_CONGESTION:
1508 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1510 case AST_CONTROL_RINGING:
1511 case AST_CONTROL_ANSWER:
1512 case AST_CONTROL_VIDUPDATE:
1513 case AST_CONTROL_SRCUPDATE:
1514 case AST_CONTROL_SRCCHANGE:
1515 case AST_CONTROL_HOLD:
1516 case AST_CONTROL_UNHOLD:
1517 case AST_CONTROL_CONNECTED_LINE:
1518 case AST_CONTROL_REDIRECTING:
1519 case AST_CONTROL_AOC:
1520 case AST_CONTROL_UPDATE_RTP_PEER:
1521 case AST_CONTROL_PVT_CAUSE_CODE:
1526 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
1529 case AST_FRAME_VOICE:
1530 /* Write audio if appropriate */
1532 if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
1533 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
1537 /* Ignore all others */
1542 ast_sched_runq(ast_channel_sched(c));
1545 ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
1547 return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
1550 int ast_waitstream_fr_w_cb(struct ast_channel *c,
1551 const char *breakon,
1552 const char *forward,
1553 const char *reverse,
1555 ast_waitstream_fr_cb cb)
1557 return waitstream_core(c, breakon, forward, reverse, ms,
1558 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, cb);
1561 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1563 return waitstream_core(c, breakon, forward, reverse, ms,
1564 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, NULL /* no callback */);
1568 * \brief Clean up the return value of a waitstream call
1570 * It's possible for a control frame to come in from an external source and break the
1571 * playback. From a consumer of most ast_waitstream_* function callers, this should
1572 * appear like normal playback termination, i.e., return 0 and not the value of the
1575 static int sanitize_waitstream_return(int return_value)
1577 switch (return_value) {
1578 case AST_CONTROL_STREAM_STOP:
1579 case AST_CONTROL_STREAM_SUSPEND:
1580 case AST_CONTROL_STREAM_RESTART:
1581 /* Fall through and set return_value to 0 */
1589 return return_value;
1592 int ast_waitstream(struct ast_channel *c, const char *breakon)
1596 res = waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL, NULL /* no callback */);
1598 return sanitize_waitstream_return(res);
1601 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1605 res = waitstream_core(c, breakon, NULL, NULL, 0,
1606 audiofd, cmdfd, NULL /* no context */, NULL /* no callback */);
1608 return sanitize_waitstream_return(res);
1611 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1615 /* Waitstream, with return in the case of a valid 1 digit extension */
1616 /* in the current or specified context being pressed */
1618 context = ast_channel_context(c);
1619 res = waitstream_core(c, NULL, NULL, NULL, 0,
1620 -1, -1, context, NULL /* no callback */);
1622 return sanitize_waitstream_return(res);
1626 * if the file name is non-empty, try to play it.
1627 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1628 * If digits == "" then we can simply check for non-zero.
1630 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1633 if (!ast_strlen_zero(file)) {
1634 res = ast_streamfile(chan, file, ast_channel_language(chan));
1636 res = ast_waitstream(chan, digits);
1642 char *ast_format_str_reduce(char *fmts)
1644 struct ast_format_def *f;
1645 struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
1646 char *fmts_str[AST_MAX_FORMATS];
1647 char *stringp, *type;
1649 int i, j, x, first, found = 0;
1650 int len = strlen(fmts) + 1;
1653 if (AST_RWLIST_RDLOCK(&formats)) {
1654 ast_log(LOG_WARNING, "Unable to lock format list\n");
1658 stringp = ast_strdupa(fmts);
1660 for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
1661 AST_RWLIST_TRAVERSE(&formats, f, list) {
1662 if (exts_compare(f->exts, type)) {
1675 AST_RWLIST_UNLOCK(&formats);
1678 for (i = 0; i < x; i++) {
1679 /* ignore invalid entries */
1681 ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
1685 /* special handling for the first entry */
1687 res = snprintf(fmts, len, "%s", fmts_str[i]);
1695 for (j = 0; j < i; j++) {
1696 /* this is a duplicate */
1697 if (fmts_ptr[j] == fmts_ptr[i]) {
1704 res = snprintf(fmts, len, "|%s", fmts_str[i]);
1711 ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
1718 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1720 #define FORMAT "%-10s %-10s %-20s\n"
1721 #define FORMAT2 "%-10s %-10s %-20s\n"
1722 struct ast_format_def *f;
1727 e->command = "core show file formats";
1729 "Usage: core show file formats\n"
1730 " Displays currently registered file formats (if any).\n";
1737 return CLI_SHOWUSAGE;
1739 ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1740 ast_cli(a->fd, FORMAT, "------", "----", "----------");
1742 AST_RWLIST_RDLOCK(&formats);
1743 AST_RWLIST_TRAVERSE(&formats, f, list) {
1744 ast_cli(a->fd, FORMAT2, ast_format_get_name(f->format), f->name, f->exts);
1747 AST_RWLIST_UNLOCK(&formats);
1748 ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1754 struct ast_format *ast_get_format_for_file_ext(const char *file_ext)
1756 struct ast_format_def *f;
1757 SCOPED_RDLOCK(lock, &formats.lock);
1758 AST_RWLIST_TRAVERSE(&formats, f, list) {
1759 if (exts_compare(f->exts, file_ext)) {
1767 static struct ast_cli_entry cli_file[] = {
1768 AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1771 static void file_shutdown(void)
1773 ast_cli_unregister_multiple(cli_file, ARRAY_LEN(cli_file));
1774 STASIS_MESSAGE_TYPE_CLEANUP(ast_format_register_type);
1775 STASIS_MESSAGE_TYPE_CLEANUP(ast_format_unregister_type);
1778 int ast_file_init(void)
1780 STASIS_MESSAGE_TYPE_INIT(ast_format_register_type);
1781 STASIS_MESSAGE_TYPE_INIT(ast_format_unregister_type);
1782 ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
1783 ast_register_cleanup(file_shutdown);