/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: hxsched.cpp,v 1.6.20.1 2004/07/09 02:06:33 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 "hxcom.h"
#include "hxtypes.h"
#include "hxresult.h"

#ifdef _WINDOWS
#include <windows.h>
#endif

#include "timeval.h"
#include "clientpq.h"
#include "ihxpckts.h"
#include "hxfiles.h"
#include "hxengin.h"
#include "hxcore.h"
#include "hxprefs.h"
#include "timeline.h"
#include "hxtick.h"
#ifdef _MACINTOSH
#include "hx_moreprocesses.h"
#endif

#if defined(_WIN32) || defined(THREADS_SUPPORTED)
#include "casyntim.h"
#endif /*_WIN32*/

#include "hxthread.h"

#include "hxsched.h"

#include "hxheap.h"
#ifdef _DEBUG
#undef HX_THIS_FILE		
static const char HX_THIS_FILE[] = __FILE__;
#endif

#if defined(_WINDOWS) && !defined(_WIN32)   /* WIN16 */
#define MINIMUM_GRANULARITY   55
#elif defined (_MACINTOSH)		    /* MACINTOSH */
#define MINIMUM_GRANULARITY   20
#elif defined (_UNIX)
#define MINIMUM_GRANULARITY   20
#else					    /* ELSE */
#define MINIMUM_GRANULARITY   20
#endif 

#define MINIMUM_DIFFERENCE    5

// HXScheduler...
HXScheduler::HXScheduler(IUnknown* pContext) :
     m_lRefCount (0)
    ,m_pScheduler(0)
    ,m_pInterruptTimeScheduler(0)
    ,m_pID(0)
    ,m_pContext(pContext)
    ,m_bLocked(FALSE)
    ,m_bUseDeferredTask(TRUE)

#if defined(_WIN32) || defined(THREADS_SUPPORTED)
    ,m_pAsyncTimer(0)
#endif 
    ,m_pTimeline(0)
    ,m_ulCurrentGranularity(0)
    ,m_pCoreMutex(NULL)
    ,m_ulLastUpdateTime(0)
    ,m_bIsInterruptEnabled(FALSE)
    ,m_ulSystemNextDueTime(0)
    ,m_ulInterruptNextDueTime(0)
    ,m_headTime(0)
    ,m_interruptHeadTime(0)
    ,m_bImmediatesPending(0)
{
    m_pID			= new CHXID(100);
    m_pScheduler		= new ClientPQ(m_pID);
    m_pInterruptTimeScheduler	= new ClientPQ(m_pID);

    (void) gettimeofday(&m_CurrentTimeVal, 0);
    m_ulLastUpdateTime = HX_GET_TICKCOUNT();

}

HXScheduler::~HXScheduler()
{
    StopScheduler();

    HX_DELETE(m_pScheduler);
    HX_DELETE(m_pInterruptTimeScheduler);
    HX_DELETE(m_pID);

#if defined(_WIN32) || defined(THREADS_SUPPORTED)
    HX_DELETE(m_pAsyncTimer);
#endif 
    HX_DELETE(m_pTimeline);
}

/*
 * IUnknown methods
 */



/////////////////////////////////////////////////////////////////////////
//	Method:
//		IUnknown::QueryInterface
//	Purpose:
//		Implement this to export the interfaces supported by your 
//		object.
//
STDMETHODIMP HXScheduler::QueryInterface(REFIID riid, void** ppvObj)
{
#ifdef _MACINTOSH
    if (IsEqualIID(riid, IID_IHXInterruptState) && m_pContext)
    {
	return m_pContext->QueryInterface(riid, ppvObj);
    }
#endif

    QInterfaceList qiList[] =
        {
            { GET_IIDHANDLE(IID_IHXScheduler), (IHXScheduler*)this },
            { GET_IIDHANDLE(IID_IUnknown), (IUnknown*)(IHXScheduler*)this },
        };
    
    return ::QIFind(qiList, QILISTSIZE(qiList), riid, ppvObj);
}

/////////////////////////////////////////////////////////////////////////
//	Method:
//		IUnknown::AddRef
//	Purpose:
//		Everyone usually implements this the same... feel free to use
//		this implementation.
//
STDMETHODIMP_(ULONG32) HXScheduler::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

