/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: pkt_list.cpp,v 1.1.2.1 2004/07/09 01:50:20 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 ***** */

/////////////////////////////////////////////////////////////////////////////
//
//  PKT_LIST.CPP
//
//  SavedPacketData and SavedPacketDataList class implementations.
//
//  SavedPacketData class:
//    - A class SavedPacketData object holds the IHXBuffer of a packet
//	along with the start and end times of the data in the buffer so
//	that the packet can be resent during a dry period in the stream
//	if it is still active, time-wise.  Its ID lets the renderer figure
//	out if it has seen the packet yet or not.
//
//  SavedPacketData class:
//    - A class SavedPacketDataList object holds all the SavedPacketData
//	objects created so far whose end times have not been exceeded.
//	A position pointer into the list is maintained and, every time the
//	stream runs dry for at least NUM_MSEC_OF_DEADTIME_BETWEEN_RESENDS
//	milliseconds, i.e., if the starttime of the latest-created packet
//	is more than that many milliseconds in the future (or, if live, no
//	data has been seen for that many milliseconds), resend the next
//	packet in this list whose (starttime < currenttime < endtime).
//	If the end of the list is reached or if the next SavedPacketData in
//	the list has a (starttime > currenttime), reset the position pointer
//	to the start of the list.  For each SavedPacketData encountered
//	whose (endtime < currenttime), delete it from the list.
//
//


#include <stdio.h>

#include "hxtypes.h"
#include "hxassert.h"

#include "hxslist.h"

#include "hxcom.h"
#include "hxcomm.h"
#include "chxpckts.h"

#include "rt_types.h" //for _CHAR
#include "atotime.h"

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


#include "pkt_list.h"


/////////////////////////////////////////////////////////////////////////////
//class SavedPacketData methods:
/////////////////////////////////////////////////////////////////////////////

SavedPacketData::SavedPacketData(
	IHXBuffer* pIHXBuffer,
	ULONG32 ulStartTimeOfData,
	ULONG32 ulEndTimeOfData,
	ULONG32 ulTimeOfLastSend
	)
	: m_ulID(0L)
{
    m_pIHXBuffer = pIHXBuffer;
    if(m_pIHXBuffer)
    {
	m_pIHXBuffer->AddRef();
    }
    m_ulStartTimeOfData = ulStartTimeOfData;
    m_ulEndTimeOfData = ulEndTimeOfData;
    m_ulTimeOfLastSend = ulTimeOfLastSend;
}


SavedPacketData::~SavedPacketData()
{
    if(m_pIHXBuffer)
    {
	m_pIHXBuffer->Release();
    }
}

/////////////////////////////////////////////////////////////////////////////
//
//  This gets called in response to a <CLEAR> tag being
//  encountered at time ulNewEndTime; if(m_ulStartTimeOfData < ulNewEndTime),
//  this function resets m_ulEndTimeOfData to the lesser of m_ulEndTimeOfData
//  and ulNewEndTime;
//  returns TRUE if change is made to m_ulEndTimeOfData, else FALSE:
//
//  NOTE!!: this class is only used in live text (rtlive module) and thus
//  we can let the third parameter to IsTimeA..SameOrMoreRecentThanTimeB()
//  default to TRUE:
BOOL SavedPacketData::MarkForClear(ULONG32 ulNewEndTime)
{
    if(IsTimeASameOrMoreRecentThanTimeB(ulNewEndTime, m_ulStartTimeOfData))
    {
	if(IsTimeAMoreRecentThanTimeB(m_ulEndTimeOfData, ulNewEndTime))
	{
	    //add -1 to fix 1-millisec overlap problem: if cur time is t
	    // and this object's end time is t, then this object won't
	    // go away right at t because (t<t) evaluates to FALSE, so
	    // we reduce the end time by 1 millisec to ensure that it
	    // goes away at t:
	    // Also, if it ends up being 0, set it to TIME_INFINITY (which
	    // is 0xfffffffe):
	    m_ulEndTimeOfData =
		    (ulNewEndTime>1L? ulNewEndTime-1L:TIME_INFINITY);
	    return TRUE;
	}
	return FALSE;
    }
    return FALSE;
}



/////////////////////////////////////////////////////////////////////////////
//class SavedPacketDataList methods:
/////////////////////////////////////////////////////////////////////////////

