/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: minisurf.cpp,v 1.22.2.3 2004/07/09 01:59:28 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 "minisite.h"

#include "minisurf.h"
#include "ciddefs.h"

#if defined(HELIX_CONFIG_NOSTATICS)
//On Symbian we don't use a colorconvert DLL. We compile in 
//one and use slightly different color converter calls that
//don't use static data.
# include "nostatic/yuv.h" //for the color_data_t struct.
# include "nostatic/colorlib.h" //for the new converters
#else
#include "colorlib.h"
#endif

#if defined(_UNIX) || defined(_MACINTOSH) || defined(_SYMBIAN) || defined(_OPENWAVE)
#  ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
                  ((ULONG32)(BYTE)(ch0) | ((ULONG32)(BYTE)(ch1) << 8) | \
                  ((ULONG32)(BYTE)(ch2) << 16) | ((ULONG32)(BYTE)(ch3) << 24 ))
#  endif //defined(MAKEFOURCC)
#endif //_UNIX || _MACINTOSH


CMiniBaseSurface::CMiniBaseSurface(IUnknown* pContext, CMiniBaseSite* pSite)
    :  m_lRefCount(0)
       ,  m_pContext(pContext)
       ,  m_pSite(pSite)
       ,  m_pOptimizedFormat(NULL)
       ,  m_nSrcCID(CID_UNKNOWN)
       ,  m_nDstBuffers(0)
       ,  m_fpColorConverter(NULL)
       ,  m_pImageHelper(NULL)
{
    memset(&m_dstBufSize, 0, sizeof(m_dstBufSize));

    m_pContext->AddRef();

    m_pImageHelper = new CFmtObj;
}

CMiniBaseSurface::~CMiniBaseSurface()
{
    HX_RELEASE(m_pContext);
    HX_DELETE(m_pImageHelper);
    HX_DELETE(m_pOptimizedFormat);
}

/************************************************************************
 *  Method:
 *    IUnknown::QueryInterface
 */
STDMETHODIMP CMiniBaseSurface::QueryInterface(REFIID riid, void** ppvObj)
{
    if (IsEqualIID(riid, IID_IHXVideoSurface))
    {
        AddRef();
        *ppvObj = (IUnknown*)(IHXVideoSurface*)this;
        return HXR_OK;
    }
    else if (IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppvObj = (IUnknown*)(IHXSite*)this;
        return HXR_OK;
    }

    *ppvObj = NULL;
    return HXR_NOINTERFACE;
}

/************************************************************************
 *  Method:
 *    IUnknown::AddRef
 */
STDMETHODIMP_(ULONG32) CMiniBaseSurface::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

/************************************************************************
 *  Method:
 *    IUnknown::Release
 */
STDMETHODIMP_(ULONG32) CMiniBaseSurface::Release()
{
    if (InterlockedDecrement(&m_lRefCount) > 0)
    {
        return m_lRefCount;
    }

    delete this;
    return 0;
}

inline
IsCompatible(const HXBitmapInfoHeader* pLeft, const HXBitmapInfoHeader* pRight)
{
    //return (0 == memcmp(m_pOptimizedFormat, pBitmapInfo, sizeof(HXBitmapInfoHeader));
    return (pLeft->biWidth == pRight->biWidth &&
            pLeft->biHeight == pRight->biHeight &&
            pLeft->biPlanes == pRight->biPlanes &&
            pLeft->biBitCount == pRight->biBitCount &&
            pLeft->biCompression == pRight->biCompression);
}

/************************************************************************
 *  Method:
 *    IHXVideoSurface::BeginOptimizedBlt
 */
