#include "tn_sndfile.h"

int32 TNPlug_TestPlayer (struct TNPlugIFace *Self, uint8 *testme, uint8 *testbuffer,
	uint32 totalsize, uint32 testsize)
{
	SNDFILE *file;
	SF_INFO info;
	file = sf_open((char *)testme, SFM_READ, &info);
	if (file) {
		sf_close(file);
	}
	return file ? PLM_File : 0;
}

BOOL TNPlug_OpenPlayer (struct TNPlugIFace *Self, uint8 *openme, struct TuneNet *inTuneNet) {
	BOOL res = FALSE;

	if (inTuneNet->playmode == PLM_File) {
		struct TNDecHandle *handle;

		dbug(("creating handle\n"));
		handle = IExec->AllocVec(sizeof(*handle), MEMF_SHARED|MEMF_CLEAR);
		inTuneNet->handle = handle;
		if (!handle) goto out;

		dbug(("sf_open()\n"));
		handle->file = sf_open((char *)openme, SFM_READ, &handle->info);
		if (!handle->file) goto out;

		dbug(("channels: %ld\n", handle->info.channels));
		if (handle->info.channels != 1 && handle->info.channels != 2)
			goto out;

		handle->pcm_size = handle->info.samplerate / 30;
		dbug(("pcm_size: %ld\n", handle->pcm_size));
		inTuneNet->pcm[0] = IExec->AllocVec((handle->pcm_size * handle->info.channels) << 1, MEMF_SHARED);
		if (!inTuneNet->pcm[0]) goto out;
		if (handle->info.channels == 2) {
			inTuneNet->pcm[1] = inTuneNet->pcm[0] + 1;
		}

		res = TRUE;
out:
		if (res) {
			dbug(("success\n"));
			inTuneNet->DirectRender = ARender_InternalBuffer;

			inTuneNet->current_subsong = 0;
			inTuneNet->max_subsongs = 0;
			
			inTuneNet->dec_frequency = handle->info.samplerate;
			inTuneNet->dec_channels = handle->info.channels;
			inTuneNet->bitrate = 0;
			inTuneNet->mix_lr = TN_STEREO_50PER;

			inTuneNet->Tune[0] = 0;

			inTuneNet->ms_duration = handle->info.frames * 1000 / handle->info.samplerate;

			inTuneNet->ST_Name[0] = 0;
			inTuneNet->ST_Url[0] = 0;
			inTuneNet->ST_Note[0] = 0;

			inTuneNet->songEOF = TRUE;
		} else {
			dbug(("failure\n"));
			TNPlug_ClosePlayer(Self, inTuneNet);
		}
	}

	return res;
}

void TNPlug_ClosePlayer (struct TNPlugIFace *Self, struct TuneNet *inTuneNet) {
	struct TNDecHandle *handle = inTuneNet->handle;
	if (handle) {
		if (handle->file) sf_close(handle->file);
		IExec->FreeVec(handle);
		inTuneNet->handle = NULL;
	}
	IExec->FreeVec(inTuneNet->pcm[0]);
	inTuneNet->pcm[0] =
	inTuneNet->pcm[1] = NULL;
}
