/*
 * Asterisk -- A telephony toolkit for Linux.
 *
 * Copyright (C) 1999, Mark Spencer
 *
 * Mark Spencer <markster@linux-support.net>
 *
 * Wait for Sound
 *   - Waits until it detects sound
 *
 * WaitForSound Application by Jose Solares <jose@solaresmaldonado.com>
 * Version 1.00 2005-03-01
 * Based on WaitForSilence by David C. Troy <dave@popvox.com>
 * 
 * This program is free software, distributed under the terms of
 * the GNU General Public License
 */

#include <asterisk/file.h>
#include <asterisk/logger.h>
#include <asterisk/channel.h>
#include <asterisk/pbx.h>
#include <asterisk/dsp.h>
#include <asterisk/module.h>
#include <asterisk/options.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

static char *tdesc = "Wait for Sound";
static char *app = "WaitForSound";
static char *synopsis = 
"Wait for Sound\n"
"  - Waits until it detects sound\n";

STANDARD_LOCAL_USER;

LOCAL_USER_DECL;

static int do_waiting(struct ast_channel *chan)
{
	struct ast_frame *f;
	int dspsilence, gotsound, rfmt, res;
	static int silencethreshold = 64;
	struct ast_dsp *sounddet;
	
	dspsilence = gotsound = rfmt = res = 0;
	rfmt = chan->readformat;
	res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
	if (res < 0) {
		ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
		return -1;
	}

	sounddet = ast_dsp_new(); /* Create the sound detector */
	if (!sounddet) {
		ast_log(LOG_WARNING, "Unable to create dsp for sound detection\n");
		return -1;
	}

	ast_dsp_set_threshold(sounddet, silencethreshold);

	/* Await sound */
	f = NULL;
	for (;;) {
		res = ast_waitfor(chan, 2000);
		if (!res) {
			ast_log(LOG_WARNING, "One waitfor failed, trying another\n");
			res = ast_waitfor(chan, 2000);
			if (!res) {
				ast_log(LOG_WARNING, "No Audio available on %s\n", chan->name);
				res = -1;
			}
		}

		if (res < 0) {
			f = NULL;
			break;
		}

		f = ast_read(chan);
		if (!f) break;
		if (f->frametype == AST_FRAME_VOICE) {
			dspsilence = 0;
			ast_dsp_silence(sounddet, f, &dspsilence);
			if (!dspsilence) {
				ast_frfree(f);
				gotsound = 1;
				break;
			}
		}
	}
	ast_dsp_free(sounddet);
	return gotsound;
}

static int waitforsound_exec(struct ast_channel *chan, void *data) 
{
	int res=1;
	struct localuser *u;

	res = ast_answer(chan); /* Answer the channel */
	
	if (data) {
		ast_log(LOG_WARNING, "WaitForSound uses no argument\n");
	}
	
	ast_verbose(VERBOSE_PREFIX_3 "Waiting until we find sound\n");

	LOCAL_USER_ADD(u);
	res = do_waiting(chan);
	LOCAL_USER_REMOVE(u);

	res = 0;
	return res;
}

int unload_module(void) 
{
	STANDARD_HANGUP_LOCALUSERS;
	return ast_unregister_application(app);
}

int load_module(void) 
{
	return ast_register_application(app, waitforsound_exec, synopsis, tdesc);
}

char *description(void) 
{
	return tdesc;
}

int usecount(void) 
{
	int res;
	STANDARD_USECOUNT(res);
	return res;
}

char *key() 
{
	return ASTERISK_GPL_KEY;
}

