/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: end_time_strategy.cpp,v 1.2.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 "end_time_strategy.h"
#include "codec_info.h"

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

static const UINT32 SeekBackSize = 4096;

COggGroupEndTimeStrategy::COggGroupEndTimeStrategy() :
    m_pPageReader(NULL),
    m_state(ssStart),
    m_ulStartOffset(0),
    m_ulLastPageOffset(0),
    m_uLastPageSize(0),
    m_serialNum(0),
    m_pCodecInfo(NULL),
    m_endGranulePos(-1),
    m_ulLastSeekOffset(0),
    m_ulLastOffsetChecked(0)
{
#ifdef _DEBUG
    debug_level() |= D_END_TIME;
#endif /* _DEBUG */

    ogg_stream_init(&m_os, 0);
}

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

// COggPageStrategy methods
HX_RESULT 
COggGroupEndTimeStrategy::ReadNextPageDone(HX_RESULT status,
                                           ULONG32 ulFileOffset,
                                           UINT32 ulPageSize,
                                           ogg_page* pPage)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (HXR_OK == status)
    {
        ogg_int64_t granulePos = ogg_page_granulepos(pPage);

        switch(m_state) {
        case ssInitialized:
            if (granulePos != -1)
            {
                m_endGranulePos = granulePos;

                changeState(ssDone);
                res = HXR_OK;
            }
            else
            {
                changeState(ssSearchingForValidGranule);
                m_ulLastSeekOffset = m_ulLastPageOffset;
                m_ulLastOffsetChecked = m_ulLastPageOffset;
                res = seekBackMore();
            }
            break;
        case ssSearchingForValidGranule:
            res = handleSearchForValidGranule(status, ulFileOffset,
                                              ulPageSize, pPage);
            break;
        case ssComputingEndTime:
            res = handleComputingEndTime(status, ulFileOffset,
                                         ulPageSize, pPage);
            break;
        default:
            res = HXR_UNEXPECTED;
            break;
        };
    }

    return res;
}

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

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

    delete m_pCodecInfo;
    m_pCodecInfo = NULL;
    ogg_stream_clear(&m_os);
}

HX_RESULT 
COggGroupEndTimeStrategy::GetDuration(COggTimestamp& duration) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (Done())
    {
        res = m_pCodecInfo->GetTimestamp(m_endGranulePos, duration);
    }
    return res;
}

HX_RESULT 
COggGroupEndTimeStrategy::Init(COggPageReader* pPageReader,
                               ULONG32 ulStartOffset,  
                               ULONG32 ulLastPageOffset, 
                               UINT32 uLastPageSize,
                               int serialNum, 
                               const COggCodecInfo* pCodecInfo)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

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

        m_ulLastPageOffset = ulLastPageOffset;
        m_uLastPageSize = uLastPageSize;
        m_serialNum = serialNum;
        m_pCodecInfo = pCodecInfo->Clone();
        ogg_stream_init(&m_os, serialNum);
        
        if (m_pCodecInfo)
        {
            m_pPageReader = pPageReader;
            m_pPageReader->AddRef();

            changeState(ssInitialized);
            res = m_pPageReader->Seek(m_ulLastPageOffset);
        }
    }

    return res;
}

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

void COggGroupEndTimeStrategy::changeState(StrategyState newState)
{
    DPRINTF(D_END_TIME, ("COGETS::changeState : %s -> %s\n",
                         STATE_STRING(m_state),
                         STATE_STRING(newState)));
    m_state = newState;
}


HX_RESULT 
COggGroupEndTimeStrategy::seekBackMore()
{
    HX_RESULT res = HXR_OK;

    ULONG32 ulDelta = m_ulLastSeekOffset - m_ulStartOffset;

    if (ulDelta == 0)
    {
        res = HXR_UNEXPECTED;
    }
    else if (ulDelta >= SeekBackSize)
    {
        m_ulLastSeekOffset -= SeekBackSize;
    }
    else
    {
        m_ulLastSeekOffset = m_ulStartOffset;
    }

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

    return res;
}

HX_RESULT 
COggGroupEndTimeStrategy::handleSearchForValidGranule(HX_RESULT status,
                                                      ULONG32 ulFileOffset,
                                                      UINT32 ulPageSize,
                                                      ogg_page* pPage)
{
    HX_RESULT res = HXR_OK;

    ogg_int64_t granulePos = ogg_page_granulepos(pPage);
    int serialNum = ogg_page_serialno(pPage);

    if (ulFileOffset == m_ulLastOffsetChecked)
    {
        // We didn't find a page with a valid
        // granule pos. Time to seek back a little
        // farther
        res = seekBackMore();
    }
    else if (serialNum == m_serialNum)
    {
        if (granulePos != -1)
        {
            res = m_pCodecInfo->SetCurrentGranulePos(granulePos);
            
            if (HXR_OK == res)
            {
                // The granule pos on the page is the end time
                // of the last full packet in the page. We need
                // to spin through this page so that we can get the
                // ogg_stream_state setup for receiving the next
                // page. This allows us to properly handle the case
                // where there is a partial packet at the end of this
                // page
                int err = ogg_stream_pagein(&m_os, pPage);
                
                if (0 == err)
                {
                    ogg_packet op;
                    err = 1;
                    while (0 != err)
                    {
                        err = ogg_stream_packetout(&m_os, &op);
                    }   
                    
                    changeState(ssComputingEndTime);
                    res = m_pPageReader->ReadNextPage();
                }
                else
                {
                    res = HXR_UNEXPECTED;
                }
            }
        }
        else
        {
            // This page doesn't have a valid granulepos so
            // lets try the next one.
            res = m_pPageReader->ReadNextPage();
        }
    }
    else 
    {
        // This page isn't for the stream we are looking for.
        // Lets try the next page
        res = m_pPageReader->ReadNextPage();
    }

    return res;
}

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

    int serialNum = ogg_page_serialno(pPage);

    if (serialNum == m_serialNum)
    {
        // Get all the packets in the page and
        // pass them to the m_pCodecInfo object.
        // This will update the current granulePos 
        // in the codec info object.
        int err = ogg_stream_pagein(&m_os, pPage);
        
        if (0 == err)
        {
            ogg_packet op;
            err = 1;
            res = HXR_OK;
            while ((HXR_OK == res) && (0 != err))
            {
                err = ogg_stream_packetout(&m_os, &op);

                if (err > 0)
                {
                    res = m_pCodecInfo->OnPacket(&op);
                }
            }   

            if (HXR_OK == res)
            {
                if (ulFileOffset == m_ulLastPageOffset)
                {
                    // This is the last page
                    changeState(ssDone);
                    m_endGranulePos = m_pCodecInfo->CurrentGranulePos();
                }
                else
                {
                    // We have more reading to do
                    res = m_pPageReader->ReadNextPage();
                }
            }
        }
        else
        {
            res = HXR_UNEXPECTED;
        }
    }
    else
    {
        // This page isn't for the stream we are looking for.
        // Lets try the next page
        res = m_pPageReader->ReadNextPage();
    }

    return res;
}
