Skip to content
Snippets Groups Projects
file.c 50.3 KiB
Newer Older
 * 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 "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#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"
/*! \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 exts_compare(const char *exts, const char *type)
	char *stringp = tmp, *ext;
	ast_copy_string(tmp, exts, sizeof(tmp));
	while ((ext = strsep(&stringp, "|"))) {
		if (!strcmp(ext, type))
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);
	}

	if (f->filename)
		free(f->filename);
	if (f->realfilename)
		free(f->realfilename);
	if (f->vfs)
		ast_closestream(f->vfs);
	if (f->write_buffer) {
		ast_free(f->write_buffer);
	}
	if (f->orig_chan_name)
		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 ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
	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);
}

Luigi Rizzo's avatar
Loading
Loading full blame...