/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: collect_headers_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 "collect_headers_strategy.h"

#include "group_info.h"
#include "codec_info.h"

#include "oggutil.h"

#include "debug.h" // DPRINTF()
#define D_COLLECT_HDRS 0 // 0x800000

class COggHeaderCollector
{
public:
    COggHeaderCollector();
    ~COggHeaderCollector();

    HX_RESULT Init(int serialNum,
                   const COggCodecInfo* pCodecInfo);

    HX_RESULT OnPage(ogg_page* pPage);

    BOOL HaveHeaders() const { return m_bHaveHeaders;}

    HX_RESULT GetNextPage(ogg_page*& pPage);

private:
    const COggCodecInfo* m_pCodecInfo;

    ogg_page* m_pFirstPage;
    BOOL m_bHaveHeaders;
    ogg_stream_state m_inStream;
    ogg_stream_state m_outStream;
};

COggHeaderCollector::COggHeaderCollector() :
    m_pCodecInfo(NULL),
    m_pFirstPage(NULL),
    m_bHaveHeaders(FALSE)
{
    ogg_stream_init(&m_inStream, 0);
    ogg_stream_init(&m_outStream, 0);
}

COggHeaderCollector::~COggHeaderCollector()
{
    HX_DELETE(m_pCodecInfo);

    ogg_stream_clear(&m_inStream);
    ogg_stream_clear(&m_outStream);

    OggUtil::DestroyPage(m_pFirstPage);
    m_pFirstPage = NULL;
}

HX_RESULT 
COggHeaderCollector::Init(int serialNum,
                          const COggCodecInfo* pCodecInfo)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pCodecInfo)
    {
        ogg_stream_clear(&m_inStream);
        ogg_stream_clear(&m_outStream);
        
        ogg_stream_init(&m_inStream, serialNum);
        ogg_stream_init(&m_outStream, serialNum);

        m_pCodecInfo = pCodecInfo->Clone();

        if (m_pCodecInfo)
        {
            res = HXR_OK;
        }
    }

    return res;
}

HX_RESULT 
COggHeaderCollector::OnPage(ogg_page* pPage)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pPage)
    {
        if (m_bHaveHeaders)
        {
            res = HXR_OK;
        }
        else if (m_pCodecInfo)
        {
            int err = ogg_stream_pagein(&m_inStream, pPage);

            if (0 == err)
            {
                ogg_packet op;
                
                res = HXR_OK;
                err = 1;

                while((HXR_OK == res) && (0 < err))
                {
                    err = ogg_stream_packetout(&m_inStream, &op);

                    if (1 == err)
                    {
                        if (m_pCodecInfo->IsHeader(&op))
                        {
                            ogg_stream_packetin(&m_outStream,
                                                &op);

                            if (!m_pFirstPage)
                            {
                                ogg_page og;
                                if (ogg_stream_flush(&m_outStream, &og))
                                {
                                    m_pFirstPage = OggUtil::CopyPage(&og);

                                    if (!m_pFirstPage)
                                    {
                                        res = HXR_OUTOFMEMORY;
                                    }
                                }
                                else
                                {
                                    res = HXR_UNEXPECTED;
                                }
                            }
                        }
                        else
                        {
                            // We are past the headers
                            m_bHaveHeaders = TRUE;
                        }
                    }
                    else if (0 > err)
                    {
                        // ignore skipped page errors
                        err = 1;
                    }
                }
            }
        }
        else
        {
            res = HXR_UNEXPECTED;
        }
    }

    return res;
}

HX_RESULT 
COggHeaderCollector::GetNextPage(ogg_page*& pPage)
{
    HX_RESULT res = HXR_NO_DATA;

    if (m_pFirstPage)
    {
        pPage = m_pFirstPage;
        m_pFirstPage = NULL;

        res = HXR_OK;
    }
    else
    {
        ogg_page og;
        if (ogg_stream_flush(&m_outStream, &og))
        {
            pPage = OggUtil::CopyPage(&og);
            
            if (pPage)
            {
                res = HXR_OK;
            }
            else
            {
                res = HXR_OUTOFMEMORY;
            }
        }
    }

    return res;
}

COggCollectHeadersStrategy::COggCollectHeadersStrategy() :
    m_pPageReader(NULL),
    m_state(ssStart)
{}

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

