/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: pxcgifrn.cpp,v 1.1.26.1 2004/07/09 01:51:31 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 "hxcomm.h"
#include "ihxpckts.h"
#include "hxplugn.h"
#include "hxfiles.h"
#include "hxauth.h"
#include "hxver.h"
#include "hxvsurf.h"

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

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

// pxcomlib
#include "gstring.h"
#include "glist.h"
#include "pxrndcod.h"
#include "pxutil.h"
#include "pxmapmgr.h"

// pxgiflib
#include "lzw.h"
#include "gifimage.h"
#include "gifcodec.h"

// pxcgif2
#include "pxcgifrn.h"
#include "rpgifdll.ver"

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

const char*  CRealPixGIFRendererCodec::m_pszDescription       = "Helix RealPix GIF Renderer Codec Plugin";
const char*  CRealPixGIFRendererCodec::m_pszCopyright         = HXVER_COPYRIGHT;
const char*  CRealPixGIFRendererCodec::m_pszMoreInfoURL       = HXVER_MOREINFO;
const char*  CRealPixGIFRendererCodec::m_ppszFileMimeType[]   = {"image/vnd.rn-realpix.gif", NULL};
const UINT32 CRealPixGIFRendererCodec::m_ulHighestSupportedContentVersion = HX_ENCODE_PROD_VERSION(0, 0, 0, 0);
const UINT32 CRealPixGIFRendererCodec::m_ulHighestSupportedStreamVersion  = HX_ENCODE_PROD_VERSION(0, 0, 0, 0);

CGIFRendererSession::CGIFRendererSession()
{
    m_lRefCount   = 0;
    m_pGIFCodec   = NULL;
    m_ulNumFrames = 0;
    m_pFrameInfo  = NULL;
}

CGIFRendererSession::~CGIFRendererSession()
{
    for (UINT32 i = 0; i < m_ulNumFrames; i++)
    {
        HX_RELEASE(m_pFrameInfo[i].m_pOutputBuffer);
    }
    HX_VECTOR_DELETE(m_pFrameInfo);
    HX_RELEASE(m_pGIFCodec);
}

STDMETHODIMP CGIFRendererSession::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) CGIFRendererSession::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

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

    delete this;

    return 0;
}

CRealPixGIFRendererCodec::CRealPixGIFRendererCodec()
{
    m_lRefCount           = 0;
    m_pContext            = NULL;
    m_pCommonClassFactory = NULL;
    m_pMapManager         = NULL;
}

CRealPixGIFRendererCodec::~CRealPixGIFRendererCodec()
{
    ReleaseAllSessions();
    HX_RELEASE(m_pContext);
    HX_RELEASE(m_pCommonClassFactory);
    HX_RELEASE(m_pMapManager);
}

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

    if (ppvObj)
    {
        // Set default
        *ppvObj = NULL;
        // Check for IID type
        if (IsEqualIID(riid, IID_IUnknown))
        {
            AddRef();
            *ppvObj = (IUnknown*) (IHXPlugin*) this;
        }
        else if (IsEqualIID(riid, IID_IHXPlugin))
        {
            AddRef();
            *ppvObj = (IHXPlugin*) this;
        }
        else if (IsEqualIID(riid, IID_IHXRealPixRendererCodec))
        {
            AddRef();
            *ppvObj = (IHXRealPixRendererCodec*) this;
        }
        else
        {
            retVal = HXR_NOINTERFACE;
        }
    }
    else
    {
        retVal = HXR_FAIL;
    }

    return retVal;
}

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


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

    delete this;

    return 0;
}

STDMETHODIMP CRealPixGIFRendererCodec::GetPluginInfo(REF(BOOL)        bMultipleLoad,
                                                     REF(const char*) pDescription,
                                                     REF(const char*) pCopyright,
                                                     REF(const char*) pMoreInfoURL,
                                                     REF(ULONG32)     ulVersionNumber)
{
    bMultipleLoad   = TRUE;
    pDescription    = m_pszDescription;
    pCopyright      = m_pszCopyright;
    pMoreInfoURL    = m_pszMoreInfoURL;
    ulVersionNumber = TARVER_ULONG32_VERSION;

    return HXR_OK;
}

