/*---------------------------------------------------------------------------*\

    FILE....: VPBTONED.CPP
    TYPE....: C++ Module
    AUTHOR..: David Rowe
    DATE....: 26/2/98

    This file contains the implementation of the programmable tone
    detection API functions, vpb_settonedet and vpb_gettonedet.


         Voicetronix Voice Processing Board (VPB) Software
         Copyright (C) 1999-2008 Voicetronix www.voicetronix.com.au

         This library is free software; you can redistribute it and/or
         modify it under the terms of the GNU Lesser General Public
         License as published by the Free Software Foundation; either
         version 2.1 of the License, or (at your option) any later version.

         This library is distributed in the hope that it will be useful,
         but WITHOUT ANY WARRANTY; without even the implied warranty of
         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
         Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
         License along with this library; if not, write to the Free Software
         Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
         MA  02110-1301  USA

\*---------------------------------------------------------------------------*/

#include "vpbtoned.h"
#include "apifunc.h"
#include "mapdev.h"
#include "objtrack.h"
//#include "mess.h"

#include <cstdio>
#include <cstring>
#include <cassert>
#include <climits>


#define	FMIN		100	// minimum tone detection frequency
#define	FMAX		3900	// maximum tone detection frequency
#define	LMAX		0	// maximum tone level in dB
#define	SNRMIN		0	// maximum SNR in dB
#define	TWISTMIN	0	// minimum twist in dB
#define	TSAM		125E-6	// sampling period

#define	SIZEOFHEADERINWORDS	15
#define	STARTNSTATES		12
#define	SIZEOFVPB_STRANINWORDS	4


static VPB_DETECT	*td;	// record of each tone detector for each ch
static unsigned short	*numtd;	// num detector for each ch

static unsigned short	logging = 0;
static unsigned short	logch;
static long		logframes;
static long		logcnt;
static FILE*		logfile;


void check_freq(float f, float bw);
void check_level(float l);
void check_snr(float snr);
void check_twist(float twist);


/*--------------------------------------------------------------------------*\

	FUNCTION.: vpbtoned_open()
	AUTHOR...: David Rowe
	DATE.....: 26/2/98

	Initialises the programmable tone detector module.  This function 
	should be called when the API is initialised.  This function loads
	allocates memory for the tone detector params mirror store in PC
	memory.

\*--------------------------------------------------------------------------*/

