/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: gifcodec.cpp,v 1.2.24.1 2004/07/09 01:54:29 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 ***** */

// system
#include <hlxclib/memory.h>
#include <string.h>

// include
#include "hxtypes.h"
#include "hxcom.h"

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

// pxcomlib
#include "glist.h"

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

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

BEGIN_INTERFACE_LIST(CGIFCodec)
END_INTERFACE_LIST

CGIFCodec::CGIFCodec()
{
    ResetParse();
    ResetDecompress();
};

CGIFCodec::~CGIFCodec()
{
    TermParse();
    TermDecompress();
};

void CGIFCodec::ResetParse()
{
    m_ulParseState           = kStateConstructed;
    m_pParseBuffer           = NULL;
    m_ulParseBufferLength    = 0;
    m_pSegment               = NULL;
    m_ulDelayTimeSum         = 0;
    m_ulNumSegmentsAllocated = 0;
    m_ulNumSegments          = 0;
    m_ulNumImages            = 0;
    m_ulCurSegIndex          = 0;
    m_ulCurSegOffset         = 0;
    m_ulLoopCount            = 1;
}

void CGIFCodec::ResetDecompress()
{
    m_cLSD.m_ulLogicalScreenWidth     = 0;
    m_cLSD.m_ulLogicalScreenHeight    = 0;
    m_cLSD.m_bGlobalColorTablePresent = FALSE;
    m_cLSD.m_ulOriginalColorBits      = 0;
    m_cLSD.m_bColorsSorted            = FALSE;
    m_cLSD.m_ulColorTableBits         = 0;
    m_cLSD.m_ulColorTableNumEntries   = 0;
    m_cLSD.m_ulBackgroundColorIndex   = 0;
    m_cLSD.m_ulPixelAspectRatio       = 0;
    m_cLSD.m_fPixelAspectRatio        = 0.0F;
    m_bIsGIF89a                       = FALSE;
    m_pucGlobalColorMap               = NULL;
    m_ulNumImages                     = 0;
    m_pImageHeaderSize                = NULL;
    m_pCompressedBufferSize           = NULL;
    m_pImage                          = NULL;
    m_ulCurrentImageIndex             = 0;
    m_bNeedPacket                     = TRUE;
    m_ulState                         = kStateConstructed;
    m_bValid                          = TRUE;
    m_ulLoopCount                     = 1;
}

void CGIFCodec::TermParse()
{
    if (m_pSegment)
    {
        delete [] m_pSegment;
        m_pSegment = NULL;
    }
    ResetParse();
}

void CGIFCodec::TermDecompress()
{
    if (m_pucGlobalColorMap)
    {
        delete [] m_pucGlobalColorMap;
        m_pucGlobalColorMap = NULL;
    }
    if (m_pImageHeaderSize)
    {
        delete [] m_pImageHeaderSize;
        m_pImageHeaderSize = NULL;
    }
    if (m_pCompressedBufferSize)
    {
        delete [] m_pCompressedBufferSize;
        m_pCompressedBufferSize = NULL;
    }
    if (m_pImage)
    {
        delete [] m_pImage;
        m_pImage = NULL;
    }
    ResetDecompress();
}

UINT32 CGIFCodec::GetMaxNumPackets(BYTE* pBuf, UINT32 ulLen)
{
    UINT32 ulNumPackets = 0;

    if (pBuf && ulLen)
    {
        BYTE* pBufLimit = pBuf + ulLen;
        if (pBuf[0] == 'G' && pBuf[1] == 'I' && pBuf[2] == 'F' &&
            pBuf[3] == '8' && pBuf[5] == 'a')
        {
            // Advance past the signature
            pBuf += 6;
            // Parse the logical screen descriptor
            LogicalScreenDescriptor cLSD;
            ParseLogicalScreenDescriptor(pBuf, cLSD);
            pBuf += 7;
            // Skip the color table
            if (cLSD.m_bGlobalColorTablePresent == TRUE)
            {
                // Advance that number of bytes
                pBuf += (UINT32) (cLSD.m_ulColorTableNumEntries * 3);
            }
            // We count this as the first packet
            ulNumPackets++;
            // Loop through the GIF blocks - we know that the max number
            // of packets would be if each GIF block were its own packet,
            // so we simply need to count the GIF blocks
            while (pBuf < pBufLimit)
            {
                if (pBuf[0] == kImageDescriptor)
                {
                    // Skip the Image Descriptor marker
                    pBuf++;
                    // Parse the image descriptor struct
                    CGIFImage::ImageDescriptor cID;
                    CGIFImage::ParseImageDescriptor(pBuf, cID);
                    pBuf += 9;
                    // If a local color table IS present, then skip it
                    if (cID.m_bLocalColorTablePresent == TRUE)
                    {
                        pBuf += cID.m_ulLocalColorTableNumEntries * 3;
                    }
                    // Skip the minimum LZW code size
                    pBuf++;
                    // We count the image descriptor as a packet
                    ulNumPackets++;
                    // Now skip the LZW blocks
                    UINT32 ulBlockSize = 0;
                    do
                    {
                        // Get the block size
                        ulBlockSize = *pBuf++;
                        // Skip that amount of bytes
                        pBuf += ulBlockSize;
                        // Count this as a packet
                        ulNumPackets++;
                    }
                    while (ulBlockSize);
                }
                else if (pBuf[0] == kExtension)
                {
                    // Skip the extension marker and type
                    pBuf += 2;
                    // Count the blocks in this extension
                    UINT32 ulBlockSize = 0;
                    do
                    {
                        // Get the block size
                        ulBlockSize = *pBuf++;
                        // Skip that amount of bytes
                        pBuf += ulBlockSize;
                        // Count this as a packet
                        ulNumPackets++;
                    }
                    while (ulBlockSize);
                }
                else if (pBuf[0] == kTrailer)
                {
                    // We found a GIF trailer - we should be at the end of the file
                    pBuf++;
                    // Go ahead and count it as a packet
                    ulNumPackets++;
                }
                else
                {
                    // Sometimes extra 0 blocks get stuck in GIFs. Check for them
                    // here - if the current byte is 0, then it's OK. If it's not,
                    // then we've gotten lost somewhere.
                    if (pBuf[0] == 0x00)
                    {
                        pBuf++;
                    }
                    else
                    {
                        // Something is wrong with the GIF file.
                        break;
                    }
                }
            }
        }
    }

    return ulNumPackets;
}