/////////////////////////////////////////////////////////////////////////
//	Method:
//		IUnknown::Release
//	Purpose:
//		Everyone usually implements this the same... feel free to use
//		this implementation.
//
STDMETHODIMP_(ULONG32) HXScheduler::Release()
{
    if (InterlockedDecrement(&m_lRefCount) > 0)
    {
	return m_lRefCount;
    }

    delete this;
    return 0;
}


/*
 * HXScheduler methods
 */
/************************************************************************
 *	Method:
 *		IHXScheduler::Enter
 *	Purpose:
 *		enter objects in the service queue
 */
STDMETHODIMP_(CallbackHandle)
HXScheduler::RelativeEnter(IHXCallback* pCallback, ULONG32 ulTime)
{
    /*
     * A RelativeEnter() of 0 ms is a special case that needs to be
     * AbsoluteEnter() of 0
     */
    if (ulTime == 0)
    {
	HXTimeval rVal;

	rVal.tv_sec = rVal.tv_usec = 0;
	return AbsoluteEnter(pCallback, rVal);
    }

    UINT32  usecs = 0;
    UINT32  secs = 0;
    Timeval lTime;

    // handle the possible overflow of UINT32 when
    // converting from milli-second to micro-second
    if (ulTime > 4000000)
    {
	secs = ulTime / 1000;
	usecs = (ulTime % 1000) * 1000;
    }
    else
    {
	secs = 0;
	usecs = ulTime * 1000;

	if (usecs >= 1000000)
	{
	    secs = usecs / 1000000;
	    usecs = usecs % 1000000;
	}
    }

    lTime.tv_sec    = secs;
    lTime.tv_usec   = usecs;

    Timeval now;
    now.tv_sec	= m_CurrentTimeVal.tv_sec;
    now.tv_usec = m_CurrentTimeVal.tv_usec;
    now += lTime;
    
    if (pCallback)
    {
	IHXInterruptSafe* pInterruptSafeCB = NULL;
	if(HXR_OK == pCallback->QueryInterface(IID_IHXInterruptSafe, 
				(void**) &pInterruptSafeCB))
	{
	    if (pInterruptSafeCB && pInterruptSafeCB->IsInterruptSafe())
	    {
    		CallbackHandle hCallback = (CallbackHandle) m_pInterruptTimeScheduler->
    							enter(now, pCallback);
	        pInterruptSafeCB->Release();
	        return hCallback;
	    }
	    pInterruptSafeCB->Release();
	}
    }
    
    return (CallbackHandle) m_pScheduler->enter(now, pCallback);
}

/************************************************************************
 *	Method:
 *	    IHXScheduler::AbsoluteEnter
 *	Purpose:
 *	    enter objects in the service queue at absolute time
 */
STDMETHODIMP_(CallbackHandle)
HXScheduler::AbsoluteEnter(IHXCallback* pCallback, HXTimeval tVal)
{
    Timeval lTime;

    lTime.tv_sec    = tVal.tv_sec;
    lTime.tv_usec   = tVal.tv_usec;

    if (pCallback)
    {
	IHXInterruptSafe* pInterruptSafeCB = NULL;
	if(HXR_OK == pCallback->QueryInterface(IID_IHXInterruptSafe, 
				(void**) &pInterruptSafeCB))
	{
	
	    if (pInterruptSafeCB && pInterruptSafeCB->IsInterruptSafe())
	    {
    		CallbackHandle hCallback = (CallbackHandle) m_pInterruptTimeScheduler->
    								enter(lTime, pCallback);
	        pInterruptSafeCB->Release();
	        return hCallback;
	    }
	    pInterruptSafeCB->Release();
	}
    }

    return (CallbackHandle) m_pScheduler->enter(lTime, pCallback);
}

/************************************************************************
 *	Method:
 *		IHXScheduler::Remove
 *	Purpose:
 *		remove objects from the service queue
 */
STDMETHODIMP HXScheduler::Remove(CallbackHandle Handle)
{
    if (m_pInterruptTimeScheduler->removeifexists(Handle))
    {
    	return HXR_OK;
    }

    m_pScheduler->remove(Handle);
    return HXR_OK;
}

/************************************************************************
 *	Method:
 *	    IHXScheduler::GetCurrentSchedulerTime
 *	Purpose:
 *	    gives the current time in the timeline of the scheduler...
 */
