/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: pximgfil.cpp,v 1.1.26.1 2004/07/09 01:54:51 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
#include "hxtypes.h"
#include "hxwintyp.h"
#include "hxcom.h"
#include "hxresult.h"
#include "hxcomm.h"
#include "ihxpckts.h"

// hxcont
#include "hxslist.h"
#include "hxstring.h"
#include "hxmap.h"

// hxmisc
#include "baseobj.h"
#include "unkimp.h"

// pxcomlib
#include "pxrect.h"
#include "pxcolor.h"
#include "pxeffect.h"
#include "wirefmgr.h"
#include "pxffmcod.h"
#include "pxcmpmgr.h"
#include "pxffcmgr.h"
#include "pximgfil.h"

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

PXImageFile::PXImageFile(PXWireFormatManager*      pWireFormatManager,
                         PXFileFormatCodecManager* pCodecManager,
                         IHXCommonClassFactory*   pCommonClassFactory)
{
    HX_ASSERT(pWireFormatManager);
    if (pWireFormatManager)
    {
        m_pWireFormatManager = pWireFormatManager;
        m_pWireFormatManager->AddRef();
    }
    HX_ASSERT(pCodecManager);
    if (pCodecManager)
    {
        m_pCodecManager = pCodecManager;
        m_pCodecManager->AddRef();
    }
    HX_ASSERT(pCommonClassFactory);
    if (pCommonClassFactory)
    {
        m_pCommonClassFactory = pCommonClassFactory;
        m_pCommonClassFactory->AddRef();
    }
    m_lRefCount     = 0;
    m_ulHandle      = 0;
    m_ulNumPackets  = 0;
    m_ulTotalBytes  = 0;
    m_ulImageWidth  = 0;
    m_ulImageHeight = 0;
    m_pPacketList   = NULL;
    m_pCookieList   = NULL;
    m_pListItr      = NULL;
}

PXImageFile::~PXImageFile()
{
    Deallocate();
};

void PXImageFile::Deallocate()
{
    HX_RELEASE(m_pWireFormatManager);
    HX_RELEASE(m_pCodecManager);
    HX_RELEASE(m_pCommonClassFactory);
    ReleaseAllPackets();
    ClearCookieList();
    HX_DELETE(m_pPacketList);
    HX_DELETE(m_pCookieList);
}

void PXImageFile::ReleaseAllPackets()
{
    if (m_pPacketList)
    {
        LISTPOSITION pos = m_pPacketList->GetHeadPosition();
        while (pos)
        {
            IHXPacket* pPacket = (IHXPacket*) m_pPacketList->GetNext(pos);
            HX_RELEASE(pPacket);
        }
        m_pPacketList->RemoveAll();
    }
}

void PXImageFile::ClearCookieList()
{
    if (m_pCookieList)
    {
        LISTPOSITION pos = m_pCookieList->GetHeadPosition();
        while (pos)
        {
            CookiePair* pPair = (CookiePair*) m_pCookieList->GetNext(pos);
            if (pPair)
            {
                HX_RELEASE(pPair->m_pURLStr);
                HX_RELEASE(pPair->m_pCookie);
            }
            HX_DELETE(pPair);
        }
        m_pCookieList->RemoveAll();
    }
}

STDMETHODIMP PXImageFile::QueryInterface(REFIID riid, void** ppvObj)
{
    HX_RESULT retVal = HXR_OK;

    if (IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppvObj = (IUnknown *) this;
    }
    else
    {
        *ppvObj = NULL;
        retVal  = HXR_NOINTERFACE;
    }

    return retVal;
}

STDMETHODIMP_(UINT32) PXImageFile::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

STDMETHODIMP_(UINT32) PXImageFile::Release()
{
    
    if (InterlockedDecrement(&m_lRefCount) > 0)
        return m_lRefCount;

    delete this;

    return 0;
}

HX_RESULT PXImageFile::AddCookie(IHXBuffer* pURLStr, IHXBuffer* pCookie)
{
    HX_RESULT retVal = HXR_OK;

    if (pURLStr && pCookie)
    {
        if (!m_pCookieList)
        {
            m_pCookieList = new CHXSimpleList();
            if (!m_pCookieList)
            {
                retVal = HXR_OUTOFMEMORY;
            }
        }

        if (SUCCEEDED(retVal))
        {
            CookiePair* pPair = new CookiePair;
            if (pPair)
            {
                pPair->m_pURLStr = pURLStr;
                pPair->m_pURLStr->AddRef();
                pPair->m_pCookie = pCookie;
                pPair->m_pCookie->AddRef();
                m_pCookieList->AddTail((void*) pPair);
            }
            else
            {
                retVal = HXR_OUTOFMEMORY;
            }
        }
    }
    else
    {
        retVal = HXR_FAIL;
    }

    return retVal;
}