HX_RESULT CGIFCodec::InitParseWireFormat(BYTE *pBuffer, UINT32 ulLen)
{
    /* Check for input error conditions */
    if (pBuffer == NULL || ulLen == 0)
    {
        return HXR_INVALID_PARAMETER;
    }

    /* Check state */
    if (m_ulParseState != kStateConstructed)
    {
        return HXR_UNEXPECTED;
    }

    /* Save copy of the buffer pointer and length */
    m_pParseBuffer        = pBuffer;
    m_ulParseBufferLength = ulLen;

    /*
     * We have to make a pass through the image to determine the mark points.
     * Will store these mark points (BYTE pointers) in cMarkList. The first
     * mark point is, of course, the beginning of the file.
     */
    GList cMarkList;
    cMarkList.PushBack((void *) m_pParseBuffer);

    /* Get local copy of buffer */
    BYTE  *pBuf      = m_pParseBuffer;
    BYTE  *pBufLimit = pBuf + m_ulParseBufferLength;

    /* Check the signature */
    if (pBuf[0] != 'G' || pBuf[1] != 'I' || pBuf[2] != 'F')
    {
        return HXR_INVALID_OPERATION;
    }
    pBuf += 3;

    /* Check the version */
    if (pBuf[0] == '8' && pBuf[1] == '9' && pBuf[2] == 'a')
    {
        m_bIsGIF89a = TRUE;
    }
    else if (pBuf[0] == '8' && pBuf[1] == '7' && pBuf[2] == 'a')
    {
        m_bIsGIF89a = FALSE;
    }
    else
    {
        return HXR_INVALID_OPERATION;
    }
    pBuf += 3;

    /* Get the logical screen descriptor */
    ParseLogicalScreenDescriptor(pBuf, m_cLSD);
    pBuf += 7;

    /* Skip the color table */
    if (m_cLSD.m_bGlobalColorTablePresent == TRUE)
    {
        /* Calculate the number of bytes for the global color table */
        UINT32 ulNumBytes = m_cLSD.m_ulColorTableNumEntries * 3;

        /* Advance that number of bytes */
        pBuf += ulNumBytes;
    }

    /*
     * Parse the file and enter marks in the mark list. We're looking for:
     *    a) Beginnings of GCEs and IDs (although if a ID immediately follows
     *       a GCE, we only mark the beginning of the GCE;
     *    b) Beginnings of LZW data for each image.
     */
    BOOL bMarkImageDescriptor = TRUE;
    m_ulDelayTimeSum          = 0;
    m_ulNumImages             = 0;
    while (pBuf < pBufLimit)
    {
        if (pBuf[0] == kImageDescriptor)
        {
            /*
             * We've found an Image Descriptor (ID). If m_bMarkImageDescriptor is
             * FALSE, then this ID is one that immediately followed a GCE, so we
             * DON'T mark it. If m_bMarkImageDescriptor is TRUE, this is an 
             * ID that was NOT preceded by a GCE - these usually happen in GIF87a's.
             */
            if (bMarkImageDescriptor == TRUE)
            {
                cMarkList.PushBack((void *) pBuf);
            }
            else
            {
                bMarkImageDescriptor = TRUE;
            }

            /* Skip the Image Descriptor marker */
            pBuf++;

            /*
             * Whether we mark it or not, we still have to parse it to find out
             * whether or not a local color table is present.
             */
            CGIFImage::ImageDescriptor cID;
            CGIFImage::ParseImageDescriptor(pBuf, cID);
            pBuf += 9;

            // We make sure this frame's dimensions are within the dimensions
            // of the logical screen. If they are not, then we are probably
            // dealing with a corrupt GIF. That's really really bad, cause we probably
            // can't trust any of the data. Therefore, we will simply fail out of
            // parsing and rely on the app above us to do the right thing.
            if (cID.m_ulImageLeft + cID.m_ulImageWidth  > m_cLSD.m_ulLogicalScreenWidth ||
                cID.m_ulImageTop  + cID.m_ulImageHeight > m_cLSD.m_ulLogicalScreenHeight)
            {
                return HXR_FAIL;
            }

            /* If a local color table IS present, then skip it */
            if (cID.m_bLocalColorTablePresent == TRUE)
            {
                pBuf += cID.m_ulLocalColorTableNumEntries * 3;
            }

            /* Now we should be at the beginning of LZW data, so mark this pointer */
            cMarkList.PushBack((void *) pBuf);

            /* Skip the minimum LZW code size */
            UINT32 ulInitialCodeSize = *pBuf++;
            if (ulInitialCodeSize > 12)
            {
                // Code size can't be any bigger than 12. If we
                // do get one bigger than that, then we're dealing
                // with a corrupt file here.
                return HXR_FAIL;
            }

            /* Now skip the LZW blocks */
            SkipBlocks(pBuf, pBufLimit);

            // Check to see if we went past the end of the buffer
            if (pBuf >= pBufLimit)
            {
                // This is really really bad if we get here. That almost certainly
                // means the GIF is corrupt, cause we were happily parsing LZW blocks
                // and went off the end of the file. In reality it probably means that
                // the GIF was corrupt earlier. We will simply fail here. We cannot
                // reliably parse any of this image.
                return HXR_FAIL;
            }

            /* We've just seen an image */
            m_ulNumImages++;
        }
        else if (pBuf[0] == kExtension)
        {
            /* This is an extension, but what type? */
            switch(pBuf[1])
            {
                case kGraphicControlExtension:
                    /* We've found a GCE - mark it but don't mark the ID */
                    cMarkList.PushBack((void *) pBuf);
                    bMarkImageDescriptor = FALSE;
                    pBuf                += 2;
                    UINT32 ulBlockSize;
                    do
                    {
                        /* Get the block size */
                        ulBlockSize = *pBuf++;

                        /* Initialize the GCE */
                        CGIFImage::GraphicControlExtension cGCE;
                        if (ulBlockSize >= 4)
                        {
                            CGIFImage::ParseGraphicControlExtension(pBuf, cGCE);

                            /* Add the delay time */
                            m_ulDelayTimeSum += cGCE.m_ulDelayTime * 10;
                        }

                        /* Advance by the block size */
                        pBuf += ulBlockSize;
                    }
                    while (ulBlockSize > 0);
                    break;
                case kCommentExtension:
                case kPlainTextExtension:
                    pBuf += 2;
                    SkipBlocks(pBuf, pBufLimit);
                    break;
                case kApplicationExtension:
                    ParseApplicationExtension(pBuf);
                    break;
                default:
                    // An extension we don't know - just try to
                    // pass it through
                    pBuf += 2;
                    SkipBlocks(pBuf, pBufLimit);
                    break;

            }
        }
        else if (pBuf[0] == kTrailer)
        {
            /* We found a GIF trailer - we should be at the end of the file */
            cMarkList.PushBack((void *) pBuf);
	    break;
        }
        else
        {
            // Sometimes extra 0 blocks get stuck in GIFs. Check for them
            // here - if the current byte is 0, then it's OK. If it's not,
            // then we've gotten lost somewhere.
            if (pBuf[0] == 0x00)
            {
                pBuf++;
            }
            else
            {
                // Something is wrong with the GIF file.
		//
		// XXXMEH - instead of returning an error, we will
		// be lax and just break here. This will have the effect
		// of potentially sending garbage GIFs down to the
		// client. The upside is that there are a lot of 
		// non-standard GIFs out there that will display in
		// browsers and this will allow them to be displayed.
		break;
            }
        }
    }

    /* The last mark is, of course, the end of the file. */
    cMarkList.PushBack((void *) pBufLimit);

    /*
     * Now we convert our list to a more usable array of ParseSegment's. First
     * we compute the number of segments, which is one less than the number
     * of marks.
     */
    m_ulNumSegmentsAllocated = cMarkList.Size() - 1;
    if (m_ulNumSegmentsAllocated == 0 || m_ulNumSegmentsAllocated > cMarkList.Size())
    {
        return HXR_UNEXPECTED;
    }

    /* Allocate memory for the segment array */
    if (m_pSegment)
    {
        delete [] m_pSegment;
        m_pSegment = NULL;
    }
    m_pSegment = new ParseSegment [m_ulNumSegmentsAllocated];
    if (!m_pSegment)
    {
        return HXR_OUTOFMEMORY;
    }

    /*
     * Now run through the list of marks, computing segments. Note that
     * if the mark in the marklist is an extension not necessary for 
     * deompression, we do not make it into a segment.
     */
    m_ulNumSegments         = 0;
    GListIterator itr       = cMarkList.Begin();
    BYTE         *pLastMark = (BYTE *) *itr;
    itr++;
    do
    {
        BYTE *pCurMark = (BYTE *) *itr;

        /*
         * Filter out all unwanted extensions. We don't send application, 
         * comment, or plain text extensions. We also don't send the GIF
         * Trailer
         */
        if (!((pLastMark[0] == kExtension && (pLastMark[1] == kApplicationExtension ||
                                              pLastMark[1] == kCommentExtension     ||
                                              pLastMark[1] == kPlainTextExtension)) ||
               pLastMark[0] == kTrailer))
        {
            m_pSegment[m_ulNumSegments].pMark  = pLastMark;
            m_pSegment[m_ulNumSegments].ulSize = pCurMark - pLastMark;
            m_ulNumSegments++;
        }
        pLastMark = pCurMark;
        itr++;
    }
    while (itr != cMarkList.End());

    /* Now we're done with the list */
    cMarkList.EraseAll();

    /* Set the state */
    m_ulParseState = kStateParseInitialized;

    return HXR_OK;
}

