HRESULT CBSoundAVI::InitializeBuffer(PAVISTREAM Stream)
{
	if(!Stream) return E_FAIL;

	SetStreaming(true);
	m_Type = SOUND_SFX;
	m_Looping = false;

	m_AudioStream = Stream;

	LONG FormatSize;
	if(AVIStreamReadFormat(m_AudioStream, 0, NULL, &FormatSize)!=0) return E_FAIL;

	LPWAVEFORMAT Format = (LPWAVEFORMAT)new BYTE[FormatSize];
	if(AVIStreamReadFormat(m_AudioStream, 0, Format, &FormatSize)!=0){
		delete [] (BYTE*)Format;
		return E_FAIL;
	}
	
	m_TotalDataLength = AVIStreamLength(m_AudioStream) * Format->nBlockAlign;


	HRESULT ret;

	memcpy(&m_Format, Format, sizeof(PCMWAVEFORMAT));
	m_Format.wf.wFormatTag = WAVE_FORMAT_PCM;
	
	// create buffer
	ret = CreateSoundBuffer(m_TotalDataLength, (PCMWAVEFORMAT*)Format);

	
	delete [] (BYTE*)Format;

	return ret;
}
WTErr WCMRAudioDevice::ResetDevice ()
{
	// Keep device sates
	bool wasStreaming = Streaming();
	bool wasActive = Active();

	WTErr err = SetStreaming(false);

	if (err == eNoErr)
		err = SetActive(false);

	if (err == eNoErr && wasActive)
		err = SetActive(true);

	if (err == eNoErr && wasStreaming)
		SetStreaming(true);

	return err;
}
void StreamService::operator()()
{
	Thread loadThread("Loader");
	loadThread.startThread(std::ref(loader));

	currentBuffer = &streamBufferA;

	UInt32 bufferOffset = 0;
	loader.ReadyForData();
	InitialDataMove(bufferOffset);
	StartProcessing();

	while (IsStreaming())
	{
		coordCV.wait(lock);

		StreamBuffer* currBuff = GetActiveBuffer();
		
		musicRef->PushData(currBuff, ByteSubmissionAmount, bufferOffset);

		bufferOffset += ByteSubmissionAmount;

		if (bufferOffset >= currBuff->numBytesInBuffer)
		{
			if (LastBuffer)
			{
				musicRef->StopProcessing();
				SetStreaming(FALSE);
			}
			currBuff->hasData = FALSE;
			SwapActiveBuffer();
			bufferOffset = 0;
			loader.ReadyForData();
		}
	}

	loadThread.join();

	streamer->StreamEnded(this);
}
void StreamService::StreamFinished()
{
	SetStreaming(FALSE);

}