STDMETHODIMP CMiniBaseSurface::BeginOptimizedBlt(HXBitmapInfoHeader* pBitmapInfo)
{
    HX_ASSERT(pBitmapInfo);    
    if(m_pOptimizedFormat && IsCompatible(m_pOptimizedFormat, pBitmapInfo))
    {
        // current optimized format bitmap info (as well as info we derive from it) is valid
        return HXR_OK;
    }

    // clean up
    EndOptimizedBlt();

    // save copy of bitmap info
    m_pOptimizedFormat = new HXBitmapInfoHeader;
    if(!m_pOptimizedFormat)
    {
        return HXR_OUTOFMEMORY;
    }
    *m_pOptimizedFormat = *pBitmapInfo;

    // save current color format id
    m_nSrcCID = m_pImageHelper->GetBitmapColor((HXBitmapInfo*) pBitmapInfo);
    HX_ASSERT(m_nSrcCID != -1);

    // determine color converter
    int nDstCID = GetDstCID();

    switch (m_nSrcCID)
    {
#if defined(HELIX_FEATURE_SMIL_SITE) && defined(HELIX_FEATURE_CC_RGB444out)
       case CID_RGB32:
       case CID_ARGB32:
           if (nDstCID == CID_RGB444)
               m_fpColorConverter = RGB32toRGB444;
           m_nSrcPitch = m_pImageHelper->GetBitmapPitch((HXBitmapInfo*)pBitmapInfo);
           break;
       case CID_RGB444:
           if (nDstCID == CID_RGB444)
               m_fpColorConverter = RGB444toRGB444;
           m_nSrcPitch = m_pImageHelper->GetBitmapPitch((HXBitmapInfo*)pBitmapInfo);
           break;
#endif //HELIX_FEATURE_SMIL_SITE
           
       case CID_I420:
        
#if defined (HELIX_FEATURE_CC_YV12out)
           if (nDstCID == CID_YV12)
               m_fpColorConverter = I420toYV12;
#endif //HELIX_FEATURE_CC_YV12out

#if defined (HELIX_FEATURE_CC_YUY2out)
           if (nDstCID == CID_YUY2)
               m_fpColorConverter = I420toYUY2;
#endif //HELIX_FEATURE_CC_YUY2out

#if defined (HELIX_FEATURE_CC_RGB32out)                     
           if (nDstCID == CID_RGB32)
               m_fpColorConverter = I420toRGB32;
#endif //HELIX_FEATURE_CC_RGB32out

#if defined (HELIX_FEATURE_CC_RGB24out)
           if (nDstCID == CID_RGB24)
               m_fpColorConverter = I420toRGB24;
#endif //HELIX_FEATURE_CC_RGB24out

#if defined (HELIX_FEATURE_CC_RGB565out)
           if (nDstCID == CID_RGB565)
               m_fpColorConverter = I420toRGB565;
#endif //HELIX_FEATURE_CC_RGB565out

#if defined (HELIX_FEATURE_CC_RGB555out)
           if (nDstCID == CID_RGB555)
               m_fpColorConverter = I420toRGB555;
#endif //HELIX_FEATURE_CC_RGB555out

#if defined (HELIX_FEATURE_CC_RGB444out)
           if (nDstCID == CID_RGB444)
               m_fpColorConverter = I420toRGB444;
#endif //HELIX_FEATURE_CC_RGB444out

#if defined (HELIX_FEATURE_CC_RGB8out)
           if (nDstCID == CID_RGB8)
               m_fpColorConverter = I420toRGB8;
#endif //HELIX_FEATURE_CC_RGB444out

           m_nSrcPitch = pBitmapInfo->biWidth;
           break;

       case CID_XING:
#if defined (HELIX_FEATURE_CC_YV12out)
           if (nDstCID == CID_YV12)
               m_fpColorConverter = XINGtoYV12;
#endif //HELIX_FEATURE_CC_YV12out

#if defined (HELIX_FEATURE_CC_YUY2out)
           if (nDstCID == CID_YUY2)
               m_fpColorConverter = XINGtoYUY2;
#endif //HELIX_FEATURE_CC_YUY2out

#if defined (HELIX_FEATURE_CC_RGB32out)
           if (nDstCID == CID_RGB32)
               m_fpColorConverter = XINGtoRGB32;
#endif //HELIX_FEATURE_CC_YUY2out
        
#if defined (HELIX_FEATURE_CC_RGB565out)
           if (nDstCID == CID_RGB565)
               m_fpColorConverter = XINGtoRGB565;
#endif //HELIX_FEATURE_CC_RGB565out

           m_nSrcPitch = 768;
           break;
    }

    HX_ASSERT(m_fpColorConverter);
    
#if defined(HELIX_CONFIG_NOSTATICS)
    SetSrcI420Colors (0, 0, 0, 0, GetColorData());
#else    
    SetSrcI420Colors (0, 0, 0, 0); 
    SetDestI420Colors (0, 0, 0, 0);
    SetI420ChromaResamplingMode (0);
#endif    
    
    return m_fpColorConverter ? HXR_OK : HXR_FAIL;
}



