/******* application API layer for the mixer..	************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

#include "modsnd.h"
#include "mixer.h"
#include "doscalls.h"
#include "modplay.h" // the mod player.

static short InMixer=0; // Mixer callback semaphore.

short StartMixer(short installinterrupt)
{
	short active;

	active = StartMod(&InMixer); // Give mod file player startup workspace.

	if ( installinterrupt && active )
	{
		InstallServiceRoutine(MixerCallback,IRATE);
	}
	return(active);
}

void StopMixer(void)
{
	RestoreServiceRoutine(); // replace hardware interrupt if installed.
	StopMod();
}

void TriggerStop(short channel)
{
	InMixer = 1;
	ChannelOff(channel);
	InMixer = 0;
}

void TriggerVolume(short channel,short volume)
{
	InMixer = 1;
	ChannelVolume(channel,volume);	// Left channel and/or mono volume.
	InMixer = 0;
}

short TriggerSound(char *sound,unsigned short length,short mode,short volume,short freq)
{
	int i,Active=-1;

	InMixer = 1;

	// Locate first inactive channel.
	for (i=0; i<PHYSICAL && ActiveState(i); i++);

	if ( i < PHYSICAL )
	{
		// *** After locating an available channel, we define it for the mixer.
		SetChannel(sound,length,i,mode);		// Set logical left/mono channel.
		ChannelFreq(i,freq);	// Set this channel frequency up.
		ChannelVolume(i,volume);	// Left channel and/or mono volume.
		// ** Activate it.
		Active = i; // channel number to return.
		SetActive(i); // Make channel active.
	}

	InMixer = 0;	// semaphore off.
	return(Active);
}

short TriggerStatus(short channel) // report status of a channel.
{
	int trig;

	InMixer = 1;
	trig = ChannelState(channel);
	InMixer = 0;
	return( trig );
}

void TriggerFrequency(short channel,short freq) // Change frequency of a channel.
{
	InMixer = 1;
	ChannelFreq(channel,freq);	// Left channel and/or mono volume.
	InMixer = 0;
}

// Hardware interrupt callback from digital mixer.
void cdecl MixerCallback(void)
{
	PollMod();
	MODTimeSlice();
}

char *TriggerLoc(short channel)
{
	return( ChannelLoc(channel) );
}