HX_RESULT PXImageFile::EnqueueCookiePacket()
{
    HX_RESULT retVal = HXR_OK;

    // Add the cookie packet
    if (m_pCookieList)
    {
        if (m_pCookieList->GetCount() > 0)
        {
            IHXBuffer** ppURL = NULL;
            ppURL              = new IHXBuffer* [m_pCookieList->GetCount()];
            if (ppURL)
            {
                IHXBuffer** ppCookie = NULL;
                ppCookie              = new IHXBuffer* [m_pCookieList->GetCount()];
                if (ppCookie)
                {
                    UINT32       i   = 0;
                    LISTPOSITION pos = m_pCookieList->GetHeadPosition();
                    while (pos)
                    {
                        CookiePair* pPair = (CookiePair*) m_pCookieList->GetNext(pos);
                        if (pPair)
                        {
                            ppURL[i]    = pPair->m_pURLStr;
                            ppCookie[i] = pPair->m_pCookie;
                            i++;
                        }
                    }

                    IHXPacket* pPacket = NULL;
                    retVal              = m_pWireFormatManager->SetCookieInfo(m_pCookieList->GetCount(),
                                                                              ppURL,
                                                                              ppCookie,
                                                                              0,
                                                                              pPacket);
                    if (SUCCEEDED(retVal))
                    {
                        // Add this to the packet list
                        // FALSE makes it add at the head instead of tail
                        retVal = AddPacket(pPacket, FALSE);
                    }
                    HX_RELEASE(pPacket);
                }
                HX_VECTOR_DELETE(ppCookie);
            }
            HX_VECTOR_DELETE(ppURL);
            // Clear the cookie list
            ClearCookieList();
        }
    }

    return retVal;
}

HX_RESULT PXImageFile::EnqueueImagePackets(UINT32      ulHandle,
                                           IHXBuffer* pFileBuffer)
{
    HX_RESULT retVal = HXR_FAIL;

    if (ulHandle && pFileBuffer)
    {
        // Save the members
        m_ulHandle = ulHandle;
        // Get a codec to parse this image
        IHXRealPixFileFormatCodec* pCodec = NULL;
        retVal                             = m_pCodecManager->GetCodec(NULL,        // file mime type
                                                                       NULL,        // file name
                                                                       pFileBuffer, // file buffer
                                                                       pCodec);
        if (SUCCEEDED(retVal))
        {
            // Get the mime type for this codec
            const char** ppTmp1        = NULL;
            const char** ppTmp2        = NULL;
            const char*  pszStreamMime = NULL;
            UINT32       ulVer         = 0;
            UINT32       ulMaxPerImg   = 0;
            UINT32       ulMaxPerPckt  = 0;
            retVal                     = pCodec->GetFileFormatCodecInfo(ppTmp1, ppTmp2, pszStreamMime,
                                                                        ulVer, ulMaxPerImg, ulMaxPerPckt);
            if (SUCCEEDED(retVal))
            {
                IHXPacket* pImageHeaderPacket = NULL;
                retVal                         = m_pWireFormatManager->SetImageHeaderInfo(ulHandle,
                                                                                          pFileBuffer->GetSize(),
                                                                                          0,
                                                                                          pszStreamMime,
                                                                                          0,
                                                                                          pImageHeaderPacket);
                if (SUCCEEDED(retVal))
                {
                    // Add image header packet to list tail
                    retVal = AddPacket(pImageHeaderPacket);
                    if (SUCCEEDED(retVal))
                    {
                        // Parse the image
                        UINT32      ulNumDataPackets = 0;
                        IHXValues* pParam           = NULL;
                        UINT32      ulSessionHandle  = 0;
                        retVal                       = pCodec->ParseImage(pFileBuffer,
                                                                          ulNumDataPackets,
                                                                          pParam,
                                                                          ulSessionHandle);
                        if (SUCCEEDED(retVal))
                        {
                            // Get width and height
                            pParam->GetPropertyULONG32("ImageWidth",  m_ulImageWidth);
                            pParam->GetPropertyULONG32("ImageHeight", m_ulImageHeight);
                            // Get all the image data packets
                            for (UINT32 i = 0; i < ulNumDataPackets && SUCCEEDED(retVal); i++)
                            {
                                IHXBuffer* pData   = NULL;
                                IHXBuffer* pOpaque = NULL;
                                BOOL        bReq    = FALSE;
                                retVal              = pCodec->GetImagePacket(ulSessionHandle, i, pData, pOpaque, bReq);
                                if (SUCCEEDED(retVal))
                                {
                                    IHXPacket* pImageDataPacket = NULL;
                                    retVal                       = m_pWireFormatManager->SetImageDataInfo(ulHandle, pData, pOpaque,
                                                                                                          i, 0, bReq, pImageDataPacket);
                                    if (SUCCEEDED(retVal))
                                    {
                                        // Add image data packet to tail of the list
                                        retVal = AddPacket(pImageDataPacket);
                                    }
                                    HX_RELEASE(pImageDataPacket);
                                }
                                HX_RELEASE(pData);
                                HX_RELEASE(pOpaque);
                            }

                            // Now we're done with this parse session
                            pCodec->ReleaseImage(ulSessionHandle);
                        }
                        HX_RELEASE(pParam);
                    }
                }
                HX_RELEASE(pImageHeaderPacket);
            }
        }
        HX_RELEASE(pCodec);
    }

    return retVal;
}

