/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: h261vidfmt.cpp,v 1.1.8.2 2004/07/26 19:51:40 milko 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 ***** */

/****************************************************************************
 * 
 *  H261 video renderer format - data type specifc portion of the
 *  renderer.
 *
 */

/****************************************************************************
 *  Defines
 */
// #define _SKIP_DECODE
#define _PAD_PACKET_BUFFERS

#define NON_KEYFRM_DCDE_FALLBEHIND_THRSHLD  33	// in milliseconds
#define BUFFER_PADDING_SIZE		    4	// in bytes

/****************************************************************************
 *  Includes
 */
#include "h261vidfmt.h"

#include "hxasm.h"
#include "hxwin.h"
#include "hxvsurf.h"
#include "hxvctrl.h"
#include "hxsite2.h"
#include "hxthread.h"

#include "hxtick.h"
#include "hxassert.h"
#include "hxstrutl.h"
#include "unkimp.h"
#include "timeval.h"
#include "cttime.h"

#include "h261video.h"


/****************************************************************************
 *  Locals
 */


/****************************************************************************
 *  Method:
 *    CQTVideoFormat::CQTVideoFormat
 *
 */
CH261VideoFormat::CH261VideoFormat(IHXCommonClassFactory* pCommonClassFactory,
				   CH261VideoRenderer* pH261VideoRenderer,
                   BOOL bSecure)
    : CVideoFormat(pCommonClassFactory, pH261VideoRenderer)
    , m_pH261VideoRenderer(pH261VideoRenderer)
    , m_pAssmDims(NULL)
{
    HX_ASSERT(m_pCommonClassFactory);
    HX_ASSERT(pH261VideoRenderer);

    m_pH261VideoRenderer->AddRef();
}


/****************************************************************************
 *  Method:
 *    CQTVideoFormat::~CQTVideoFormat
 *
 */
CH261VideoFormat::~CH261VideoFormat()
{
    HX_RELEASE(m_pH261VideoRenderer);

    _Reset();
}


/****************************************************************************
 *  Method:
 *    CQTVideoFormat::Init
 *
 */
HX_RESULT CH261VideoFormat::Init(IHXValues* pHeader)
{
    HX_RESULT retVal = CVideoFormat::Init(pHeader);

    return retVal;
}


/****************************************************************************
 *  Method:
 *    CQTVideoFormat::CreateAssembledPacket
 *
 */
CMediaPacket* CH261VideoFormat::CreateAssembledPacket(IHXPacket* pCodecData)
{
    CMediaPacket* pFramePacket = NULL;

    if (!pCodecData->IsLost())
    {	
	IHXBuffer* pBuffer = pCodecData->GetBuffer();
	ULONG32 ulFlags = 0;
	UINT8* pData = NULL;
	
	if (pCodecData->GetASMRuleNumber() == 1)
	{
	    ulFlags |= MDPCKT_HAS_MARKER_FLAG;
	}

	// MBO Test
#ifndef _PAD_PACKET_BUFFERS
	ulFlags |= MDPCKT_USES_IHXBUFFER_FLAG;

	pData = pBuffer->GetBuffer();
#else	// _PAD_PACKET_BUFFERS
	pData = new UINT8 [pBuffer->GetSize() + BUFFER_PADDING_SIZE];

	if (pData)
	{
	    memcpy(pData, pBuffer->GetBuffer(), pBuffer->GetSize()); /* Flawfinder: ignore */
	    memset(pData + pBuffer->GetSize(), 0, BUFFER_PADDING_SIZE);
	}

	if (pData)
#endif	// _PAD_PACKET_BUFFERS
	{
	    pFramePacket = new CMediaPacket(pData,
					    pData, 
					    pBuffer->GetSize(),
					    pBuffer->GetSize(),
					    pCodecData->GetTime(),
					    ulFlags,
					    NULL);
	}
	
	HX_RELEASE(pBuffer);
    }
    else
    {
	m_pH261VideoRenderer->ReportLostFrame();
    }

    return pFramePacket;
}


/****************************************************************************
 *  Method:
 *    CQTVideoFormat::Reset
 *
 */
void CH261VideoFormat::Reset()
{
    _Reset();
    CVideoFormat::Reset();
}

void CH261VideoFormat::_Reset(void)
{
    HX_DELETE(m_pAssmDims);
}


/****************************************************************************
 *  Method:
 *    CQTVideoFormat::CreateDecodedPacket
 *
 */