STDMETHODIMP_(HXTimeval) HXScheduler::GetCurrentSchedulerTime(void)
{
    HXTimeval hxTimeval;
    hxTimeval.tv_sec = m_CurrentTimeVal.tv_sec;
    hxTimeval.tv_usec = m_CurrentTimeVal.tv_usec;
    return hxTimeval;
}


/************************************************************************
 *	Method:
 *		OnTimeSync
 *	Purpose:
 *		TBD
 *
 */
HX_RESULT HXScheduler::OnTimeSync(BOOL bAtInterrupt)
{
    HX_RESULT theErr = HXR_OK;
    
    if (m_pCoreMutex)
    {
	m_pCoreMutex->Lock();
    }

    if (!m_bLocked)
    {
	m_bLocked = TRUE;
	theErr = ExecuteCurrentFunctions (bAtInterrupt);
	m_bLocked = FALSE;
    }

    if (m_pCoreMutex)
    {
	m_pCoreMutex->Unlock();
    }
    return theErr;
}

HX_RESULT HXScheduler::ExecuteCurrentFunctions(BOOL bAtInterrupt)
{
    BOOL bShouldServiceSystem	    = FALSE;
    BOOL bShouldServiceInterrupt    = FALSE;
    BOOL bImmediatesPending	    = FALSE;
    BOOL bInterruptImmediatesPending = FALSE;

    if (FALSE == UpdateCurrentTime(bAtInterrupt, bShouldServiceSystem, bShouldServiceInterrupt))
    {
        return HXR_OK;
    }

    /* if not at interrupt time, execute interrupt safe & 
     * non-interrupt safe tasks 
     */
    if( bShouldServiceInterrupt && !m_pInterruptTimeScheduler->empty() )
    {
	m_pInterruptTimeScheduler->execute(m_CurrentTimeVal);
	/*
	 * Don't execute more then 100 immediate elements.  We don't wanna
	 * hold on too long and spin here.
	 */
	int count = 0;
	// Keep executing until there are no more zero time elements
	while ((bInterruptImmediatesPending = m_pInterruptTimeScheduler->immediate()) && 
	       (count < 100))
	{
            count += m_pInterruptTimeScheduler->execute(m_CurrentTimeVal);
	}
    }

    if (bShouldServiceSystem && !m_pScheduler->empty())
    {
	m_pScheduler->execute(m_CurrentTimeVal);
	/*
	 * Don't execute more then 100 immediate elements.  We don't wanna
	 * hold on too long and spin here.
	 */
	int count = 0;
	// Keep executing until there are no more zero time elements
	while ((bImmediatesPending = m_pScheduler->immediate()) && 
	       (count < 100))
	{
	    count += m_pScheduler->execute(m_CurrentTimeVal);
	}

#if defined(_WIN32) || defined(THREADS_SUPPORTED)
	BOOL bChange = FALSE;
	if (m_pScheduler->empty())
        {
            if (m_ulCurrentGranularity < MINIMUM_GRANULARITY &&
		(MINIMUM_GRANULARITY - m_ulCurrentGranularity >= 
						MINIMUM_DIFFERENCE))
	    {
		bChange = TRUE;
		m_ulCurrentGranularity = MINIMUM_GRANULARITY;
	    }
        }
        else if (m_ulCurrentGranularity > MINIMUM_DIFFERENCE)
        {
	    Timeval timeout	  = m_pScheduler->head_time() - m_CurrentTimeVal;
	    INT32  lTimeoutInMs;
	    
	    if (timeout.tv_sec >= 0)
	    {
		lTimeoutInMs = timeout.tv_sec * 1000 + 
			       timeout.tv_usec / 1000;
	    }
	    else
	    {
		lTimeoutInMs = 0;
	    }

	    if (lTimeoutInMs > 0 &&
		(UINT32) lTimeoutInMs < m_ulCurrentGranularity &&
		(m_ulCurrentGranularity - (UINT32) lTimeoutInMs >= 
					    MINIMUM_DIFFERENCE))
	    {
		bChange = TRUE;
		m_ulCurrentGranularity = (UINT32) ((lTimeoutInMs >= MINIMUM_DIFFERENCE ? 
						lTimeoutInMs: MINIMUM_DIFFERENCE));
	    }
	}

	if (bChange)
	{
		m_pTimeline->Pause();
		/* Reset the granularity */
		m_pTimeline->SetGranularity(m_ulCurrentGranularity);
		/* Resume */
		m_pTimeline->Resume();
	}
#endif /*_WIN32*/
    }

    m_bImmediatesPending = bImmediatesPending || bInterruptImmediatesPending;

    Timeval timeout;
    if (!m_pScheduler->empty())
    {
	timeout = m_pScheduler->head_time() - m_CurrentTimeVal;
	if (timeout.tv_sec >= 0)
	{
	    m_ulSystemNextDueTime = (UINT32) (timeout.tv_sec*1000+timeout.tv_usec/1000);
	}
	else
	{
	    m_ulSystemNextDueTime = 0;
	}
    }
    else
    {
	m_ulSystemNextDueTime = m_ulCurrentGranularity;
    }

    if (!m_pInterruptTimeScheduler->empty())
    {
	timeout = m_pInterruptTimeScheduler->head_time() - m_CurrentTimeVal;
	
	if (timeout.tv_sec >= 0)
	{
	    m_ulInterruptNextDueTime = (UINT32) (timeout.tv_sec*1000+timeout.tv_usec/1000);
	}
	else
	{
	    m_ulInterruptNextDueTime = 0;
	}
    }
    else
    {
	m_ulInterruptNextDueTime = m_ulCurrentGranularity;
    }

    return HXR_OK;
}