UINT32 CGIFCodec::GetDelayTime(UINT32 i)
{
    if (i >= m_ulNumImages || m_bIsGIF89a == FALSE)
    {
        return 0;
    }

    UINT32        ulDelay;
    ParseSegment *pSeg = &m_pSegment[1 + (i << 1)];
    if (pSeg->pMark[0] == kExtension && pSeg->pMark[1] == kGraphicControlExtension)
    {
        CGIFImage::GraphicControlExtension cGCE;
        CGIFImage::ParseGraphicControlExtension(pSeg->pMark + 3, cGCE);
        ulDelay = cGCE.m_ulDelayTime;
        if (ulDelay == 0)
        {
            ulDelay = 1;
        }
    }
    else
    {
        ulDelay = 0;
    }

    return ulDelay;
}

UINT32 CGIFCodec::GetImageDataSize(UINT32 i)
{
    if (i >= m_ulNumImages)
    {
        return 0;
    }

    return m_pSegment[2 + (i << 1)].ulSize;
}

HX_RESULT CGIFCodec::GetPacketBufferLength(UINT32 &rulLen)
{
    /* Check state */
    if (m_ulParseState != kStateParseInitialized &&
        m_ulParseState != kStateParseInProgress)
    {
        return HXR_UNEXPECTED;
    }

    /* Is this our first time here? */
    if (m_ulParseState == kStateParseInitialized)
    {
        /* This is the first time here - we need to find the header length */
        UINT32 ulLen = 8                    +  /* Container header size, num images */
                       8 * m_ulNumImages    +  /* Image header size and compressed data size */
                       m_pSegment[0].ulSize;   /* Container header */
        /*
         * Add the individual image header sizes - these are the segments which
         * begin with either an Image Descriptor or a GCE.
         */
        UINT32 i;
        for (i = 0; i < m_ulNumSegments; i++)
        {
            BYTE *pMark = m_pSegment[i].pMark;
            if ( pMark[0] == kImageDescriptor ||
                (pMark[0] == kExtension && pMark[1] == kGraphicControlExtension))
            {
                ulLen += m_pSegment[i].ulSize;
            }
        }

        /* Set the initial segment for data packet parsing */
        m_ulCurSegIndex  = 2;
        m_ulCurSegOffset = 0;

        /* We have our length */
        rulLen = ulLen;
    }
    else
    {
        /* This is NOT the first time here - we need to find the data packet length */
        BYTE  *pBufStart = m_pSegment[m_ulCurSegIndex].pMark;
        BYTE  *pBuf      = pBufStart + m_ulCurSegOffset;
        UINT32 ulSize    = 0;

        /* If we are at the beginning of a LZW segment, we need to skip the min code size */
        if (m_ulCurSegOffset == 0)
        {
            pBuf++;
            ulSize++;
        }

        /* Advance through the blocks, until we reach the ideal packet size */
        UINT32 ulBlockSize;
        do
        {
            ulBlockSize = *pBuf;
            ulSize     += ulBlockSize + 1;
            pBuf       += ulBlockSize + 1;
        }
        while (ulBlockSize > 0 && ulSize < kIdealPacketSize);

        /*
         * Make a check to see if what's left over is not less than the
         * minimum packet size. If it IS less than the minimum packet size,
         * then go ahead and get the rest of it.
         */
        UINT32 ulBytesLeftInSegment = pBufStart + m_pSegment[m_ulCurSegIndex].ulSize - pBuf;
        if (ulBytesLeftInSegment > 0 && ulBytesLeftInSegment < kMinimumPacketSize)
        {
            ulSize += ulBytesLeftInSegment;
        }

        /* Now we have our length */
        rulLen = ulSize;
    }

    return HXR_OK;
}

