/*  $Id: soundoutput_generic.cpp,v 1.13 2004/02/01 20:28:56 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#include "Sound/precomp.h"
#include "soundoutput_generic.h"
#include "soundbuffer_session_generic.h"
#include "API/Core/System/threadfunc_v0.h"
#include "API/Sound/soundfilter.h"

/////////////////////////////////////////////////////////////////////////////
// CL_SoundOutput_Generic construction:

CL_SoundOutput_Generic::CL_SoundOutput_Generic(int mixing_frequency) :
	mixing_frequency(mixing_frequency), volume(1.0f), pan(0.0f), ref_count(0)
{
	thread = CL_Thread(new CL_ThreadFunc_Runnable_v0<CL_SoundOutput_Generic>(this, &CL_SoundOutput_Generic::mixer_thread));
}

CL_SoundOutput_Generic::~CL_SoundOutput_Generic()
{
	int size = filters.size();
	for (int i=0; i<size; i++) if (delete_filters[i]) delete filters[i];
}

/////////////////////////////////////////////////////////////////////////////
// CL_SoundOutput_Generic attributes:


/////////////////////////////////////////////////////////////////////////////
// CL_SoundOutput_Generic operations:

void CL_SoundOutput_Generic::add_ref()
{
	ref_count++;
}

void CL_SoundOutput_Generic::release_ref()
{
	if (--ref_count == 0)
	{
		// We shut down the mixer thread here, because in the generic constructor it is too late.
		// The platform specific implementations of soundoutput's destructors get called prior to
		// the generic destructor, so we need to do it here.
		//
		// This is a bit hacky way of doing it - the cleanest solution would have been to detach
		// the mixer code from the output code. If any further hacking is needed on this area,
		// this is what should be done. -- mbn 23. april 2003

		CL_MutexSection mutex_lock(&mutex);
		stop_mixer.set_flag();
		mutex_lock.leave();
		thread.wait();
		delete this;
	}
}

void CL_SoundOutput_Generic::play_session(CL_MutexSharedPtr<CL_SoundBuffer_Session_Generic> session)
{
	CL_MutexSection mutex_lock(&mutex);
	sessions.push_back(session);
}

void CL_SoundOutput_Generic::stop_session(CL_MutexSharedPtr<CL_SoundBuffer_Session_Generic> session)
{
	CL_MutexSection mutex_lock(&mutex);
	sessions.remove(session);
}

/////////////////////////////////////////////////////////////////////////////
// CL_SoundOutput_Generic implementation:

void CL_SoundOutput_Generic::mixer_thread()
{
	int mix_buffer_size = get_fragment_size();
	int *mix_buffers[2];
	mix_buffers[0] = new int[mix_buffer_size];
	mix_buffers[1] = new int[mix_buffer_size];
	int *temp_buffers[2];
	temp_buffers[0] = new int[mix_buffer_size];
	temp_buffers[1] = new int[mix_buffer_size];
	short *stereo_buffer = new short[mix_buffer_size*2];
	memset(stereo_buffer, 0, sizeof(short)*mix_buffer_size*2);

	while (true)
	{
		CL_MutexSection mutex_lock(&mutex);
		if (stop_mixer.get_flag()) break;
		mutex_lock.leave();
		
		// Clear channel mixing buffers:
		memset(mix_buffers[0], 0, sizeof(int)*mix_buffer_size);
		memset(mix_buffers[1], 0, sizeof(int)*mix_buffer_size);

		// Mix playing soundbuffers into mixing buffers:
		mutex_lock.enter();
		std::vector< CL_MutexSharedPtr<CL_SoundBuffer_Session_Generic> > ended_sessions;
		std::list< CL_MutexSharedPtr<CL_SoundBuffer_Session_Generic> >::iterator it;
		for (it = sessions.begin(); it != sessions.end(); ++it)
		{
			CL_MutexSharedPtr<CL_SoundBuffer_Session_Generic> session = *it;
			bool playing = session->mix_to(mix_buffers, temp_buffers, mix_buffer_size, 2);
			if (!playing) ended_sessions.push_back(session);
		}

		// Apply global filters to mixing buffers:
		int size_filters = filters.size();
		int i;
		for (i = 0; i < size_filters; i++)
		{
			filters[i]->filter(mix_buffers, mix_buffer_size, 2);
		}

		// Release any sessions pending for removal:
		int size_ended_sessions = ended_sessions.size();
		for (i = 0; i < size_ended_sessions; i++) stop_session(ended_sessions[i]);

		mutex_lock.leave();

		// Make sure values stay inside 16 bit range:
		for (int chan = 0; chan < 2; chan++)
		{
			for (int k=0; k<mix_buffer_size; k++)
			{
				if      (mix_buffers[chan][k] > 32767)  mix_buffers[chan][k] = 32767;
				else if (mix_buffers[chan][k] < -32767) mix_buffers[chan][k] = -32767;
				else                                    mix_buffers[chan][k] = mix_buffers[chan][k];
			}
		}

		// Calculate volume on left and right channel:
		double left_pan = 1-pan;
		double right_pan = 1+pan;
		if (left_pan < 0.0) left_pan = 0.0;
		if (left_pan > 1.0) left_pan = 1.0;
		if (right_pan < 0.0) right_pan = 0.0;
		if (right_pan > 1.0) right_pan = 1.0;
		if (volume < 0.0) volume = 0.0;
		if (volume > 1.0) volume = 1.0;

		double left_volume = volume * left_pan;
		double right_volume = volume * right_pan;

		// Interleave channels before sending them to sound card:
		short *ptr = stereo_buffer;
		for (int k=0; k<mix_buffer_size; k++)
		{
			*(ptr++) = short(mix_buffers[0][k]*left_volume);
			*(ptr++) = short(mix_buffers[1][k]*right_volume);
		}

		// Send mixed data to sound card:
		write_fragment(stereo_buffer);
		wait();
	}

	delete[] stereo_buffer;
	delete[] mix_buffers[0];
	delete[] mix_buffers[1];
	delete[] temp_buffers[0];
	delete[] temp_buffers[1];
}