SavedPacketDataList::SavedPacketDataList()
	: m_LISTPOSITIONofLastPacketDataSent(0)
	, m_ulLatestInsertedPacketDataID(1L) //Start out with 1; 0 is invalid
	, m_ulTimeOfLastResend(0L)
{
}

SavedPacketDataList::~SavedPacketDataList()
{
    flush();
}

    
LISTPOSITION SavedPacketDataList::GetEndPosition()
{
    if (GetCount() > 0)
    {
	return (SavedPacketData*)GetTailPosition();
    }
    else
    {
	return NULL;
    }
}


/////////////////////////////////////////////////////////////////////////////
//
LISTPOSITION SavedPacketDataList::GetStartPosition()
{
    if (GetCount() > 0)
    {
	return (SavedPacketData*)GetHeadPosition();
    }
    else
    {
	return NULL;
    }
}


/////////////////////////////////////////////////////////////////////////////
//
SavedPacketData* SavedPacketDataList::end() //returns NULL if list is empty.
{
    if (GetCount() > 0)
    {
	return (SavedPacketData*)GetTail();
    }
    else
    {
	return NULL;
    }
}


/////////////////////////////////////////////////////////////////////////////
//
SavedPacketData* SavedPacketDataList::start() //returns NULL if list is empty.
{
    if (GetCount() > 0)
    {
	return (SavedPacketData*)GetHead();
    }
    else
    {
	return NULL;
    }
}


/////////////////////////////////////////////////////////////////////////////
//
BOOL SavedPacketDataList::insertAtEndOfList(SavedPacketData* pSPD)
{
    HX_ASSERT_VALID_PTR(pSPD);
    if (pSPD)
    {
	LISTPOSITION lpos = AddTail(pSPD);
	pSPD->setID(getLatestInsertedPacketDataID());
	incrementLatestInsertedPacketDataID();
	return (lpos!=NULL);
    }
    return FALSE;
}


/////////////////////////////////////////////////////////////////////////////
//
ULONG32 SavedPacketDataList::flush() //Returns number of nodes deleted.
{
    ULONG32 numDeleted = 0L;
    while(nodeCount())
    {
	SavedPacketData* pSPDHead =
		(SavedPacketData*)CHXSimpleList::RemoveHead();
	HX_ASSERT_VALID_PTR(pSPDHead);
	if(pSPDHead) 
	{
	    delete pSPDHead;
	    pSPDHead = NULL;
	    numDeleted++;
	}
    }

    return numDeleted;
}


/////////////////////////////////////////////////////////////////////////////
//
//Returns the next-to-be-resent SavedPacketData.  This function calls
// deleteAllExpiredSPDs() and then bumps the 
// m_LISTPOSITIONofLastPacketDataSent and returns the SavedPacketData
// found there.
// Returns NULL if fails to find a node that is valid at current time:
//
// NOTE!!: this class is only used in live text (rtlive module) and thus
// we can let the third parameter to IsTimeA..SameOrMoreRecentThanTimeB()
// default to TRUE:
SavedPacketData* SavedPacketDataList::getNextPacketDataToBeResent(
	ULONG32 ulCurrentTime)
{
    if(!size())
    {
	return NULL;  //there's nothing in the list.
    }
    
    ULONG32 ulNumDeleted = deleteAllExpiredSPDs(ulCurrentTime);

    if(!m_LISTPOSITIONofLastPacketDataSent)
    {
	m_LISTPOSITIONofLastPacketDataSent = GetStartPosition();
    }
    if(!m_LISTPOSITIONofLastPacketDataSent)
    {
	return NULL; //list is empty, so we're done.
    }

    SavedPacketData* pSPD = (SavedPacketData*)GetAt(
	    m_LISTPOSITIONofLastPacketDataSent);
    if(!pSPD)
    {
	m_LISTPOSITIONofLastPacketDataSent = GetStartPosition();

	if(!m_LISTPOSITIONofLastPacketDataSent)
	{
	    return NULL; //list is empty, so we're done.
	}
    }
    else
    {
	if(IsTimeAMoreRecentThanTimeB(
		pSPD->getStartTimeOfData(), ulCurrentTime))
	{
	    //Don't send pSPD because it's not time yet for it,
	    // so go back to the start of the list:
	    m_LISTPOSITIONofLastPacketDataSent = GetStartPosition();
	    SavedPacketData* pSPD = (SavedPacketData*)GetAt(
		    m_LISTPOSITIONofLastPacketDataSent);

	    HX_ASSERT_VALID_PTR(pSPD);
	    if(pSPD)
	    {
		if(IsTimeAMoreRecentThanTimeB(
			pSPD->getStartTimeOfData(), ulCurrentTime))
		{
		    //there are no time-active SPDs in the list:
		    return NULL;
		}
		else
		{
		    GetNext(m_LISTPOSITIONofLastPacketDataSent);
		    return pSPD;
		}
	    }
	    return NULL; //GetAt() failed.
	}
	else
	{
	    //increment m_LISTPOSITIONofLastPacketDataSent and return pSPD:
	    GetNext(m_LISTPOSITIONofLastPacketDataSent);
	    return pSPD;
	}
    }

    return NULL; //GetAt() failed.
}

