/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: jpegvsrc.cpp,v 1.2.24.1 2004/07/09 01:53:35 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 "jpgfformat.ver"

#include "hxcom.h"
#include "hxtypes.h"
#include "hxcomm.h"
#include "ihxpckts.h"
#include "hxformt.h"
#include "hxplugn.h"
#include "hxvsrc.h"  /*IHXFileViewSource*/
#include "ihxfgbuf.h"
#include "baseobj.h"
#include "chxfgbuf.h"
#include "growingq.h" /*CHXFragmentedBuffer*/
#include "hxassert.h"

#include "jpegvsrc.h"
#include "vsrcinfo.h"
#include "timerep.h"

const UINT32 INITIAL_QUEUESIZE = 1000;

CJPEGViewSource::CJPEGViewSource(IUnknown* pContext, 
				     IUnknown* pContainer)
    :	m_lRefCount(0)
    ,	m_pContext(NULL)
    ,	m_pCommonClassFactory(NULL)
    ,	m_pFileObject(NULL)
    ,	m_pViewSourceResponse(NULL)
    ,	m_type(HTML_SOURCE)
    ,	m_pContainer(NULL)
    ,	m_ulFileSize(0)
    ,	m_pFragFileBuffer(NULL)
    ,	m_ulNumBytesRead(0)
    ,	m_state(kStateConstructed)
    ,	m_ulWidth(0)
    ,	m_ulHeight(0)
    ,	m_ulNumComponents(0)
    ,	m_bProgressive(FALSE)
    ,	m_pViewSourceOptions(NULL)
{
    HX_RELEASE(m_pContext);
    m_pContext = pContext;
    HX_ASSERT(m_pContext != NULL);
    m_pContext->AddRef();

    HX_RELEASE(m_pContainer);
    m_pContainer = pContainer;
    HX_ASSERT(m_pContainer != NULL);
    m_pContainer->AddRef();
};
CJPEGViewSource::~CJPEGViewSource()
{
    Close();
}
/* *** IUnknown methods *** */

/************************************************************************
 *  Method:
 *	IUnknown::QueryInterface
 *  Purpose:
 *	Implement this to export the interfaces supported by your 
 *	object.
 */
STDMETHODIMP CJPEGViewSource::QueryInterface(REFIID riid, void** ppvObj)
{
    if (IsEqualIID(riid, IID_IHXFileViewSource))
    {
	AddRef();
	*ppvObj = (IHXFileViewSource*)this;
	return HXR_OK;
    }
    else if (m_pContainer != NULL)
    {
        // deligate to our container
        return m_pContainer->QueryInterface(riid, ppvObj);
    }
    else if (IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppvObj = m_pContainer;
        return HXR_OK;
    }
    *ppvObj = NULL;
    return HXR_NOINTERFACE;
}

/************************************************************************
 *  Method:
 *	IUnknown::AddRef
 *  Purpose:
 *	Everyone usually implements this the same... feel free to use
 *	this implementation.
 */
STDMETHODIMP_(ULONG32) CJPEGViewSource::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

/************************************************************************
 *  Method:
 *	IUnknown::Release
 *  Purpose:
 *	Everyone usually implements this the same... feel free to use
 *	this implementation.
 */
STDMETHODIMP_(ULONG32) CJPEGViewSource::Release()
{
    if (InterlockedDecrement(&m_lRefCount) > 0)
    {
        return m_lRefCount;
    }

    delete this;
    return 0;
}

/************************************************************************
 *	Method:
 *	    IHXFileViewSource::Close()
 *	Purpose:
 *	    Close down...
 */
STDMETHODIMP 
CJPEGViewSource::Close()
{
    HX_RELEASE(m_pViewSourceOptions);
    HX_RELEASE(m_pContext);
    HX_RELEASE(m_pCommonClassFactory);
    HX_RELEASE(m_pContainer);
    HX_RELEASE(m_pFragFileBuffer);
    if ( m_pFileObject != NULL )
    {
	m_pFileObject->Close();
	HX_RELEASE(m_pFileObject);
    }
    
    m_state = kStateConstructed;
    if ( m_pViewSourceResponse != NULL )
    {
	m_pViewSourceResponse->CloseDone(HXR_OK);
	HX_RELEASE(m_pViewSourceResponse);
    }
    return HXR_OK;
}