HX_RESULT PXImageFile::EnqueueEffectPacket(UINT32      ulEffectType,
                                           UINT32      ulStart,
                                           UINT32      ulDuration,
                                           UINT32      ulTarget,
                                           const char* pszURL,
                                           UINT32      ulFillColor,
                                           BOOL        bBackChannel,
                                           BOOL        bLastUse,
                                           BOOL        bDisplayImmediately)
{
    HX_RESULT retVal = HXR_OK;

    // Create an effect object
    PXEffect* pEffect = NULL;
    retVal            = PXEffect::CreateObject(&pEffect);
    if (SUCCEEDED(retVal))
    {
        // AddRef the effect
        pEffect->AddRef();
        // Set a bunch of parameters
        pEffect->SetEffectType((BYTE) ulEffectType);
        pEffect->SetStart(ulStart);
        pEffect->SetDuration(ulDuration);
        pEffect->SetTarget(ulTarget);
        if (pszURL)
        {
            pEffect->SetURL(pszURL);
        }
        pEffect->SetColor(ulFillColor);
        pEffect->SetPostBackChannel(bBackChannel);
        pEffect->SetLastUse(bLastUse);
        pEffect->SetDisplayImmediately(bDisplayImmediately);

        // Get the packet
        IHXPacket* pEffectPacket = NULL;
        retVal                     = m_pWireFormatManager->SetEffectInfo(pEffect, 0, pEffectPacket);
        if (SUCCEEDED(retVal))
        {
            // Add the effect packet to the tail
            retVal = AddPacket(pEffectPacket);
        }
        HX_RELEASE(pEffectPacket);
    }
    HX_RELEASE(pEffect);

    return retVal;
}

void PXImageFile::ComputeStatistics()
{
    m_ulNumPackets = 0;
    m_ulTotalBytes = 0;

    if (m_pPacketList)
    {
        if (m_pPacketList->GetCount() > 0)
        {
            // Set the number of packets
            m_ulNumPackets = m_pPacketList->GetCount();
            // Compute the size with overhead
            m_ulTotalBytes   = 0;
            LISTPOSITION pos = m_pPacketList->GetHeadPosition();
            while (pos)
            {
                IHXPacket* pListPacket = (IHXPacket*) m_pPacketList->GetNext(pos);
                if (pListPacket)
                {
                    IHXBuffer *pListBuffer = pListPacket->GetBuffer();
                    if (pListBuffer)
                    {
                        m_ulTotalBytes += pListBuffer->GetSize();
                    }
                    HX_RELEASE(pListBuffer);
                }
            }
        }
    }
}

HX_RESULT PXImageFile::DequeuePacket(REF(IHXPacket*) rpPacket,
                                     UINT32           ulBitrate,
                                     REF(INT32)       rlCurrentTimeStamp)
{
    HX_RESULT retVal = HXR_FAIL;

    if (ulBitrate && m_pPacketList)
    {
        if (m_pPacketList->GetCount() > 0)
        {
            IHXPacket* pPacket = (IHXPacket*) m_pPacketList->RemoveHead();
            if (pPacket)
            {
                UINT32      ulTimeStamp = (UINT32) (rlCurrentTimeStamp >= 0 ? rlCurrentTimeStamp : 0);
                UINT32      ulSize      = 0;
                IHXPacket* pNewPacket  = NULL;
                retVal                  = SetPacketTimeStamp(pPacket, ulTimeStamp,
                                                             ulSize, pNewPacket);
                if (SUCCEEDED(retVal))
                {
                    // Update the time stamp
                    rlCurrentTimeStamp += (INT32) (ulSize * 8000 / ulBitrate);
                    // Assign the out parameter
                    HX_RELEASE(rpPacket);
                    rpPacket = pNewPacket;
                    rpPacket->AddRef();
                }
                HX_RELEASE(pNewPacket);
            }
            HX_RELEASE(pPacket);
        }
    }

    return retVal;
}

