/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: ijglwrap.h,v 1.1.26.1 2004/07/09 01:53:19 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 ***** */

#ifndef _CIJG_LIBRARY_WRAPPER_H
#define _CIJG_LIBRARY_WRAPPER_H

extern "C"
{
    #include "jinclude.h"
    #include "jpeglib.h"
    #include "jerror.h"
}

#include <setjmp.h>

class CIJGLibraryWrapper : public CHXBaseCountingObject,
                           public IUnknown
{
protected:
    enum
    {
        kStateNotCreated       = 0, // Constructed, but jpeg_create_decompress() not called
        kStateCreated          = 1, // jpeg_create_decompress() has been called
        kStateHeaderRead       = 2, // jpeg_read_header() been called
        kStateStarted          = 3, // jpeg_start_decompress() has been called
        kStateReadingScanlines = 4, // In the middle of calling jpeg_read_scanlines()
        kStateReadingCompleted = 5, // Done with scanlines loop but not called jpeg_finish_decompress()
        kStateFinished         = 6, // jpeg_finish_decompress() called
        kStateDestroyed        = 7, // jpeg_destroy() called
        kStateFatalError       = 8  // Fatal error occurred - no more processing possible
    };

    struct BufferListSrcMgr
    {
        struct jpeg_source_mgr m_cPubSrcMgr;     // IJGL source manager
        GList                  m_cBufferList;    // List of IHXBuffers
        INT32                  m_lCurrentIndex;  // Current IHXBuffer in list
        BOOL                   m_bFirstFill;     // First call to fill_input_buffer()?
        UINT32                 m_ulBufferOffset; // How many header bytes at the beginning of each buffer?
    };
    struct WrapperErrorMgr
    {
        struct jpeg_error_mgr m_cPubErrMgr;    // IJGL error manager
        GString               m_cErrStr;       // Holds error string
        jmp_buf               m_cSetJmpBuf;    // Jump buffer for getting out of error_exit()
    };

    INT32                         m_lRefCount;
    struct jpeg_decompress_struct m_cDecompress;       // Primary IJGL decompression struct
    UINT32                        m_ulState;           // Decompression state
    BufferListSrcMgr              m_cSrcMgr;           // Our "buffer list" source manager
    WrapperErrorMgr               m_cErrMgr;           // Our error manager
    BYTE                         *m_pImageBuffer;      // Output buffer
    UINT32                        m_ulImageBufferSize; // Size in bytes of output buffer
    UINT32                        m_ulPadWidth;        // Length (in bytes) of output scanline
    BOOL                          m_bRowsInverted;     // Should decode into row-inverted buffer
    BOOL                          m_bSuspended;        // TRUE - suspended FALSE - enough data
    INT32                         m_lSessionHandle;    // id of this session
    BOOL                          m_bNeedPacket;       // have we received the first packet
    BOOL                          m_bValid;            // true if we received a valid header
    UINT32                        m_ulLastSeqNum;      // sequence number of last packet received
    BOOL                          m_bBigEndian;
    IHXBuffer*                   m_pLastOpaque;       // last opaque data buffer
    UINT32                        m_ulOpacity;         // forced opacity
    BOOL                          m_bChromaKeySpecified; // use chroma key or not
    UINT32                        m_ulChromaKey;         // chroma key color
    UINT32                        m_ulChromaKeyTol;      // chroma key tolerance
    UINT32                        m_ulChromaKeyOpacity;  // chroma key opacity

    void             ExpandGrayToRGB(BYTE*  pBuf,
                                     UINT32 ulWidth,
                                     BOOL   bBigEndian);
    void             ProcessOpacityAndChromaKey(BYTE*  pBuf,
                                                UINT32 ulWidth,
                                                UINT32 ulOpacity,
                                                BOOL   bChromaKey,
                                                UINT32 ulChromaKey,
                                                UINT32 ulChromaKeyTol,
                                                UINT32 ulChromaKeyOpacity);
    static void      ErrorExit(j_common_ptr cinfo);
    static void      OutputMessage(j_common_ptr cinfo);
    static void      InitSource(j_decompress_ptr cinfo);
    static boolean   FillInputBuffer(j_decompress_ptr cinfo);
    static void      SkipInputData(j_decompress_ptr cinfo, long num_bytes);
    static void      TermSource(j_decompress_ptr cinfo);
public:
    CIJGLibraryWrapper();

    ~CIJGLibraryWrapper();

    // IUnknown methods
    STDMETHOD(QueryInterface)  (THIS_ REFIID riid, void** ppvObj);
    STDMETHOD_(UINT32,AddRef)  (THIS);
    STDMETHOD_(UINT32,Release) (THIS);

    HX_RESULT    Initialize() { return Initialize(20); }
    HX_RESULT    Initialize(UINT32 ulBufferOffset);
    void         Terminate();
    HX_RESULT    ReadHeader(IHXValues *pValues);
    HX_RESULT    ReadHeader();
    HX_RESULT    SetOutputParameters(BYTE *pImageBuffer, UINT32 ulImageBufferSize,
                                     UINT32 ulPadWidth,  BOOL   bRowsInverted);
    HX_RESULT    Decompress();
    void         AppendBuffer(IHXBuffer *pBuffer);
    void         GetLastPacketBuffer(IHXBuffer **ppBuffer);
    UINT32       GetMemorySum();
    INT32        GetLastError()   { return m_cDecompress.err->msg_code; }
    const char * GetErrorString() { return m_cErrMgr.m_cErrStr.c_str(); }
    BOOL         IsSuspended()    { return m_bSuspended; }
    BOOL         IsFinished()     { return (m_ulState == kStateFinished ? TRUE : FALSE); }

    INT32        GetImageWidth()    const { return (INT32) m_cDecompress.image_width;    }
    INT32        GetImageHeight()   const { return (INT32) m_cDecompress.image_height;   }
    INT32        GetNumComponents() const { return (INT32) m_cDecompress.num_components; }

    INT32        GetSessionHandle()                     { return m_lSessionHandle; }
    void         SetSessionHandle(INT32 lSessionHandle) { m_lSessionHandle = lSessionHandle; }

    BOOL         GetNeedPacket()                 { return m_bNeedPacket; }
    void         SetNeedPacket(BOOL bNeedPacket) { m_bNeedPacket = bNeedPacket; }

    BOOL         GetValid()            { return m_bValid; }
    void         SetValid(BOOL bValid) { m_bValid = bValid; }

    UINT32       GetLastSequenceNumber()                { return m_ulLastSeqNum; }
    void         SetLastSequenceNumber(UINT32 ulSeqNum) { m_ulLastSeqNum = ulSeqNum; }

    HX_RESULT    GetLastOpaqueBuffer(REF(IHXBuffer*) rpOpaque);
    void         SetLastOpaqueBuffer(IHXBuffer* pOpaque);

    UINT32       GetRestartInterval()   { return m_cDecompress.restart_interval; }

    UINT32       GetOpacity() const      { return m_ulOpacity; }
    void         SetOpacity(UINT32 ulOp) { m_ulOpacity = ulOp; }

    void         SetChromaKeyInfo(UINT32 ulKey, UINT32 ulTol, UINT32 ulOp);

    static HX_RESULT TranscodeToRestartInterval(IHXBuffer *      pInputImage,
                                                UINT32            ulRestartInterval,
                                                REF(IHXBuffer *) rpOutputImage);
};

#endif
