/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: CHXEQProcessor.cpp,v 1.1.20.3 2004/07/09 01:49:47 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "CHXEQProcessor.h"

#include "enter_hx_headers.h"
#include "hxcore.h"
#include "ihxpckts.h"

#include "hxsmartptr.h"
HX_SMART_POINTER_INLINE( SPIHXAudioPlayer, IHXAudioPlayer );
HX_SMART_POINTER_INLINE( SPIHXAudioHookManager, IHXAudioHookManager );
HX_SMART_POINTER_INLINE( SPIHXAudioDeviceManager, IHXAudioDeviceManager );
#include "exit_hx_headers.h"

CHXEQProcessor::~CHXEQProcessor( void )
{
	DestroyEQData();
	m_pAudioPlayer->Release();
}

CHXEQProcessor::CHXEQProcessor( IHXPlayer* pIHXPlayer )
	: m_lCount( 0 )
	, m_pAudioPlayer( NULL )
	, m_pEQData( NULL )
	, m_HasHookedAudio( false )
	, m_IsEnabled( false )
	, m_IsAutoPreGainEnabled( false )
	, m_PreGain( 0 )
	, m_RoomSize( 0 )
	, m_Reverb( 0 )
{
	SPIHXAudioPlayer( pIHXPlayer ).AsPtr( &m_pAudioPlayer );
	memset( &m_AudioFormat, 0, sizeof( m_AudioFormat ) );
	memset( m_Gains, 0, sizeof( m_Gains ) );
}

DEFINE_SINGLE_INTERFACE_COMPONENT( CHXEQProcessor, IHXAudioHook, m_lCount )

void
CHXEQProcessor::HookAudio( void )
{
	if ( !m_HasHookedAudio )
	{
		// XXXSEH: This method should allow for independent EQ settings per Player instance.
		// However, CHXAudioPlayer::ActualAddPostMixHook() fails since m_pPMixHookList is NULL and is never actually created in this file.
		//static const HXBOOL kEnableWrite = FALSE;
		//static const HXBOOL kIsFinal = TRUE; // XXXSEH: What does this mean?
		//m_HasHookedAudio = ( 0 != SUCCEEDED( m_pAudioPlayer->AddPostMixHook( this, kEnableWrite, kIsFinal ) ) );

		SPIHXAudioHookManager spAudioHookManager = m_pAudioPlayer;
		if ( spAudioHookManager.IsValid() )
		{
			m_HasHookedAudio = ( 0 != SUCCEEDED( spAudioHookManager->AddHook( this ) ) );
			return;
		}
		SPIHXAudioDeviceManager spAudioDeviceManager = m_pAudioPlayer;
		if ( spAudioDeviceManager.IsValid() )
		{
			m_HasHookedAudio = ( 0 != SUCCEEDED( spAudioDeviceManager->SetFinalHook( this ) ) );
			return;
		}
	}
}

void
CHXEQProcessor::UnhookAudio( void )
{
	if (  m_HasHookedAudio )
	{
		//( void ) m_pAudioPlayer->RemovePostMixHook( this );

		SPIHXAudioHookManager spAudioHookManager = m_pAudioPlayer;
		if ( spAudioHookManager.IsValid() )
		{
			spAudioHookManager->RemoveHook( this );
		}
		else
		{
			SPIHXAudioDeviceManager spAudioDeviceManager = m_pAudioPlayer;
			if ( spAudioDeviceManager.IsValid() )
			{
				spAudioDeviceManager->RemoveFinalHook( this );
			}
		}
		m_HasHookedAudio = false;
		
		// Clear EQ Data and audio format. Since we're no longer hooked, we have no way of knowing whether the format will subsequently change.
		DestroyEQData();
		memset( &m_AudioFormat, 0, sizeof( m_AudioFormat ) );
	}
}

void
CHXEQProcessor::DestroyEQData( void )
{
	if ( m_pEQData )
	{
		::EQFree( m_pEQData );
		m_pEQData = NULL;
	}
}

bool
CHXEQProcessor::SetupEQData( void )
{
	DestroyEQData();
	if ( m_AudioFormat.ulSamplesPerSec > 0 )
	{
		m_pEQData = ::EQInit( m_AudioFormat.ulSamplesPerSec, m_AudioFormat.uChannels );
		if ( m_pEQData )
		{
			::EQSetGain( m_pEQData, m_Gains );
			::EQEnableAutoPreGain( m_pEQData, ( m_IsAutoPreGainEnabled ? 1 : 0 ) );
			if ( !m_IsAutoPreGainEnabled )
			{
				::EQSetPreGain( m_pEQData, m_PreGain );
			}
			::EQSetReverb( m_pEQData, m_RoomSize, m_Reverb );
			
			return true;
		}
	}
	return false;
}

