#include <MediaKit.h>
#include "g_main.h"
#include "m_main.h"

static cFile *smp=0;

static BSubscriber *subs;
static BDACStream *dac;

extern bool nosound;

static bool stream_function(void *userData, char *buffer, size_t count, void *header)
{
	static uint32 index=0;
	int16 *b = (int16 *)buffer;
	int8 *s = (int8 *)smp->data;
	for(int c=0;c<(count/sizeof(int32));c+=4)
	{
		float d1 = s[index+0];
		float d2 = s[index+1];
		b[c*2+0] = b[c*2+1] = (int16)((d1 * 0.25 + d2 * 0.75)*256.0);
		b[c*2+2] = b[c*2+3] = (int16)((d1 * 0.50 + d2 * 0.50)*256.0);
		b[c*2+4] = b[c*2+5] = (int16)((d1 * 0.75 + d2 * 0.25)*256.0);
		b[c*2+6] = b[c*2+7] = (int16)((d2                   )*256.0);
		index++;
		if(index>=(smp->len-1))return FALSE;
	}
	return TRUE;
}

void    s_init(void) 
{
	if(!nosound)
	{
		if(smp=m_loadfile("sfx/sample.raw"))
		{
			subs = new BSubscriber("Yeha!");
			dac = new BDACStream();
			if(subs->Subscribe(dac)!=B_NO_ERROR)
			{
				nosound=true;
			}	
		}
		else
		{
			nosound=true;
		}
	}
}

void    s_start(void) 
{
	if(!nosound)
	{
		subs->EnterStream(NULL,true,NULL,stream_function,NULL,true);
	}
}

void    s_play(int) 
{
	// void
}

void    s_shutdown(void) 
{
	if(!nosound)
	{
		if(smp) m_freefile(smp);
		subs->ExitStream();
		delete subs;
	}
}

