/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: ppffstrm.cpp,v 1.3.30.1 2004/07/19 21:04:16 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 ***** */

/////////////////////////////////////////////////////////////////////////////
// 
//  Single stream representation of RTP session
//

/////////////////////////////////////////////////////////////////////////////
//  Defines
//
#define MAX_STAT_WINDOW_DURATION	60000	    // 60 seconds
#define MIN_STAT_WINDOW_DURATION	1000	    // 1 second
#define MAX_STAT_WINDOW_SIZE		4000000	    // ~4MB

#define MAX_INITIAL_RESEQ_BUFFER_SIZE	1000
#define PROBATION_PACKET_COUNT		1
#define RESEQ_BUFFER_TIMESPAN		1000	    // in milliseconds

/////////////////////////////////////////////////////////////////////////////
//  Includes
//
#include "hxtypes.h"
#include "hxcom.h"
#include "hxcomm.h"
#include "hxprefs.h"
#include "hxengin.h"
#include "ihxpckts.h"
#include "hxerror.h"
#include "rtspif.h"
#include "rtptypes.h"
#include "rtpwrap.h"

#include "hxslist.h"
#include "hxstring.h"
#include "hxstrutl.h"
#include "chxpckts.h"
#include "hxbuffer.h"
#include "tconverter.h"
#include "asmrulep.h"
#include "hxtick.h"

#include "netbyte.h"

#include "carray.h"
#include "ppbin.h"

#include "ppffsrc.h"

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

/////////////////////////////////////////////////////////////////////////////
// CMember
//
CMember::CMember()
    : m_pSrc(NULL)
    , m_ulSSRC(0)
    , m_pCName(NULL)
    , m_pName(NULL)
    , m_pTool(NULL)
    , m_pEmail(NULL)
    , m_pPhone(NULL)
    , m_pPriv(NULL)
    , m_pLoc(NULL)
    , m_pNote(NULL)
{
    m_binInfo.pos = NULL;
    m_binInfo.lBin = -1;
}

CMember::CMember(CPurePlaySource* pSrc, UINT32 ulSsrc)
    : m_pSrc(pSrc)
    , m_ulSSRC(ulSsrc)
    , m_pCName(NULL)
    , m_pName(NULL)
    , m_pTool(NULL)
    , m_pEmail(NULL)
    , m_pPhone(NULL)
    , m_pPriv(NULL)
    , m_pLoc(NULL)
    , m_pNote(NULL)
{
    m_pSrc->AddRef();
    m_binInfo.pos = NULL;
    m_binInfo.lBin = -1;
}

CMember::~CMember()
{
    HX_DELETE(m_pCName);
    HX_DELETE(m_pName);
    HX_DELETE(m_pTool);
    HX_DELETE(m_pEmail);
    HX_DELETE(m_pPhone);
    HX_DELETE(m_pPriv);
    HX_DELETE(m_pLoc);
    HX_DELETE(m_pNote);

    HX_RELEASE(m_pSrc);
}


/////////////////////////////////////////////////////////////////////////////
// CStream
//
#define RTP_SEQ_MOD		(1 << 16) 
#define MIN_SEQUENTIAL		2
#define MAX_DROPOUT		3000
#define MAX_MISORDER		1000

CStream::CStream(CPurePlaySource* pSrc, 
		 UINT32 ulSsrc, 
		 UINT16 unSeq, 
		 ULONG32 ulHXAFactor,
		 ULONG32 ulRTPFactor,
		 IHXCommonClassFactory* pFactory,
		 BOOL bIsSyncMaster) 
    : m_pSrc(pSrc)
    , m_ulSSRC(ulSsrc)
    , m_pTransBuf(NULL)
    , m_pMasterTSConverter(NULL)
    , m_pLastHXSentRcvdPair(NULL)
{
    IHXTransportSyncServer* pSyncServer = NULL;

    m_pTransBuf = new PacketQueue(MAX_INITIAL_RESEQ_BUFFER_SIZE, 
				  PROBATION_PACKET_COUNT,
				  RESEQ_BUFFER_TIMESPAN,
				  (!pSrc->IsRMSource())); 
    m_pTransBuf->Init(pFactory);

    pSrc->QueryInterface(IID_IHXTransportSyncServer,
			 (void**) &pSyncServer);

    m_Syncer.Init(ulHXAFactor,
		  ulRTPFactor,
		  pSyncServer,
		  bIsSyncMaster);

    HX_RELEASE(pSyncServer);

    Init();
    InitSeqNum(unSeq);
}

CStream::~CStream()
{
    HX_DELETE(m_pMasterTSConverter);
    HX_VECTOR_DELETE(m_pLastHXSentRcvdPair);
    HX_DELETE(m_pTransBuf);
    HX_RELEASE(m_pSrc);
}