/************************************************************************
 *  Method:
 *    IHXVideoSurface::Blt
 */
STDMETHODIMP CMiniBaseSurface::Blt(UCHAR*              pSrcBuffer,
                                   HXBitmapInfoHeader* pBitmapInfo,
                                   REF(HXxRect)        rDestRect,
                                   REF(HXxRect)        rSrcRect)
{
    
    HX_RESULT hr = BeginOptimizedBlt(pBitmapInfo);
    if (FAILED(hr))
    {
        return hr;
    }
        
    int nDstWidth   = rDestRect.right - rDestRect.left;
    int nDstHeight  = rDestRect.bottom - rDestRect.top;

    // ensure destination buffers are allocated, ensuring that we properly handle image stretching.
    if(ScaleDuringRender(GetDstCID()))
    {
        hr = AllocateDestBuffers(pBitmapInfo->biWidth, pBitmapInfo->biHeight);
    }
    else
    {
        // we stretch during the transfer from source to dest 
        // buffer; dest buffer must be same size as dest rect.
        hr = AllocateDestBuffers(nDstWidth, nDstHeight);
    }
    if(FAILED(hr))
    {
        return hr;
    }


    UCHAR*  pDestBuffer = NULL;
    LONG32  nDestPitch  = 0;
    HXxSize dstSize     = m_dstBufSize;

    hr = _LockDestBuffer(&pDestBuffer,
                         &nDestPitch,
                         m_nSrcCID,
                         dstSize);

    if (FAILED(hr))
        return hr;

    HXxRect rcDst = rDestRect;
    HXxRect rcSrc = rSrcRect;

    // If the dest buffer dimensions do not match the dest rect,
    // map the dest rect to the dest buffer for video transfer.
    if ((m_dstBufSize.cx != nDstWidth) | 
        (m_dstBufSize.cy != nDstHeight))
    {
 
        rcDst.left = (rcDst.left*m_dstBufSize.cx) / nDstWidth;
        rcDst.right = (rcDst.right*m_dstBufSize.cx) / nDstWidth;
        rcDst.top = (rcDst.top*m_dstBufSize.cy) / nDstHeight;
        rcDst.bottom = (rcDst.bottom*m_dstBufSize.cy) / nDstHeight;
    }


    hr = _TransferToDestBuffer(pSrcBuffer,
                               pBitmapInfo,
                               &rcSrc,
                               &rcDst,
                               pDestBuffer,
                               nDestPitch);
    
    _UnlockDestBuffer(pDestBuffer);

    if (SUCCEEDED(hr))
        hr = _RenderDestBuffer(&rcDst, &rDestRect);
    
    //Give the device a chance to keep the screen alive.
    _KeepScreenAlive();
    
    return hr;
}

/************************************************************************
 *  Method:
 *    IHXVideoSurface::OptimizedBlt
 */
STDMETHODIMP CMiniBaseSurface::OptimizedBlt(UCHAR* pSrcBuffer,
                                            REF(HXxRect) rDestRect,
                                            REF(HXxRect) rSrcRect)
{
    return Blt(pSrcBuffer, 
               m_pOptimizedFormat,
               rDestRect,
               rSrcRect); 
}