void vpbtoned_open(int numdev)
//  int    numdev	total number of channel devices (and hence tone dets)
{
	td = new VPB_DETECT[numdev*VPB_MD];
	numtd = new unsigned short[numdev*VPB_MD];
	for(int i=0; i<numdev; ++i) numtd[i] = 0;
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: vpbtoned_close()
	AUTHOR...: David Rowe
	DATE.....: 26/2/98

	Frees memory used for storing tone detector info.

\*--------------------------------------------------------------------------*/

void vpbtoned_close()
//  int    numdev	total number of channel devices (and hence tone dets)
{
	delete [] td;
	delete [] numtd;
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: check_states()
	AUTHOR...: David Rowe
	DATE.....: 27/2/98

	Validation function for cadence states, also scales ton and toff for
	each state to 10ms increments rather than API level 1ms increments.

\*--------------------------------------------------------------------------*/

static void check_states(const VPB_DETECT &d)
{
	if(d.nstates > VPB_MS)
		throw VpbException("settonedet: too many cadence states (%d)",
				   d.nstates);
	if(d.nstates == 0)
		throw VpbException("settonedet: no cadence states");

	for(int i=0; i < d.nstates; ++i)
		switch( d.stran[i].type )
		{
		    case VPB_TIMER:
		    case VPB_RISING:
		    case VPB_FALLING:
		    case VPB_DELAY:
			break;

		    default:
			throw VpbException("settonedet: invalid cadence state"
					   " (%d = %d)", i, d.stran[i].type);
		}
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: settonedet()
	AUTHOR...: David Rowe
	DATE.....: 26/2/98

	Enables user to set a user programmed tone, or replace an exisiting 
	tone.  Performs translation of user parameters to VPB message.  The
	tones are defined on a per channel basis.

	This version should only be called when the config manager for this
	VPB is not running, use vpb_settonedet() if the config manager is
	running.

\*--------------------------------------------------------------------------*/

void settonedet(int chdev, const VPB_DETECT &d)
//  int		chdev		channel device to add tone to
//  VPB_DETECT	*d		structure containing detector parameters
{
	int	i;
	unsigned short	b,ch;
	int	vpbmodel=-1;

	int id = d.tone_id;

	// determine if a detector with this identifier already exists

	int exists = 0;
	int index = 0;

	for(i=0; i < numtd[chdev]; ++i) {
		if (td[chdev*VPB_MD+i].tone_id == id) {
			exists = 1;
			index = i;
			break;
		}
	}

	// if ident doesn't exist, make new tone

	if( ! exists ) {
		if(numtd[chdev] >= VPB_MD)
			throw VpbException("settonedet: too many detectors");

		index = numtd[chdev]++;
	}

	// validate tone parameters

	if(d.ntones != 1 && d.ntones != 2)
		throw VpbException("settonedet: invalid number of tones (%d)",
				   d.ntones);

	check_freq(d.freq1, d.bandwidth1);
	check_level(d.minlevel1);
	if(d.ntones == 2) {
		check_freq(d.freq2, d.bandwidth2);
		check_level(d.minlevel2);
		check_twist(d.twist);
	}
	check_snr(d.snr);
	check_states(d);

	// OK, translate params into message and send to VPB

	maphndletodev(chdev, &b, &ch);
	uint16_t	mess[COMM_MAX_MESSPCDSP];
	assert(COMM_MAX_MESSPCDSP > (SIZEOFHEADERINWORDS+VPB_MS* SIZEOFVPB_STRANINWORDS));

	mess[0] = (uint16_t)(SIZEOFHEADERINWORDS+d.nstates* SIZEOFVPB_STRANINWORDS);
	mess[1] = (uint16_t)PC_TONED_ST;
	vpbmodel=vpb_c->vpbreg(b)->model;
//	mprintf("settonedet: Model [%d]\n",vpbmodel);
	switch(vpbmodel)
	{
	    case VPB_OPCI:
	    case VPB_OSW:
		mess[2] = (uint16_t)ch;
		break;

	  #ifdef _OPENPRI
	    case VPB_PRI:
                // This may throw...
                mess[2] = get_idx_from_ch(vpb_c->vpbreg(b),ch);
		break;
	  #endif

	    default:
		mess[2] = (uint16_t)objtrack_handle_to_id(CPOBJ,chdev);
	}
	memcpy(&mess[3], &d, sizeof(VPB_DETECT));
//	mprintf("settonedet: Sending message to bd[%d]\n",b);
	vpb_c->PutMessageVPB(b, mess);
//	mprintf("settonedet: Checking for assert on bd[%d]\n",b);

	// keep record of tone detector in PC
	memcpy(&td[chdev*VPB_MD+index], &d, sizeof(VPB_DETECT));
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: deltonedet()
	AUTHOR...: Ben Kramer
	DATE.....: 14/10/04

	Enables user to delete a user programmed tone, only implemented in the
	OpenSwitch cards.

\*--------------------------------------------------------------------------*/

void deltonedet(int chdev, const VPB_DETECT &d)
//  int		chdev		channel device to add tone to
//  VPB_DETECT	*d		structure containing detector parameters
{
	int	i;
	unsigned short	b,ch;

	int id = d.tone_id;

	// determine if a detector with this identifier already exists

	int exists = 0;
//	int index = 0;

	for(i=0; i < numtd[chdev]; ++i) {
		if (td[chdev*VPB_MD+i].tone_id == id) {
			exists = 1;
//			index = i;
			break;
		}
	}

	// if ident doesn't exist, giveup

	if (!exists)
		return;


	// OK, translate params into message and send to VPB

	uint16_t	mess[COMM_MAX_MESSPCDSP];
	assert(COMM_MAX_MESSPCDSP > (SIZEOFHEADERINWORDS+VPB_MS*
				SIZEOFVPB_STRANINWORDS));

	mess[0] = (uint16_t)(SIZEOFHEADERINWORDS+d.nstates*
			 SIZEOFVPB_STRANINWORDS);
	mess[1] = (uint16_t)PC_TONED_ST_DEL;
	mess[2] = (uint16_t)objtrack_handle_to_id(CPOBJ,chdev);
	memcpy(&mess[3], &d, sizeof(VPB_DETECT));
	maphndletodev(chdev, &b, &ch);
	vpb_c->PutMessageVPB(b, mess);
//	//mprintf(" settonedet half way\n");

	// delete record of tone detector in PC
/*
	if (!exists) {
		memcpy(&td[chdev*VPB_MD+index], d, sizeof(VPB_DETECT));
	}
*/
}

void WINAPI vpb_settonedet(VPBPortHandle handle, const VPB_DETECT &d)
{
	CheckHandle(handle, "vpb_settonedet");
	settonedet(handle, d);
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: vpb_gettonedet()
	AUTHOR...: David Rowe
	DATE.....: 27/2/98

	Enables user to extract a tone detectors parameters.

\*--------------------------------------------------------------------------*/

void WINAPI vpb_gettonedet(VPBPortHandle handle, int id, VPB_DETECT *d)
//  int		handle channel device holding tone detector
//  int		id     tone identifier
//  VPB_DETECT  *d     structure containing detector parameters
{
	CheckHandle(handle, "vpb_gettonedet");

	// determine if a detector with this identifier already exists

	int exists = 0;
	int index = 0;

	for(int i=0; i < numtd[handle]; ++i) {
		if (td[handle * VPB_MD + i].tone_id == id) {
			exists = 1;
			index = i;
			break;
		}
	}

	if( ! exists )
		throw VpbException("vpb_gettonedet: invalid id (%d)", id);

	// copy tone params from PC mirror

	memcpy(d, &td[handle * VPB_MD + index], sizeof(VPB_DETECT));
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: vpb_deltonedet()
	AUTHOR...: Ben Kramer
	DATE.....: 14/10/04

	Enables user to delete a user programmed tone, this is only
	implemented for use with the host side tone detector.

    int		chdev	channel device to add tone to
    VPB_DETECT	*d      structure containing detector parameters

\*--------------------------------------------------------------------------*/

void WINAPI vpb_deltonedet(VPBPortHandle handle, const VPB_DETECT &d)
{
	CheckHandle(handle, "vpb_deltonedet");
	deltonedet(handle, d);
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: check_freq()
	AUTHOR...: David Rowe
	DATE.....: 27/2/98

	Frequency validation function.

\*--------------------------------------------------------------------------*/

void check_freq(float f, float bw)
//  float f
//  float bw
{
	bw /= 2;
	if ( ((f-bw) < FMIN) || ((f+bw) > FMAX) )
		throw Wobbly(VPBAPI_DETECT_INVALID_FREQUENCY);
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: check_level()
	AUTHOR...: David Rowe
	DATE.....: 27/2/98

	Level validation function.

\*--------------------------------------------------------------------------*/

void check_level(float l)
//	float	l	Level in dB with maximum of LMAX dB
{
	if (l > LMAX)
		throw Wobbly(VPBAPI_DETECT_INVALID_LEVEL);
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: check_snr()
	AUTHOR...: David Rowe
	DATE.....: 27/2/98

	SNR validation function.

\*--------------------------------------------------------------------------*/

void check_snr(float snr)
//	float	snr		SNR in dB with minimum of SNRMIN dB
{
	if (snr < SNRMIN)
		throw Wobbly(VPBAPI_DETECT_INVALID_SNR);
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: check_twist()
	AUTHOR...: David Rowe
	DATE.....: 27/2/98

	Twist validation function.

\*--------------------------------------------------------------------------*/

void check_twist(float twist)
//	float	twist		twist in dB with minimum of TWISTMIN dB
{
	if (twist < TWISTMIN)
		throw Wobbly(VPBAPI_DETECT_INVALID_TWIST);
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: vpb_debug_tonedet()
	AUTHOR...: David Rowe
	DATE.....: 29/4/98

	Instructs API to produce a debug file of tone detector parameters for
	one channel. 

\*--------------------------------------------------------------------------*/

int WINAPI vpb_debug_tonedet(int chdev, int id, char file_name[], int sec)
//	int	chdev		channel to log debug info for
//	int	id		ID of tone detector to log
//	char	file_name[]	name of file where debug info is to be written
//	int	sec		number of seconds of info to log
{

	try {
		if (logging)
			throw Wobbly(VPBAPI_DETECT_ALREADY_LOGGING);
		logging = 1;

		logfile = fopen(file_name, "wt");
		if (logfile == NULL)
			throw Wobbly(VPBAPI_DETECT_BAD_LOG_FILE_NAME);

		// set up statics

		unsigned short b,ch;
		maphndletodev(chdev, &b, &ch);

		logch = chdev;
		VPBREG* pvpbreg = vpb_c->vpbreg(b);
		logframes = (long)sec*8000l/(pvpbreg->lsf);
		if (logframes > SHRT_MAX) logframes = SHRT_MAX;
		logcnt = 0;

		// tell DSP to switch debugging on

		uint16_t	mess[PC_LTONED_DEBUG];
		mess[0] = PC_LTONED_DEBUG;
		mess[1] = PC_TONED_DEBUG;
		mess[2] = objtrack_handle_to_id(CPOBJ, chdev);
		mess[3] = id;
		mess[4] = (uint16_t)logframes;
		vpb_c->PutMessageVPB(b, mess);
	}
	catch(const Wobbly &w){
		return(RunTimeError(w,"vpb_debug_tonedet"));
	}
	return VPB_OK;
}

/*--------------------------------------------------------------------------*\

	FUNCTION.: toned_debug_log
	AUTHOR...: David Rowe
	DATE.....: 29/4/98

	This function is called from the MMQ to iterate the debug logging
	data.

\*--------------------------------------------------------------------------*/

void toned_debug_log(unsigned short board, uint16_t mess[])
//	unsigned short	board
//	uint16_t	mess[]		messge from DSP
{
	unsigned short	chdev;

	// validate

	assert(logging);
	assert(mess[1] == DSP_TONED_LOG);
	assert(logfile != NULL);
	assert(logframes);
	assert(mess[4] == logcnt);

	// extract params from message and print to text file

	chdev = objtrack_id_to_handle(CPOBJ, mess[2], board);
	assert(chdev == logch);

	fprintf(logfile,"[%06ld] ch:%02d id:%02d t1:%d t2:%d tw:%d snr:%d t:%d "
		"ton:%5d toff:%5d r:%d f:%d s:%02d ns:%02d\n",
					logcnt,
					chdev,
					mess[3],	// tone id
					mess[5],	// tone1
					mess[6],	// tone2
					mess[7],	// twist
					mess[8],	// snr
					mess[9],	// tone

					mess[10],	// tone_on
					mess[11],	// tone_off
					mess[12],	// rising
					mess[13],	// falling
					mess[14],	// state
					mess[15]	// next_state
			);

	// if we have finished logging close file and send event to API

	logcnt++;
	if (logframes == logcnt) {
		logging = 0;
		fclose(logfile);

		VPB_EVENT e;
		e.type = VPB_TONE_DEBUG_END;
		e.handle = logch;
		e.data = 0;
		putevt(&e, 0);
	}
}



//XXX All this lot is completely unused now right?
#if 0
//{{{
// message describing state transitions for Studio 308 ring 
static short toned_ring[] ={
    0,				// work out length at run time	
    PC_TONED_ST,
    0,				// ID				

    3,				// number of cadence states	
    1,				// event code			
    1,				// number of tones		
    425,			// f1:  centre frequency	
    100,			// bw1: bandwidth		
    0,				// f2: N/A			
    0,				// bw2: N/A			
    -20,			// A1: -10 dbm0			
    0,				// A2: N/A 			
    0,				// twist: N/A			
    10,				// SNR: 10dB			

    RISING,			// state 0			
    0,
    0,
    0,

    FALLING,		// state 1			
    0,
    80,				// 800ms ton min		
    120,			// 1200ms ton max		

    RISING,			// state 2			
    0,
    360,			// 3800ms toff min		
    440,			// 4200ms toff max		
};


static short toned_busy[] ={
    0,				// work out length at run time	
    PC_TONED_ST,
    0,				// ID				

    3,				// number of states		
    2,				// event code			
    1,				// number of tones		
    425,			// f1:  centre frequency	
    100,			// bw1: bandwidth		
    0,				// f2: N/A			
    0,				// bw2: N/A			
    -20,			// A1: -10 dbm0			
    0,				// A2: N/A 			
    0,				// twist: N/A			
    10,				// SNR: 10dB			

    RISING,			// state 0			
    0,
    0,
    0,

    FALLING,		// state 1			
    0,
    45,				// 450ms ton min		
    55,				// 550ms ton max		

    RISING,			// state 2			
    0,
    45,				// 450ms toff min		
    55,				// 550ms toff max		
};

// message describing state transitions for DTMF tone 

static short toned_dtmf[] ={
    0,				// work out length at run time	
    PC_TONED_ST,
    0,				// ID				

    2,				// number of states		
    3,				// event code			
    2,				// number of tones		
    697,			// f1:  697Hz			
    100,			// bw1: 100 Hz			
    1209,			// f2: 1209Hz			
    100,			// bw2: 100 Hz			
    -20,			// A1: -10 dbm0			
    -20,			// A2: -10 dbm0 		
    10,				// allowable twist: 10dB	
    10,				// SNR: 10dB			

    RISING,			// state 0			
    0,
    0,
    0,

    FALLING,		// state 1			
    0,
    5,				// 50ms ton min			
    15,				// 150ms ton max		
};
#endif

#ifdef AUSTEL

// message describing state transitions for AUSTEL ring 

static short toned_ring[] ={
    0,				// work out length at run time	
    PC_TONED_ST,
    0,				// ID				

    4,				// number of cadence states	
    1,				// event code			
    1,				// number of tones		
    425,			// f1:  centre frequency	
    100,			// bw1: bandwidth		
    0,				// f2: N/A			
    0,				// bw2: N/A			
    -20,			// A1: -10 dbm0			
    0,				// A2: N/A 			
    0,				// twist: N/A			
    10,				// SNR: 10dB			

    RISING,			// state 0			
    0,
    0,
    0,

    FALLING,		// state 1			
    0,
    32,				// 320ms ton min		
    48,				// 480ms ton max		

    RISING,			// state 2			
    0,
    16,				// 160ms toff min		
    24,				// 240ms toff max		

    FALLING,			// state 3			
    0,
    32,				// 320ms ton min		
    48				// 480ms ton max		

};

// message describing state transitions for AUSTEL busy 

static short toned_busy[] ={
    0,				// work out length at run time	
    PC_TONED_ST,
    0,				// tone detector object ID				

    4,				// number of states		
    2,				// event code			
    1,				// number of tones		
    425,			// f1:  centre frequency	
    100,			// bw1: bandwidth		
    0,				// f2: N/A			
    0,				// bw2: N/A			
    -10,			// A1: -10 dbm0			
    0,				// A2: N/A 			
    0,				// twist: N/A			
    10,				// SNR: 10dB			

    RISING,			// state 0			
    0,
    0,
    0,

    FALLING,		// state 1			
    0,
    30,				// 300ms ton min		
    45,				// 450ms ton max		

    RISING,			// state 2			
    0,
    30,				// 300ms toff min		
    45,				// 450ms toff max		

    FALLING,		// state 3			
    0,
    30,				// 300ms ton min		
    45,				// 450ms ton max		

};
//}}}
#endif