UINT32 CGIFCodec::ComputeLZWDataSize(BYTE *pLZW)
{
    /* Skip the minimum code size */
    pLZW++;

    /* Run through blocks, adding up sizes */
    UINT32 ulSum = 0;
    UINT32 ulBlockSize;
    do
    {
        ulBlockSize = *pLZW++;
        ulSum      += ulBlockSize;
        pLZW       += ulBlockSize;
    }
    while (ulBlockSize > 0);

    return ulSum;
}

HX_RESULT CGIFCodec::GetPacketBuffer(BYTE *pBuffer, UINT32 ulLen, BOOL &rbFirstInImage)
{
    /* Check for input error conditions */
    if (pBuffer == NULL || ulLen == 0)
    {
        return HXR_INVALID_PARAMETER;
    }

    /* Check state */
    if (m_ulParseState != kStateParseInitialized &&
        m_ulParseState != kStateParseInProgress)
    {
        return HXR_UNEXPECTED;
    }

    /* Is this our first time here? */
    if (m_ulParseState == kStateParseInitialized)
    {
        /* Conainer header size */
        Pack32(m_pSegment[0].ulSize, pBuffer);
        pBuffer += 4;
        /* Number of Images */
        Pack32(m_ulNumImages,      pBuffer);
        pBuffer += 4;
        /* Individual image parameters */
        UINT32 i;
        for (i = 0; i < m_ulNumImages; i++)
        {
            /* Individual image header size */
            Pack32(m_pSegment[1 + (i << 1)].ulSize, pBuffer);
            pBuffer += 4;

            /* Individual image compressed data size */
            Pack32(ComputeLZWDataSize(m_pSegment[2 + (i << 1)].pMark), pBuffer);
            pBuffer += 4;
        }

        /* Copy container header */
        memcpy(pBuffer, m_pSegment[0].pMark, m_pSegment[0].ulSize); /* Flawfinder: ignore */
        pBuffer += m_pSegment[0].ulSize;

        /* Copy each individual image header */
        for (i = 0; i < m_ulNumImages; i++)
        {
            ParseSegment *pSegment = &m_pSegment[1 + (i << 1)];
            memcpy(pBuffer, pSegment->pMark, pSegment->ulSize); /* Flawfinder: ignore */
            pBuffer += pSegment->ulSize;
        }

        /* Clear the flag */
        rbFirstInImage = FALSE;

        /* Set the new state */
        m_ulParseState = kStateParseInProgress;
    }
    else
    {
        /* Copy the data packet */
        memcpy(pBuffer, /* Flawfinder: ignore */
               m_pSegment[m_ulCurSegIndex].pMark + m_ulCurSegOffset,
               ulLen);

        /* Was this the first packet for one of the images? */
        if (m_ulCurSegOffset == 0)
        {
            rbFirstInImage = TRUE;
        }
        else
        {
            rbFirstInImage = FALSE;
        }

        /* Check to see if we're done with this segment */
        if (m_ulCurSegOffset + ulLen >= m_pSegment[m_ulCurSegIndex].ulSize)
        {
            m_ulCurSegIndex += 2;
            m_ulCurSegOffset = 0;
        }
        else
        {
            m_ulCurSegOffset += ulLen;
        }

        /* Check to see if we finished */
        if (m_ulCurSegIndex >= m_ulNumSegments)
        {
            m_ulParseState = kStateParseFinished;
        }
    }

    return HXR_OK;
}

