/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: imagemgr.cpp,v 1.1.24.1 2004/07/09 01:51:47 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 ***** */

// From include
#include "hxtypes.h"
#include "hxwintyp.h"
#include "hxresult.h"
#include "hxcom.h"
#include "ihxpckts.h"
#include "hxvsurf.h"
#include "hxfiles.h"
#include "hxerror.h"
#include "hxccf.h"

// From pncont
#include "hxmap.h"
#include "hxbuffer.h"
#include "hxslist.h"

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

// From pxcomlib
#include "pxrect.h"
#include "pxcolor.h"
#include "pximage.h"
#include "pxeffect.h"
#include "pxrndcod.h"
#include "pxcmpmgr.h"

// pxrend
#include "rncodmgr.h"
#include "imghelpr.h"
#include "imagemgr.h"

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

BEGIN_INTERFACE_LIST(PXImageManager)
END_INTERFACE_LIST

PXImageManager::PXImageManager()
{
    Reset();
    m_pCodecManager      = NULL;
    m_pErrorMessages     = NULL;
    m_pDisplayImage      = NULL;
    m_pHandleToImageMap  = NULL;
    m_pScratchBufferList = NULL;
    m_pCCF               = NULL;
}

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

HX_RESULT PXImageManager::Init(PXRenderCodecManager* pCodecMgr, IHXErrorMessages* pErrorMessages,
                               UINT32 ulW, UINT32 ulH, UINT32 ulBpp,
                               UINT32 ulFormat, BOOL bInvert,
                               UINT32 ulBackgroundColor, UINT32 ulBackgroundOpacity)
{
    HX_RESULT retVal = HXR_OK;

    if (pCodecMgr && ulW && ulH && ulBpp)
    {
        // Clear out anything that's already here
        Deallocate();
        Reset();

        // Assign member variables
        m_pCodecManager          = pCodecMgr;
        m_pCodecManager->AddRef();
        m_pErrorMessages         = pErrorMessages;
        m_pErrorMessages->AddRef();
        // try to get a common class factory from the error messages!
        m_pErrorMessages->QueryInterface(IID_IHXCommonClassFactory, (void**)&m_pCCF);
        m_ulDisplayWidth         = ulW;
        m_ulDisplayHeight        = ulH;
        m_ulDefaultBitsPerPixel  = ulBpp;
        m_ulDefaultBytesPerPixel = (ulBpp + 7) >> 3;
        m_ulDefaultPixelFormat   = ulFormat;
        m_bDefaultRowsInverted   = bInvert;
        m_ulBackgroundColor      = ulBackgroundColor;
        m_ulBackgroundOpacity    = (ulBackgroundOpacity > 255 ? 255 : ulBackgroundOpacity);

        // Create a display image object
        retVal = PXImage::CreateObject(&m_pDisplayImage);
        if (SUCCEEDED(retVal))
        {
            // Addref the image
            m_pDisplayImage->AddRef();
            // Set up the display image
            retVal = m_pDisplayImage->Create((INT32) m_ulDisplayWidth,
                                             (INT32) m_ulDisplayHeight,
                                             m_ulDefaultBitsPerPixel,
                                             m_ulDefaultPixelFormat,
                                             m_bDefaultRowsInverted);
            if (SUCCEEDED(retVal))
            {
#ifdef XXXMEH_DEBUG_LOG
                DEBUG_OUTF("c:\\realpix.log",
                           (s, "PXImageManager::Init() - created display image (w=%lu,h=%lu)\n",
                           m_ulDisplayWidth, m_ulDisplayHeight));
#endif
                // Update the background color with the opacity
                UINT32 ulAlpha = 255 - ulBackgroundOpacity;
                m_ulBackgroundColor = (m_ulBackgroundColor & 0x00FFFFFF) |
                                      ((ulAlpha << 24)     & 0xFF000000);
                // Fill the display with the background color
                retVal = m_pDisplayImage->Fill32(m_ulBackgroundColor);
                if (SUCCEEDED(retVal))
                {
                    // Set the uses-alpha flag
                    if (ulBackgroundOpacity < 255)
                    {
                        m_pDisplayImage->SetHasAlpha(TRUE);
                    }
                    // Create the map object
                    m_pHandleToImageMap = new CHXMapLongToObj();
                    if (m_pHandleToImageMap)
                    {
                        // Create the scratch image list
                        HX_DELETE(m_pScratchBufferList);
                        m_pScratchBufferList = new CHXSimpleList();
                        if (!m_pScratchBufferList)
                        {
                            retVal = HXR_OUTOFMEMORY;
                        }
                    }
                    else
                    {
                        retVal = HXR_OUTOFMEMORY;
                    }
                }
            }
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    if (FAILED(retVal))
    {
        Deallocate();
        Reset();
        HX_ASSERT(FALSE);
    }

    return retVal;
}

HX_RESULT PXImageManager::CreateImage(UINT32 ulHandle, UINT32 ulLength, const char* pszMimeType,
                                      UINT32 ulOpaqueSize)
{
#ifdef XXXMEH_DEBUG_LOG
    DEBUG_OUTF("c:\\realpix.log",
               (s, "PXImageManager::CreateImage(%lu,%lu,%s,%lu)\n",
               ulHandle, ulLength, pszMimeType, ulOpaqueSize));
#endif
    HX_RESULT retVal = HXR_OK;

    if (ulHandle && ulLength && pszMimeType)
    {
        if (m_pHandleToImageMap)
        {
            // Check to see if there's already an entry for this handle
            BOOL  bNeedCreate   = TRUE;
            void* pVoid         = NULL;
            BOOL  bEntryPresent = m_pHandleToImageMap->Lookup((LONG32) ulHandle, pVoid);
            if (bEntryPresent)
            {
                // There was already an entry for this image, so
                // we will check to see if we have already successfully
                // decoded the whole image. If so, then we will flag this
                // image's data packets to be ignored. If not, then we will
                // blow this image away and try to receive it again.
                // XXXMEH - later, when we update the wire format to
                // be more precise about what part of the file is being
                // sent in every packet, then we won't have to blow away
                // the whole image - we can selectively replace missing
                // packets.
                //
                // Get the PXImageHelper object
                PXImageHelper* pHelper = (PXImageHelper*) pVoid;
                if (pHelper->AllBytesDecoded() && !pHelper->DecodeFailed())
                {
                    // Set the ignore data packets flag
                    pHelper->SetIgnoreDataPackets(TRUE);
                    // We don't need to create a new helper
                    bNeedCreate = FALSE;
#ifdef XXXMEH_DEBUG_OUT
                    DEBUG_OUT(m_pErrorMessages,
                              DOL_REALPIX_EXTENDED,
                              (s, "Image (handle=%lu) already exists and completely decoded. IGNORING data packets.",
                               ulHandle));
#endif
                }
                else
                {
                    // Release this PXImageHelper object
                    HX_RELEASE(pHelper);
                    // Remove it from the map
                    m_pHandleToImageMap->RemoveKey((LONG32) ulHandle);
#ifdef XXXMEH_DEBUG_OUT
                    DEBUG_OUT(m_pErrorMessages,
                              DOL_REALPIX_EXTENDED,
                              (s, "Image (handle=%lu) already exists but not completely decoded. RE-DECODING data packets.",
                               ulHandle));
#endif
                }
            }

            if (bNeedCreate)
            {
                // Create the image helper object
                PXImageHelper* pHelper = NULL;
                retVal                 = PXImageHelper::CreateObject(&pHelper);
                if (SUCCEEDED(retVal))
                {
                    // AddRef the object
                    pHelper->AddRef();
                    // Get the codec for this mime type
                    BOOL      bPresent = FALSE;
                    IUnknown* pUnk     = NULL;
                    retVal             = m_pCodecManager->GetComponent(pszMimeType, &bPresent, &pUnk);
                    if (SUCCEEDED(retVal))
                    {
                        if (bPresent)
                        {
                            // Init the helper object
                            retVal = pHelper->Init(m_pErrorMessages, ulHandle, ulLength, pUnk, ulOpaqueSize,
                                                   m_ulDisplayWidth, m_ulDisplayHeight, m_ulDefaultPixelFormat,
                                                   m_ulDefaultBitsPerPixel, m_bDefaultRowsInverted);
                            if (SUCCEEDED(retVal))
                            {
                                // AddRef the helper object before we add it to the map
                                pHelper->AddRef();
                                // Add the helper object to the map
                                m_pHandleToImageMap->SetAt((LONG32) ulHandle, (void *) pHelper);
                            }
                        }
                        else
                        {
                            retVal = HXR_FAIL;
                        }
                    }
                    HX_RELEASE(pUnk);
                }
                HX_RELEASE(pHelper);
            }
        }
        else
        {
            retVal = HXR_NOT_INITIALIZED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::DeleteImage(UINT32 ulHandle)
{
    HX_RESULT retVal = HXR_OK;

    if (ulHandle)
    {
        if (m_pHandleToImageMap)
        {
            // Check to see if there really is an entry for this handle
            void* pVoid         = NULL;
            BOOL  bEntryPresent = m_pHandleToImageMap->Lookup((LONG32) ulHandle, pVoid);
            if (bEntryPresent)
            {
#ifdef XXXMEH_DEBUG_OUT
                DEBUG_OUT(m_pErrorMessages,
                          DOL_REALPIX_EXTENDED,
                          (s, "Deleting image (handle=%lu)",
                           ulHandle));
#endif
                // Release the object
                PXImageHelper* pHelper = (PXImageHelper*) pVoid;
                HX_RELEASE(pHelper);
                // Remove it from the map
                m_pHandleToImageMap->RemoveKey((LONG32) ulHandle);
            }
            else
            {
                retVal = HXR_FAIL;
            }
        }
        else
        {
            retVal = HXR_NOT_INITIALIZED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::OnImageDataPacket(UINT32 ulHandle, IHXBuffer* pOpaque, IHXBuffer* pData)
{
    HX_RESULT retVal  = HXR_OK;

    if (ulHandle && pOpaque && pData)
    {
        // If we get a packet for which we don't have an image, we will just
        // throw it away.
        PXImageHelper* pHelper = NULL;
        HX_RESULT rv           = GetImageHelper(ulHandle, &pHelper);
        if (SUCCEEDED(rv))
        {
            if (!pHelper->GetIgnoreDataPackets())
            {
                retVal = pHelper->OnImageDataPacket(pOpaque, pData);
            }
        }
        HX_RELEASE(pHelper);
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

void PXImageManager::ReleasePresentationImages()
{
    if (m_pHandleToImageMap)
    {
        // Run through the map, deleting all image objects
        POSITION pos = m_pHandleToImageMap->GetStartPosition();
        while (pos)
        {
            // Get the object pointer at the current position
            // and advance to the next position
            LONG32 lKey     = 0;
            void*  pElement = NULL;
            m_pHandleToImageMap->GetNextAssoc(pos, lKey, pElement);

            // Release the object
            PXImageHelper* pHelper = (PXImageHelper*) pElement;
            HX_RELEASE(pHelper);
        }
        // Clear the map
        m_pHandleToImageMap->RemoveAll();
    }
}

HX_RESULT PXImageManager::GetImage(UINT32 ulHandle, PXImage** ppImage) const
{
    HX_RESULT retVal = HXR_OK;

    if (ulHandle && ppImage)
    {
        if (m_pHandleToImageMap)
        {
            // Set out parameter default
            *ppImage = NULL;
            // Check to see if there really is an entry for this handle
            void* pVoid         = NULL;
            BOOL  bEntryPresent = m_pHandleToImageMap->Lookup((LONG32) ulHandle, pVoid);
            if (bEntryPresent)
            {
                // Get the helper object
                PXImageHelper* pHelper = (PXImageHelper*) pVoid;
                if (pHelper)
                {
                    retVal = pHelper->GetFrame(0, ppImage);
                }
                else
                {
                    retVal = HXR_FAIL;
                }
            }
            else
            {
                retVal = HXR_FAIL;
            }
        }
        else
        {
            retVal = HXR_NOT_INITIALIZED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::IsImagePresent(UINT32 ulHandle, BOOL* pbPresent) const
{
    HX_RESULT retVal = HXR_OK;

    if (ulHandle && pbPresent)
    {
        // Set default
        *pbPresent = FALSE;
        if (m_pHandleToImageMap)
        {
            // Check to see if there really is an entry for this handle
            void* pVoid = NULL;
            *pbPresent  = m_pHandleToImageMap->Lookup((LONG32) ulHandle, pVoid);
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

BOOL PXImageManager::IsImagePresent(UINT32 ulHandle) const
{
    BOOL bPresent = FALSE;
    IsImagePresent(ulHandle, &bPresent);
    return bPresent;
}

HX_RESULT PXImageManager::IsImageCompletelyDecoded(UINT32 ulHandle, BOOL* pbComplete)
{
    HX_RESULT retVal = HXR_OK;

    if (ulHandle && pbComplete)
    {
        // Set default
        *pbComplete = FALSE;

        PXImageHelper* pHelper = NULL;
        retVal                 = GetImageHelper(ulHandle, &pHelper);
        if (SUCCEEDED(retVal))
        {
            *pbComplete = pHelper->AllBytesDecoded();
        }
        HX_RELEASE(pHelper);
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

HX_RESULT PXImageManager::GetNumImages(UINT32* pulNumImages) const
{
    HX_RESULT retVal = HXR_OK;

    if (pulNumImages)
    {
        // Set default
        *pulNumImages = 0;
        if (m_pHandleToImageMap)
        {
            *pulNumImages = m_pHandleToImageMap->GetCount();
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

UINT32 PXImageManager::GetNumImages() const
{
    UINT32 ulNum = 0;
    GetNumImages(&ulNum);
    return ulNum;
}

HX_RESULT PXImageManager::GetDisplayImage(PXImage** ppImage)
{
    HX_RESULT retVal = HXR_OK;

    if (ppImage)
    {
        if (m_pDisplayImage)
        {
            *ppImage = m_pDisplayImage;
            (*ppImage)->AddRef();
        }
        else
        {
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::GetDisplaySubImage(PXImage** ppImage, UINT32 ulX, UINT32 ulY,
                                             UINT32 ulW, UINT32 ulH, BOOL bCopy)
{
    HX_RESULT   retVal    = HXR_OK;
    PXImage*    pSubImage = NULL;
    IHXBuffer* pScratch  = NULL;

    if (ppImage)
    {
        // Assign default for out parameter
        *ppImage = NULL;
        // Make sure we're initialized
        if (m_pDisplayImage)
        {
            // Create an image object
            retVal = PXImage::CreateObject(&pSubImage);
            if (SUCCEEDED(retVal))
            {
                // Addref the image
                pSubImage->AddRef();

                if (bCopy)
                {
                    // We need a COPY of the subrect of the display image (as
                    // opposed to just referencing the same memory. Therefore,
                    // we will: 1) determine how many bytes we need; 2) get
                    // a scratch buffer which has that many bytes; and 3) init
                    // the image with that buffer
                    if (ulW == 0 || ulW > (UINT32) m_pDisplayImage->GetWidth())
                    {
                        ulW = m_pDisplayImage->GetWidth();
                    }
                    if (ulX + ulW > (UINT32) m_pDisplayImage->GetWidth())
                    {
                        ulX = m_pDisplayImage->GetWidth() - ulW;
                    }
                    if (ulH == 0 || ulH > (UINT32) m_pDisplayImage->GetHeight())
                    {
                        ulH = m_pDisplayImage->GetHeight();
                    }
                    if (ulY + ulH > (UINT32) m_pDisplayImage->GetHeight())
                    {
                        ulH = m_pDisplayImage->GetHeight() - ulY;
                    }
                    UINT32 ulBytesNeeded = ulW * ulH * m_ulDefaultBytesPerPixel;
                    retVal               = GetScratchBuffer(ulBytesNeeded, &pScratch);
                    if (SUCCEEDED(retVal))
                    {
                        retVal = pSubImage->CreateSubImageFromBuffer(m_pDisplayImage,
                                                                     (INT32) ulX,
                                                                     (INT32) ulY,
                                                                     (INT32) ulW,
                                                                     (INT32) ulH,
                                                                     pScratch);
                    }
                }
                else
                {
                    // We only need a reference to the display image's buffer. So
                    // we can just create a subimage that refs the display image's
                    // image store.
                    retVal = pSubImage->CreateSubImage(m_pDisplayImage,
                                                       (INT32) ulX,
                                                       (INT32) ulY,
                                                       (INT32) ulW,
                                                       (INT32) ulH);
                }

                if (SUCCEEDED(retVal))
                {
                    // Set the out parameter
                    *ppImage = pSubImage;
                    // Addref it before it goes out
                    (*ppImage)->AddRef();
                }
            }
        }
        else
        {
            retVal = HXR_NOT_INITIALIZED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    // Release our local ref
    HX_RELEASE(pScratch);
    HX_RELEASE(pSubImage);

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::GetDisplaySubImage(PXImage** ppImage, const PXRect& rSubRect, BOOL bCopy)
{
    return GetDisplaySubImage(ppImage, (INT32) rSubRect.GetX(), (INT32) rSubRect.GetY(),
                              (INT32) rSubRect.GetWidth(), (INT32) rSubRect.GetHeight(), bCopy);
}

HX_RESULT PXImageManager::GetDisplaySubImage(PXImage** ppImage, const HXxRect& rSubRect, BOOL bCopy)
{
    return GetDisplaySubImage(ppImage, rSubRect.left, rSubRect.top, HXxRECT_WIDTH(rSubRect),
                              HXxRECT_HEIGHT(rSubRect), bCopy);
}

HX_RESULT PXImageManager::GetPresentationSubImage(PXImage** ppImage, UINT32 ulHandle,
                                                  const PXRect& rSrcRect, const PXRect& rDstRect,
                                                  BOOL bPreserveAspect)
{
    HX_RESULT retVal = HXR_OK;
    PXImage*  pImage    = NULL;
    PXImage*  pSubImage = NULL;
    PXRect    cSrc;
    PXRect    cDst;

    // Set the rects
    cSrc.Set(rSrcRect.GetX(), rSrcRect.GetY(), rSrcRect.GetWidth(), rSrcRect.GetHeight());
    cDst.Set(rDstRect.GetX(), rDstRect.GetY(), rDstRect.GetWidth(), rDstRect.GetHeight());

    if (ppImage && ulHandle)
    {
        // Get the presentation image
        retVal = GetImage(ulHandle, &pImage);
        if (SUCCEEDED(retVal))
        {
            // Here we check for zero values of width or height in the 
            // src and dst rects. The convention is that a zero for width
            // means the full width of the image. Same for height. However,
            // we have to adjust these values to their true values in
            // order to do comparisons.
            cSrc.AdjustForZeroValues((UINT32) pImage->GetWidth(),
                                     (UINT32) pImage->GetHeight());
            cDst.AdjustForZeroValues((UINT32) m_pDisplayImage->GetWidth(),
                                     (UINT32) m_pDisplayImage->GetHeight());
            if (cSrc.GetWidth()  == cDst.GetWidth() &&
                cSrc.GetHeight() == cDst.GetHeight())
            {
                // The src and dst rects are the same, so we don't need to modify
                // the src image in any way - we can just get a ref to the subimage.
                retVal = PXImage::CreateObject(&pSubImage);
                if (SUCCEEDED(retVal))
                {
                    // Addref the image
                    pSubImage->AddRef();
                    // Create the subimage
                    retVal = pSubImage->CreateSubImage(pImage, cSrc);
                }
            }
            else
            {
                // Src and dst rects are not the same, so we will have to
                // do a resize into memory.
                retVal = GetScratchImage(&pSubImage, cDst.GetWidth(), cDst.GetHeight());
                if (SUCCEEDED(retVal))
                {
                    // If the presentation image has alpha, then this
                    // image must have alpha too.
                    pSubImage->SetHasAlpha(pImage->GetHasAlpha());
                    // Do we have to preserve aspect ratio?
                    if (bPreserveAspect)
                    {
                        // First we resolve the rectangles - we currently change the destination
                        // rectangle
                        PXRect cNewDst;
                        PXRect cFill1;
                        PXRect cFill2;
                        retVal = ResolveAspectRatio(cSrc, cDst, cNewDst, cFill1, cFill2, TRUE);
                        if (SUCCEEDED(retVal))
                        {
                            if (cFill1.GetWidth() > 0 && cFill1.GetHeight() > 0)
                            {
                                PXImage cTmp;
                                retVal = cTmp.CreateSubImage(pSubImage, cFill1);
                                if (SUCCEEDED(retVal))
                                {
                                    // If we have transparency in this image, then fill
                                    // with fully transparent. If not, then fill with
                                    // background color.
                                    if (cTmp.GetHasAlpha())
                                    {
                                        retVal = cTmp.Fill32(0xFF000000); // fully transparent
                                    }
                                    else
                                    {
                                        retVal = cTmp.Fill32(m_ulBackgroundColor);
                                    }
                                }
                            }

                            if (SUCCEEDED(retVal))
                            {
                                if (cNewDst.GetWidth() > 0 && cNewDst.GetHeight() > 0)
                                {
                                    PXImage cTmpDst;
                                    retVal = cTmpDst.CreateSubImage(pSubImage, cNewDst);
                                    if (SUCCEEDED(retVal))
                                    {
                                        PXImage cTmpSrc;
                                        retVal = cTmpSrc.CreateSubImage(pImage, cSrc);
                                        if (SUCCEEDED(retVal))
                                        {
                                            retVal = cTmpDst.ChangeSizeFromNN(&cTmpSrc);
                                        }
                                    }
                                }

                                if (SUCCEEDED(retVal))
                                {
                                    if (cFill2.GetWidth() > 0 && cFill2.GetHeight() > 0)
                                    {
                                        PXImage cTmp;
                                        retVal = cTmp.CreateSubImage(pSubImage, cFill2);
                                        if (SUCCEEDED(retVal))
                                        {
                                            // If we have transparency in this image, then fill
                                            // with fully transparent. If not, then fill with
                                            // background color.
                                            if (cTmp.GetHasAlpha())
                                            {
                                                retVal = cTmp.Fill32(0xFF000000); // fully transparent
                                            }
                                            else
                                            {
                                                retVal = cTmp.Fill32(m_ulBackgroundColor);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // We don't have to preserve aspect ratio, so we draw into the
                        // destination rect AS IS.
                        //
                        // Now we get a ref to the src rect
                        PXImage cTmp;
                        retVal = cTmp.CreateSubImage(pImage, cSrc);
                        if (SUCCEEDED(retVal))
                        {
                            // Now we change sizes into the scratch image
                            retVal = pSubImage->ChangeSizeFromNN(&cTmp);
                        }
                    }
                }
            }

            if (SUCCEEDED(retVal))
            {
                // Assign the out parameter
                *ppImage = pSubImage;
                // AddRef it before it goes out
                (*ppImage)->AddRef();
            }
        }
        else
        {
            HX_ASSERT(FALSE);
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    HX_RELEASE(pSubImage);
    HX_RELEASE(pImage);

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::GetPresentationSubImage(PXImage** ppImage, UINT32 ulHandle, const PXRect& rSrcRect)
{
    HX_RESULT retVal    = HXR_OK;
    PXImage*  pImage    = NULL;
    PXImage*  pSubImage = NULL;
    PXRect    cSrc;

    // Set the rects
    cSrc.Set(rSrcRect.GetX(), rSrcRect.GetY(), rSrcRect.GetWidth(), rSrcRect.GetHeight());

    if (ppImage && ulHandle)
    {
        // Get the presentation image
        retVal = GetImage(ulHandle, &pImage);
        if (SUCCEEDED(retVal))
        {
            retVal = PXImage::CreateObject(&pSubImage);
            if (SUCCEEDED(retVal))
            {
                // Addref the image
                pSubImage->AddRef();
                // Here we check for zero values of width or height in the 
                // src and dst rects. The convention is that a zero for width
                // means the full width of the image. Same for height. However,
                // we have to adjust these values to their true values in
                // order to do comparisons.
                cSrc.AdjustForZeroValues((UINT32) pImage->GetWidth(),
                                         (UINT32) pImage->GetHeight());
                // Adjust for rects that exceed image boundaries
                if (cSrc.GetWidth() > (UINT32) pImage->GetWidth())
                {
                    cSrc.SetWidth(pImage->GetWidth());
                }
                if (cSrc.GetX() + cSrc.GetWidth() > (UINT32) pImage->GetWidth())
                {
                    cSrc.SetX(pImage->GetWidth() - cSrc.GetWidth());
                }
                if (cSrc.GetHeight() > (UINT32) pImage->GetHeight())
                {
                    cSrc.SetHeight(pImage->GetHeight());
                }
                if (cSrc.GetY() + cSrc.GetHeight() > (UINT32) pImage->GetHeight())
                {
                    cSrc.SetY(pImage->GetHeight() - cSrc.GetHeight());
                }
                // Create the subimage
                retVal = pSubImage->CreateSubImage(pImage, cSrc);
                if (SUCCEEDED(retVal))
                {
                    // Assign the out parameter
                    *ppImage = pSubImage;
                    // AddRef it before it goes out
                    (*ppImage)->AddRef();
                }
            }

        }
        else
        {
            HX_ASSERT(FALSE);
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    HX_RELEASE(pSubImage);
    HX_RELEASE(pImage);

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::GetScratchImage(PXImage** ppImage, UINT32 ulW, UINT32 ulH)
{
    HX_RESULT   retVal = HXR_OK;
    IHXBuffer* pBuffer = NULL;
    PXImage*    pImage = NULL;

    if (ppImage && ulW && ulH)
    {
        UINT32 ulBytes = ulW * ulH * m_ulDefaultBytesPerPixel;
        retVal         = GetScratchBuffer(ulBytes, &pBuffer);
        if (SUCCEEDED(retVal))
        {
            retVal = PXImage::CreateObject(&pImage);
            if (SUCCEEDED(retVal))
            {
                // AddRef the image
                pImage->AddRef();
                // Create the subimage
                retVal = pImage->CreateFromBuffer((INT32) ulW, (INT32) ulH,
                                                  m_ulDefaultBitsPerPixel,
                                                  m_ulDefaultPixelFormat,
                                                  m_bDefaultRowsInverted,
                                                  pBuffer);
                if (SUCCEEDED(retVal))
                {
                    // Set the out parameter
                    *ppImage = pImage;
                    // Addref it before it goes out
                    (*ppImage)->AddRef();
                }
            }
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    HX_RELEASE(pBuffer);
    HX_RELEASE(pImage);

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::GetOpaqueDataSize(UINT32 ulHandle, REF(UINT32) rulOpaqueSize)
{
    HX_RESULT retVal = HXR_FAIL;

    if (ulHandle)
    {
        if (m_pHandleToImageMap)
        {
            // Check to see if there really is an entry for this handle
            void* pVoid         = NULL;
            BOOL  bEntryPresent = m_pHandleToImageMap->Lookup((LONG32) ulHandle, pVoid);
            if (bEntryPresent)
            {
                // Get the helper object
                PXImageHelper* pHelper = (PXImageHelper*) pVoid;
                if (pHelper)
                {
                    rulOpaqueSize = pHelper->GetOpaqueSize();
                    retVal        = HXR_OK;
                }
            }
        }
    }

    return retVal;
}

HX_RESULT PXImageManager::GetScratchBuffer(UINT32 ulNumBytesNeeded, IHXBuffer** ppBuffer)
{
#ifdef XXXMEH_DEBUG_LOG
    DEBUG_OUTF("c:\\realpix.log", (s, "PXImageManager::GetScratchBuffer(%lu,0x%08x)\n", ulNumBytesNeeded, ppBuffer));
#endif
    HX_RESULT   retVal  = HXR_OK;
    IHXBuffer* pBuffer = NULL;

    if (ppBuffer)
    {
        // Set default
        *ppBuffer = NULL;
        // See if we can an unused one with enough bytes
        BOOL bFound = FALSE;
        retVal      = ChooseScratchBuffer(ulNumBytesNeeded, &pBuffer, &bFound);
        if (SUCCEEDED(retVal))
        {
            if (!bFound)
            {
                // Now we'll just try to find an unused one (minimum bytes = 0)
                retVal = ChooseScratchBuffer(0, &pBuffer, &bFound);
                if (SUCCEEDED(retVal))
                {
                    if (bFound)
                    {
                        // We found one that's not being used, but it's too small, so
                        // let's realloc it to make it bigger.
                        //
                        // XXXMEH - Weird bug here - CHXBuffer only allows you do change
                        // the size of the buffer IF AND ONLY IF the ref count is
                        // one. Well, since we know we got this buffer from the list
                        // we KNOW that the only refs on it are the list's and the
                        // local one here. Sooooo, we artificially set the ref count
                        // down and then up.
                        UINT32 ulRefCount = pBuffer->Release();
                        HX_ASSERT(ulRefCount == 1);
                        retVal = pBuffer->SetSize(ulNumBytesNeeded);
                        pBuffer->AddRef();
#ifdef XXXMEH_DEBUG_LOG
                        DEBUG_OUTF("c:\\realpix.log",
                                   (s, "PXImageManager::GetScratchBuffer(%lu,0x%08x) - found unused existing buffer - RESIZED\n",
                                   ulNumBytesNeeded, ppBuffer));
#endif
                    }
                    else
                    {
                        // Well, we still haven't found one, so we'll have
                        // to create one and add it to the list
                        //

                        /* Create an IHXBuffer */
                        if (m_pCCF)
                        {   
                            IUnknown* pUnk = NULL;
                            m_pCCF->CreateInstance(CLSID_IHXBuffer, (void**)&pUnk);
                            if (pUnk)
                            {
                                pUnk->QueryInterface(IID_IHXBuffer, (void**)&pBuffer);
                            }
                            HX_RELEASE(pUnk);
                        }   

                        if (pBuffer)
                        {
                            // Set the size of the buffer
                            retVal = pBuffer->SetSize(ulNumBytesNeeded);
                            if (SUCCEEDED(retVal))
                            {
                                // Addref the object before adding it to the list
                                pBuffer->AddRef();
                                // Add the image to the scratch image list
                                m_pScratchBufferList->AddTail((void*) pBuffer);
#ifdef XXXMEH_DEBUG_LOG
                                DEBUG_OUTF("c:\\realpix.log",
                                           (s, "PXImageManager::GetScratchBuffer(%lu,0x%08x) - new buffer added to list\n",
                                           ulNumBytesNeeded, ppBuffer));
#endif
                            }
                        }
                        else
                        {
                            retVal = HXR_OUTOFMEMORY;
                        }
                    }
                }
            }
            else
            {
#ifdef XXXMEH_DEBUG_LOG
                DEBUG_OUTF("c:\\realpix.log",
                           (s, "PXImageManager::GetScratchBuffer(%lu,0x%08x) - found unused existing buffer with required size\n",
                           ulNumBytesNeeded, ppBuffer));
#endif
            }
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    // Assign the out parameter
    if (SUCCEEDED(retVal))
    {
        *ppBuffer = pBuffer;
        (*ppBuffer)->AddRef();
    }

    // Release local refs
    HX_RELEASE(pBuffer);

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

HX_RESULT PXImageManager::GetImageHelper(UINT32 ulHandle, PXImageHelper** ppHelper)
{
    HX_RESULT retVal = HXR_OK;

    if (ulHandle && ppHelper)
    {
        if (m_pHandleToImageMap)
        {
            // Set out parameter default
            *ppHelper = NULL;
            // Check to see if there really is an entry for this handle
            void* pVoid         = NULL;
            BOOL  bEntryPresent = m_pHandleToImageMap->Lookup((LONG32) ulHandle, pVoid);
            if (bEntryPresent)
            {
                // Get the helper object
                *ppHelper = (PXImageHelper*) pVoid;
                // Addref it before it leaves
                (*ppHelper)->AddRef();
            }
            else
            {
                retVal = HXR_FAIL;
            }
        }
        else
        {
            retVal = HXR_NOT_INITIALIZED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

HX_RESULT PXImageManager::ChooseScratchBuffer(UINT32 ulMinBytes, IHXBuffer** ppBuffer, BOOL* pbFound)
{
    HX_RESULT retVal = HXR_OK;

    if (ppBuffer && pbFound)
    {
        if (m_pScratchBufferList)
        {
            // Run through the current list of scratch buffers, and try
            // to find one with a ref count < 2 (not currently being used by anybody
            // else) AND enough space
            *pbFound         = FALSE;
            LISTPOSITION pos = m_pScratchBufferList->GetHeadPosition();
            while (pos)
            {
                IHXBuffer* pBuffer = (IHXBuffer*) m_pScratchBufferList->GetNext(pos);
                if (pBuffer)
                {
                    if (GET_REFCOUNT(pBuffer) < 2 && pBuffer->GetSize() >= ulMinBytes)
                    {
                        *ppBuffer = pBuffer;
                        (*ppBuffer)->AddRef();
                        *pbFound = TRUE;
                        break;
                    }
                }
            }
        }
        else
        {
            retVal = HXR_NOT_INITIALIZED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

#ifdef XXXMEH_DEBUG_ASSERT
    // Debug-only assert
    HX_ASSERT(SUCCEEDED(retVal));
#endif

    return retVal;
}

UINT32 PXImageManager::GetMaxChannelDepth() const
{
    UINT32 ulRetVal = 0;

    switch (m_ulDefaultBitsPerPixel)
    {
        case 16:
            if (m_ulDefaultPixelFormat == HXCOLOR_RGB565_ID)
            {
                ulRetVal = 6;
            }
            else if (m_ulDefaultPixelFormat == HXCOLOR_RGB555_ID)
            {
                ulRetVal = 5;
            }
            break;
        case 24:
        case 32:
            ulRetVal = 8;
            break;
        default:
            break;
    }

    return ulRetVal;
}

HX_RESULT PXImageManager::PacketLost()
{
    return HXR_OK;
}

void PXImageManager::ReleaseScratchBuffers()
{
    if (m_pScratchBufferList)
    {
        // Run through the map, deleting all buffer objects
        POSITION pos = m_pScratchBufferList->GetHeadPosition();
        while (pos)
        {
            // Get the pointer to the next image
            IHXBuffer* pBuffer = (IHXBuffer*) m_pScratchBufferList->GetNext(pos);
            // Release the image
            HX_RELEASE(pBuffer);
        }
        // Clear the list
        m_pScratchBufferList->RemoveAll();
    }
}

void PXImageManager::Reset()
{
    m_ulDisplayWidth        = 0;
    m_ulDisplayHeight       = 0;
    m_ulDefaultBitsPerPixel = 32;
    m_ulDefaultPixelFormat  = HX_RGB;
    m_bDefaultRowsInverted  = FALSE;
    m_ulBackgroundColor     = 0;
    m_ulBackgroundOpacity   = 255;
}

void PXImageManager::Deallocate()
{
    HX_RELEASE(m_pCodecManager);
    HX_RELEASE(m_pErrorMessages);
    HX_RELEASE(m_pCCF);
    HX_RELEASE(m_pDisplayImage);
    ReleasePresentationImages();
    ReleaseScratchBuffers();
    HX_DELETE(m_pHandleToImageMap);
    HX_DELETE(m_pScratchBufferList);
}

HX_RESULT PXImageManager::ResolveAspectRatio(const PXRect& rSrc, const PXRect& rDst,
                                             PXRect& rNewDst, PXRect& rEmpty1, PXRect& rEmpty2,
                                             BOOL bRelativeToDst)
{
    HXxRect cSrc, cDst, cNew, cEmp1, cEmp2;

    CONVERT_PXRECT_TO_PNxRECT(rSrc, cSrc);
    CONVERT_PXRECT_TO_PNxRECT(rDst, cDst);

    HX_RESULT retVal = ResolveAspectRatio(cSrc, cDst, cNew, cEmp1, cEmp2, bRelativeToDst);

    CONVERT_PNxRECT_TO_PXRECT(rNewDst, cNew);
    CONVERT_PNxRECT_TO_PXRECT(rEmpty1, cEmp1);
    CONVERT_PNxRECT_TO_PXRECT(rEmpty2, cEmp2);

    return retVal;
}

HX_RESULT PXImageManager::ResolveAspectRatio(const HXxRect& rSrc, const HXxRect& rDst,
                                             HXxRect& rNewDst, HXxRect& rEmpty1, HXxRect& rEmpty2,
                                             BOOL bRelativeToDst)
{
    HX_RESULT retVal = HXR_OK;

    if (rSrc.right > rSrc.left && rSrc.bottom > rSrc.top &&
        rDst.right > rDst.left && rDst.bottom > rDst.top)
    {
        INT32 lSrcW = HXxRECT_WIDTH(rSrc);
        INT32 lSrcH = HXxRECT_HEIGHT(rSrc);
        INT32 lDstW = HXxRECT_WIDTH(rDst);
        INT32 lDstH = HXxRECT_HEIGHT(rDst);
        INT32 lModW = 0;
        INT32 lModH = 0;
        if (lSrcW * lDstH > lSrcH * lDstW)
        {
            lModW          = lDstW;
            lModH          = lSrcH * lDstW / lSrcW;
            rNewDst.left   = rDst.left;
            rNewDst.top    = rDst.top + (lDstH >> 1) - (lModH >> 1);
            rNewDst.right  = rDst.right;
            rNewDst.bottom = rNewDst.top + lModH;
            rEmpty1.left   = rDst.left;
            rEmpty1.top    = rDst.top;
            rEmpty1.right  = rDst.right;
            rEmpty1.bottom = rNewDst.top;
            rEmpty2.left   = rDst.left;
            rEmpty2.top    = rNewDst.bottom;
            rEmpty2.right  = rDst.right;
            rEmpty2.bottom = rDst.bottom;
        }
        else
        {
            lModW          = lSrcW * lDstH / lSrcH;
            lModH          = lDstH;
            rNewDst.left   = rDst.left + (lDstW >> 1) - (lModW >> 1);
            rNewDst.top    = rDst.top;
            rNewDst.right  = rNewDst.left + lModW;
            rNewDst.bottom = rDst.bottom;
            rEmpty1.left   = rDst.left;
            rEmpty1.top    = rDst.top;
            rEmpty1.right  = rNewDst.left;
            rEmpty1.bottom = rDst.bottom;
            rEmpty2.left   = rNewDst.right;
            rEmpty2.top    = rDst.top;
            rEmpty2.right  = rDst.right;
            rEmpty2.bottom = rDst.bottom;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    if (bRelativeToDst)
    {
        rNewDst.left   -= rDst.left;
        rNewDst.top    -= rDst.top;
        rNewDst.right  -= rDst.left;
        rNewDst.bottom -= rDst.top;
        rEmpty1.left   -= rDst.left;
        rEmpty1.top    -= rDst.top;
        rEmpty1.right  -= rDst.left;
        rEmpty1.bottom -= rDst.top;
        rEmpty2.left   -= rDst.left;
        rEmpty2.top    -= rDst.top;
        rEmpty2.right  -= rDst.left;
        rEmpty2.bottom -= rDst.top;
    }

    return retVal;
}