/************************************************************************
 *  Method:
 *    IHXVideoSurface::EndOptimizedBlt
 */
STDMETHODIMP CMiniBaseSurface::EndOptimizedBlt(void)
{
    HX_RESULT hr =  DestroyDestBuffers(m_nDstBuffers);
    HX_DELETE(m_pOptimizedFormat);
    m_nSrcCID = CID_UNKNOWN;

    return hr;
}

/************************************************************************
 *  Method:
 *    IHXVideoSurface::GetOptimizedFormat
 */
STDMETHODIMP CMiniBaseSurface::GetOptimizedFormat(REF(HX_COMPRESSION_TYPE) ulType)
{
    ulType = 0;
    return HXR_OK;
}

/************************************************************************
 *  Method:
 *    IHXVideoSurface::GetPreferredFormat
 */
STDMETHODIMP CMiniBaseSurface::GetPreferredFormat(REF(HX_COMPRESSION_TYPE) ulType)
{                             
    ulType = 0;
    return HXR_OK;
}                                                        
                                      

HX_RESULT 
CMiniBaseSurface::_TransferToDestBuffer(UCHAR* pSrcBuffer,
                                        HXBitmapInfoHeader* pBitmapInfo,
                                        HXxRect* prSrcRect,
                                        HXxRect* prDstRect,
                                        UCHAR* pDstBuffer,
                                        LONG32 nDstPitch)
{
    if (!m_fpColorConverter)
        return HXR_FAIL;

    int nRet = m_fpColorConverter( pDstBuffer,
                                   m_dstBufSize.cx,
                                   m_dstBufSize.cy,
                                   nDstPitch,
                                   prDstRect->left, prDstRect->top,
                                   prDstRect->right-prDstRect->left, 
                                   prDstRect->bottom-prDstRect->top,
                                   pSrcBuffer,
                                   pBitmapInfo->biWidth,
                                   pBitmapInfo->biHeight,
                                   m_nSrcPitch,
                                   prSrcRect->left, prSrcRect->top,
                                   prSrcRect->right-prSrcRect->left, 
                                   prSrcRect->bottom-prSrcRect->top
#if defined(HELIX_CONFIG_NOSTATICS)    
                                   ,GetColorData()
#endif    
                                   );
    if (nRet < 0)
        return HXR_FAIL;
    else
        return HXR_OK;
}


BOOL CMiniBaseSurface::ScaleDuringRender(int nCID)
{
    // Our YUVtoYUV color converters do not scale so scaling
    // must be done during rendering.
    //
    // Our XXXtoRGB do scaling
    return (nCID == CID_DVPF) | 
           (nCID >= CID_I420 && nCID <= CID_UYVY);
}

HX_RESULT CMiniBaseSurface::AllocateDestBuffers(int nWidth,
                                                int nHeight,
                                                int nCount)
{
    if (nWidth == m_dstBufSize.cx &&
        nHeight == m_dstBufSize.cy &&
        nCount == m_nDstBuffers)
    {
        return HXR_OK;
    }
    else
    {
        DestroyDestBuffers(m_nDstBuffers);
    }

    HX_RESULT hr = _CreateDestBuffer(m_nSrcCID, nWidth, nHeight, nCount);

    if (HXR_OK == hr)
    {
        m_dstBufSize.cx = nWidth;
        m_dstBufSize.cy = nHeight;

        m_nDstBuffers = nCount;
    }

    return hr;
}

HX_RESULT CMiniBaseSurface::DestroyDestBuffers(int nCount)
{
    HX_RESULT hr = HXR_OK;

    if (m_dstBufSize.cx || m_dstBufSize.cy)
    {
        hr = _DestroyDestBuffer(m_nSrcCID, nCount); 

        memset(&m_dstBufSize, 0, sizeof(m_dstBufSize));
        m_nDstBuffers = 0;
    }

    return hr;
}
