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

#include "debug.h" // DPRINTF()
#define D_EOF 0 //0x8000000

static const UINT32 SeekBackSize = 4096;
static const UINT32 MaxSeekBackSize = 128 * 1024; // 128k should be plenty

COggFindEOFStrategy::COggFindEOFStrategy() :
    m_pPageReader(NULL),
    m_state(ssStart),
    m_ulLastSeekOffset(0),
    m_uSeekBackTotal(0),
    m_bLastPageInfoValid(FALSE),
    m_ulLastPageOffset(0),
    m_uLastPageSize(0),
    m_lastPageSerialNum(0)
{
#ifdef _DEBUG
    debug_level() |= D_EOF;
#endif /* _DEBUG */
}

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

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

    if (pPageReader)
    {
        if (pPageReader->IsSeekable())
        {            
            ULONG32 ulFileSize = pPageReader->FileSize();
            if (!ulFileSize)
            {
                res = HXR_UNEXPECTED;
            }
            else
            {
                // Clear out old state
                Close();

                changeState(ssInitialized);

                m_pPageReader = pPageReader;
                m_pPageReader->AddRef();

                m_ulLastSeekOffset = ulFileSize;
                m_uSeekBackTotal = 0;
                res = seekBackMore();
            }
        }
        else
        {
            res = HXR_UNEXPECTED;
        }
    }

    return res;
}

HX_RESULT 
COggFindEOFStrategy::ReadNextPageDone(HX_RESULT status,
                                      ULONG32 ulFileOffset,
                                      UINT32 ulPageSize,
                                      ogg_page* pPage)
{
    HX_RESULT res = HXR_OK;
    DPRINTF(D_EOF, 
            ("COFEOFS::RNPD(%08x, %u, %u)\n",
             status, ulFileOffset, ulPageSize));

    if (HXR_OK == status)
    {
        m_bLastPageInfoValid = TRUE;

        m_ulLastPageOffset = ulFileOffset;
        m_uLastPageSize = ulPageSize;
        m_lastPageSerialNum = ogg_page_serialno(pPage);

        res = m_pPageReader->ReadNextPage();
    }
    else if (m_bLastPageInfoValid)
    {
        // We hit the end of the file again, but
        // we now have valid page info. We are
        // done now.
        changeState(ssDone);
    }
    else if (m_ulLastSeekOffset && (m_uSeekBackTotal < MaxSeekBackSize))
    {
        // Time to seek back more to see if we can find a page
        res = seekBackMore();
    }
    else
    {
        // we either had to seek back too far to find a page or
        // we seeked back to the beginning and still didn't find 
        // a page. This is likely an invalid file
        res = HXR_INVALID_FILE;
    }

    return res;
}

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

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

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

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

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

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

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

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

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

void COggFindEOFStrategy::changeState(StrategyState newState)
{
    DPRINTF(D_EOF, ("COFEOFS::changeState : %s -> %s\n",
                            STATE_STRING(m_state),
                            STATE_STRING(newState)));
    m_state = newState;
}

HX_RESULT 
COggFindEOFStrategy::seekBackMore()
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (m_pPageReader && (m_ulLastSeekOffset != 0))
    {
        if (m_ulLastSeekOffset >= SeekBackSize)
        {
            m_ulLastSeekOffset -= SeekBackSize;
            m_uSeekBackTotal += SeekBackSize;
        }
        else
        {
            m_uSeekBackTotal += m_ulLastSeekOffset;
            m_ulLastSeekOffset = 0;
        }

        DPRINTF(D_EOF, 
                ("COFEOFS::seekBackMore : seeking to %u\n",
                 m_ulLastSeekOffset));
        res = m_pPageReader->Seek(m_ulLastSeekOffset);
    }

    return res;
}
