#include <ogcsys.h>
#include <stdio.h>
#include <string.h>
#include "../sound.h"

unsigned long cur_play=0;
int sound_enable=0;
short sound_buf[MAX_SOUND_BANKLEN*4] __attribute__ ((__aligned__ (32)));

static void sound_callback()
{
	if (!sound_enable) {
		return;
	}
	
	DCFlushRange(&sound_buf[cur_play/2], PGA_SAMPLES);
	AUDIO_InitDMA((u32) &sound_buf[cur_play/2], PGA_SAMPLES);
	AUDIO_StartDMA();
	
	cur_play += PGA_SAMPLES;
	if (cur_play>=MAX_SOUND_BANKLEN*4)
		cur_play = 0;
}

void sound_clear()
{
	memset(sound_buf, 0, sizeof(sound_buf));
}

int sound_init()
{
	sound_enable=0;
	sound_clear();
	
	AUDIO_Init(NULL);
	AUDIO_SetDSPSampleRate(AI_SAMPLERATE_48KHZ);
	AUDIO_RegisterDMACallback (sound_callback);
	return 0;
}

void sound_start()
{
	sound_enable = 1;
	sound_callback();
}

void sound_stop()
{
	sound_enable = 0;
	sound_clear();
	AUDIO_StopDMA();
}
