/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: wbmpff.cpp,v 1.2.18.1 2004/07/09 01:53:15 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "hxcom.h"
#include "hxtypes.h"
#include "hxwintyp.h"
#include "hxcomm.h"
#include "ihxpckts.h"
#include "hxfiles.h"
#include "hxformt.h"
#include "hxplugn.h"
#include "hxpends.h"
#include "hxasm.h"
#include "hxerror.h"
#include "hxver.h"
#include "pckunpck.h"
#include "baseobj.h"
#ifdef _AIX
#include "dllpath.h"
ENABLE_MULTILOAD_DLLACCESS_PATHS(wbmpff);
#endif
#include "wbmphdr.h"
#include "wbmpff.h"
#include "wbmpffdll.ver"

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

const char*  const CWBMPFileFormat::m_pszDescription       = "Helix WBMP File Format Plugin";
const char*  const CWBMPFileFormat::m_pszCopyright         = HXVER_COPYRIGHT;
const char*  const CWBMPFileFormat::m_pszMoreInfoURL       = HXVER_MOREINFO;
const char*  const CWBMPFileFormat::m_ppszFileMimeTypes[]  = {"image/x-wap.wbmp", NULL};
const char*  const CWBMPFileFormat::m_ppszFileExtensions[] = {"wbmp", NULL};
const char*  const CWBMPFileFormat::m_ppszFileOpenNames[]  = {"Wireless BMP Images (*.wbmp)", NULL};
const char*  const CWBMPFileFormat::m_pszStreamMimeType    = "application/vnd.rn-wbmpstream";
const UINT32 CWBMPFileFormat::m_ulContentVersion     = HX_ENCODE_PROD_VERSION(0, 0, 0, 0);
const UINT32 CWBMPFileFormat::m_ulStreamVersion      = HX_ENCODE_PROD_VERSION(0, 0, 0, 0);

#ifdef _WINDOWS
extern HINSTANCE g_hInstance;
#endif

CWBMPFileFormat::CWBMPFileFormat()
{
    m_lRefCount           = 0;
    m_pContext            = NULL;
    m_pFileObject         = NULL;
    m_pFormatResponse     = NULL;
    m_pCommonClassFactory = NULL;
    m_pFileHeader         = NULL;
    m_ulState             = kStateReady;
    m_ulImageWidth        = 0;
    m_ulImageHeight       = 0;
    m_ulHeaderSize        = 0;
    m_ulDesiredFileOffset = 0;
    m_ulFileOffset        = 0;
    m_ulBytesPerRow       = 0;
    m_ulRowsPerPacket     = 0;
    m_ulNextRow           = 0;
}

CWBMPFileFormat::~CWBMPFileFormat()
{
    HX_RELEASE(m_pContext);
    HX_RELEASE(m_pFileObject);
    HX_RELEASE(m_pFormatResponse);
    HX_RELEASE(m_pCommonClassFactory);
    HX_RELEASE(m_pFileHeader);
};

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

    if (IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppvObj = (IUnknown*) (IHXPlugin*) this;
    }
    else if (IsEqualIID(riid, IID_IHXPlugin))
    {
        AddRef();
        *ppvObj = (IHXPlugin*) this;
    }
    else if (IsEqualIID(riid, IID_IHXFileFormatObject))
    {
        AddRef();
        *ppvObj = (IHXFileFormatObject*) this;
    }
    else if (IsEqualIID(riid, IID_IHXFileResponse))
    {
        AddRef();
        *ppvObj = (IHXFileResponse*) this;
    }
    else
    {
        *ppvObj = NULL;
        retVal  = HXR_NOINTERFACE;
    }

    return retVal;
}

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

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

    delete this;

    return 0;
}

STDMETHODIMP CWBMPFileFormat::GetPluginInfo(REF(BOOL)        rbLoadMultiple,
                                            REF(const char*) rpszDescription,
                                            REF(const char*) rpszCopyright,
                                            REF(const char*) rpszMoreInfoURL,
                                            REF(UINT32)      rulVersionNumber)
{
    rbLoadMultiple   = TRUE;
    rpszDescription  = m_pszDescription;
    rpszCopyright    = m_pszCopyright;
    rpszMoreInfoURL  = m_pszMoreInfoURL;
    rulVersionNumber = TARVER_ULONG32_VERSION;

    return HXR_OK;
}

