/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: stream_info_strategy.cpp,v 1.1.4.1 2004/11/24 18:02:52 acolwell 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 "stream_info_strategy.h"
#include "stream_info.h"

#include "debug.h" // DPRINTF()
#define D_STREAM_INFO 0 //0x2000000

COggStreamInfoStrategy::COggStreamInfoStrategy() :
    m_pPageReader(NULL),
    m_state(ssStart),
    m_ulStartPageOffset(0),
    m_uStartPageSize(0),
    m_pSerialNums(NULL)
{
#ifdef _DEBUG
    debug_level() |= D_STREAM_INFO;
#endif /* _DEBUG */
}

COggStreamInfoStrategy::~COggStreamInfoStrategy()
{
    Close();
}

// COggPageStrategy methods
HX_RESULT 
COggStreamInfoStrategy::Init(COggPageReader* pPageReader)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pPageReader)
    {
        // Clear out old state
        Close();

        m_pPageReader = pPageReader;
        m_pPageReader->AddRef();

        changeState(ssInitialized);
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggStreamInfoStrategy::ReadNextPageDone(HX_RESULT status,
                                         ULONG32 ulFileOffset,
                                         UINT32 ulPageSize,
                                         ogg_page* pPage)
{
    DPRINTF(D_STREAM_INFO, ("COSIS::RNPD(%08x, %u, %u)\n",
                            this, ulFileOffset, ulPageSize));
    HX_RESULT res = HXR_UNEXPECTED;

    if (HXR_OK == status)
    {
        switch(m_state) {
        case ssInitialized:
            if (ogg_page_bos(pPage))
            {
                res = createStream(pPage);

                if (HXR_OK == res)
                {
                    m_ulStartPageOffset = ulFileOffset;
                    m_uStartPageSize = ulPageSize;
                    changeState(ssGetStreamCount);
                }
            }
            break;
        case ssGetStreamCount:
            if (ogg_page_bos(pPage))
            {
                if (!haveStream(pPage))
                {
                    res = createStream(pPage);
                }
            }
            else
            {
                changeState(ssGetStreamHeaders);
                res = handleHeaderPage(pPage);
            }
            break;
        case ssGetStreamHeaders:
            res = handleHeaderPage(pPage);
            break;
        case ssGetBaseTimes:
            res = handleDataPage(pPage);
            break;
        };

        if (!Done())
        {
            res = m_pPageReader->ReadNextPage();
        }
    }

    return res;
}

BOOL COggStreamInfoStrategy::Done() const
{
    return (m_state == ssDone) ? TRUE : FALSE;
}

void COggStreamInfoStrategy::Close()
{
    DPRINTF(D_STREAM_INFO, ("COSIS::Close()\n"));

    HX_RELEASE(m_pPageReader);
    changeState(ssStart);

    delete [] m_pSerialNums;
    m_pSerialNums = NULL;
    
    m_ulStartPageOffset = 0;
    m_uStartPageSize = 0;

    CHXMapLongToObj::Iterator itr = m_streamMap.Begin();

    for (;itr != m_streamMap.End(); ++itr)
    {
        COggStreamInfo* pInfo = (COggStreamInfo*)*itr;

        delete pInfo;
    }
    m_streamMap.RemoveAll();
}

UINT16
COggStreamInfoStrategy::StreamCount() const
{
    return (UINT16)m_streamMap.GetCount();
}

HX_RESULT 
COggStreamInfoStrategy::StartPageOffset(ULONG32& ulStartPageOffset) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (ssDone == m_state)
    {
        ulStartPageOffset = m_ulStartPageOffset;
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggStreamInfoStrategy::StartPageSize(UINT32& uStartPageSize) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (ssDone == m_state)
    {
        uStartPageSize = m_uStartPageSize;
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggStreamInfoStrategy::GetStreamSerialNum(UINT32 i, int& serialNum) const
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (ssDone != m_state)
    {
        res = HXR_UNEXPECTED;
    }
    else if (i < (UINT32)m_streamMap.GetCount())
    {
        if (m_pSerialNums)
        {
            serialNum = m_pSerialNums[i];
            res = HXR_OK;
        }
        else
        {
            res = HXR_UNEXPECTED;
        }
    }

    return res;
}

HX_RESULT 
COggStreamInfoStrategy::GetCodecInfo(int serialNum, 
                                     const COggCodecInfo*& pInfo) const
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (ssDone != m_state)
    {
        res = HXR_UNEXPECTED;
    }
    else 
    {
        COggStreamInfo* pStreamInfo = getStreamInfo(serialNum);
        if (pStreamInfo)
        {
            const COggCodecInfo* pCodecInfo = pStreamInfo->CodecInfo();
            
            if (pCodecInfo)
            {
                pInfo = pCodecInfo;
                
                res = HXR_OK;
            }
            else
            {
                res = HXR_UNEXPECTED;
            }
        }
    }

    return res;
}

BOOL COggStreamInfoStrategy::HaveSerialNum(int serialNum)
{
    return (getStreamInfo(serialNum) != 0);
}

#define STATE_STRING(state) \
    ((state == ssStart) ? "ssStart" : \
     (state == ssInitialized) ? "ssInitialized" : \
     (state == ssGetStreamCount) ? "ssGetStreamCount" : \
     (state == ssGetStreamHeaders) ? "ssGetStreamHeaders" : \
     (state == ssGetBaseTimes) ? "ssGetBaseTimes" : \
     (state == ssDone) ? "ssDone" :  \
     "Unknown")

void COggStreamInfoStrategy::changeState(StategyState newState)
{
    DPRINTF(D_STREAM_INFO, ("COSIS::changeState : %s -> %s\n",
                            STATE_STRING(m_state),
                            STATE_STRING(newState)));
    m_state = newState;
}

HX_RESULT 
COggStreamInfoStrategy::createStream(ogg_page* pPage)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    int serialNum = ogg_page_serialno(pPage);

    if (!HaveSerialNum(serialNum))
    {
        COggStreamInfo* pInfo = new COggStreamInfo(serialNum);
        
        int oldSize = m_streamMap.GetCount();
        int* pNewSerialNums = new int [oldSize + 1];
        
        if (pInfo && pNewSerialNums && m_streamMap.SetAt(serialNum, pInfo))
        {
            if (m_pSerialNums)
            {
                memcpy(pNewSerialNums, m_pSerialNums, sizeof(int) * oldSize);
                delete [] m_pSerialNums;
            }
            m_pSerialNums = pNewSerialNums;
            m_pSerialNums[oldSize] = serialNum;
            
            res = pInfo->OnPage(pPage);
        }
        else
        {
            res = HXR_OUTOFMEMORY;

            delete pInfo;
            delete [] pNewSerialNums;
        }
    }

    return res;
}