void CGIFCodec::ParseLogicalScreenDescriptor(BYTE *pBuffer, LogicalScreenDescriptor &cLSD)
{
    /* Read Logical Screen Descriptor */
    cLSD.m_ulLogicalScreenWidth     =  (pBuffer[1] << 8) | pBuffer[0];
    cLSD.m_ulLogicalScreenHeight    =  (pBuffer[3] << 8) | pBuffer[2];
    cLSD.m_bGlobalColorTablePresent =  (pBuffer[4] & 0x80 ? TRUE : FALSE);
    cLSD.m_ulOriginalColorBits      = ((pBuffer[4] & 0x70) >> 4) + 1;
    cLSD.m_bColorsSorted            =  (pBuffer[4] & 0x08 ? TRUE : FALSE);
    cLSD.m_ulColorTableBits         =  (pBuffer[4] & 0x07) + 1;
    cLSD.m_ulColorTableNumEntries   = 1 << cLSD.m_ulColorTableBits;
    cLSD.m_ulBackgroundColorIndex   =   pBuffer[5];
    cLSD.m_ulPixelAspectRatio       =   pBuffer[6];
    cLSD.m_fPixelAspectRatio        = (cLSD.m_ulPixelAspectRatio + 15.0F) / 64.0F;
}

HX_RESULT CGIFCodec::ParseContainerHeader(BYTE * &pBuffer)
{
    /* Verify the signature */
    if (pBuffer[0] != 'G' || pBuffer[1] != 'I' || pBuffer[2] != 'F')
    {
        return HXR_INVALID_OPERATION;
    }
    pBuffer += 3;

    /* Get the version */
    if (pBuffer[0] == '8' && pBuffer[1] == '9' && pBuffer[2] == 'a')
    {
        m_bIsGIF89a = TRUE;
    }
    else if (pBuffer[0] == '8' && pBuffer[1] == '7' && pBuffer[2] == 'a')
    {
        m_bIsGIF89a = FALSE;
    }
    else
    {
        return HXR_INVALID_OPERATION;
    }
    pBuffer += 3;

    /* Read the Logical Screen Descriptor */
    ParseLogicalScreenDescriptor(pBuffer, m_cLSD);
    pBuffer += 7;

    /* Read the colortable if present */
    if (m_cLSD.m_bGlobalColorTablePresent == TRUE)
    {
        /* Allocate space for the global color table */
        if (m_pucGlobalColorMap)
        {
            delete [] m_pucGlobalColorMap;
            m_pucGlobalColorMap = NULL;
        }
        UINT32 ulColorTableBytes = m_cLSD.m_ulColorTableNumEntries * 3;
        m_pucGlobalColorMap = new BYTE [ulColorTableBytes];
        if (!m_pucGlobalColorMap)
        {
            return HXR_OUTOFMEMORY;
        }

        /* Copy the global color table */
        memcpy(m_pucGlobalColorMap, pBuffer, ulColorTableBytes); /* Flawfinder: ignore */

        /* Advance the pointer */
        pBuffer += ulColorTableBytes;

        /* Loop through the images, setting the global color map */
        UINT32 i;
        for (i = 0; i < m_ulNumImages; i++)
        {
            m_pImage[i].SetGlobalColorMap(m_cLSD.m_ulColorTableNumEntries,
                                          m_pucGlobalColorMap);
        }
    }

    // Reset the delay time sum
    m_ulDelayTimeSum = 0;
    /* Here we loop through looking for Image Descriptors or Graphic Control Extensions */
    HX_RESULT retVal;
    UINT32    ulImageNum = 0;
    for (;;)
    {
        UINT32 ulMarker = *pBuffer;

        switch(ulMarker)
        {
            case kImageDescriptor:
                retVal = m_pImage[ulImageNum].InitDecompress(pBuffer, m_pImageHeaderSize[ulImageNum]);
                if (retVal != HXR_OK)
                {
                    return retVal;
                }
                retVal = m_pImage[ulImageNum].SetCompressedBufferSize(m_pCompressedBufferSize[ulImageNum]);
                if (retVal != HXR_OK)
                {
                    return retVal;
                }
                pBuffer += m_pImageHeaderSize[ulImageNum];
                ulImageNum++;
                break;
            case kExtension:
                if (pBuffer[1] == kGraphicControlExtension)
                {
                    retVal = m_pImage[ulImageNum].InitDecompress(pBuffer, m_pImageHeaderSize[ulImageNum]);
                    if (retVal != HXR_OK)
                    {
                        return retVal;
                    }
                    // Add the delay time to the delay time sum
                    m_ulDelayTimeSum += m_pImage[ulImageNum].GetDelayTime() * 10;
                    retVal = m_pImage[ulImageNum].SetCompressedBufferSize(m_pCompressedBufferSize[ulImageNum]);
                    if (retVal != HXR_OK)
                    {
                        return retVal;
                    }
                    pBuffer += m_pImageHeaderSize[ulImageNum];
                    ulImageNum++;
                }
                else if (pBuffer[1] == kApplicationExtension)
                {
                    ParseApplicationExtension(pBuffer);
                }
                else
                {
                    /* Skip the extension marker and type */
                    pBuffer += 2;
                    /* Now skip the extension itself */
                    SkipBlocks(pBuffer);
                }
                break;
            case kTrailer:
            default:
                /* Something went wrong */
                return HXR_INVALID_OPERATION;
                break;
        }

        /* If we've gotten all intialized all images, then we're done */
        if (ulImageNum >= m_ulNumImages)
        {
            break;
        }
    }

    return HXR_OK;
}