HX_RESULT PXImageFile::GetFirstPacket(REF(IHXPacket*) rpPacket)
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pPacketList)
    {
        LISTPOSITION pos = m_pPacketList->GetHeadPosition();
        if (pos)
        {
            IHXPacket* pPacket = (IHXPacket*) m_pPacketList->GetNext(pos);
            if (pPacket)
            {
                HX_RELEASE(rpPacket);
                rpPacket = pPacket;
                rpPacket->AddRef();
                m_pListItr = pos;
                retVal     = HXR_OK;
            }
        }
    }

    return retVal;
}

HX_RESULT PXImageFile::GetNextPacket(REF(IHXPacket*) rpPacket)
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pPacketList && m_pListItr)
    {
        IHXPacket* pPacket = (IHXPacket*) m_pPacketList->GetNext(m_pListItr);
        if (pPacket)
        {
            HX_RELEASE(rpPacket);
            rpPacket = pPacket;
            rpPacket->AddRef();
            retVal   = HXR_OK;
        }
    }

    return retVal;
}

HX_RESULT PXImageFile::SetPacketTimeStamp(IHXPacket*      pPacket,
                                          UINT32           ulTimeStamp,
                                          REF(UINT32)      rulPacketSize,
                                          REF(IHXPacket*) rpPacket)
{
    return FactorySetTimeStamp(pPacket, m_pCommonClassFactory, ulTimeStamp,
                               rulPacketSize, rpPacket);
}

HX_RESULT PXImageFile::FactorySetTimeStamp(IHXPacket*             pPacket,
                                           IHXCommonClassFactory* pFactory,
                                           UINT32                  ulTimeStamp,
                                           REF(UINT32)             rulPacketSize,
                                           REF(IHXPacket*)        rpPacket)
{
    HX_RESULT retVal = HXR_OK;

    if (pPacket && pFactory)
    {
        // Get the packet parameters
        IHXBuffer* pBuffer         = NULL;
        UINT32      ulTime          = 0;
        UINT16      usStreamNumber  = 0;
        UINT8       ucASMFlags      = 0;
        UINT16      usASMRuleNumber = 0;
        retVal                      = pPacket->Get(pBuffer,
                                                   ulTime,
                                                   usStreamNumber,
                                                   ucASMFlags,
                                                   usASMRuleNumber);
        if (SUCCEEDED(retVal))
        {
            // Create a new packet
            IHXPacket* pNewPacket = NULL;
            retVal                 = pFactory->CreateInstance(CLSID_IHXPacket,
                                                              (void**) &pNewPacket);
            if (SUCCEEDED(retVal))
            {
                // Set these values with the new timestamp into the new packet
                retVal = pNewPacket->Set(pBuffer,
                                         ulTimeStamp,
                                         usStreamNumber,
                                         ucASMFlags,
                                         usASMRuleNumber);
                if (SUCCEEDED(retVal))
                {
                    // Assign the out parameters
                    rulPacketSize = pBuffer->GetSize();
                    HX_RELEASE(rpPacket);
                    rpPacket = pNewPacket;
                    rpPacket->AddRef();
                }
            }
            HX_RELEASE(pNewPacket);
        }
        HX_RELEASE(pBuffer);
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

HX_RESULT PXImageFile::AddPacket(IHXPacket* pPacket, BOOL bTail)
{
    HX_RESULT retVal = HXR_OK;

    if (pPacket)
    {
        // Create list if it doesn't exist
        if (!m_pPacketList)
        {
            m_pPacketList = new CHXSimpleList();
            if (!m_pPacketList)
            {
                retVal = HXR_OUTOFMEMORY;
            }
        }

        // AddRef the packet
        pPacket->AddRef();
        if (bTail)
        {
            // Add the packet at the tail
            m_pPacketList->AddTail((void*) pPacket);
        }
        else
        {
            // Add the packet at the head
            m_pPacketList->AddHead((void*) pPacket);
        }
    }
    else
    {
        retVal = HXR_FAIL;
    }

    return retVal;
}

UINT32 PXImageFile::GetNumPacketsLeft() const
{
    return (m_pPacketList ? m_pPacketList->GetCount() : 0);
}

UINT32 PXImageFile::GetTotalSendTime(UINT32 ulBitrate) const
{
    UINT32 ulTime = 0;
    if (ulBitrate)
    {
        ulTime = (m_ulTotalBytes * 8000 + (ulBitrate >> 1)) / ulBitrate;
    }
    return ulTime;
}

UINT32 PXImageFile::GetPacketSendTime(IHXPacket* pPacket, UINT32 ulBitrate)
{
    UINT32 ulTime = 0;
    if (pPacket && ulBitrate)
    {
        IHXBuffer* pBuffer = pPacket->GetBuffer();
        if (pBuffer)
        {
            ulTime = (pBuffer->GetSize() * 8000 + (ulBitrate >> 1)) / ulBitrate;
        }
        HX_RELEASE(pBuffer);
    }
    return ulTime;
}