CMediaPacket* CH261VideoFormat::CreateDecodedPacket(CMediaPacket* pFrameToDecode)
{
    ULONG32 ulFrameSize;
    LONG32 lTimeAhead;
    HXxSize* pFrameDims = NULL;
    CMediaPacket* pDecodedFrame = NULL;
    UINT8* pData = NULL;

#ifdef _SKIP_DECODE
    if (pFrameToDecode != NULL)
    {
	pFrameToDecode->Clear();
	delete pFrameToDecode;
    }

    return NULL;
#endif	// _SKIP_DECODE

    // Decode
    lTimeAhead = m_pH261VideoRenderer->ComputeTimeAhead(
		    pFrameToDecode->m_ulTime, 
		    0);
    
    if ((!m_pH261VideoRenderer->IsActive()) ||
	(lTimeAhead >= (-NON_KEYFRM_DCDE_FALLBEHIND_THRSHLD)))
    {
	H261Decoder::recv(((pFrameToDecode->m_ulFlags & MDPCKT_HAS_MARKER_FLAG) != 0), 
			  pFrameToDecode->m_pData, 
			  pFrameToDecode->m_ulDataSize);

	HX_ASSERT(codec_);
    }
    else
    {
	m_pH261VideoRenderer->ReportDroppedFrame();
    }
        
    if (frame_needs_rendering_)
    {
	frame_needs_rendering_ = FALSE;

	// Determine Frame Size
	if (frame_needs_resizing_ || (!m_pAssmDims))
	{
	    HXxSize FrameDims;
	    
	    frame_needs_resizing_ = FALSE;
	    
	    FrameDims.cx = codec_->width();
	    FrameDims.cy = codec_->height();
	    
	    if (!m_pAssmDims)
	    {
		m_pAssmDims = new HXxSize;
		pFrameDims = new HXxSize;
		
		if (pFrameDims && m_pAssmDims)
		{
		    *m_pAssmDims = *pFrameDims = FrameDims;
		    m_pH261VideoRenderer->ResizeViewFrame(FrameDims);
		}
		else
		{
		    HX_DELETE(m_pAssmDims);
		    HX_DELETE(pFrameDims);
		}
	    }
	    else
	    {
		if (*m_pAssmDims != FrameDims)
		{
		    pFrameDims = new HXxSize;
		    
		    if (pFrameDims)
		    {
			*pFrameDims = FrameDims;
		    }
		    else
		    {
			HX_DELETE(m_pAssmDims);
		    }
		}
	    }
	}

	// Get the storage for the Decode Buffer
	ulFrameSize = (ULONG32) codec_->frame_size();
	
	if (ulFrameSize > 0)
	{
	    CMediaPacket* pVideoPacket = NULL;
	    
	    pVideoPacket = (CMediaPacket*) m_pFramePool->Get(ulFrameSize);
	    
	    if (pVideoPacket)
	    {
		pData = pVideoPacket->m_pData;
		
		HX_ASSERT(pData);
		
		pVideoPacket->Init(pData,
				   ulFrameSize,
				   pFrameToDecode->m_ulTime,
				   0,
				   pFrameDims);
		
		pFrameDims = NULL;
		
		pDecodedFrame = pVideoPacket;
	    }
	    else
	    {
		pData = new UINT8 [ulFrameSize];
	    }
	}

	// Transfer Decoded frame
	if (pData)
	{
	    memcpy(pData, codec_->frame(), ulFrameSize); /* Flawfinder: ignore */
	}
    }
	    
    // If the frame is not formed yet, form it
    if (!pDecodedFrame)
    {
	if (pData)
	{
	    // Data exists to form the docoded packet with
	    pFrameToDecode->SetBuffer(pData,
				      pData,
				      ulFrameSize, 
				      ulFrameSize);

	    pDecodedFrame = pFrameToDecode;
	    pFrameToDecode = NULL;

	    pDecodedFrame->SetSampleDesc(pFrameDims);
	    pFrameDims = NULL;
	}
	else if (pFrameDims)
	{
	    // No data exists to form the frame with, but description
	    // exists and must be passed down the pipe - form empty 
	    // frame packet
	    pDecodedFrame = pFrameToDecode;
	    pDecodedFrame->m_pData = NULL;
	    pDecodedFrame->m_ulDataSize = 0;
	    pFrameToDecode = NULL;

	    pDecodedFrame->SetSampleDesc(pFrameDims);
	    pFrameDims = NULL;
	}
    }
  
    if (pDecodedFrame)
    {
	pDecodedFrame->SetSampleDescKiller(
	    pDecodedFrame->m_pSampleDesc ? KillH261SampleDesc : NULL);
    }

    if (pFrameToDecode != NULL)
    {
	pFrameToDecode->Clear();
	delete pFrameToDecode;
    }

    HX_DELETE(pFrameDims);
    
    return pDecodedFrame;
}


/****************************************************************************
 *  Method:
 *    CH261VideoFormat::IsBitmapFormatChanged
 *
 */
BOOL CH261VideoFormat::IsBitmapFormatChanged(
			    HXBitmapInfoHeader &BitmapInfoHeader,
			    CMediaPacket* pVideoPacket)
{
    if (pVideoPacket->m_pSampleDesc != NULL)
    {
	HXxSize* pDims = (HXxSize*) pVideoPacket->m_pSampleDesc;

	if ((BitmapInfoHeader.biWidth != pDims->cx) ||
	    (BitmapInfoHeader.biHeight != pDims->cy))
	{
	    return TRUE;
	}
    }

    return FALSE;
}


/****************************************************************************
 *  Method:
 *    CH261VideoFormat::InitBitmapInfoHeader
 *
 */
HX_RESULT CH261VideoFormat::InitBitmapInfoHeader(
    HXBitmapInfoHeader &bitmapInfoHeader,
    CMediaPacket* pVideoPacket)
{
    HXxSize* pDims = (HXxSize*) pVideoPacket->m_pSampleDesc;

    if (pDims)
    {
	bitmapInfoHeader.biWidth = pDims->cx;
	bitmapInfoHeader.biHeight = pDims->cy;
	bitmapInfoHeader.biSizeImage = bitmapInfoHeader.biWidth * 
				       bitmapInfoHeader.biHeight * 
				       bitmapInfoHeader.biBitCount / 
				       8;
    }

    return HXR_OK;
}


/****************************************************************************
 *  Method:
 *    CH261VideoFormat::KillH261ampleDesc
 *
 */
void CH261VideoFormat::KillH261SampleDesc(void* pSampleDesc, void* pUserData)
{
    if (pSampleDesc)
    {
	HXxSize* pFrameDims = (HXxSize*) pSampleDesc;

	delete pFrameDims;
    }
}