void CGIFCodec::SkipBlocks(BYTE * &pBuffer, BYTE* pBufLimit)
{
    // If pBufLimit is NULL, then we won't use it at all.
    // If pBufLimit is not NULL, then we will make sure
    // we don't go past the end of the buffer
    UINT32 ulBlockSize;
    do
    {
        /* Get the block size */
        ulBlockSize = *pBuffer++;

        /* Skip that amount of bytes */
        pBuffer += ulBlockSize;
    }
    while (ulBlockSize > 0 &&
           (!pBufLimit || (pBufLimit && pBuffer < pBufLimit)));
}

HX_RESULT CGIFCodec::InitDecompress(BYTE *pBuffer, UINT32 ulLen)
{
    /* Check for input error conditions */
    if (pBuffer == NULL || ulLen == 0)
    {
        return HXR_INVALID_PARAMETER;
    }

    /* Check the state */
    if (m_ulState != kStateConstructed)
    {
        return HXR_UNEXPECTED;
    }

    /* Get the master header length */
    UINT32 ulHeaderLength = UnPack32(pBuffer);
    pBuffer += 4;

    /* Get the number of images */
    m_ulNumImages = UnPack32(pBuffer);
    pBuffer += 4;
    if (m_ulNumImages == 0)
    {
        return HXR_UNEXPECTED;
    }

    /* Allocate array of images */
    if (m_pImage)
    {
        delete [] m_pImage;
        m_pImage = NULL;
    }
    m_pImage = new CGIFImage [m_ulNumImages];
    if (!m_pImage)
    {
        return HXR_OUTOFMEMORY;
    }

    /* Allocate array for image header sizes */
    if (m_pImageHeaderSize)
    {
        delete [] m_pImageHeaderSize;
        m_pImageHeaderSize = NULL;
    }
    m_pImageHeaderSize = new UINT32 [m_ulNumImages];
    if (!m_pImageHeaderSize)
    {
        if (m_pImage)
        {
            delete [] m_pImage;
            m_pImage = NULL;
        }
        return HXR_OUTOFMEMORY;
    }

    /* Allocate array for image header sizes */
    if (m_pCompressedBufferSize)
    {
        delete [] m_pCompressedBufferSize;
        m_pCompressedBufferSize = NULL;
    }
    m_pCompressedBufferSize = new UINT32 [m_ulNumImages];
    if (!m_pCompressedBufferSize)
    {
        if (m_pImage)
        {
            delete [] m_pImage;
            m_pImage = NULL;
        }
        if (m_pImageHeaderSize)
        {
            delete [] m_pImageHeaderSize;
            m_pImageHeaderSize = NULL;
        }
        return HXR_OUTOFMEMORY;
    }

    /* Now set the compressed buffer size for each image */
    HX_RESULT retVal;
    UINT32    i;
    for (i = 0; i < m_ulNumImages; i++)
    {
        /* Get the image header size */
        m_pImageHeaderSize[i] = UnPack32(pBuffer);
        pBuffer += 4;

        /* Get a compressed buffer size */
        m_pCompressedBufferSize[i] = UnPack32(pBuffer);
        pBuffer += 4;
    }

    /* Now parse the container header */
    retVal = ParseContainerHeader(pBuffer);
    if (retVal != HXR_OK)
    {
        if (m_pImage)
        {
            delete [] m_pImage;
            m_pImage = NULL;
        }
        if (m_pImageHeaderSize)
        {
            delete [] m_pImageHeaderSize;
            m_pImageHeaderSize = NULL;
        }
        return retVal;
    }

    /* Set the current image */
    m_ulCurrentImageIndex = 0;

    /* Set the new state */
    m_ulState = kStateDecoInitialized;

    return HXR_OK;
}