// COggPageStrategy methods
HX_RESULT 
COggCollectHeadersStrategy::Init(COggPageReader* pPageReader,
                                 const COggGroupInfo* pGroupInfo)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pPageReader && pGroupInfo)
    {
        Close();

        m_pPageReader = pPageReader;
        m_pPageReader->AddRef();

        changeState(ssInitialized);

        ULONG32 ulStartOffset;

        res = HXR_OK;
        for (UINT32 i = 0; ((HXR_OK == res) && 
                            (i < pGroupInfo->StreamCount())); i++)
        {
            int serialNum;
            const COggCodecInfo* pCodecInfo = NULL;

            res = pGroupInfo->GetStreamSerialNum(i, serialNum);

            if (HXR_OK == res)
            {
                res = pGroupInfo->GetCodecInfo(serialNum, pCodecInfo);
            }

            if (HXR_OK == res)
            {
                COggHeaderCollector* pCollector = new COggHeaderCollector;

                if (pCollector)
                {
                    res = pCollector->Init(serialNum, pCodecInfo);

                    if (HXR_OK != res)
                    {
                        HX_DELETE(pCollector);
                    }
                    else if (!m_collectorMap.SetAt(serialNum, pCollector))
                    {
                        res = HXR_OUTOFMEMORY; 
                        HX_DELETE(pCollector);
                    }
                }
                else
                {
                    res = HXR_OUTOFMEMORY; 
                }
            }
        }

        if (HXR_OK == res)
        {
            res = pGroupInfo->GetStartPageOffset(ulStartOffset);
        }

        if (HXR_OK == res)
        {
            res = m_pPageReader->Seek(ulStartOffset);
        }
    }

    return res;
}

HX_RESULT 
COggCollectHeadersStrategy::ReadNextPageDone(HX_RESULT status,
                                             ULONG32 ulFileOffset,
                                             UINT32 ulPageSize,
                                             ogg_page* pPage)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (HXR_OK == status)
    {
        COggHeaderCollector* pCollector = NULL;

        m_collectorMap.Lookup(ogg_page_serialno(pPage), (void*&)pCollector);

        if (pCollector)
        {
            res = pCollector->OnPage(pPage);

            if (HXR_OK == res)
            {
                if (checkIfDone())
                {
                    res = collectPages();

                    if (HXR_OK == res)
                    {
                        changeState(ssDone);
                    }
                }
                else
                {
                    res = m_pPageReader->ReadNextPage();
                }
            }
        }
    }

    return res;
}

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

void COggCollectHeadersStrategy::Close()
{
    HX_RELEASE(m_pPageReader);
    changeState(ssStart);

    CHXMapLongToObj::Iterator itr = m_collectorMap.Begin();
    for (; itr != m_collectorMap.End(); ++itr)
    {
        COggHeaderCollector* pCollector = 
            (COggHeaderCollector*)*itr;

        HX_DELETE(pCollector);
    }
    m_collectorMap.RemoveAll();

    while(!m_pageList.IsEmpty())
    {
        ogg_page* pPage = (ogg_page*) m_pageList.RemoveHead();

        OggUtil::DestroyPage(pPage);
    }
}

HX_RESULT 
COggCollectHeadersStrategy::GetNextPage(ogg_page*& pPage)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (ssDone == m_state)
    {
        if (m_pageList.IsEmpty())
        {
            res = HXR_NO_DATA;
        }
        else
        {
            pPage = (ogg_page*)m_pageList.RemoveHead();
            res = HXR_OK;
        }
    }

    return res;
}

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

void COggCollectHeadersStrategy::changeState(StrategyState newState)
{
    DPRINTF(D_COLLECT_HDRS, ("COCHS::changeState : %s -> %s\n",
                         STATE_STRING(m_state),
                         STATE_STRING(newState)));
    m_state = newState;
}

BOOL 
COggCollectHeadersStrategy::checkIfDone()
{
    BOOL bRet = TRUE;
    
    CHXMapLongToObj::Iterator itr = m_collectorMap.Begin();
    for (; bRet && (itr != m_collectorMap.End()); ++itr)
    {
        COggHeaderCollector* pCollector = 
            (COggHeaderCollector*)*itr;

        bRet = pCollector->HaveHeaders();
    }

    return bRet;
}

HX_RESULT 
COggCollectHeadersStrategy::collectPages()
{
    HX_RESULT res = HXR_OK;

    BOOL bDone = FALSE;

    while((HXR_OK == res) && !bDone)
    {
        // Assume this is the last pass through the loop
        bDone = TRUE;

        CHXMapLongToObj::Iterator itr = m_collectorMap.Begin();
        for (; (HXR_OK == res) && (itr != m_collectorMap.End()); ++itr)
        {
            COggHeaderCollector* pCollector = 
                (COggHeaderCollector*)*itr;
            
            ogg_page* pPage = NULL;
            res = pCollector->GetNextPage(pPage);

            if (HXR_OK == res)
            {
                if (m_pageList.AddTail(pPage))
                {
                    // We got a page so we aren't
                    // done quite yet.
                    bDone = FALSE;
                }
                else
                {
                    OggUtil::DestroyPage(pPage);
                    res = HXR_OUTOFMEMORY;
                }
            }
            else if (HXR_NO_DATA == res)
            {
                // It's ok if one of the streams
                // runs out of pages before others do
                res = HXR_OK;
            }
        }
    }

    return res;
}