BOOL HXScheduler::IsEmpty() 
{
    return (m_pScheduler->empty() && m_pInterruptTimeScheduler->empty());
}

BOOL	HXScheduler::GetNextEventDueTimeDiff(ULONG32 &ulEarliestDueTimeDiff)
{
    if (m_pScheduler->empty() && m_pInterruptTimeScheduler->empty())
	return FALSE;

    Timeval nextDueTime;
    Timeval now;
    now.tv_sec	= m_CurrentTimeVal.tv_sec;
    now.tv_usec = m_CurrentTimeVal.tv_usec;

    if (m_pScheduler->empty())
    {
	nextDueTime = m_pInterruptTimeScheduler->head_time();
    }
    else if (m_pInterruptTimeScheduler->empty())
    {
	nextDueTime = m_pScheduler->head_time();
    }
    else
    {
	if (m_pInterruptTimeScheduler->head_time() < m_pScheduler->head_time())
	{
	    nextDueTime = m_pInterruptTimeScheduler->head_time();
	}
	else
	{
	    nextDueTime = m_pScheduler->head_time();
	}
    }


    if (nextDueTime > now)
    {
	nextDueTime -= now;
    }
    else
    {
	nextDueTime = 0.0;
    }

    ulEarliestDueTimeDiff = (ULONG32) (	nextDueTime.tv_sec*1000 + 
					nextDueTime.tv_usec/1000);

    return TRUE;
}

HX_RESULT    HXScheduler::StartScheduler()
{
    return StartSchedulerImplementation(FALSE);
}

HX_RESULT    HXScheduler::StartSchedulerTimerFixup()
{
    return StartSchedulerImplementation(TRUE);
}

HX_RESULT    HXScheduler::StartSchedulerImplementation(BOOL TimerFixup)
{
    HX_RESULT theErr = HXR_OK;
    /* Stop any already running scheduler*/
    StopScheduler();
    (void) gettimeofday((Timeval*)&m_CurrentTimeVal, 0);
    m_ulLastUpdateTime = HX_GET_TICKCOUNT();

#if defined(_WIN32) || defined(THREADS_SUPPORTED)
    if (m_bIsInterruptEnabled)
    {
	if (!m_pAsyncTimer)
	{
	    m_pAsyncTimer = new CAsyncTimer(this);
	}

	if (!m_pAsyncTimer)
	{
	    return HXR_OUTOFMEMORY;
	}

	m_pAsyncTimer->SetGranularity(MINIMUM_GRANULARITY);
        theErr = m_pAsyncTimer->StartTimer();
    }
#endif // _WIN32 || THREADS_SUPPORTED

    if (!m_pTimeline)
    {
	m_pTimeline = new Timeline;
    }

    if (m_pTimeline)
    {
	m_pTimeline->Init( (IUnknown*) (IHXScheduler*) this, m_bUseDeferredTask);
#if defined(_MACINTOSH) && defined(THREADS_SUPPORTED)
	m_pTimeline->SetCoreMutex(m_pCoreMutex);
#endif
	m_pTimeline->SetStartTime(0);
	m_ulCurrentGranularity = MINIMUM_GRANULARITY;
	m_pTimeline->SetGranularity(m_ulCurrentGranularity);	
	if (TimerFixup)
	    m_pTimeline->SetTimerFixup(TRUE);
	m_pTimeline->Resume();
    }
    else
    {
	theErr = HXR_OUTOFMEMORY;
    }
    return theErr;
}


