#include <PushGameSound.h>
#include <GameSoundDefs.h>

#include "quakedef.h"

#define BUFFER_FRAME_COUNT 1024

int snd_inited;

//static int tryrates[] = { 11025, 22051, 44100, 8000 };

BPushGameSound	*gs = NULL;
void			*base = NULL;
size_t			size = 0;

qboolean SNDDMA_Init(void)
{
	gs_audio_format	gs_fmt;
	gs_fmt.format = gs_audio_format::B_GS_S16;
	gs_fmt.frame_rate = 22050;
	gs_fmt.channel_count = 2;
	gs_fmt.byte_order = 2;
	gs_fmt.buffer_size = BUFFER_FRAME_COUNT * 2 * 2;

	gs = new BPushGameSound( BUFFER_FRAME_COUNT, &gs_fmt );
	if(gs->InitCheck() != B_OK)
	{
		printf("sound InitCheck failed\n");
		delete gs;
		gs = NULL;
		return qfalse;
	}

	// get access to the complete buffer
	if(BPushGameSound::lock_failed == gs->LockForCyclic(&base, &size))
	{
		printf("sound: lock failed\n");
		delete gs;
		gs = NULL;
		return qfalse;
	}
	
	// at this point base points to the first byte of the audio buffer and
	// size is the total size of this buffer in bytes
	shm = &sn;
	shm->splitbuffer = qfalse;
	shm->submission_chunk = 1;

	shm->samplebits = 16;
	shm->speed = 22050;
	shm->channels = 2;
	shm->samples = size / (shm->samplebits/8);
	shm->buffer = (unsigned char*)base;
	shm->samplepos = 0;
	if(gs->StartPlaying() == B_OK)
	{
		snd_inited = 1;
		return qtrue;
	}
	else
	{
		gs->UnlockCyclic();
		delete gs;
		gs = NULL;
		return qfalse;
	}
}

int SNDDMA_GetDMAPos(void)
{
	if(!snd_inited) return 0;

	shm->samplepos = gs->CurrentPosition()/(shm->samplebits/8);
	return shm->samplepos;
}

void SNDDMA_Shutdown(void)
{
	if(snd_inited)
	{
		gs->StopPlaying();
		gs->UnlockCyclic();
	}
	delete gs;
	gs = NULL;
	snd_inited = 0;
}

/*
==============
SNDDMA_Submit

Send sound to device if buffer isn't really the dma buffer
===============
*/
void SNDDMA_Submit(void)
{
}