/************************************************************************
 *	Method:
 *	    IHXFileViewSource::InitViewSource
 *	Purpose:
 *	    Called by the user to init before a viewsource.
 */

STDMETHODIMP
CJPEGViewSource::InitViewSource(IHXFileObject* pFileObject,
	IHXFileViewSourceResponse* pResp, SOURCE_TYPE sourceType,
	IHXValues* pOptions)
{
    if ( m_state != kStateConstructed )
    {
	return HXR_UNEXPECTED;
    }
    HX_ASSERT(pFileObject != NULL);
    HX_ASSERT(pResp != NULL);
    
    if ( sourceType == HTML_SOURCE )
    {
	m_type = HTML_SOURCE;
    }
    else if ( sourceType == RAW_SOURCE )
    {
	m_type = RAW_SOURCE;
	HX_ASSERT(FALSE);
	return HXR_NOTIMPL;
    }
    else
    {
	HX_ASSERT(FALSE);
	return HXR_UNEXPECTED;
    }

    HX_RELEASE(m_pViewSourceOptions);
    m_pViewSourceOptions = pOptions;
    if ( m_pViewSourceOptions )
    {
	m_pViewSourceOptions->AddRef();
    }

    HX_RELEASE(m_pCommonClassFactory);
    HX_RESULT ret = m_pContext->QueryInterface(IID_IHXCommonClassFactory, 
	(void**)&m_pCommonClassFactory);
    if ( SUCCEEDED(ret) )
    {
	HX_RELEASE(m_pFileObject);
	m_pFileObject = pFileObject;
	m_pFileObject->AddRef();
	HX_RELEASE(m_pViewSourceResponse);
	m_pViewSourceResponse = pResp;
	m_pViewSourceResponse->AddRef();

	m_state = kStateInitFilePending;
	ret = m_pFileObject->Init(HX_FILE_READ | HX_FILE_BINARY, this);
    }
    else
    {
	ret = pResp->InitDone(HXR_FAIL);
    }
    return ret;
}

/************************************************************************
 *	Method:
 *	    IHXFileViewSource::GetSource
 *	Purpose:
 *	    Called to get source html source.  Return the source
 *	through m_pViewSourceResoponse
 */
STDMETHODIMP
CJPEGViewSource::GetSource()
{
    if ( m_state != kStateReady ) 
    {
	return HXR_UNEXPECTED;
    }

    HX_ASSERT(m_pFileObject != NULL);
    IHXFileStat* pFileStat = NULL;
    HX_RESULT ret = m_pFileObject->QueryInterface(IID_IHXFileStat, 
	(void**)&pFileStat);
    if ( SUCCEEDED(ret) )
    {
	m_state = kStateStatPending;
	ret = pFileStat->Stat(this);
    }
    else
    {
	m_pViewSourceResponse->SourceReady(ret, NULL);
    }
    HX_RELEASE(pFileStat);
    return ret;
}

/************************************************************************
 *  Method:
 *	IHXStatResponse::StatDone
 */