STDMETHODIMP CWBMPFileFormat::InitPlugin(IUnknown* pContext)
{
    HX_RESULT retVal = HXR_FAIL;

    if (pContext)
    {
        // Save a copy of the calling context
        HX_RELEASE(m_pContext);
        m_pContext = pContext;
        m_pContext->AddRef();
        // Get an interface to the common class factory
        HX_RELEASE(m_pCommonClassFactory);
        retVal = m_pContext->QueryInterface(IID_IHXCommonClassFactory,
                                            (void**) &m_pCommonClassFactory);
    }

    return retVal;
}


STDMETHODIMP CWBMPFileFormat::GetFileFormatInfo(REF(const char**) rppszFileMimeTypes,
                                                REF(const char**) rppszFileExtensions,  
                                                REF(const char**) rppszFileOpenNames)
{
    rppszFileMimeTypes  = (const char**) m_ppszFileMimeTypes;
    rppszFileExtensions = (const char**) m_ppszFileExtensions;
    rppszFileOpenNames  = (const char**) m_ppszFileOpenNames;
    return HXR_OK;
}

STDMETHODIMP CWBMPFileFormat::InitFileFormat(IHXRequest*        pRequest, 
                                             IHXFormatResponse* pFormatResponse,
                                             IHXFileObject*     pFileObject)
{
    HX_RESULT retVal = HXR_FAIL;

    if (pFormatResponse && pFileObject)
    {
        // Save members
        HX_RELEASE(m_pFormatResponse);
        m_pFormatResponse = pFormatResponse;
        m_pFormatResponse->AddRef();
        HX_RELEASE(m_pFileObject);
        m_pFileObject = pFileObject;
        m_pFileObject->AddRef();
        // Set the state
        m_ulState = kStateFileInitDonePending;
        // Init the file object
        retVal = m_pFileObject->Init(HX_FILE_READ | HX_FILE_BINARY, this);
    }

    if (FAILED(retVal) && pFormatResponse)
    {
        pFormatResponse->InitDone(HXR_FAIL);
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::GetFileHeader()
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateReady)
    {
        // Set the state
        m_ulState = kStateFileHeaderSeekDonePending;
        // Seek back to the beginning
        m_pFileObject->Seek(0, FALSE);
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::GetStreamHeader(UINT16 usStreamNum)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateReady)
    {
        // Create an IHXValues object
        IHXValues* pStreamHeader = NULL;
        retVal = m_pCommonClassFactory->CreateInstance(CLSID_IHXValues, (void**) &pStreamHeader);
        if (SUCCEEDED(retVal))
        {
            // Set the mime type
            SetCStringProperty(pStreamHeader, "MimeType",
                               m_pszStreamMimeType, m_pContext);
            // Set the intrinsic duration
            // This is a "discrete" media stream; it has no
            // intrinsic (native) duration; we want to
            // continue declaring 5000 for the duration,
            // however, since we may be serving this stream
            // to an old, SMIL 1.0 presentation or as a
            // stand-alone play in which the author expects
            // the old 5000-msec duration:
            SetCStringProperty(pStreamHeader, "intrinsicDurationType",
                               "intrinsicDurationDiscrete", m_pContext);
            // Create ASM rulebook string
            char szASM[64]; /* Flawfinder: ignore */
            sprintf(szASM, /* Flawfinder: ignore */
                    "AverageBandwidth=%lu,Priority=5;",
                    kDefaultBitrate);
            // Set the ASM rulebook
            SetCStringProperty(pStreamHeader, "ASMRuleBook", szASM, m_pContext);
            // Create an opaque data buffer object
            IHXBuffer* pOpaque = NULL;
            retVal = m_pCommonClassFactory->CreateInstance(CLSID_IHXBuffer,
                                                           (void**) &pOpaque);
            if (SUCCEEDED(retVal))
            {
                // Copy the header into the opaque data
                retVal = pOpaque->Set((BYTE*) m_pFileHeader->GetBuffer(), m_ulHeaderSize);
                if (SUCCEEDED(retVal))
                {
                    // Now that we've copied the data into the
                    // opaque stream header data, we can release
                    // the buffer we read from the GetFileHeader call.
                    HX_RELEASE(m_pFileHeader);
                    // Set the properties
                    pStreamHeader->SetPropertyBuffer ("OpaqueData",       pOpaque);
                    pStreamHeader->SetPropertyULONG32("StreamNumber",     0);
                    pStreamHeader->SetPropertyULONG32("MaxBitRate",       kDefaultBitrate);
                    pStreamHeader->SetPropertyULONG32("AvgBitRate",       kDefaultBitrate);
                    pStreamHeader->SetPropertyULONG32("MaxPacketSize",    kIdealPacketSize);
                    pStreamHeader->SetPropertyULONG32("AvgPacketSize",    kIdealPacketSize);
                    pStreamHeader->SetPropertyULONG32("Duration",         kDefaultDuration);
                    pStreamHeader->SetPropertyULONG32("ContentVersion",   m_ulContentVersion);
                    pStreamHeader->SetPropertyULONG32("StreamVersion",    m_ulStreamVersion);
                    // Set the new state
                    m_ulState = kStateReady;
                    // Set that we want to starting reading at row 0
                    m_ulNextRow = 0;
                    // Pass the stream header back to the server
                    m_pFormatResponse->StreamHeaderReady(HXR_OK, pStreamHeader);
                }
            }
            HX_RELEASE(pOpaque);
        }
        HX_RELEASE(pStreamHeader);

        if (FAILED(retVal))
        {
            m_pFormatResponse->StreamHeaderReady(retVal, NULL);
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::GetPacket(UINT16 usStreamNum)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateReady)
    {
        if (usStreamNum == 0)
        {
            // Is the current row inside the height of the image?
            if (m_ulNextRow < m_ulImageHeight)
            {
                // Compute the file offset we should be at based
                // on which row we want to send
                m_ulDesiredFileOffset = m_ulHeaderSize + m_ulNextRow * m_ulBytesPerRow;
                // Are we already at this offset?
                if (m_ulDesiredFileOffset == m_ulFileOffset)
                {
                    // Compute the number of bytes to read
                    UINT32 ulBytesToRead = m_ulBytesPerRow * m_ulRowsPerPacket;
                    // Set the state for a read
                    m_ulState = kStateGetPacketReadDonePending;
                    // Read that many bytes
                    m_pFileObject->Read(ulBytesToRead);
                }
                else
                {
                    // We need to seek, so set the state
                    m_ulState = kStateGetPacketSeekDonePending;
                    // Seek to the desired offset
                    m_pFileObject->Seek(m_ulDesiredFileOffset, FALSE);
                }
            }
            else
            {
                // We're done, so send a stream done
                m_pFormatResponse->StreamDone(0);
            }
        }
        else
        {
            retVal = HXR_INVALID_PARAMETER;
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::Seek(UINT32 ulOffset)
{
    HX_RESULT retVal = HXR_OK;

    if (m_pFormatResponse)
    {
        // Whenever we get a Seek(), we resend all
        // the packets
        m_ulNextRow = 0;
        // Reset the state
        m_ulState = kStateReady;
        // Tell the format response we're ready
        m_pFormatResponse->SeekDone(HXR_OK);
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::Close()
{
    HX_RESULT retVal = HXR_OK;

    // Close the file
    if (m_pFileObject)
    {
        m_pFileObject->Close();
    }
    HX_RELEASE(m_pContext);
    HX_RELEASE(m_pFileObject);
    HX_RELEASE(m_pFormatResponse);
    HX_RELEASE(m_pCommonClassFactory);
    HX_RELEASE(m_pFileHeader);
    m_ulState             = kStateReady;
    m_ulImageWidth        = 0;
    m_ulImageHeight       = 0;
    m_ulHeaderSize        = 0;
    m_ulDesiredFileOffset = 0;
    m_ulFileOffset        = 0;
    m_ulBytesPerRow       = 0;
    m_ulRowsPerPacket     = 0;
    m_ulNextRow           = 0;

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::InitDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateFileInitDonePending)
    {
        // Set the state
        m_ulState = kStateReady;
        // Call back to the response interface
        m_pFormatResponse->InitDone(status);
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::ReadDone(HX_RESULT status, IHXBuffer* pBuffer)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateFileHeaderReadDonePending)
    {
        retVal = status;
        if (SUCCEEDED(retVal))
        {
            // Save the header to be send as opaque
            // data in the stream header
            HX_RELEASE(m_pFileHeader);
            m_pFileHeader = pBuffer;
            m_pFileHeader->AddRef();
            // Set the file offset
            m_ulFileOffset = pBuffer->GetSize();
            // Parse the buffer to determine type, width, height
            // For now, we assume that the type will be Type 0,
            // since that's the only one the standard currently defines.
            retVal = ParseWBMPHeader(pBuffer->GetBuffer(),
                                     pBuffer->GetSize(),
                                     m_ulImageWidth,
                                     m_ulImageHeight,
                                     m_ulHeaderSize);
            if (SUCCEEDED(retVal))
            {
                // We assume type 0, which is 8 bits per pixel monochrome
                // where white = 1 and black = 0. If the width is not
                // a multiple of 8, then rows are padded up to a multiple
                // of 8. So compute how many bytes in a row.
                m_ulBytesPerRow = (m_ulImageWidth + 7) >> 3;
                // Each packet will hold an integral number of rows.
                // Determine how many rows per packet
                m_ulRowsPerPacket = kIdealPacketSize / m_ulBytesPerRow;
                // Create an IHXValues
                IHXValues* pFileHeader = NULL;
                retVal = m_pCommonClassFactory->CreateInstance(CLSID_IHXValues,
                                                               (void**) &pFileHeader);
                if (SUCCEEDED(retVal))
                {
                    // Set the stream count
                    pFileHeader->SetPropertyULONG32("StreamCount", 1);
                    // Set the state
                    m_ulState = kStateReady;
                    // Send the file header
                    m_pFormatResponse->FileHeaderReady(HXR_OK, pFileHeader);
                }
                HX_RELEASE(pFileHeader);
            }
        }

        if (FAILED(retVal))
        {
            // Set the state
            m_ulState = kStateFileHeaderCloseDonePending;
            // Close the file
            m_pFileObject->Close();
        }
    }
    else if (m_ulState == kStateGetPacketReadDonePending)
    {
        retVal = status;
        if (SUCCEEDED(retVal))
        {
            // Compute the number of rows in this buffer
            UINT32 ulNumRows = pBuffer->GetSize() / m_ulBytesPerRow;
            // Update the file offset
            m_ulFileOffset += pBuffer->GetSize();
            // Create a packet buffer
            IHXBuffer* pPacketBuffer = NULL;
            retVal = m_pCommonClassFactory->CreateInstance(CLSID_IHXBuffer, (void**) &pPacketBuffer);
            if (SUCCEEDED(retVal))
            {
                // Set the size
                retVal = pPacketBuffer->SetSize(pBuffer->GetSize() + 4);
                if (SUCCEEDED(retVal))
                {
                    // Set the starting row number in the buffer
                    // in big endian format
                    BYTE* pBuf = pPacketBuffer->GetBuffer();
                    pBuf[0] = (BYTE) ((m_ulNextRow & 0xFF000000) >> 24);
                    pBuf[1] = (BYTE) ((m_ulNextRow & 0x00FF0000) >> 16);
                    pBuf[2] = (BYTE) ((m_ulNextRow & 0x0000FF00) >>  8);
                    pBuf[3] = (BYTE)  (m_ulNextRow & 0x000000FF);
                    // Copy the data
                    memcpy(pBuf + 4, pBuffer->GetBuffer(), ulNumRows * m_ulBytesPerRow);
                    // Create a packet
                    IHXPacket* pPacket = NULL;
                    retVal = m_pCommonClassFactory->CreateInstance(CLSID_IHXPacket, (void**) &pPacket);
                    if (SUCCEEDED(retVal))
                    {
                        retVal = pPacket->Set(pPacketBuffer,    // opaque data
                                              0,                // time stamp
                                              0,                // stream 0
                                              HX_ASM_SWITCH_ON, // ASM flag
                                              0);               // ASM rule
                        if (SUCCEEDED(retVal))
                        {
                            // Update the next row
                            m_ulNextRow += ulNumRows;
                            // Set the state
                            m_ulState = kStateReady;
                            // Send the packet
                            m_pFormatResponse->PacketReady(retVal, pPacket);
                        }
                    }
                    HX_RELEASE(pPacket);
                }
            }
            HX_RELEASE(pPacketBuffer);
        }
        if (FAILED(retVal))
        {
            // Issue a StreamDone
            m_pFormatResponse->StreamDone(0);
            // Set the state
            m_ulState = kStateGetPacketCloseDonePending;
            // Close the file
            m_pFileObject->Close();
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}


STDMETHODIMP CWBMPFileFormat::SeekDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateFileHeaderSeekDonePending)
    {
        if (SUCCEEDED(status))
        {
            // Set the state
            m_ulState = kStateFileHeaderReadDonePending;
            // Read some header bytes
            m_pFileObject->Read(kHeaderReadSize);
        }
        else
        {
            // Set the state
            m_ulState = kStateFileHeaderCloseDonePending;
            // Close the file
            m_pFileObject->Close();
        }
    }
    else if (m_ulState == kStateGetPacketSeekDonePending)
    {
        if (SUCCEEDED(status))
        {
            // Set the file offset
            m_ulFileOffset = m_ulDesiredFileOffset;
            // Compute the number of bytes to read
            UINT32 ulBytesToRead = m_ulBytesPerRow * m_ulRowsPerPacket;
            // Set the state for a read
            m_ulState = kStateGetPacketReadDonePending;
            // Read that many bytes
            m_pFileObject->Read(ulBytesToRead);
        }
        else
        {
            // We failed, so issue a StreamDone()
            m_pFormatResponse->StreamDone(0);
            // Set the state
            m_ulState = kStateGetPacketCloseDonePending;
            // Close the file
            m_pFileObject->Close();
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::CloseDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateFileHeaderCloseDonePending)
    {
        // We can release the file object
        HX_RELEASE(m_pFileObject);
        // Set the state
        m_ulState = kStateReady;
        // The only reason we would have gotten here during
        // reading the file header is if we failed, so 
        // respond that we failed
        m_pFormatResponse->FileHeaderReady(HXR_FAIL, NULL);
    }
    else if (m_ulState == kStateGetPacketCloseDonePending)
    {
        // We can release the file object
        HX_RELEASE(m_pFileObject);
        // Reset the state
        m_ulState = kStateReady;
        // Don't really have to do anything else, since
        // we have already issued a StreamDone() if we
        // ever encountered an error during GetPacket().
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CWBMPFileFormat::WriteDone(HX_RESULT status)
{
    // We don't ever write, so we don't expect to get this...
    return HXR_UNEXPECTED;
}

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

    if (ppIUnknown)
    {
        // Set default
        *ppIUnknown = NULL;
        // Create the object
        CWBMPFileFormat *pObj = new CWBMPFileFormat();
        if (pObj)
        {
            // QI for IUnknown
            retVal = pObj->QueryInterface(IID_IUnknown, (void**) ppIUnknown);
        }
        else
        {
            retVal = HXR_OUTOFMEMORY;
        }
        if (FAILED(retVal))
        {
            HX_DELETE(pObj);
        }
    }
    else
    {
        retVal = HXR_FAIL;
    }

    return HXR_OK;
}