STDMETHODIMP CRealPixGIFRendererCodec::InitPlugin(IUnknown* pContext)
{
    HX_RESULT retVal = HXR_OK;

    if (pContext)
    {
        // Save a copy of the context
        HX_RELEASE(m_pContext);
        m_pContext = pContext;
        m_pContext->AddRef();

        // Get an IHXCommonClassFactory interface
        HX_RELEASE(m_pCommonClassFactory);
        retVal = m_pContext->QueryInterface(IID_IHXCommonClassFactory,
                                            (void**) &m_pCommonClassFactory);
        if (SUCCEEDED(retVal))
        {
            HX_RELEASE(m_pMapManager);
            m_pMapManager = new PXMapManager();
            if (m_pMapManager)
            {
                m_pMapManager->AddRef();
            }
            else
            {
                retVal = HXR_OUTOFMEMORY;
            }
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::GetRendererCodecInfo(REF(const char**) rppszFileMimeType,
                                                            REF(UINT32)       rulHighestSupportedContentVersion,
                                                            REF(UINT32)       rulHighestSupportedStreamVersion)
{
    rppszFileMimeType                 = m_ppszFileMimeType;
    rulHighestSupportedContentVersion = m_ulHighestSupportedContentVersion;
    rulHighestSupportedStreamVersion  = m_ulHighestSupportedStreamVersion;

    return HXR_OK;
}

STDMETHODIMP CRealPixGIFRendererCodec::ValidInputData(IHXBuffer* pBuffer, REF(BOOL) rbValid)
{
    HX_RESULT retVal = HXR_OK;

    // Set default
    rbValid = FALSE;

    if (pBuffer)
    {
        BYTE* pBuf = pBuffer->GetBuffer();
        if (pBuf)
        {
            if (pBuf[0] == 'G'                     &&
                pBuf[1] == 'I'                     &&
                pBuf[2] == 'F'                     &&
                pBuf[3] == '8'                     &&
                (pBuf[4] == '7' || pBuf[4] == '9') &&
                pBuf[5] == 'a')
            {
                rbValid = TRUE;
            }
        }
        else
        {
            retVal = HXR_FAIL;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::GetHeaderInfo(IHXBuffer*      pBuffer,
                                                     IHXBuffer*      pOpaqueImageData,
                                                     REF(HXxSize)     rImageDim,
                                                     REF(UINT32)      rulNumFrames,
                                                     REF(IHXValues*) rpImageInfo,
                                                     REF(UINT32)      rulSessionHandle)
{
    HX_RESULT retVal = HXR_FAIL;

    if (pBuffer && m_pMapManager)
    {
        // First we create a new CGIFCodec object
        CGIFCodec* pGIFCodec = NULL;
        retVal               = CGIFCodec::CreateObject(&pGIFCodec);
        if (SUCCEEDED(retVal))
        {
            // Addref the object
            pGIFCodec->AddRef();
            // Init decompression
            retVal = pGIFCodec->InitDecompress(pBuffer->GetBuffer(), pBuffer->GetSize());
            if (SUCCEEDED(retVal))
            {
                // Set the need packet flag
                pGIFCodec->SetNeedPacket(FALSE);
                // Set the outgoing parameters
                rImageDim.cx     = pGIFCodec->GetLogicalScreenWidth();
                rImageDim.cy     = pGIFCodec->GetLogicalScreenHeight();
                rulNumFrames     = pGIFCodec->GetNumImages();
                rpImageInfo      = NULL;
                // Create a session object
                CGIFRendererSession* pSession = new CGIFRendererSession();
                if (pSession)
                {
                    // AddRef the object
                    pSession->AddRef();
                    // Set the session parameters
                    pSession->m_pGIFCodec   = pGIFCodec;
                    pSession->m_pGIFCodec->AddRef();
                    pSession->m_ulNumFrames = rulNumFrames;
                    // Allocate an array of FrameInfo structs
                    pSession->m_pFrameInfo  = new CGIFRendererSession::FrameInfo [rulNumFrames];
                    if (pSession->m_pFrameInfo)
                    {
                        // NULL out the frame info structs output buffer pointers
                        for (UINT32 i = 0; i < rulNumFrames; i++)
                        {
                            pSession->m_pFrameInfo[i].m_pOutputBuffer = NULL;
                        }

                        // Add this session to the map
                        retVal = m_pMapManager->AddEntry((void*) pSession, rulSessionHandle);
                        if (SUCCEEDED(retVal))
                        {
                            // AddRef the session since it's now in the map
                            pSession->AddRef();
                            // Create an IHXValues for the image info
                            IHXValues* pImageInfo = NULL;
                            m_pCommonClassFactory->CreateInstance(CLSID_IHXValues, (void**) &pImageInfo);
                            if (pImageInfo)
                            {
                                // Set the loop count in the image info struct
                                pImageInfo->SetPropertyULONG32("LoopCount", pGIFCodec->GetLoopCount());
                                // Assign the out parameter
                                rpImageInfo = pImageInfo;
                                rpImageInfo->AddRef();
                            }
                            HX_RELEASE(pImageInfo);
                        }
                    }
                    else
                    {
                        retVal = HXR_OUTOFMEMORY;
                    }
                }
                else
                {
                    retVal = HXR_OUTOFMEMORY;
                }
                HX_RELEASE(pSession);
            }
        }
        HX_RELEASE(pGIFCodec);
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::GetFrameInfo(UINT32           ulSessionHandle,
                                                    UINT32           ulFrameNum,
                                                    REF(HXxRect)     rFrameDim,
                                                    REF(IHXValues*) rpMoreInfo)
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pMapManager)
    {
        CGIFRendererSession* pSession = NULL;
        m_pMapManager->GetEntry(ulSessionHandle, (void**) &pSession);
        if (pSession)
        {
            if (pSession->m_pGIFCodec)
            {
                if (ulFrameNum < pSession->m_pGIFCodec->GetNumImages())
                {
                    CGIFImage* pImage = pSession->m_pGIFCodec->GetImage(ulFrameNum);
                    if (pImage)
                    {
                        // Set the frame dimensions in the session
                        pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim.left   = pImage->GetImageLeft();
                        pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim.top    = pImage->GetImageTop();
                        pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim.right  = pImage->GetImageLeft() +
                                                                                pImage->GetImageWidth();
                        pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim.bottom = pImage->GetImageTop() +
                                                                                pImage->GetImageHeight();
                        // Set the outgoing frame dimensions
                        rFrameDim = pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim;
                        // Create an IHXValues
                        IHXValues* pValues = NULL;
                        retVal              = m_pCommonClassFactory->CreateInstance(CLSID_IHXValues,
                                                                                    (void**) &pValues);
                        if (pValues)
                        {
                            pValues->SetPropertyULONG32("DelayTime",        pImage->GetDelayTime());
                            pValues->SetPropertyULONG32("DisposalMethod",   pImage->GetDisposalMethod());
			    pValues->SetPropertyULONG32("UsesAlphaChannel", (pImage->Transparent() ? 1 : 0));
                            // Set the outgoing parameter
                            HX_RELEASE(rpMoreInfo);
                            rpMoreInfo = pValues;
                            rpMoreInfo->AddRef();
                            retVal = HXR_OK;
                        }
                        HX_RELEASE(pValues);
                    }
                }
            }
        }
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::SetDecompressParam(UINT32      ulSessionHandle,
                                                          UINT32      ulFrameNum,
                                                          IHXBuffer* pOutputBuffer,
                                                          HXxSize     cFrameDim,
                                                          UINT32      ulRowStride,
                                                          UINT32      ulBitsPerPixel,
                                                          UINT32      ulColorFormat,
                                                          BOOL        bRowsInverted,
                                                          IHXValues* pMoreParam)
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pMapManager)
    {
        CGIFRendererSession* pSession = NULL;
        m_pMapManager->GetEntry(ulSessionHandle, (void**) &pSession);
        if (pSession)
        {
            if (ulFrameNum < pSession->m_ulNumFrames &&
                pOutputBuffer                        &&
                ulBitsPerPixel == 32                 &&
                ulColorFormat == HX_RGB)
            {
                if (pSession->m_pGIFCodec)
                {
                    if (ulFrameNum < pSession->m_pGIFCodec->GetNumImages())
                    {
                        CGIFImage* pImage = pSession->m_pGIFCodec->GetImage(ulFrameNum);
                        if (pImage)
                        {
                            if (cFrameDim.cx == HXxRECT_WIDTH(pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim) &&
                                cFrameDim.cy == HXxRECT_HEIGHT(pSession->m_pFrameInfo[ulFrameNum].m_cFrameDim))
                            {
                                // Set the frame parameters
                                pSession->m_pFrameInfo[ulFrameNum].m_pOutputBuffer  = pOutputBuffer;
                                pSession->m_pFrameInfo[ulFrameNum].m_ulRowStride    = ulRowStride;
                                pSession->m_pFrameInfo[ulFrameNum].m_ulBitsPerPixel = ulBitsPerPixel;
                                pSession->m_pFrameInfo[ulFrameNum].m_ulColorFormat  = ulColorFormat;
                                pSession->m_pFrameInfo[ulFrameNum].m_bRowsInverted  = bRowsInverted;
                                // Addref the output buffer
                                pSession->m_pFrameInfo[ulFrameNum].m_pOutputBuffer->AddRef();
                                retVal = HXR_OK;
                            }
                        }
                    }
                }
            }
        }
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::Decompress(UINT32      ulSessionHandle,
                                                  IHXBuffer* pBuffer,
                                                  IHXBuffer* pOpaquePacketData)
{
    HX_RESULT retVal = HXR_OK;

    if (m_pMapManager)
    {
        CGIFRendererSession* pSession = NULL;
        retVal = m_pMapManager->GetEntry(ulSessionHandle, (void**) &pSession);
        if (SUCCEEDED(retVal))
        {
            if (pBuffer && pOpaquePacketData && pSession->m_pGIFCodec)
            {
                if (pSession->m_pGIFCodec->GetValid())
                {
                    if (pSession->m_pGIFCodec->GetNeedPacket())
                    {
                        if (!pSession->m_pGIFCodec->DecompressFinished())
                        {
                            BYTE* pBuf = pOpaquePacketData->GetBuffer();
                            if (pBuf)
                            {
                                // Unpack seq num
                                UINT32 ulSeqNum = 0;
                                UnPack32(pBuf, ulSeqNum);
                                // Unpack flags
                                UINT32 ulFlags = 0;
                                UnPack32(pBuf, ulFlags);
                                // Recover the "new frame" flag
                                BOOL bNewImage = (ulFlags & 1 ? TRUE : FALSE);
                                // Decompress this buffer
                                retVal = pSession->m_pGIFCodec->Decompress(pBuffer->GetBuffer(),
                                                                           pBuffer->GetSize(),
                                                                           bNewImage);
                                if (SUCCEEDED(retVal))
                                {
                                    if (pSession->m_pGIFCodec->DecompressFinished())
                                    {
                                        for (UINT32 i = 0; i < pSession->m_ulNumFrames; i++)
                                        {
                                            retVal = pSession->m_pGIFCodec->GetRGB32(i,
                                                                                     pSession->m_pFrameInfo[i].m_pOutputBuffer->GetBuffer(),
                                                                                     pSession->m_pFrameInfo[i].m_ulRowStride,
                                                                                     pSession->m_pFrameInfo[i].m_bRowsInverted);
                                            if (FAILED(retVal))
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                retVal = HXR_FAIL;
                            }
                        }
                    }
                    else
                    {
                        pSession->m_pGIFCodec->SetNeedPacket(TRUE);
                    }
                }
            }
            else
            {
                retVal = HXR_FAIL;
            }
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::GetDecompressStatus(UINT32     ulSessionHandle,
                                                           REF(INT32) rlStatus)
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pMapManager)
    {
        CGIFRendererSession* pSession = NULL;
        retVal                        = m_pMapManager->GetEntry(ulSessionHandle, (void**) &pSession);
        if (SUCCEEDED(retVal))
        {
            if (pSession->m_pGIFCodec)
            {
                if (pSession->m_pGIFCodec->GetValid())
                {
                    if (pSession->m_pGIFCodec->DecompressFinished())
                    {
                        rlStatus = DECOMPRESS_STATUS_FINISHED;
                    }
                    else
                    {
                        rlStatus = DECOMPRESS_STATUS_INPROGRESS;
                    }
                }
                else
                {
                    rlStatus = DECOMPRESS_STATUS_ABORTED;
                }
            }
            else
            {
                retVal = HXR_FAIL;
            }
        }
    }

    return retVal;
}

STDMETHODIMP CRealPixGIFRendererCodec::FinishDecompress(UINT32 ulSessionHandle)
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pMapManager)
    {
        CGIFRendererSession* pSession = NULL;
        retVal = m_pMapManager->DeleteEntry(ulSessionHandle, (void**) &pSession);
        HX_RELEASE(pSession);
    }

    return retVal;
}

HX_RESULT STDAPICALLTYPE CRealPixGIFRendererCodec::HXCreateInstance(IUnknown** ppIUnknown)
{
    HX_RESULT retVal = HXR_OK;

    if (ppIUnknown)
    {
        // Create renderer codec
        CRealPixGIFRendererCodec* pCodec = new CRealPixGIFRendererCodec();
        if (pCodec)
        {
            // QI for IUnknown
            retVal = pCodec->QueryInterface(IID_IUnknown, (void**) ppIUnknown);
        }
        else
        {
            retVal = HXR_OUTOFMEMORY;
        }
        if (FAILED(retVal))
        {
            HX_DELETE(pCodec);
        }
    }
    else
    {
        retVal = HXR_FAIL;
    }

    return retVal;
}

void CRealPixGIFRendererCodec::ReleaseAllSessions()
{
    if (m_pMapManager)
    {
        UINT32               ulHandle = 0;
        CGIFRendererSession* pSession = NULL;
        HX_RESULT            retVal   = m_pMapManager->GetFirstEntry(ulHandle, (void**) &pSession);
        while (SUCCEEDED(retVal))
        {
            HX_RELEASE(pSession);
            retVal = m_pMapManager->GetNextEntry(ulHandle, (void**) &pSession);
        }
        m_pMapManager->DeleteAllEntries();
    }
}
