/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: src/drivers/wintel32/audio/fmod/fmodsampledata.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/audio/audio.hpp"

#include "drivers/wintel32/audio/fmod.hpp"

CFMODSampleData::CFMODSampleData(const sgxString &filename, const CSGXAudioEngine::ResourceContext context, FMOD_SYSTEM *pSystem) 
	: CSampleData(filename, context)
{
	m_pSystem = pSystem;
	if (context == CSGXAudioEngine::eDiscStream) {
		FMOD_System_CreateStream(m_pSystem, filename.c_str(), FMOD_DEFAULT, NULL, &m_pHandle);
	} else {
		FMOD_System_CreateSound(m_pSystem, filename.c_str(), FMOD_DEFAULT, NULL, &m_pHandle);
	}
	FMOD_Sound_SetLoopCount(m_pHandle, 0);

}

tREAL32
CFMODSampleData::getDuration() const
{
	unsigned int length = 0;
	FMOD_Sound_GetLength(m_pHandle, &length, FMOD_TIMEUNIT_MS);
	return length / 1000.0f;
}


CDeviceChannel * 
CFMODSampleData::play(CLogicalChannel *pLogicalChannel) 
{
	if (pLogicalChannel == NULL) {
		pLogicalChannel = CSGXAudioEngine::get()->getFreeChannel();
	}
	if (pLogicalChannel == NULL) {
		return NULL;
	}

	CFMODSoundEngine *pEngine = (CFMODSoundEngine *)CFMODSoundEngine::get();
	CFMODDeviceChannel *pDevice = pEngine->m_pDeviceChannel[pLogicalChannel->m_iIndex];
	
	FMOD_System_PlaySound(m_pSystem, FMOD_CHANNEL_REUSE, m_pHandle, TRUE, &pDevice->m_pChannel);
	
	CMixOutput output;
	CSGXAudioEngine::get()->evaluateMixerChain(&output, pLogicalChannel, 0);
	
	pDevice->refreshChannel(&output);
	FMOD_Channel_SetLoopCount(pDevice->m_pChannel, pLogicalChannel->m_pMixChannel->m_bLoop?-1:0);
	
	if (!pLogicalChannel->m_pMixChannel->m_bStartPaused) {
		FMOD_Channel_SetPaused(pDevice->m_pChannel, FALSE);
	}

	return (CDeviceChannel *)pDevice;
}