HX_RESULT CGIFCodec::Decompress(BYTE *pBuffer, UINT32 ulLen, BOOL bNewImage)
{
    /* Check for input error conditions */
    if (pBuffer == NULL || ulLen == 0)
    {
        return HXR_INVALID_PARAMETER;
    }

    /* Check the state */
    if (m_ulState != kStateDecoInitialized && m_ulState != kStateDecoInProgress)
    {
        return HXR_UNEXPECTED;
    }

    /* Check to see if the we lost a packet on this image */
    if (m_pImage[m_ulCurrentImageIndex].GetValid() == FALSE)
    {
        /* This image was declared invalid due to a lost packet */
        if (bNewImage == FALSE)
        {
            // We're still on the same image, so we can't do anything
            return HXR_OK;
        }
        // We've moved on to a new image, so we can begin decompressing again
        m_ulCurrentImageIndex++;
    }

    /* All we have to do is pass this data on to the current image */
    HX_RESULT retVal = m_pImage[m_ulCurrentImageIndex].Decompress(pBuffer, ulLen);
    if (retVal != HXR_OK)
    {
        return retVal;
    }

    /* Set the state */
    m_ulState = kStateDecoInProgress;

    /* Are we finished with this image? */
    if (m_pImage[m_ulCurrentImageIndex].Finished() == TRUE)
    {
        /* Move on to the next image */
        m_ulCurrentImageIndex++;

        /* If we've done all images, then we're done */
        if (m_ulCurrentImageIndex >= m_ulNumImages)
        {
            m_ulState = kStateDecoFinished;
        }
    }

    return HXR_OK;
}

INT32 CGIFCodec::ComputeStartingImageIndex(INT32 lCurIndex, INT32 lDesiredIndex)
{
    // Does the buffer currently hold any image now?
    INT32 lStartIndex;
    INT32 lBaseIndex;
    if (lCurIndex == -1 || lCurIndex > lDesiredIndex)
    {
        // The buffer doesn't have anything in it now, so we must build
        // from the last full screen image before or equal to ulImgIndex
        // all the way back to 0.
        lBaseIndex = 0;
    }
    else
    {
        // The buffer currently has a valid image in it, so we only need
        // to go back to the first full screen image greater than lCurIndex.
        lBaseIndex = lCurIndex + 1;
    }

    // Find the index of the first image we need to do
    for (lStartIndex = lDesiredIndex; lStartIndex >= lBaseIndex; lStartIndex--)
    {
        if (m_pImage[lStartIndex].GetImageWidth()  == m_cLSD.m_ulLogicalScreenWidth &&
            m_pImage[lStartIndex].GetImageHeight() == m_cLSD.m_ulLogicalScreenHeight)
        {
            break;
        }
    }
    if (lStartIndex < lBaseIndex)
    {
        lStartIndex = 0;
    }

    return lStartIndex;
}

HX_RESULT CGIFCodec::GetIndexImage(INT32 lCurIndex, UINT32 ulImgIndex, BYTE *pBuffer, UINT32 ulWidth, UINT32 ulHeight,
                                   UINT32 ulPadWidth, BOOL bRowsInverted)
{
    // Check for input error
    if (lCurIndex < -1 || lCurIndex >= (INT32) m_ulNumImages || ulImgIndex >= m_ulNumImages ||
        pBuffer == NULL || ulWidth == 0 || ulHeight == 0 || ulPadWidth == 0)
    {
        return HXR_INVALID_PARAMETER;
    }

    // Since frames of a GIF can be dependent upon prior frames, we need to
    // determine which frame we need to go back to
    INT32 lStartIndex = ComputeStartingImageIndex(lCurIndex, (INT32) ulImgIndex);

    // Now do the images from lStartIndex to ulImgIndex
    INT32 i;
    for (i = lStartIndex; i <= (INT32) ulImgIndex; i++)
    {
        HX_RESULT retVal = m_pImage[i].GetIndexImage(pBuffer, ulWidth, ulHeight,
                                                     ulPadWidth, bRowsInverted);
        if (retVal != HXR_OK)
        {
            return retVal;
        }
    }

    return HXR_OK;
}