/////////////////////////////////////////////////////////////////////////////
//
//  If <CLEAR> tag is sent, effective at time t, then this function is
//  called to change all in this list whose m_ulEndTimeOfData is > t;
//  Returns the number of nodes in the list whose endTimes were reduced to t:
//
ULONG32 SavedPacketDataList::MarkAllForClear(ULONG32 ulTimeOfClear)
{
    ULONG32 listSize = size();
    ULONG32 numSPDsWhoseEndTimesWereReduced = 0L;

    if(listSize)
    {
	LISTPOSITION pos = GetStartPosition();

	while(pos)
	{
	    SavedPacketData* pSPD = (SavedPacketData*)GetAt(pos);

	    HX_ASSERT_VALID_PTR(pSPD);
	    if(pSPD)
	    {
		if(pSPD->MarkForClear(ulTimeOfClear))
		{
		    numSPDsWhoseEndTimesWereReduced++;
		}
	    }

	    GetNext(pos);
	} //end "while(pos)".
    } //end "if(listSize)".	
    return numSPDsWhoseEndTimesWereReduced;
}


/////////////////////////////////////////////////////////////////////////////
//
// This function allows the file format or encoder to delete all in this list
// whose end times are earlier than the current time;
// Returns the number of nodes in the list that were deleted:
//
//  NOTE!!: this class is only used in live text (rtlive module) and thus
//  we can let the third parameter to IsTimeA..SameOrMoreRecentThanTimeB()
//  default to TRUE:
//
ULONG32 SavedPacketDataList::deleteAllExpiredSPDs(ULONG32 ulCurrentTime)
{
    ULONG32 listSize = size();
    ULONG32 numSPDsDeleted = 0L;

    if(listSize)
    {
	//start @ tail so GetPrev() is always valid after a RemoveAt(pos):
	LISTPOSITION pos = GetEndPosition();

	//Now, delete all the expired SPDs:
	while(pos)
	{
	    SavedPacketData* pSPD = (SavedPacketData*)GetAt(pos);

	    HX_ASSERT_VALID_PTR(pSPD);
	    if(pSPD)
	    {
		if(IsTimeASameOrMoreRecentThanTimeB(
			pSPD->getEndTimeOfData(), ulCurrentTime))
		{
		    GetPrev(pos); //Keep this one in the list.
		    continue;
		}

		SavedPacketData* pTempSPD = (SavedPacketData*)GetAt(pos);

		if(pos == m_LISTPOSITIONofLastPacketDataSent)
		{
		    GetNext(m_LISTPOSITIONofLastPacketDataSent);
		}
		
		pos = RemoveAt(pos);//returns pos of NEXT (or prev if at end)

		HX_ASSERT_VALID_PTR(pTempSPD);
		if(pTempSPD)  
		{
		    delete pTempSPD;
		    pTempSPD = NULL;
		    numSPDsDeleted++;
		}

		LISTPOSITION endPos = GetEndPosition();
		if(!pos  ||  !endPos)
		{
		    m_LISTPOSITIONofLastPacketDataSent = NULL;
		    break; //list is empty, so we're done.
		}
		
		if(pos != endPos)
		{
		    GetPrev(pos);
		}
		//else we're already at previous node.

		continue; //RemoveAt() already moved us back in the list.
	    }

	    GetPrev(pos);
	} //end "while(pos)".
    } //end "if(listSize)".	
    return numSPDsDeleted;   
}