HX_RESULT 
COggStreamInfoStrategy::handleHeaderPage(ogg_page* pPage)
{
    HX_RESULT res = HXR_UNEXPECTED;

    COggStreamInfo* pInfo = getStreamInfo(pPage);
    if (pInfo)
    {
        res = pInfo->OnPage(pPage);

        if ((HXR_OK == res) && haveAllHeaders())
        {
            if (haveAllBaseGranulePos())
            {
                adjustBaseTimestamps();
                changeState(ssDone);
            }
            else
            {
                changeState(ssGetBaseTimes);
            }
        }
    }

    return res;
}

HX_RESULT 
COggStreamInfoStrategy::handleDataPage(ogg_page* pPage)
{
    HX_RESULT res = HXR_UNEXPECTED;

    COggStreamInfo* pInfo = getStreamInfo(pPage);
    if (pInfo)
    {
        res = pInfo->OnPage(pPage);

        if ((HXR_OK == res) && haveAllBaseGranulePos())
        {
            changeState(ssDone);
        }
    }

    return res;
}

BOOL COggStreamInfoStrategy::haveStream(ogg_page* pPage) const
{
    return (getStreamInfo(pPage)) ? TRUE : FALSE;
}

COggStreamInfo* 
COggStreamInfoStrategy::getStreamInfo(ogg_page* pPage) const
{
    return getStreamInfo(ogg_page_serialno(pPage));
}

COggStreamInfo* 
COggStreamInfoStrategy::getStreamInfo(int serialNum) const
{
    COggStreamInfo* pRet = NULL;
    
    m_streamMap.Lookup(serialNum, (void*&)pRet);

    return pRet;
}

BOOL COggStreamInfoStrategy::haveAllHeaders()
{
    BOOL  bRet = TRUE;

    CHXMapLongToObj::Iterator itr = m_streamMap.Begin();

    for (;bRet && itr != m_streamMap.End(); ++itr)
    {
        COggStreamInfo* pInfo = (COggStreamInfo*)*itr;

        if (pInfo && !pInfo->HaveHeaders())
        {
            bRet = FALSE;
        }
    }

    return bRet;
}

BOOL COggStreamInfoStrategy::haveAllBaseGranulePos()
{
    BOOL  bRet = TRUE;

    CHXMapLongToObj::Iterator itr = m_streamMap.Begin();

    for (;bRet && itr != m_streamMap.End(); ++itr)
    {
        COggStreamInfo* pInfo = (COggStreamInfo*)*itr;

        if (pInfo && !pInfo->HaveBaseGranulePos())
        {
            bRet = FALSE;
        }
    }

    return bRet;
}

void COggStreamInfoStrategy::adjustBaseTimestamps()
{
    CHXMapLongToObj::Iterator itr = m_streamMap.Begin();

    BOOL bMinSet = FALSE;
    COggTimestamp minTS;
    
    // find the lowest base timestamp
    for (;itr != m_streamMap.End(); ++itr)
    {
        COggStreamInfo* pInfo = (COggStreamInfo*)*itr;

        COggTimestamp baseTS;
        if (pInfo)
        {
            const COggCodecInfo* pCodecInfo = pInfo->CodecInfo();

            if (pCodecInfo &&
                (HXR_OK == pCodecInfo->GetBaseTimestamp(baseTS)))
            {
                if (!bMinSet || (baseTS < minTS))
                {
                    bMinSet = TRUE;
                    minTS = baseTS;
                }
            }
        }
    }

    // Now that we know the minimum, set the base timestamp in
    // all the codec info objects to the minimum
    itr = m_streamMap.Begin();
    for (;itr != m_streamMap.End(); ++itr)
    {
        COggStreamInfo* pInfo = (COggStreamInfo*)*itr;

        COggTimestamp baseTS;
        if (pInfo)
        {
            pInfo->SetBaseTimestamp(minTS);
        }
    }
}
