/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: ogg_depack.cpp,v 1.1.2.2 2004/11/24 18:07:05 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 "hlxclib/stdio.h" // printf
#include "hlxclib/stdlib.h" // calloc

#include "ogg_depack.h"

#include "debug.h" // DPRINTF()
#define D_OGG_DEPACK 0 //0x2000000

OggDepacketizer::OggDepacketizer() :
    m_currentSerialNum(0),
    m_bNeedPage(TRUE)
{
#ifdef _DEBUG
    debug_level() |= D_OGG_DEPACK;
#endif /* _DEBUG */

    ogg_sync_init(&m_oy);
    ogg_stream_init(&m_os, m_currentSerialNum);
}

OggDepacketizer::~OggDepacketizer()
{
    ClearQueue();
    ogg_stream_clear(&m_os);
    ogg_sync_clear(&m_oy);
}

VorbisDepacketizer* OggDepacketizer::Create()
{
    return new OggDepacketizer();
}

/* VorbisDepacketizer interface methods */

/* Init()
 *   Called right after the object is created. 
 *   This allows the depacketizer to grab any
 *   interfaces it may need to do it's job.
 */
HX_RESULT OggDepacketizer::Init(IUnknown* pContext)
{
    return HXR_OK;
}

/* OnStreamHeader()
 *    Used to pass the stream header to the depacketizer 
 */
HX_RESULT OggDepacketizer::OnStreamHeader(IHXValues* pStreamHdr)
{
    return HXR_OK;
}

/* OnPacket()
 *    Called when a packet arrives 
 */
HX_RESULT OggDepacketizer::OnPacket(IHXPacket* pPacket)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (pPacket)
    {
        pPacket->AddRef();
        m_packetQueue.Add(pPacket);

        res = HXR_OK;
    }

    return res;
}

/* GetVorbisPacket()
 *    Called to get the next vorbis packet 
 */
HX_RESULT OggDepacketizer::GetVorbisPacket(REF(ogg_packet*) pVorbisPkt)
{
    HX_RESULT res = HXR_FAILED;
    BOOL bDone = FALSE;

    pVorbisPkt = 0;

    while(!bDone)
    {
        while(!bDone && m_bNeedPage)
        {
            if (1 == ogg_sync_pageout(&m_oy, &m_og))
            {
                if (m_currentSerialNum != ogg_page_serialno(&m_og))
                {
                    /* We've switched streams. Reinit stream object */
                    m_currentSerialNum = ogg_page_serialno(&m_og);
                    ogg_stream_init(&m_os, m_currentSerialNum);
                }
               
                if (ogg_stream_pagein(&m_os, &m_og) == 0)
                {
                    /* We've got a page */
                    DPRINTF(D_OGG_DEPACK, 
                            ("got page : granule %lld\n", 
                             ogg_page_granulepos(&m_og)));

                    m_bNeedPage = FALSE;
                }
                else
                {
                    /* An error occured */
                    bDone = TRUE;
                }
            }
            else
            {
                /* need more data for the next page */

                IHXPacket* pPkt = (IHXPacket*)m_packetQueue.Remove();

                if (!pPkt)
                {
                    /* We ran out of packets before we got a page */
                    bDone = TRUE;
                    res = HXR_NO_DATA;
                }
                else if (!pPkt->IsLost())
                {
                    DPRINTF(D_OGG_DEPACK, ("Processing pkt : ts %u\n",
                                           pPkt->GetTime()));

                    IHXBuffer* pPktBuf = pPkt->GetBuffer();
                    
                    if (pPktBuf && (pPktBuf->GetSize() != 0))
                    {
                        /* Hand packet data to ogg_sync layer */
                        char* buffer = ogg_sync_buffer(&m_oy, pPktBuf->GetSize());
                        memcpy(buffer, pPktBuf->GetBuffer(), pPktBuf->GetSize());
                        ogg_sync_wrote(&m_oy, pPktBuf->GetSize());
                    }
                }
            }

        }

        if (!bDone)
        {
            pVorbisPkt = (ogg_packet*)_ogg_calloc(1, sizeof(ogg_packet));

            if (1 == ogg_stream_packetout(&m_os, pVorbisPkt))
            {
                /* We've got an ogg packet*/
                DPRINTF(D_OGG_DEPACK, ("packet %I64d %u\n",
                                       pVorbisPkt->packetno,
                                       pVorbisPkt->bytes));
                bDone = TRUE;
                res = HXR_OK;
            }
            else
            {
                /* We need more data */
                m_bNeedPage = TRUE;

                _ogg_free(pVorbisPkt);
                pVorbisPkt = 0;
            }
        }
    }


    if (HXR_OK != res)
    {
        DPRINTF(D_OGG_DEPACK, 
                ("OggDepacketizer::GetVorbisPacket() res %08x\n", res));
    }
    
    return res;
}

/* Reset()
 *    Flushes the depacketizer. This should be called when a 
 *    seek occurs.
 */
HX_RESULT OggDepacketizer::Reset()
{
    ClearQueue();
    ogg_stream_reset(&m_os);
    ogg_sync_reset(&m_oy);
    m_bNeedPage = TRUE;

    return HXR_OK;
}

/* EndOfStream()
 *   Called after the last packet has been received.
 *   This lets the depacketizer know that it needs
 *   to output any packets it has left.
 */
HX_RESULT OggDepacketizer::EndOfStream()
{
    HX_RESULT res = HXR_FAILED;

    return res;
}

void OggDepacketizer::ClearQueue()
{
    IHXPacket* pPkt = (IHXPacket*)m_packetQueue.Remove();
    while(pPkt)
    {
        HX_RELEASE(pPkt);
        pPkt = (IHXPacket*)m_packetQueue.Remove();
    }
}