HX_RESULT CGIFCodec::GetRGBImage(INT32 lCurIndex, UINT32 ulImgIndex, BYTE *pBuffer, UINT32 ulWidth, UINT32 ulHeight, UINT32 ulPadWidth,
                                 UINT32 ulBytesPerPixel, BOOL bRowsInverted, BOOL bRGBOrdering, BYTE ucBackRed, BYTE ucBackGreen, BYTE ucBackBlue,
                                 BYTE ucBackAlpha)
{
    // Check for input error
    if (lCurIndex < -1 || lCurIndex >= (INT32) m_ulNumImages || ulImgIndex >= m_ulNumImages ||
        pBuffer == NULL || ulWidth == 0 || ulHeight == 0 || ulPadWidth == 0 || ulBytesPerPixel == 0)
    {
        return HXR_INVALID_PARAMETER;
    }

    // Since frames of a GIF can be dependent upon prior frames, we need to
    // determine which frame we need to go back to
    INT32 lStartIndex = ComputeStartingImageIndex(lCurIndex, (INT32) ulImgIndex);

    // Now do the images from lStartIndex to ulImgIndex
    INT32 i;
    for (i = lStartIndex; i <= (INT32) ulImgIndex; i++)
    {
        HX_RESULT retVal = m_pImage[i].GetRGBImage(pBuffer, ulWidth, ulHeight, ulPadWidth,
                                                   ulBytesPerPixel, bRowsInverted, bRGBOrdering,
                                                   ucBackRed, ucBackGreen, ucBackBlue, ucBackAlpha);
        if (retVal != HXR_OK)
        {
            return retVal;
        }
    }

    return HXR_OK;
}

HX_RESULT CGIFCodec::GetRGBImageEx(INT32 lCurIndex, UINT32 ulImgIndex, BYTE *pBuffer, UINT32 ulWidth, UINT32 ulHeight,
                                   UINT32 ulPadWidth, UINT32 ulBytesPerPixel, BOOL bRowsInverted, BOOL bRGBOrdering,
                                   UINT32 ulBgColor, BOOL bMediaOpacity, UINT32 ulMediaOpacity,
                                   BOOL bChromaKey, UINT32 ulChromaKey, UINT32 ulChromaKeyTol, UINT32 ulChromaKeyOpacity)
{
    HX_RESULT retVal = HXR_OK;

    if (lCurIndex >= -1 && lCurIndex < (INT32) m_ulNumImages &&
        ulImgIndex < m_ulNumImages && pBuffer && ulWidth && ulHeight &&
        ulPadWidth && ulBytesPerPixel)
    {
        // Since frames of a GIF can be dependent upon prior frames, we need to
        // determine which frame we need to go back to
        INT32 lStartIndex = ComputeStartingImageIndex(lCurIndex, (INT32) ulImgIndex);
        // Now do the images from lStartIndex to ulImgIndex
        INT32 i = 0;
        for (i = lStartIndex; i <= (INT32) ulImgIndex; i++)
        {
            retVal = m_pImage[i].GetRGBImageEx(pBuffer, ulWidth, ulHeight, ulPadWidth,
                                               ulBytesPerPixel, bRowsInverted, bRGBOrdering,
                                               ulBgColor, bMediaOpacity, ulMediaOpacity,
                                               bChromaKey, ulChromaKey, ulChromaKeyTol, ulChromaKeyOpacity);
            if (FAILED(retVal))
            {
                break;
            }
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

HX_RESULT CGIFCodec::GetRGB32(UINT32 ulImageNum, BYTE *pBuffer, UINT32 ulRowStride, BOOL bRowsInverted)
{
    HX_RESULT retVal = HXR_OK;

    if (pBuffer)
    {
        if (ulImageNum < m_ulNumImages && m_pImage)
        {
            retVal = m_pImage[ulImageNum].GetRGB32(pBuffer, ulRowStride, bRowsInverted);
        }
        else
        {
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

void CGIFCodec::PacketLost()
{
    // Clear the valid flag for the current image
    m_pImage[m_ulCurrentImageIndex].SetValid(FALSE);
    // Set the finished flag for this image
    m_pImage[m_ulCurrentImageIndex].SetFinished();
}

BOOL CGIFCodec::LocalColorMapsPresent()
{
    UINT32 i;
    for (i = 0; i < m_ulNumImages; i++)
    {
        if (m_pImage[i].LocalColorMapPresent())
        {
            return TRUE;
        }
    }
    return FALSE;
}

void CGIFCodec::ParseApplicationExtension(BYTE * &pBuf)
{
    pBuf += 2; // skip the extension introducer and the application extension label
    // The next block should always be 11 bytes - 8 bytes for application identifier
    // and 3 bytes for the application authentication code. If it's not then just
    // skip these blocks
    if (pBuf[0] == 11)
    {
        // Now we check to see if this is a NETSCAPE2.0 application extension.
        // If it is, then it contains the loop count for the animation.
        if (!strncmp((const char *) pBuf + 1, "NETSCAPE2.0", 11))
        {
            // Yep, we've got a NETSCAPE2.0 application extension,
            // so attempt to extract the loop count
            if (pBuf[12] == 0x03 && pBuf[13] == 0x01 && pBuf[16] == 0x00)
            {
                UINT32 ulCount = (pBuf[15] << 8) | pBuf[14];
                if (ulCount == 0)
                {
                    m_ulLoopCount = 0;
                }
                else
                {
                    m_ulLoopCount = ulCount + 1;
                }
                pBuf += 17;
            }
            else
            {
                SkipBlocks(pBuf);
            }
        }
        else
        {
            SkipBlocks(pBuf);
        }
    }
    else
    {
        SkipBlocks(pBuf);
    }
}
