#include <v_lib.h>

#define	DEC_SIZE	4096
#define	MAX_QUEUE_LEN	(DEC_SIZE * 10)

vboolean play(char *fname)
{
	vhandle_t wavedev;
	vhandle_t in;
	u32_t nc,bps,freq;
	u32_t len,queue_len;
	u8_t decompressed[DEC_SIZE];
	u32_t i,pages;
	u8_t pagebuf[4096];
	in = mp3Open(fname);
//	in = wavOpenRead(fname);
	if(!in)
	{
		return false;
	}
	/* Re-open wave output device, if necessary */
	fileControl(in,pctl_wave_get_sampling_frequency,&freq);
	fileControl(in,pctl_wave_get_bits_per_sample,&bps);
	fileControl(in,pctl_wave_get_num_channels,&nc);
	wavedev = wavePlaybackOpen(nc,freq,bps);
	for(;;)
	{
		len = fileRead(in,decompressed,DEC_SIZE);
		if(!len)
			break;
		len = fileWrite(wavedev,decompressed,len);
		queue_len = 0;
		fileControl(wavedev,pctl_waveout_get_pending_samples,&queue_len);
		while(queue_len > MAX_QUEUE_LEN)
		{
			timeDelay(20);
			queue_len = 0;
			fileControl(wavedev,pctl_waveout_get_pending_samples,&queue_len);
		}
	}
	fileClose(in);
	fileControl(wavedev,pctl_waveout_wait,NULL);
	fileClose(wavedev);
}

int main(int argc, char *argv[])
{
	if(argc != 2)
		return -1;
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	return play(argv[1]) ? 0 : -1;
}