void
CStream::Init()
{
    m_pSrc->AddRef();

    m_ulProbation = MIN_SEQUENTIAL;
    m_ulTransit			= 0;		// relative trans time for prev pkt
    m_ulJitter			= 0;		// estimated jitter

    m_pCName = NULL;
    m_pName  = NULL;
    m_pTool  = NULL; 
    m_pEmail = NULL;
    m_pPhone = NULL;
    m_pPriv  = NULL;
    m_pLoc   = NULL;
    m_pNote  = NULL;
		
    m_ulLSR = 0;
    m_ulLastSRArrivalTime = 0;

    m_bInitialPkt = TRUE;

    m_ulStartTimeMS = HX_GET_TICKCOUNT();
    
    // need to calculate offset
    m_ulLastRawRTPTS = 0;
    m_ulLastRTPTS = 0;
    m_ulLastHXTS = 0;
    HX_VECTOR_DELETE(m_pLastHXSentRcvdPair);

    m_bHeardSinceLastTime = TRUE;
    m_ulNumRRIntervals = 0;
    m_unStreamNum = 0; 
    m_bPending = FALSE;
    m_ulLastHXTime = 0;
    m_ulLost = 0;
    m_bMarkedAsEnd = FALSE;
    m_bMadeCut = TRUE;

    m_ulClipBandwidthID = 0;
    m_fTotalBytesRecv = 0.0;
    m_ulStatBytesRecv = 0;
    m_ulStatStartMS = m_ulStartTimeMS;

    m_ulNormal = 0;
    
    m_ulStreamRegId = 0;
}


void
CStream::InitSeqNum(UINT16 unSeq)
{
    m_unMaxSeq			= unSeq;	// highest seq# seen
    m_ulCycles			= 0;		// shifted count of seq#
    m_ulBaseSeq			= unSeq - 1;// base seq#
    m_ulBadSeq			= RTP_SEQ_MOD + 1;		// last 'bad' seq# - 1
    m_ulReceived		= 0;		// packets received
    m_ulExpectedPrior	= 0;		// pkt expected at last interval
    m_ulReceivedPrior	= 0;		// pkt received at last interval
}


// Taken from RFC 1889 Appendix A.1
// with a little modification.
// ...the sequence number is considered valid if it is no more than 
// MAX_DROPOUT ahead of m_ulMaxSeq nor more than MAX_MISORDER behind.
// If the new sequence number is ahead of m_unMaxSeq modulo the RTP sequence
// number range (16 bits), but is smaller than m_unMaxSeq, it has wrqpped around
// and the (shifted) count of sequence number cycle is incremented.  A value
// of TURE is returned to indicate a valid sequence number.
BOOL
CStream::UpdateSeqNum(UINT16 unSeq, ULONG32 ulRTPTS)
{
    INT16 nDelta = unSeq - m_unMaxSeq;
#if 0
#ifdef XXXGo_DEBUG
    if ( m_pLogFile && 1 != nDelta)
    {
	fprintf(m_pLogFile, "Delta = %d\n", nDelta);
    }
#endif
#endif

    if (unSeq == (m_unMaxSeq + 1))
    {
	m_ulNormal++;
    }

    // Source is not valid until MIN_SEQUENTIAL pkts with 
    // sequential sequence numbers have been received
    if (m_ulProbation)
    {
	if (unSeq == (m_unMaxSeq + 1))
	{
	    // pkt is in sequence
	    m_ulProbation--;
	    m_unMaxSeq = unSeq;
	    if (0 == m_ulProbation)
	    {	
		InitSeqNum(unSeq);
		m_ulReceived++;
		return TRUE;
	    }
	}
	else
	{
	    // pkt is NOT in sequence
	    m_ulProbation 	= MIN_SEQUENTIAL - 1;
	    m_unMaxSeq		= unSeq;
	}
	return FALSE;
    }

    if ((nDelta < MAX_DROPOUT) && (nDelta > 0))
    {
	// in order, with permissible gap
	if (unSeq < m_unMaxSeq)
	{
	    // seq# wrapped - count another 64k cycle
	    m_ulCycles += RTP_SEQ_MOD;
	    
#if 0    
#ifdef XXXGo_DEBUG
	    if (m_pLogFile)
	    {    	
		char sz[100]; /* Flawfinder: ignore */
		memset(sz, 0, 100);
		SafeSprintf( sz, 100, "!@#Wrapping\n"
		    "unSeq	    = %d\n"
		    "m_unMaxSeq	    = %d\n"
		    "m_ulCycles	    = %d\n"
		    "unDelta	    = %d\n",
		    unSeq,  
		    m_unMaxSeq, 
		    m_ulCycles,
		    unDelta);
		
		::MessageBox( NULL, sz, "Wrapping Sequence Number", MB_OK );
		//fprintf(m_pLogFile, sz);
	    } 
#endif
#endif	    
	}
	m_unMaxSeq = unSeq;
    }
    else if (nDelta < (-MAX_MISORDER))
    {
	// seq# made a very large jump
	if (unSeq == m_ulBadSeq)
	{
	    // two sequential pkts -- assume that the other side
	    // restarted w/o telling us, so just re-sync
	    // (i.e., pretned this was the first pkt)
	    InitSeqNum(unSeq);
	}
	else
	{
	    
	    m_ulBadSeq	= (unSeq + 1) & (RTP_SEQ_MOD - 1);
	    // (i.e. m_ulBadSeq = unSeq + 1;)
	    return FALSE;
	}
    }
    else
    {
	// duplicate or reordered packet
	//HX_ASSERT(FALSE && "duplicate or reordered pkt in UpdateSeqNum()");
    }
    
    m_ulReceived++;
    return TRUE;
}