void HXScheduler::StopScheduler()
{
#if defined(_WIN32) || defined(THREADS_SUPPORTED)
    if (m_pAsyncTimer)
    {
	m_pAsyncTimer->StopTimer();
    }
#endif    
    if (m_pTimeline)
    {
	m_pTimeline->Pause();
	m_pTimeline->Done();
    }
}



BOOL HXScheduler::IsAtInterruptTime(void)
{
#ifdef _MACINTOSH
    return !IsMacInCooperativeThread();
#elif defined (_WIN32)  || defined(THREADS_SUPPORTED)
    return (m_bIsInterruptEnabled &&
	    m_pAsyncTimer->InTimerThread());
#endif
    return FALSE;
}

BOOL HXScheduler::UpdateCurrentTime(BOOL bAtInterrupt, BOOL& bShouldServiceSystem, 
                                     BOOL& bShouldServiceInterrupt)
{
    BOOL    bResult = TRUE;

#if defined(_WINDOWS) || defined(_WIN32) || defined (_MACINTOSH) || defined(THREADS_SUPPORTED)

    UINT32 ulCurrentTime = HX_GET_TICKCOUNT();
    UINT32 ulElapsedTime = CALCULATE_ELAPSED_TICKS(m_ulLastUpdateTime, ulCurrentTime);

//    UINT32 ulCurrentTimeBetter = HX_GET_BETTERTICKCOUNT();
//{FILE* f1 = ::fopen("d:\\temp\\better.txt", "a+"); ::fprintf(f1, "Diff %lu %lu %lu %lu\n", ulCurrentTime, ulCurrentTimeBetter, ulElapsedTime, CALCULATE_ELAPSED_TICKS(ulCurrentTimeBetter, ulCurrentTime));::fclose(f1);}

    if (ulElapsedTime >= m_ulInterruptNextDueTime)
    {
	bShouldServiceInterrupt = TRUE;
    }

    if (!bAtInterrupt &&
	ulElapsedTime >= m_ulSystemNextDueTime)
    {
	bShouldServiceSystem = TRUE;
    }

//{FILE* f1 = ::fopen("d:\\temp\\pq.txt", "a+"); ::fprintf(f1, "\nUpdateCurrentTime %d %lu", m_ulCoreThreadID == GetCurrentThreadId(), CALCULATE_ELAPSED_TICKS(m_ulLastUpdateTime, ulCurrentTime));::fclose(f1);}
    if (bShouldServiceSystem || bShouldServiceInterrupt)
    {
	m_CurrentTimeVal    += (1000 * ulElapsedTime);
	m_ulLastUpdateTime  = ulCurrentTime;
    }
#else
    if (!bAtInterrupt)
    {
	bShouldServiceSystem    = TRUE;
    }

    bShouldServiceInterrupt = TRUE;
    (void) gettimeofday(&m_CurrentTimeVal, 0);
#endif

    if (!(bShouldServiceSystem || bShouldServiceInterrupt))
    {
	bResult = FALSE;

	if (!m_pScheduler->empty() &&
	    m_pScheduler->head_time() != m_headTime)
	{
	    m_headTime = m_pScheduler->head_time();
	    bResult = TRUE;
	}
	    
	if (!m_pInterruptTimeScheduler->empty() &&
	    m_pInterruptTimeScheduler->head_time() != m_interruptHeadTime)
	{
	    m_interruptHeadTime = m_pInterruptTimeScheduler->head_time();
	    bResult = TRUE;
	}
    }

    return bResult;
}

void HXScheduler::NotifyPlayState(BOOL bInPlayingState)
{
#if defined(_WIN32) || defined(THREADS_SUPPORTED)
    if (m_pAsyncTimer)
    {
	m_pAsyncTimer->NotifyPlayState(bInPlayingState);
    }
#endif
}