STDMETHODIMP 
CJPEGViewSource::StatDone(HX_RESULT status,  UINT32 ulSize,
    UINT32 ulCreationTime, UINT32 ulAccessTime, UINT32 ulModificationTime,
    UINT32 ulMode)
{
    if ( m_state != kStateStatPending )
    {
	return HXR_UNEXPECTED;
    }

    HX_RESULT ret = HXR_OK;

    if ( SUCCEEDED(status) )
    {
	HX_ASSERT(m_pViewSourceResponse != NULL);
	HX_ASSERT(m_pFileObject != NULL);
	m_ulFileSize = ulSize;
	m_ulModTime = ulModificationTime;
	
	// Create an IHXFragmentedBuffer to hold the file
	CHXFragmentedBuffer* pTmp = NULL;
        ret = CHXFragmentedBuffer::CreateObject(&pTmp);
        if (SUCCEEDED(ret))
        {
            HX_RELEASE(m_pFragFileBuffer);
            ret = pTmp->QueryInterface(IID_IHXFragmentedBuffer,
		(void**) &m_pFragFileBuffer);
            if (SUCCEEDED(ret))
            {
                // Clear the bytes read counter
                m_ulNumBytesRead = 0;
                
		
		// We will read 1k at first - in most cases
		// this will have the complete file header
		m_state = kStateReadPending;
                ret = m_pFileObject->Read(1024);
            }
            else
            {
		m_state = kStateReady;
                ret = m_pViewSourceResponse->SourceReady(ret, NULL);
            }
	}
	else
	{
	    m_state = kStateReady;
	    ret = m_pViewSourceResponse->SourceReady(ret, NULL);
	}
    }
    else
    {
	m_state = kStateReady;
	ret = m_pViewSourceResponse->SourceReady(status, NULL);
    }
    return ret;
}


/************************************************************************
 *  Method:
 *    IHXFileResponse::InitDone
 *  Purpose:
 *    Notification interface provided by users of the IHXFileObject
 *    interface. This method is called by the IHXFileObject when the
 *    initialization of the file is complete.
 */