// ref 1889 Appendix A.3 & A.8
BOOL
CStream::GetReceptionReport(REF(ReceptionReport) rr)
{
    UINT8 uchFraction = 0;

    /* get  last seq# and pkt loss */
    UINT32 ulExtendedMax = m_ulCycles + m_unMaxSeq; // extended max seq#
    UINT32 ulExpected    = ulExtendedMax - m_ulBaseSeq + 1; // #pkt expected

    // extedned highest seq# reveived
    rr.last_seq = ulExtendedMax;
    // the loss may be negative if there are duplicates
    rr.lost = ulExpected - m_ulReceived; // #pkt lost
    //XXXGH we could use m_ulLost which keeps track of real lost count
    
    /* get a fraction */
    UINT32 ulExpectedInterval = ulExpected - m_ulExpectedPrior;
    m_ulExpectedPrior = ulExpected;

    UINT32 ulReceivedInterval = m_ulReceived - m_ulReceivedPrior;
    m_ulReceivedPrior = m_ulReceived;

    UINT32 ulLostInterval = ulExpectedInterval - ulReceivedInterval;

    if (0 == ulExpectedInterval || 0 >= ulLostInterval)
    {
    	// uchFraction = 0;
    }
    else
    {
    	uchFraction = (UINT8)((ulLostInterval << 8) / ulExpectedInterval);
    }

    // The resulting fraction is an 8-bit fixed point number with 
    // the binary point at the left edge.
    rr.fraction = uchFraction;

    rr.ssrc = m_ulSSRC;
/***************************
****  The rest of stuff need to be tested later.  Im not sure what kind of
****  values Im supposed to get!  look also HandleRT[C]PMsg.
****************************/

    /* get jitter */
    // Jitter is acutally calculated everytime a pkt arrives in 
    rr.jitter = m_ulJitter;

    /* get last SR timestamp (lsr) */
    rr.lsr = m_ulLSR;

    /* get delay since last SR */
    rr.dlsr = m_ulLastSRArrivalTime 
    		? HX_GET_TICKCOUNT() - m_ulLastSRArrivalTime
    		: 0;

    return TRUE;
}

UINT16
CStream::GetPercentDone()
{
    return m_pTransBuf->GetPercentDone();    
}


/* need to send all packets we have buffered to the core. */
BOOL
CStream::MarkAsEnd()
{
    m_bMarkedAsEnd = TRUE;
    SetMinTransportWindowSize(0);
    return TRUE;
}

void
CStream::SetMinTransportWindowSize(INT32 lSize)
{
    m_pTransBuf->SetMinWindowSize(lSize);
}

void
CStream::SetStats(ULONG32 ulPacketTime, ULONG32 ulPacketSize)
{
    ULONG32 ulStatTimeSpan = ulPacketTime - m_ulStatStartMS;

    m_fTotalBytesRecv += ulPacketSize;
    m_ulStatBytesRecv += ulPacketSize;

    if ((ulStatTimeSpan > MAX_STAT_WINDOW_DURATION) ||
	((m_ulStatBytesRecv > MAX_STAT_WINDOW_SIZE) &&
	 (ulStatTimeSpan > MIN_STAT_WINDOW_DURATION)))
    {
	// Move Stat window
	double fByterate = ((double) m_ulStatBytesRecv) / 
			   ((double) ulStatTimeSpan);

	m_ulStatStartMS += (ulStatTimeSpan / 2);
	ulStatTimeSpan = ulPacketTime - m_ulStatStartMS;
	m_ulStatBytesRecv = (ULONG32) (((double) ulStatTimeSpan) * 
				       fByterate + 
				       0.5);
    }
}


void
CStream::UpdateStatistics(IHXRegistry* pReg, ULONG32 ulTimeNow)
{
    HX_ASSERT(0 != m_ulClipBandwidthID);
	
    /*
    * Calculate the number of bits that have come across
    * since the last time we checked
    */
    ULONG32 lTimeElapsed = (ulTimeNow - m_ulStatStartMS);
    ULONG32 ulBandwidth = 0;
    if (lTimeElapsed > 0)
    {
	ulBandwidth = (ULONG32) (((double) m_ulStatBytesRecv) * 
				 8000.0 / 
				 ((double) lTimeElapsed) +
				 0.5);
    }
            
    pReg->SetIntById(m_ulClipBandwidthID, ulBandwidth);
}

BOOL CStream::IsRMStream(void)	    
{ 
    return m_pSrc->IsRMSource(); 
}

CStream::StreamType CStream::GetStreamtype(void)
{
    return m_pSrc->GetStreamType(); 
}

