/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: seek_strategy.cpp,v 1.2.4.2 2005/01/21 19:30:13 nhart 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 "seek_strategy.h"

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

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

COggSeekStrategy::COggSeekStrategy() :
    m_pPageReader(NULL),
    m_state(ssStart),
    m_pGroupInfo(NULL),
    m_uSeekTime(0),
    m_ulLowerOffset(0),
    m_uLowerPageSize(0),
    m_ulUpperOffset(0),
    m_ulLastSeekOffset(0),
    m_ulSeekPointOffset(0)
{
#ifdef _DEBUG
    debug_level() |= D_SEEK;
#endif // _DEBUG
}

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

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

    if (pPageReader)
    {
        Close();

        m_pPageReader = pPageReader;
        m_pPageReader->AddRef();
        
        m_pGroupInfo = pGroupInfo;
        m_uSeekTime = uSeekTime;
        
        res = m_pGroupInfo->GetPageOffsetInfo(m_ulLowerOffset,
                                              m_uLowerPageSize,
                                              m_ulUpperOffset);

        if (HXR_OK == res)
        {
            changeState(ssInitialized);
            res = seekToTheMiddle();
        }
    }

    return res;
}

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

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

        if (granulepos == -1)
        {
            // We can't calculate a timestamp for this page so
            // we should move on to the next page
            res = m_pPageReader->ReadNextPage();
        }
        else
        {
            COggTimestamp timestamp;
            res = m_pGroupInfo->GetTimestamp(ogg_page_serialno(pPage), 
                                             granulepos,
                                             timestamp);

            if (HXR_OK == res)
            {
                timestamp.SetSampleRate(1000);

                UINT32 uTimestamp = timestamp.Samples();
                
                DPRINTF(D_SEEK,("COSS::RNPD : timestamp %u\n",
                                uTimestamp));
                
                if (ulFileOffset >= m_ulUpperOffset)
                {
                    // The last seek offset resulted in the same
                    // upper page. Update the upper offset and
                    // seek to the middle again,
                    m_ulUpperOffset = m_ulLastSeekOffset;
                    
                    DPRINTF(D_SEEK, ("COSS::RNPD : Updating upper offset 1\n"));
                    
                    res = seekToTheMiddle();
                }
                else if ((ulFileOffset + uPageSize) >= m_ulUpperOffset)
                {
                    // The current page is the one before the upper page
                    BOOL bSeekPointInNextPage = FALSE;
                    BOOL bSeekPointInThisPage = FALSE;
                    
                    ULONG32 ulSecondPageOffset = 
                        (m_ulLowerOffset + m_uLowerPageSize);
                    
                    if (uTimestamp < m_uSeekTime)
                    {
                        // We've found a page that is lower
                        // than the seek time. We know that
                        // the upper offset page is >= the 
                        // seek time.
                        DPRINTF(D_SEEK, ("COSS::RNPD : seek point is in the upper offset page\n"));
                        m_ulSeekPointOffset = m_ulUpperOffset;

                        changeState(ssDone);
                        res = HXR_OK;
                    }
                    else if (ulFileOffset == m_ulLowerOffset)
                    {
                        // We are at lower offset page
                        if (uTimestamp < m_uSeekTime)
                        {
                            bSeekPointInNextPage = TRUE;
                        }
                        else
                        {
                            bSeekPointInThisPage = TRUE;
                        }
                    }
                    else if (ulFileOffset == ulSecondPageOffset)
                    {
                        // We are at the page after the lower offset
                        // page and it's timestamp >= the seek time.
                        // Seek to the lower bound page
                    
                        m_ulUpperOffset = ulSecondPageOffset;
                        res = doSeek(m_ulLowerOffset);
                    }
                    else
                    {
                        // There must still be pages between the lower
                        // offset and this page. 
                        DPRINTF(D_SEEK, ("COSS::RNPD : Updating upper offset 2\n", res));
                        m_ulUpperOffset = ulFileOffset;
                    
                        res = seekToTheMiddle();
                    }

                    if (bSeekPointInNextPage)
                    {
                        // The seek point is in the next page

                        DPRINTF(D_SEEK, ("COSS::RNPD : seek point is in the next page\n"));
                        m_ulSeekPointOffset = ulSecondPageOffset;

                        changeState(ssDone);
                        res = HXR_OK;
                    }
                    else if (bSeekPointInThisPage)
                    {
                        // The seek point is in this page
                    
                        DPRINTF(D_SEEK, ("COSS::RNPD : seek point is in this page\n"));
                        m_ulSeekPointOffset = ulFileOffset;
                        changeState(ssDone);
                    }
                }
                else 
                {
                    if (uTimestamp < m_uSeekTime)
                    {
                        DPRINTF(D_SEEK, ("COSS::RNPD : Updating lower offset\n", res));
                        m_ulLowerOffset = ulFileOffset;
                        m_uLowerPageSize = uPageSize;
                    }
                    else
                    {
                        DPRINTF(D_SEEK, ("COSS::RNPD : Updating upper offset 3\n", res));
                        m_ulUpperOffset = ulFileOffset;
                    }
                    res = seekToTheMiddle();
                }
            }
        }
    }

    return res;
}

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

void COggSeekStrategy::Close()
{
    HX_RELEASE(m_pPageReader);
    changeState(ssStart);
}

HX_RESULT 
COggSeekStrategy::GetSeekPointOffset(ULONG32& ulSeekPointOffset) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (Done())
    {
        ulSeekPointOffset = m_ulSeekPointOffset;
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggSeekStrategy::GetGroupInfo(const COggGroupInfo*& pGroupInfo) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (Done())
    {
        pGroupInfo = m_pGroupInfo;
        res = HXR_OK;
    }

    return res;
}

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

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

HX_RESULT 
COggSeekStrategy::seekToTheMiddle()
{
    HX_RESULT res = HXR_FAILED;

    if (m_ulUpperOffset > m_ulLowerOffset)
    {
        ULONG32 ulDelta = m_ulUpperOffset - m_ulLowerOffset;

        ULONG32 ulSeekOffset = m_ulLowerOffset + ulDelta / 2;

        DPRINTF(D_SEEK, 
                ("COSS::sTTM() : seekOffset %u\n",
                 ulSeekOffset));
        
        res = doSeek(ulSeekOffset);
    }

    DPRINTF(D_SEEK, ("COSS::sTTM() : done %08x\n", res));
    return res;
}

HX_RESULT 
COggSeekStrategy::doSeek(ULONG32 ulFileOffset)
{
    DPRINTF(D_SEEK, ("COSS::dS() : ulFileOffset %u\n", ulFileOffset));
    m_ulLastSeekOffset = ulFileOffset;
    return m_pPageReader->Seek(m_ulLastSeekOffset);
}