STDMETHODIMP
CHXEQProcessor::OnInit( HXAudioFormat* pFormat )
{
	if ( !pFormat ) return HXR_INVALID_PARAMETER;
	
	m_AudioFormat = *pFormat;
	if ( m_IsEnabled )
	{
		SetupEQData();
	}
	return HXR_OK; // XXXSEH: When would we return a different value?
}

STDMETHODIMP
CHXEQProcessor::OnBuffer( HXAudioData* pAudioInData, HXAudioData* pAudioOutData )
{
	if ( pAudioInData && pAudioInData->pData && pAudioOutData )
	{
		if ( m_IsEnabled && m_pEQData )
		{
			short* inPCMData = ( short* ) pAudioInData->pData->GetBuffer();
			short* outPCMData = inPCMData; // XXXSEH: Modify this inline. Don't know why Windows doesn't do this.
			int numOfSamples = pAudioInData->pData->GetSize() / sizeof( short );
			( void ) ::EQProcess( m_pEQData, inPCMData, outPCMData, numOfSamples );
		}
		HX_RELEASE( pAudioOutData->pData );
		pAudioOutData->pData = pAudioInData->pData;
		HX_ADDREF( pAudioOutData->pData ); // Caller assumes this had been AddRef'd, so let's oblige
	}
	return HXR_OK; // XXXSEH: When would we return a different value?
}

void
CHXEQProcessor::Enable( bool enable )
{
	if ( !m_IsEnabled != !enable )
	{
		m_IsEnabled = enable;
		if ( m_IsEnabled )
		{
			if ( m_AudioFormat.ulSamplesPerSec > 0 )
			{
				SetupEQData(); // XXXSEH: If this fails, should we reset m_IsEnabled?
			}
		}
		else
		{
			DestroyEQData();
		}
	}
}

void
CHXEQProcessor::SetGain( int band, int gain )
{
	if ( ( 0 <= band ) && ( band < EQ_MAXBANDS ) )
	{
		int newGain = gain;
		if ( newGain < EQ_MINGAIN ) newGain = EQ_MINGAIN;
		else if ( newGain > EQ_MAXGAIN ) newGain = EQ_MAXGAIN;
		
		if ( m_Gains[ band ] != newGain )
		{
			m_Gains[ band ] = newGain; // XXXSEH: Should this be limited to specific values as in Jukebox?
			if ( m_pEQData )
			{
				::EQSetGain( m_pEQData, m_Gains );
			}
		}
	}
}

int
CHXEQProcessor::GetGain( int band ) const
{
	return ( ( 0 <= band ) && ( band < EQ_MAXBANDS ) ) ? m_Gains[ band ] : 0;
}

void
CHXEQProcessor::SetPreGain( int preGain )
{
	int newPreGain = preGain;
	if ( newPreGain < EQ_MINGAIN ) newPreGain = EQ_MINGAIN;
	else if ( newPreGain > EQ_MAXGAIN ) newPreGain = EQ_MAXGAIN;
	
	if ( m_PreGain != newPreGain )
	{
		m_PreGain = newPreGain;
		if ( m_pEQData && !m_IsAutoPreGainEnabled )
		{
			::EQSetPreGain( m_pEQData, m_PreGain );
		}
	}
}

int
CHXEQProcessor::GetPreGain( void ) const
{
	return m_PreGain; // XXXSEH: Jukebox returns ::EQGetPreGain(...). If this value differs from m_PreGain, sync. up m_PreGain with it on setting it.
}

void
CHXEQProcessor::EnableAutoPreGain( bool enableAutoPreGain )
{
	if ( !m_IsAutoPreGainEnabled != !enableAutoPreGain )
	{
		m_IsAutoPreGainEnabled = enableAutoPreGain;
		if ( m_pEQData )
		{
			::EQEnableAutoPreGain( m_pEQData, ( m_IsAutoPreGainEnabled ? 1 : 0 ) );
			if ( !m_IsAutoPreGainEnabled )
			{
				::EQSetPreGain( m_pEQData, m_PreGain );
			}
		}
	}
}

void
CHXEQProcessor::SetReverb( int roomSize, int reverb )
{
    // Negative args can be passed in to set only reverb or roomsize
	int newRoomSize = ( roomSize < 0 ) ? m_RoomSize : roomSize;
	int newReverb = ( reverb < 0 ) ? m_Reverb : reverb;
	if ( ( m_RoomSize != newRoomSize ) || ( m_Reverb != newReverb ) )
	{
		m_RoomSize = newRoomSize;
		m_Reverb = newReverb;
		if ( m_pEQData )
		{
			::EQSetReverb( m_pEQData, m_RoomSize, m_Reverb );
		}
	}
}

void
CHXEQProcessor::GetReverb( int* pRoomSize, int* pReverb ) const
{
	// XXXSEH: Jukebox returns ::EQGetReverb(...). If these values differ from the data members, sync. them up on setting them.
	if ( pRoomSize ) *pRoomSize = m_RoomSize;
	if ( pReverb ) *pReverb = m_Reverb;
}