STDMETHODIMP
CJPEGViewSource::InitDone( HX_RESULT status )
{
    if ( m_state != kStateInitFilePending )
    {
	return HXR_UNEXPECTED;
    }

    HX_ASSERT(m_pViewSourceResponse != NULL);
    m_state = kStateReady;
    return m_pViewSourceResponse->InitDone(status);
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::ReadDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	last read from the file is complete and a buffer is available.
 */
STDMETHODIMP
CJPEGViewSource::ReadDone(HX_RESULT status, IHXBuffer* pBuffer)
{
    if ( m_state != kStateReadPending )
    {
	return HXR_UNEXPECTED;
    }

    HX_RESULT result = HXR_OK;

    HX_ASSERT(m_pViewSourceResponse != NULL);
    if ( SUCCEEDED(status) )
    {
        // Append the buffer to the fragmented buffer
        result = m_pFragFileBuffer->Append(pBuffer, 0, pBuffer->GetSize());
	m_ulNumBytesRead += pBuffer->GetSize();
        if (SUCCEEDED(result))
        {
	    // We will parse this buffer.  The majority of JPEGs will have
	    // all the info we need in the first 1k so we will end here.
	    // There are some though that might go longer.  So if our parse
	    // fails, we will grab another 2k of the file until we are
	    // successful
	    // 
	    IHXBuffer* pBuf = NULL;
	    result = m_pFragFileBuffer->QueryInterface(IID_IHXBuffer, 
		(void**)&pBuf);
	    if ( SUCCEEDED(result) )
	    {
		JPEGResult jret = ParseForJPEGInfo(pBuf);
		if ( jret == kHeaderFound )
		{
		    IHXBuffer* pReturnBuffer = NULL;
		    result = CreateInfoBuffer(pBuf, pReturnBuffer);
		    if ( SUCCEEDED(result) )
		    {
			m_state = kStateReady;
			result = m_pViewSourceResponse->SourceReady(HXR_OK,
			    pReturnBuffer);
		    }
		    else
		    {
			m_state = kStateReady;
			result = m_pViewSourceResponse->SourceReady(result, NULL);
		    }
		    HX_RELEASE(pReturnBuffer);
		}
		else if ( jret == kNotJPEG )
		{
		    // not a valid JPEG....
		    m_state = kStateReady;
		    result = m_pViewSourceResponse->SourceReady(HXR_FAIL, NULL);
		}
		else if ( jret == kNoSuccess )
		{
		    // No, we haven't reached the end of the header yet...
		    // we need to do another read.
		    m_state = kStateReadPending;
		    result = m_pFileObject->Read(2048);
		}
		else
		{
		    HX_ASSERT(FALSE);
		}
	    }
	    else
	    {
		m_state = kStateReady;
		result = m_pViewSourceResponse->SourceReady(result, NULL);
	    }
	    HX_RELEASE(pBuf);
	}
	else
	{
	    m_state = kStateReady;
	    result = m_pViewSourceResponse->SourceReady(result, NULL);
	}
    }
    else
    {
	// We should never get here with a valid file...  So we will return
	// an error.  It means that the file must not be a jpeg.
	// Becase we check the entire amount read after each read, we
	// will have allready checked the entire file...
	m_state = kStateReady;
	result = m_pViewSourceResponse->SourceReady(status, NULL);
    }
    return result;
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::WriteDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	last write to the file is complete.
 */
STDMETHODIMP
CJPEGViewSource::WriteDone(HX_RESULT status)
{
    // We don't ever write, so we don't expect to get this...
    return HXR_UNEXPECTED;
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::SeekDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	last seek in the file is complete.
 */
STDMETHODIMP
CJPEGViewSource::SeekDone(HX_RESULT status)
{
    return HXR_UNEXPECTED;
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::CloseDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	close of the file is complete.
 */
STDMETHODIMP
CJPEGViewSource::CloseDone(HX_RESULT status)
{
    return HXR_OK;
}

/************************************************************************
 *  Method:
 *	CJPEGViewSource::CreateInfoBuffer
 */
STDMETHODIMP 
CJPEGViewSource::CreateInfoBuffer(IHXBuffer* pFileBuf, REF(IHXBuffer*) pBuffer)
{
    char buf[128]; /* Flawfinder: ignore */

    CBigByteGrowingQueue queue(INITIAL_QUEUESIZE);
    queue.EnQueue(z_pOpen);
    
    sprintf(buf, z_pImage_ss, z_pJPEGGif, z_pJPEGGif); /* Flawfinder: ignore */
    queue.EnQueue(buf);
    queue.EnQueue(z_pImageType);
    queue.EnQueue(" JPEG Image");
    queue.EnQueue(z_pEndLine);
    
    queue.EnQueue(z_pFileName);
    const char* pFileName;
    m_pFileObject->GetFilename(pFileName);
    queue.EnQueue(pFileName);
    queue.EnQueue(z_pEndLine);
    
    QueueModificationTime(&queue, m_ulModTime);
    QueueFileSize(&queue, m_ulFileSize);
    
    sprintf(buf, z_pImageDimen_ii, m_ulWidth, m_ulHeight); /* Flawfinder: ignore */
    queue.EnQueue(buf);
    queue.EnQueue(z_pEndLine);

    sprintf(buf, z_pJPEGComponents_i, m_ulNumComponents); /* Flawfinder: ignore */
    queue.EnQueue(buf);
    queue.EnQueue(z_pEndLine);

    queue.EnQueue(z_pJPEGProgressive);
    if ( m_bProgressive )
    {
	queue.EnQueue("YES");
    }
    else
    {
	queue.EnQueue("NO");
    }
    queue.EnQueue(z_pEndLine);
    IHXBuffer* pRam = NULL;
    IHXBuffer* pCD = NULL;
    if (m_pViewSourceOptions && 
	SUCCEEDED(m_pViewSourceOptions->GetPropertyCString("RamGenURL",
	pRam)) && 
	SUCCEEDED(m_pViewSourceOptions->GetPropertyCString("CurrentPath",
	pCD)) )
    {
	queue.EnQueue(z_pRamLink);
	queue.EnQueue("<a href =\"");
	queue.EnQueue((const char*)pRam->GetBuffer());
	const char* p = (const char*)pCD->GetBuffer();
	if ( *p == '/' )
	{
	    p++;
	}
	queue.EnQueue(p);
	queue.EnQueue("/");
	const char* pFileName;
	m_pFileObject->GetFilename(pFileName);
	queue.EnQueue(pFileName);
	queue.EnQueue("\">");
	queue.EnQueue((const char*)pRam->GetBuffer());
	queue.EnQueue(p);
	queue.EnQueue("/");
	queue.EnQueue(pFileName);
	queue.EnQueue("</a>");
	queue.EnQueue(z_pEndLine);
    }
    HX_RELEASE(pRam);
    HX_RELEASE(pCD);
    queue.EnQueue((void*)z_pClose, strlen(z_pClose));
    HX_RELEASE(pBuffer);
    m_pCommonClassFactory->CreateInstance(IID_IHXBuffer, (void**)&pBuffer);
    if ( !pBuffer )
    {
	return HXR_OUTOFMEMORY;
    }
    pBuffer->SetSize(queue.GetQueuedItemCount());
    unsigned char* chr = pBuffer->GetBuffer();
    queue.DeQueue(chr, queue.GetQueuedItemCount());
    return HXR_OK;
}


CJPEGViewSource::JPEGResult 
CJPEGViewSource::ParseForJPEGInfo(IHXBuffer* pFileBuf)
{
    JPEGResult jret = kNoSuccess;

    HX_ASSERT(pFileBuf != NULL);

    enum {kMarkerSOF0 = 0xC0, kMarkerSOF1 = 0xC1, kMarkerSOF2 = 0xC2, kMarkerDHT  = 0xC4,
          kMarkerRST0 = 0xD0, kMarkerRST1 = 0xD1, kMarkerRST2 = 0xD2, kMarkerRST3 = 0xD3,
          kMarkerRST4 = 0xD4, kMarkerRST5 = 0xD5, kMarkerRST6 = 0xD6, kMarkerRST7 = 0xD7,
          kMarkerSOI  = 0xD8, kMarkerEOI  = 0xD9, kMarkerSOS  = 0xDA, kMarkerDQT  = 0xDB,
          kMarkerDRI  = 0xDD, kMarkerAPP0 = 0xE0, kMarkerTEM  = 0x01};

    
    // Now parse the file buffer
    BOOL   bHeaderComplete  = FALSE;
    BYTE  *pCurByte         = pFileBuf->GetBuffer();
    BYTE  *pBufLimit        = pCurByte + pFileBuf->GetSize();
    while (bHeaderComplete == FALSE && pCurByte < pBufLimit)
    {
        // Look for a 0xFF, which would signify a marker
        if (*pCurByte++ == 0xFF)
        {
            // Now take different actions depending on what kind of
            // marker this is - some markers have data associated with
            // them (such as DRI) and others don't (such as SOI and EOI)
            BYTE ucMarker = *pCurByte++;

            if (!(ucMarker == kMarkerSOI ||
                  ucMarker == kMarkerEOI ||
                  ucMarker == kMarkerTEM ||
                  (ucMarker >= kMarkerRST0 && ucMarker <= kMarkerRST7)))
            {
                UINT32 ulSegLen = (pCurByte[0] << 8) | pCurByte[1];

                if (ucMarker == kMarkerAPP0)
                {
                    // We look at this marker to verify this is a JFIF image file
                    if (pCurByte[0] != 0x00 || pCurByte[1] != 0x10 ||
                        pCurByte[2] != 'J'  || pCurByte[3] != 'F'  ||
                        pCurByte[4] != 'I'  || pCurByte[5] != 'F'  ||
                        pCurByte[6] != '\0')
                    {
                        return kNotJPEG;
                    }
                }
                else if (ucMarker == kMarkerSOF0 )
                {
		    m_bProgressive = FALSE;
                    // We look at this marker to extract the width and height
                    m_ulHeight     = (pCurByte[3] << 8) | pCurByte[4];
                    m_ulWidth      = (pCurByte[5] << 8) | pCurByte[6];
		    m_ulNumComponents = pCurByte[7];
                }
		else if ( ucMarker == kMarkerSOF1 || ucMarker == kMarkerSOF2 )
		{
		    m_bProgressive = TRUE;
                    // We look at this marker to extract the width and height
                    m_ulHeight     = (pCurByte[3] << 8) | pCurByte[4];
                    m_ulWidth      = (pCurByte[5] << 8) | pCurByte[6];
		    m_ulNumComponents = pCurByte[7];
		}
                else if (ucMarker == kMarkerSOS)
                {
                    // This marker is the last marker in the header
		    jret = kHeaderFound;
                    bHeaderComplete = TRUE;
                }

                // Advance the pointer
                pCurByte += ulSegLen;
            }
        }
    }
    return jret;
}
