/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: find_gend_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 "find_gend_strategy.h"
#include "stream_info_strategy.h"

#include "debug.h" // DPRINTF()
#define D_GROUP_END 0 //0x400000

COggFindGroupEndStrategy::COggFindGroupEndStrategy() :
    m_pPageReader(NULL),
    m_pStreamInfoStrategy(NULL),
    m_state(ssStart),
    m_ulLastSeekOffset(0),
    m_ulLeftOffset(0),
    m_uLeftPageSize(0),
    m_leftSerialNum(0),
    m_ulRightOffset(0)
{}

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

// COggPageStrategy methods
HX_RESULT 
COggFindGroupEndStrategy::Init(COggPageReader* pPageReader,
                                 COggStreamInfoStrategy* pStreamInfoStrategy,
                                 ULONG32 ulLastPageOffset)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pPageReader && pStreamInfoStrategy)
    {
        if ((HXR_OK == pStreamInfoStrategy->StartPageOffset(m_ulLeftOffset))&&
            (HXR_OK == pStreamInfoStrategy->StartPageSize(m_uLeftPageSize)) &&
            (HXR_OK == pStreamInfoStrategy->GetStreamSerialNum(0, 
                                                               m_leftSerialNum)))
        {
            // Clear out old state
            Close();

            m_pPageReader = pPageReader;
            m_pPageReader->AddRef();
            
            m_pStreamInfoStrategy = pStreamInfoStrategy;
            
            m_ulRightOffset = ulLastPageOffset;

            changeState(ssInitialized);
            
            res = seekToTheMiddle();
        }
    }

    return res;
}

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

    if (HXR_OK == status)
    {
        DPRINTF(D_GROUP_END, ("COFGES::RNPD(%u, %u)\n",
                              ulFileOffset, uPageSize));

        int serialNum = ogg_page_serialno(pPage);

        if (m_pStreamInfoStrategy->HaveSerialNum(serialNum))
        {
            DPRINTF(D_GROUP_END, ("COFGES::RNPD : page in group\n"));

            // This page is part of the group
            if ((ulFileOffset + uPageSize) >= m_ulRightOffset)
            {
                // We've found the page before the right offset
                // and it is part of the group. Since seeking to 
                // the right offset ALWAYS gets you to a page 
                // from a different group we know we are at the 
                // last page. The end page information is stored
                // in m_ulLeftOffset & m_uLeftPageSize
                m_ulLeftOffset = ulFileOffset;
                m_uLeftPageSize = uPageSize;
                m_leftSerialNum = serialNum;

                changeState(ssDone);
                res = HXR_OK;
            }
            else
            {
                // We found another page that is part of
                // this stream. Keep track of it's offset
                // and seek to the middle
                m_ulLeftOffset = ulFileOffset;
                m_uLeftPageSize = uPageSize;

                res = seekToTheMiddle();
            }
        }
        else
        {
            DPRINTF(D_GROUP_END, ("COFGES::RNPD : page NOT in group\n"));

            // This page is not part of the group
            ULONG32 ulEndOfLeftPage = m_ulLeftOffset + m_uLeftPageSize;

            if ((ulEndOfLeftPage == ulFileOffset) ||
                (m_ulLastSeekOffset < ulEndOfLeftPage))
            {
                // The offset of this page is right after the left side
                // page or it points to the next page after the left side. 
                // In either case it means that this page is the first page 
                // of the next group. The left side information points to the
                // last page of the group. This is right were we want it so,
                // just transition to the ssDone state
                changeState(ssDone);
                res = HXR_OK;
            }
            else 
            {
                // Update the right side with the seek offset that got
                // us to this page. Using the seek offset helps us avoid
                // the case where we seek half way and get the same page
                // again. 
                m_ulRightOffset = m_ulLastSeekOffset;

                res = seekToTheMiddle();
            }
        }
    }

    return res;
}

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

void COggFindGroupEndStrategy::Close()
{
    HX_RELEASE(m_pPageReader);
    changeState(ssStart);
    
    m_pStreamInfoStrategy = NULL;
}

HX_RESULT 
COggFindGroupEndStrategy::LastPageOffset(ULONG32& ulOffset) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (ssDone == m_state)
    {
        ulOffset = m_ulLeftOffset;
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggFindGroupEndStrategy::LastPageSize(UINT32& uPageSize) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (ssDone == m_state)
    {
        uPageSize = m_uLeftPageSize;
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggFindGroupEndStrategy::LastPageSerialNum(int& serialNum) const
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (ssDone == m_state)
    {
        serialNum = m_leftSerialNum;
        res = HXR_OK;
    }

    return res;
}

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

void COggFindGroupEndStrategy::changeState(StrategyState newState)
{
    DPRINTF(D_GROUP_END, ("COFGES::changeState : %s -> %s\n",
                          STATE_STRING(m_state),
                          STATE_STRING(newState)));
    m_state = newState;
}

HX_RESULT 
COggFindGroupEndStrategy::seekToTheMiddle()
{
    HX_RESULT res = HXR_UNEXPECTED;

    ULONG32 ulDelta = m_ulRightOffset - m_ulLeftOffset;

    if (ulDelta > 1)
    {
        m_ulLastSeekOffset = m_ulLeftOffset + ulDelta / 2;

        DPRINTF(D_GROUP_END, ("COFGES::seekToTheMiddle : %u\n",
                              m_ulLastSeekOffset));
        
        res = m_pPageReader->Seek(m_ulLastSeekOffset);
    }

    return res;
}
