Skip to content
Snippets Groups Projects
file.c 51 KiB
Newer Older
  • Learn to ignore specific revisions
  •  * Asterisk -- An open source telephony toolkit.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Copyright (C) 1999 - 2006, Digium, Inc.
    
     *
     * Mark Spencer <markster@digium.com>
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * See http://www.asterisk.org for more information about
     * the Asterisk project. Please do not directly contact
     * any of the maintainers of this project for assistance;
     * the project provides a web site, mailing lists and IRC
     * channels for your use.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
     * This program is free software, distributed under the terms of
    
     * the GNU General Public License Version 2. See the LICENSE file
     * at the top of the source tree.
     */
    
    
     * \brief Generic File Format Support.
    
     * \author Mark Spencer <markster@digium.com>
    
    /*** MODULEINFO
    	<support_level>core</support_level>
     ***/
    
    
    #include <dirent.h>
    #include <sys/stat.h>
    
    #include <sys/wait.h>
    
    #include <math.h>
    
    #include "asterisk/_private.h"	/* declare ast_file_init() */
    
    #include "asterisk/paths.h"	/* use ast_config_AST_DATA_DIR */
    
    #include "asterisk/mod_format.h"
    
    #include "asterisk/cli.h"
    #include "asterisk/channel.h"
    #include "asterisk/sched.h"
    #include "asterisk/translate.h"
    #include "asterisk/utils.h"
    #include "asterisk/lock.h"
    #include "asterisk/app.h"
    
    #include "asterisk/linkedlists.h"
    
    #include "asterisk/astobj2.h"
    
    #include "asterisk/test.h"
    
    #include "asterisk/stasis.h"
    #include "asterisk/json.h"
    
    #include "asterisk/stasis_system.h"
    
    #include "asterisk/media_cache.h"
    
    /*! \brief
    
     * The following variable controls the layout of localized sound files.
     * If 0, use the historical layout with prefix just before the filename
     * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
     * if 1 put the prefix at the beginning of the filename
     * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
     * The latter permits a language to be entirely in one directory.
    
     *
     * This is settable in asterisk.conf.
    
    static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
    
    STASIS_MESSAGE_TYPE_DEFN(ast_format_register_type);
    STASIS_MESSAGE_TYPE_DEFN(ast_format_unregister_type);
    
    static struct ast_json *json_array_from_list(const char *list, const char *sep)
    {
    	RAII_VAR(struct ast_json *, array, ast_json_array_create(), ast_json_unref);
    
    Kevin Harwell's avatar
    Kevin Harwell committed
    	char *stringp, *ext;
    
    Kevin Harwell's avatar
    Kevin Harwell committed
    	stringp = ast_strdupa(list);	/* this is in the stack so does not need to be freed */
    
    	if (!array || !stringp) {
    		return NULL;
    	}
    
    	while ((ext = strsep(&stringp, sep))) {
    		if (ast_json_array_append(array, ast_json_string_create(ext))) {
    			return NULL;
    		}
    	}
    
    	return ast_json_ref(array);
    }
    
    static int publish_format_update(const struct ast_format_def *f, struct stasis_message_type *type)
    {
    	RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
    	RAII_VAR(struct ast_json_payload *, json_payload, NULL, ao2_cleanup);
    	RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
    
    
    	json_object = ast_json_pack("{s: s, s: o}",
    		"format", f->name,
    		"extensions", json_array_from_list(f->exts, "|"));
    	if (!json_object) {
    		return -1;
    	}
    
    	json_payload = ast_json_payload_create(json_object);
    	if (!json_payload) {
    		return -1;
    	}
    
    	msg = stasis_message_create(type, json_payload);
    	if (!msg) {
    		return -1;
    	}
    
    	stasis_publish(ast_system_topic(), msg);
    	return 0;
    }
    
    
    int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	AST_RWLIST_WRLOCK(&formats);
    	AST_RWLIST_TRAVERSE(&formats, tmp, list) {
    
    		if (!strcasecmp(f->name, tmp->name)) {
    
    			AST_RWLIST_UNLOCK(&formats);
    
    			ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			return -1;
    		}
    
    	if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
    
    		AST_RWLIST_UNLOCK(&formats);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		return -1;
    	}
    
    	if (tmp->buf_size) {
    		/*
    		 * Align buf_size properly, rounding up to the machine-specific
    		 * alignment for pointers.
    		 */
    		struct _test_align { void *a, *b; } p;
    		int align = (char *)&p.b - (char *)&p.a;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
    
    	memset(&tmp->list, 0, sizeof(tmp->list));
    
    
    	AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
    	AST_RWLIST_UNLOCK(&formats);
    
    	ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
    
    	publish_format_update(f, ast_format_register_type());
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return 0;
    }
    
    
    int ast_format_def_unregister(const char *name)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	AST_RWLIST_WRLOCK(&formats);
    	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if (!strcasecmp(name, tmp->name)) {
    
    			AST_RWLIST_REMOVE_CURRENT(list);
    
    			publish_format_update(tmp, ast_format_unregister_type());
    
    	AST_RWLIST_TRAVERSE_SAFE_END;
    
    	AST_RWLIST_UNLOCK(&formats);
    
    	if (!res)
    		ast_verb(2, "Unregistered format %s\n", name);
    	else
    
    		ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
    
    	return res;
    
    Mark Spencer's avatar
    Mark Spencer committed
    }
    
    int ast_stopstream(struct ast_channel *tmp)
    {
    
    	ast_channel_lock(tmp);
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	/* Stop a running stream if there is one */
    
    	if (ast_channel_stream(tmp)) {
    		ast_closestream(ast_channel_stream(tmp));
    		ast_channel_stream_set(tmp, NULL);
    
    		if (ast_channel_oldwriteformat(tmp) && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
    			ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_format_get_name(ast_channel_oldwriteformat(tmp)));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    	/* Stop the video stream too */
    
    	if (ast_channel_vstream(tmp) != NULL) {
    		ast_closestream(ast_channel_vstream(tmp));
    		ast_channel_vstream_set(tmp, NULL);
    
    
    	ast_channel_unlock(tmp);
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return 0;
    }
    
    int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
    {
    	int res = -1;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (f->frametype == AST_FRAME_VIDEO) {
    
    		if (ast_format_get_type(fs->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    			/* This is the audio portion.  Call the video one... */
    			if (!fs->vfs && fs->filename) {
    
    				const char *type = ast_format_get_name(f->subclass.format);
    
    Mark Spencer's avatar
    Mark Spencer committed
    				fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
    
    				ast_debug(1, "Opened video output file\n");
    
    Mark Spencer's avatar
    Mark Spencer committed
    			}
    			if (fs->vfs)
    				return ast_writestream(fs->vfs, f);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		}
    	} else if (f->frametype != AST_FRAME_VOICE) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
    		return -1;
    	}
    
    	if (ast_format_cmp(f->subclass.format, fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		res =  fs->fmt->write(fs, f);
    
    		if (res < 0)
    
    Mark Spencer's avatar
    Mark Spencer committed
    			ast_log(LOG_WARNING, "Natural write failed\n");
    
    Mark Spencer's avatar
    Mark Spencer committed
    			ast_log(LOG_WARNING, "Huh??\n");
    	} else {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		/* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
    		       the one we've setup a translator for, we do the "wrong thing" XXX */
    
    		if (fs->trans && (ast_format_cmp(f->subclass.format, fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
    
    			ast_translator_free_path(fs->trans);
    			fs->trans = NULL;
    		}
    
    		if (!fs->trans) {
    			fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass.format);
    		}
    		if (!fs->trans) {
    
    			ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
    
    				fs->fmt->name, ast_format_get_name(f->subclass.format));
    		} else {
    
    			struct ast_frame *trf;
    
    			ao2_replace(fs->lastwriteformat, f->subclass.format);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			/* Get the translated frame but don't consume the original in case they're using it on another stream */
    
    			if ((trf = ast_translate(fs->trans, f, 0))) {
    				struct ast_frame *cur;
    
    				/* the translator may have returned multiple frames, so process them */
    				for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
    					if ((res = fs->fmt->write(fs, trf))) {
    						ast_log(LOG_WARNING, "Translated frame write failed\n");
    						break;
    					}
    				}
    
    				ast_frfree(trf);
    
    Mark Spencer's avatar
    Mark Spencer committed
    				res = 0;
    
    static int copy(const char *infile, const char *outfile)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	int ifd, ofd, len;
    	char buf[4096];	/* XXX make it lerger. */
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if ((ifd = open(infile, O_RDONLY)) < 0) {
    		ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
    		return -1;
    	}
    
    	if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
    		close(ifd);
    		return -1;
    	}
    
    	while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
    		int res;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if (len < 0) {
    			ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
    
    Mark Spencer's avatar
    Mark Spencer committed
    		}
    
    		/* XXX handle partial writes */
    		res = write(ofd, buf, len);
    		if (res != len) {
    			ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
    			len = -1; /* error marker */
    			break;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	close(ifd);
    	close(ofd);
    
    	if (len < 0) {
    		unlink(outfile);
    		return -1; /* error */
    	}
    	return 0;	/* success */
    
    /*!
     * \brief construct a filename. Absolute pathnames are preserved,
     * relative names are prefixed by the sounds/ directory.
     * The wav49 suffix is replaced by 'WAV'.
     * Returns a malloc'ed string to be freed by the caller.
     */
    
    static char *build_filename(const char *filename, const char *ext)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	if (!strcmp(ext, "wav49"))
    		ext = "WAV";
    
    		if (ast_asprintf(&fn, "%s.%s", filename, ext) < 0) {
    
    		if (ast_asprintf(&fn, "%s/sounds/%s.%s",
    
    			     ast_config_AST_DATA_DIR, filename, ext) < 0) {
    			fn = NULL;
    		}
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return fn;
    }
    
    
    /* compare type against the list 'exts' */
    /* XXX need a better algorithm */
    
    static int type_in_list(const char *list, const char *type, int (*cmp)(const char *s1, const char *s2))
    
    	char *stringp = ast_strdupa(list), *item;
    
    	while ((item = strsep(&stringp, "|"))) {
    		if (!cmp(item, type)) {
    
    #define exts_compare(list, type) (type_in_list((list), (type), strcmp))
    
    
    Richard Mudgett's avatar
    Richard Mudgett committed
    /*!
     * \internal
     * \brief Close the file stream by canceling any pending read / write callbacks
     */
    
    static void filestream_close(struct ast_filestream *f)
    {
    
    	enum ast_media_type format_type = ast_format_get_type(f->fmt->format);
    
    
    	if (!f->owner) {
    		return;
    	}
    
    	/* Stop a running stream if there is one */
    	switch (format_type)
    	{
    
    		ast_channel_stream_set(f->owner, NULL);
    		AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
    
    		ast_settimeout(f->owner, 0, NULL, NULL);
    		break;
    
    		ast_channel_vstream_set(f->owner, NULL);
    		AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
    
    		break;
    	default:
    		ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
    		break;
    	}
    }
    
    
    static void filestream_destructor(void *arg)
    {
    	struct ast_filestream *f = arg;
    
    	int status;
    	int pid = -1;
    
    
    	/* Stop a running stream if there is one */
    
    	/* destroy the translator on exit */
    	if (f->trans)
    		ast_translator_free_path(f->trans);
    
    
    	if (f->fmt->close) {
    		void (*closefn)(struct ast_filestream *) = f->fmt->close;
    		closefn(f);
    	}
    
    	if (f->f) {
    		fclose(f->f);
    	}
    
    
    	if (f->realfilename && f->filename) {
    
    		pid = ast_safe_fork(0);
    		if (!pid) {
    
    			execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
    
    			_exit(1);
    		}
    		else if (pid > 0) {
    			/* Block the parent until the move is complete.*/
    			waitpid(pid, &status, 0);
    
    	ast_free(f->filename);
    	ast_free(f->realfilename);
    
    	if (f->vfs)
    		ast_closestream(f->vfs);
    
    	ast_free(f->write_buffer);
    	ast_free((void *)f->orig_chan_name);
    
    	ao2_cleanup(f->lastwriteformat);
    	ao2_cleanup(f->fr.subclass.format);
    
    	ast_module_unref(f->fmt->module);
    }
    
    
    static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
    
    {
    	struct ast_filestream *s;
    	int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;	/* total allocation size */
    
    
    	if (!ast_module_running_ref(fmt->module)) {
    		return NULL;
    	}
    
    	s = ao2_alloc(l, filestream_destructor);
    	if (!s) {
    		ast_module_unref(fmt->module);
    
    	s->fmt = fmt;
    	s->f = bfile;
    
    	if (fmt->desc_size)
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		s->_private = ((char *)(s + 1)) + fmt->buf_size;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		s->buf = (char *)(s + 1);
    
    	s->fr.src = fmt->name;
    
    
    	if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_AUDIO) {
    		s->fr.frametype = AST_FRAME_VOICE;
    	} else if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_VIDEO) {
    		s->fr.frametype = AST_FRAME_VIDEO;
    	}
    	s->fr.mallocd = 0;
    	s->fr.subclass.format = ao2_bump(fmt->format);
    
    
    	return s;
    }
    
    /*
     * Default implementations of open and rewrite.
     * Only use them if you don't have expensive stuff to do.
     */
    enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
    
    static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
    {
    
    	struct ast_format_def *f = s->fmt;
    
    	int (*openfn)(struct ast_filestream *s);
    
    	if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
    
    	else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
    
    		/* preliminary checks succeed. */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	return ret;
    
    }
    
    static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
    {
    	return fn_wrapper(s, comment, WRAP_REWRITE);
    }
    
    static int open_wrapper(struct ast_filestream *s)
    {
    	return fn_wrapper(s, NULL, WRAP_OPEN);
    }
    
    
    	ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
    	ACTION_DELETE,	/* delete file, return 0 on success, -1 on error */
    	ACTION_RENAME,	/* rename file. return 0 on success, -1 on error */
    
    	ACTION_COPY	/* copy file. return 0 on success, -1 on error */
    
     * \brief perform various actions on a file. Second argument
    
     * \note arg2 depends on the command:
     *	unused for DELETE
     *  optional ast_format_cap holding all the formats found for a file, for EXISTS.
    
     *	destination file name (const char *) for COPY and RENAME
    
     *	struct ast_channel * for OPEN
    
     * if fmt is NULL, OPEN will return the first matching entry,
     * whereas other functions will run on all matching entries.
    
    static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	struct ast_format_def *f;
    	int res = (action == ACTION_EXISTS) ? 0 : -1;
    
    	AST_RWLIST_RDLOCK(&formats);
    
    	/* Check for a specific format */
    
    	AST_RWLIST_TRAVERSE(&formats, f, list) {
    
    		char *stringp, *ext = NULL;
    
    
    		if (fmt && !exts_compare(f->exts, fmt))
    			continue;
    
    		/* Look for a file matching the supported extensions.
    		 * The file must exist, and for OPEN, must match
    		 * one of the formats supported by the channel.
    		 */
    
    		stringp = ast_strdupa(f->exts);	/* this is in the stack so does not need to be freed */
    
    		while ( (ext = strsep(&stringp, "|")) ) {
    			struct stat st;
    
    			char *fn = build_filename(filename, ext);
    
    
    			if (fn == NULL)
    				continue;
    
    			if ( stat(fn, &st) ) { /* file not existent */
    
    				continue;
    			}
    			/* for 'OPEN' we need to be sure that the format matches
    			 * what the channel can process
    			 */
    			if (action == ACTION_OPEN) {
    				struct ast_channel *chan = (struct ast_channel *)arg2;
    				FILE *bfile;
    				struct ast_filestream *s;
    
    
    				if ((ast_format_cmp(ast_channel_writeformat(chan), f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
    				     !(((ast_format_get_type(f->format) == AST_MEDIA_TYPE_AUDIO) && fmt) ||
    					  ((ast_format_get_type(f->format) == AST_MEDIA_TYPE_VIDEO) && fmt))) {
    
    					continue;	/* not a supported format */
    				}
    				if ( (bfile = fopen(fn, "r")) == NULL) {
    
    					continue;	/* cannot open file */
    				}
    				s = get_filestream(f, bfile);
    				if (!s) {
    					fclose(bfile);
    
    Mark Spencer's avatar
    Mark Spencer committed
    				}
    
    				if (open_wrapper(s)) {
    
    					ast_closestream(s);
    
    					continue;	/* cannot run open on file */
    				}
    
    Jeff Peeler's avatar
    Jeff Peeler committed
    				if (st.st_size == 0) {
    					ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
    				}
    
    				/* ok this is good for OPEN */
    				res = 1;	/* found */
    				s->lasttimeout = -1;
    				s->fmt = f;
    				s->trans = NULL;
    				s->filename = NULL;
    
    				if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
    
    					if (ast_channel_stream(chan))
    						ast_closestream(ast_channel_stream(chan));
    					ast_channel_stream_set(chan, s);
    
    					if (ast_channel_vstream(chan))
    						ast_closestream(ast_channel_vstream(chan));
    					ast_channel_vstream_set(chan, s);
    
    			switch (action) {
    			case ACTION_OPEN:
    				break;	/* will never get here */
    
    			case ACTION_EXISTS:	/* return the matching format */
    
    				/* if arg2 is present, it is a format capabilities structure.
    				 * Add this format to the set of formats this file can be played in */
    				if (arg2) {
    
    					ast_format_cap_append((struct ast_format_cap *) arg2, f->format, 0);
    
    				}
    				res = 1; /* file does exist and format it exists in is returned in arg2 */
    
    				break;
    
    			case ACTION_DELETE:
    				if ( (res = unlink(fn)) )
    					ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
    				break;
    
    			case ACTION_RENAME:
    			case ACTION_COPY: {
    				char *nfn = build_filename((const char *)arg2, ext);
    				if (!nfn)
    					ast_log(LOG_WARNING, "Out of memory\n");
    				else {
    					res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
    					if (res)
    						ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
    							action == ACTION_COPY ? "copy" : "rename",
    							 fn, nfn, strerror(errno));
    
    				ast_log(LOG_WARNING, "Unknown helper %u\n", action);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    	AST_RWLIST_UNLOCK(&formats);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return res;
    }
    
    static int is_absolute_path(const char *filename)
    {
    	return filename[0] == '/';
    }
    
    
    /*!
     * \brief test if a file exists for a given format.
     * \note result_cap is OPTIONAL
     * \retval 1, true and result_cap represents format capabilities file exists in.
     * \retval 0, false
     */
    static int fileexists_test(const char *filename, const char *fmt, const char *lang,
    			   char *buf, int buflen, struct ast_format_cap *result_cap)
    
    {
    	if (buf == NULL) {
    
    	if (!ast_media_cache_retrieve(filename, NULL, buf, buflen)) {
    		return filehelper(buf, result_cap, NULL, ACTION_EXISTS);
    	}
    
    
    	if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
    
    		if (lang) {
    			snprintf(buf, buflen, "%s/%s", lang, filename);
    		} else {
    			snprintf(buf, buflen, "%s", filename);
    		}
    	} else { /* old layout */
    		strcpy(buf, filename);	/* first copy the full string */
    		if (lang) {
    			/* insert the language and suffix if needed */
    			const char *c = strrchr(filename, '/');
    			int offset = c ? c - filename + 1 : 0;	/* points right after the last '/' */
    			snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
    		}
    	}
    
    
    	return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
    
    /*!
     * \brief helper routine to locate a file with a given format
     * and language preference.
    
     * \note Try preflang, preflang with stripped '_' suffices, or NULL.
    
     * \note The last parameter(s) point to a buffer of sufficient size,
    
     * which on success is filled with the matching filename.
    
     * \param filename Name of the file.
     * \param fmt Format to look for the file in. OPTIONAL
     * \param preflang The perfered language
     * \param buf Returns the matching filename
     * \param buflen Size of the buf
     * \param result_cap OPTIONAL format capabilities result structure
    
     *        returns what formats the file was found in.
     *
     * \retval 1, true. file exists and result format is set
     * \retval 0, false. file does not exist.
    
    static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
    			   char *buf, int buflen, struct ast_format_cap *result_cap)
    
    	if (buf == NULL) {
    
    	/* We try languages in the following order:
    
    	 *    preflang (may include dialect and style codes)
    
    	 *    lang (preflang without dialect - if any)
    	 *    <none>
    	 *    default (unless the same as preflang or lang without dialect)
    	 */
    
    
    	lang = ast_strdupa(preflang);
    
    	/* Try preferred language, including removing any style or dialect codes */
    	while (!ast_strlen_zero(lang)) {
    		char *end;
    
    
    		if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
    			return 1;
    
    
    		if ((end = strrchr(lang, '_')) != NULL) {
    			*end = '\0';
    			continue;
    		}
    
    		break;
    
    	}
    
    	/* Try without any language */
    
    	if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
    		return 1;
    
    	}
    
    	/* Finally try the default language unless it was already tried before */
    	if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
    
    		if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
    			return 1;
    
    	return 0;
    
    struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
    
    {
    	return ast_openstream_full(chan, filename, preflang, 0);
    }
    
    struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	 * Use fileexists_core() to find a file in a compatible
    	 * language and format, set up a suitable translator,
    	 * and open the stream.
    	 */
    
    	struct ast_format_cap *file_fmt_cap;
    	int res;
    
    
    	if (!asis) {
    		/* do this first, otherwise we detect the wrong writeformat */
    		ast_stopstream(chan);
    
    		if (ast_channel_generator(chan))
    
    	if (preflang == NULL)
    		preflang = "";
    
    	buflen = strlen(preflang) + strlen(filename) + 4;
    
    	buf = ast_alloca(buflen);
    
    	if (!(file_fmt_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
    
    		return NULL;
    	}
    	if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
    
    		!ast_format_cap_has_type(file_fmt_cap, AST_MEDIA_TYPE_AUDIO)) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		return NULL;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    
    	/* Set the channel to a format we can work with and save off the previous format. */
    
    	ast_channel_set_oldwriteformat(chan, ast_channel_writeformat(chan));
    
    	/* Set the channel to the best format that exists for the file. */
    	res = ast_set_write_format_from_cap(chan, file_fmt_cap);
    
    	/* don't need this anymore now that the channel's write format is set. */
    
    	if (res == -1) {	/* No format available that works with this channel */
    		return NULL;
    	}
    
    	res = filehelper(buf, chan, NULL, ACTION_OPEN);
    
    		return ast_channel_stream(chan);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return NULL;
    }
    
    
    struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	/* As above, but for video. But here we don't have translators
    	 * so we must enforce a format.
    	 */
    
    	struct ast_format_cap *nativeformats, *tmp_cap;
    
    	buflen = strlen(preflang) + strlen(filename) + 4;
    
    	buf = ast_alloca(buflen);
    
    	ast_channel_lock(chan);
    	nativeformats = ao2_bump(ast_channel_nativeformats(chan));
    	ast_channel_unlock(chan);
    
    
    	/* is the channel capable of video without translation ?*/
    
    	if (!ast_format_cap_has_type(nativeformats, AST_MEDIA_TYPE_VIDEO)) {
    		ao2_cleanup(nativeformats);
    
    	if (!(tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
    
    		ao2_cleanup(nativeformats);
    
    		return NULL;
    	}
    	/* Video is supported, so see what video formats exist for this file */
    	if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
    
    		ao2_cleanup(nativeformats);
    
    	/* iterate over file formats and pick the first one compatible with the channel's native formats */
    
    	for (i = 0; i < ast_format_cap_count(tmp_cap); ++i) {
    		struct ast_format *format = ast_format_cap_get_format(tmp_cap, i);
    
    		if ((ast_format_get_type(format) != AST_MEDIA_TYPE_VIDEO) ||
    
    			!ast_format_cap_iscompatible(nativeformats, tmp_cap)) {
    
    		fd = filehelper(buf, chan, ast_format_get_name(format), ACTION_OPEN);
    
    			ao2_ref(format, -1);
    			ao2_ref(tmp_cap, -1);
    
    			ao2_cleanup(nativeformats);
    
    			return ast_channel_vstream(chan);
    
    		ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    	ao2_cleanup(nativeformats);
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return NULL;
    }
    
    
    static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
    
    	struct ast_frame *fr, *new_fr;
    
    	if (!s || !s->fmt) {
    		return NULL;
    	}
    
    	if (!(fr = s->fmt->read(s, whennext))) {
    		return NULL;
    	}
    
    	if (!(new_fr = ast_frisolate(fr))) {
    		ast_frfree(fr);
    		return NULL;
    	}
    
    	if (new_fr != fr) {
    		ast_frfree(fr);
    		fr = new_fr;
    
    
    	return fr;
    }
    
    struct ast_frame *ast_readframe(struct ast_filestream *s)
    {
    	int whennext = 0;
    
    	return read_frame(s, &whennext);
    
    enum fsread_res {
    	FSREAD_FAILURE,
    	FSREAD_SUCCESS_SCHED,
    	FSREAD_SUCCESS_NOSCHED,
    };
    
    
    static int ast_fsread_audio(const void *data);
    
    
    static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int whennext = 0;
    
    
    		struct ast_frame *fr;
    
    		if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
    
    			goto return_failure;
    
    
    		fr = read_frame(s, &whennext);
    
    
    		if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
    
    				ast_debug(2, "Failed to write frame\n");
    
    			goto return_failure;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (whennext != s->lasttimeout) {
    
    		if (ast_channel_timingfd(s->owner) > -1) {
    
    			float samp_rate = (float) ast_format_get_sample_rate(s->fmt->format);
    
    			unsigned int rate;
    
    			rate = (unsigned int) roundf(samp_rate / ((float) whennext));
    
    
    			ast_settimeout_full(s->owner, rate, ast_fsread_audio, s, 1);
    
    			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));
    
    Mark Spencer's avatar
    Mark Spencer committed
    		s->lasttimeout = whennext;
    
    		return FSREAD_SUCCESS_NOSCHED;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    	return FSREAD_SUCCESS_SCHED;
    
    return_failure:
    
    	ast_channel_streamid_set(s->owner, -1);
    
    	ast_settimeout(s->owner, 0, NULL, NULL);
    	return FSREAD_FAILURE;
    
    static int ast_fsread_audio(const void *data)
    
    	struct ast_filestream *fs = (struct ast_filestream *)data;
    
    	enum fsread_res res;
    
    	res = ast_readaudio_callback(fs);
    
    	if (res == FSREAD_SUCCESS_SCHED)
    		return 1;
    
    static int ast_fsread_video(const void *data);
    
    
    static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    	int whennext = 0;
    
    
    		struct ast_frame *fr = read_frame(s, &whennext);
    
    
    		if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
    			if (fr) {
    
    				ast_debug(2, "Failed to write frame\n");
    
    			ast_channel_vstreamid_set(s->owner, -1);
    
    			return FSREAD_FAILURE;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		}
    
    		if (fr) {
    			ast_frfree(fr);
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (whennext != s->lasttimeout) {
    
    		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));
    
    Mark Spencer's avatar
    Mark Spencer committed
    		s->lasttimeout = whennext;
    
    		return FSREAD_SUCCESS_NOSCHED;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	}
    
    
    	return FSREAD_SUCCESS_SCHED;
    }
    
    
    static int ast_fsread_video(const void *data)
    
    	struct ast_filestream *fs = (struct ast_filestream *)data;
    
    	enum fsread_res res;