/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: ogg_stream.cpp,v 1.3.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 "ogg_stream.h"
#include "ogg_payload.h"
#include "oggutil.h"

#include "debug.h"

#define D_OGG_STR 0 //0x80000

COggStream::COggStream() :
    m_type(ostUnknown),
    m_pCCF(NULL),
    m_pCodecInfo(NULL),
    m_pPayload(NULL),
    m_bNeedStartTime(TRUE),
    m_bIsFirstStream(FALSE)
{
#ifdef _DEBUG
    debug_level() |= D_OGG_STR;
#endif // _DEBUG

    ogg_stream_init(&m_os, 0);
}

COggStream::~COggStream()
{
    HX_RELEASE(m_pCCF);
    HX_DELETE(m_pCodecInfo);
    HX_DELETE(m_pPayload);

    ogg_stream_clear(&m_os);

    flushUntimedPkts();
}

HX_RESULT 
COggStream::Init(UINT16 uStreamNum, OggStreamType type, IUnknown* pContext)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if ((ostUnknown != type) && pContext)
    {
        m_type = type;

        res = pContext->QueryInterface(IID_IHXCommonClassFactory, 
                                       (void**)&m_pCCF);

        if (HXR_OK == res)
        {
            HX_DELETE(m_pPayload);
            m_pPayload = new COggPayload();

            if (m_pPayload)
            {
                res = m_pPayload->Init(uStreamNum, pContext);
            }
            else
            {
                res = HXR_OUTOFMEMORY;
            }
        }
    }

    return res;
}

HX_RESULT 
COggStream::CreateStreamHeader(REF(IHXValues*) pStreamHdr)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (m_pCCF)
    {
        res = m_pCCF->CreateInstance(CLSID_IHXValues, (void**)&pStreamHdr);

        if (HXR_OK == res)
        {
            res = pStreamHdr->SetPropertyULONG32("Preroll", 1000);
        }
        
        if (HXR_OK == res)
        {
            IHXBuffer* pBuf = NULL;
            res = m_pCCF->CreateInstance(CLSID_IHXBuffer, (void**)&pBuf);

            if (HXR_OK == res)
            {
                const char* pMimeType = 
                    (m_type == ostAudioStream) ? "application/ogg" :
                    (m_type == ostVideoStream) ? "video/x-rn-theora" : NULL;

                if (pMimeType)
                {
                    res = pBuf->Set((UCHAR*)pMimeType, strlen(pMimeType) + 1);

                    if (HXR_OK == res)
                    {
                        res = pStreamHdr->SetPropertyCString("MimeType", 
                                                             pBuf);
                    }
                }
            }
            HX_RELEASE(pBuf);
        }

        // Add bitrate info here later
    }

    return res;
}

HX_RESULT 
COggStream::SetCodecInfo(int serialNum, const COggCodecInfo* pCodecInfo)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pCodecInfo)
    {
        delete m_pCodecInfo;
        
        m_serialNum = serialNum;
        ogg_stream_clear(&m_os);
        ogg_stream_init(&m_os, serialNum);

        m_pCodecInfo = pCodecInfo->Clone();

        if (m_pCodecInfo)
        {
            m_bNeedStartTime = TRUE;
            m_pCodecInfo->SetCurrentGranulePos(0);

            res = m_pPayload->SetCodecInfo(serialNum, m_pCodecInfo);
        }
        else
        {
            res = HXR_OUTOFMEMORY;
        }
    }

    return res;
}

void COggStream::SetIsFirstStream()
{
    m_bIsFirstStream = TRUE;
}

HX_RESULT 
COggStream::OnPage(ogg_page* pPage)
{
    DPRINTF(D_OGG_STR, 
            ("COggStream::OnPage %p\n",
             this));

    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pPage)
    {
        if (ogg_stream_pagein(&m_os, pPage) == 0)
        {
            ogg_packet op;
            BOOL bDone = FALSE;
            BOOL bSeenError = FALSE;

            res = HXR_OK;
            while(!bDone && (HXR_OK == res))
            {
                int poErr = ogg_stream_packetout(&m_os, &op);

                if(poErr > 0)
                {
                    res = onPacket(&op);
                }
                else if (poErr == 0)
                {
                    bDone = TRUE;
                }
                else if (!bSeenError)
                {
                    // Allow one error. This handles the case
                    // in live streams, where there is a gap in
                    // the packet sequence numbers between the
                    // headers and the first data packet
                    bSeenError = TRUE;
                }
                else
                {
                    res = HXR_UNEXPECTED;
                }
            }
        }
        else
        {
            DPRINTF(D_OGG_STR, 
            ("COggStream::OnPage %p : pagein failed\n",
             this));
        }
        res = HXR_OK;
    }

    DPRINTF(D_OGG_STR, 
            ("COggStream::OnPage %p : res %08x\n",
             this, res));
    return res;
}

HX_RESULT 
COggStream::OnEndOfGroup()
{
    HX_RESULT res = m_pPayload->OnEndOfGroup();

    if (HXR_OK == res)
    {
        m_bIsFirstStream = FALSE;
        HX_DELETE(m_pCodecInfo);
    }

    return res;
}

HX_RESULT 
COggStream::OnEndOfFile()
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (m_pPayload)
    {
        res = m_pPayload->OnEndOfFile();
    }

    return res;
}

HX_RESULT 
COggStream::OnSeek(UINT32 uRequestedTime)
{
    m_bNeedStartTime = TRUE;

    m_bIsFirstStream = FALSE;
    HX_DELETE(m_pCodecInfo);
    ogg_stream_reset(&m_os);
    flushUntimedPkts();

    return m_pPayload->OnSeek(uRequestedTime);
}

HX_RESULT 
COggStream::GetStartTimestamp(COggTimestamp& timestamp)
{
    ogg_int64_t currentPos = m_pCodecInfo->CurrentGranulePos();

    return m_pCodecInfo->GetTimestamp(currentPos, timestamp);
}

HX_RESULT 
COggStream::NextPacketTimestamp(REF(UINT32) uTimestamp) const
{
    return m_pPayload->NextPacketTimestamp(uTimestamp);
}

HX_RESULT 
COggStream::GetNextPacket(REF(IHXPacket*) pPkt)
{
    return m_pPayload->GetNextPacket(pPkt);
}

HX_RESULT 
COggStream::onPacket(ogg_packet* pPkt)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;
    
    if (pPkt)
    {
        ogg_packet* pCommentPkt = NULL;

        if (!m_bIsFirstStream && 
            m_pCodecInfo->IsCommentHeader(pPkt))
        {
            pCommentPkt = m_pCodecInfo->CreateBlankCommentPacket();

            if (pCommentPkt)
            {
                pCommentPkt->packetno = pPkt->packetno;
                pPkt = pCommentPkt;
            }
        }

        if (m_bNeedStartTime)
        {
            res = m_pCodecInfo->OnPacket(pPkt);

            if (HXR_OK == res)
            {
                res = cachePacket(pPkt);

                if ((HXR_OK == res) && (pPkt->granulepos > 0))
                {
                    ogg_int64_t currentPos = m_pCodecInfo->CurrentGranulePos();
                    ogg_int64_t startPos = 0;

                    if (currentPos < pPkt->granulepos)
                    {
                        startPos = 
                            m_pCodecInfo->GranulePosDifference(pPkt->granulepos,
                                                               currentPos);
                    }

                    res = m_pCodecInfo->SetCurrentGranulePos(startPos);

                    if (HXR_OK == res)
                    {
                        COggTimestamp timestamp;
                        res = m_pCodecInfo->GetTimestamp(startPos, timestamp);

                        if (HXR_OK == res)
                        {
                            m_pPayload->SetStartTimestamp(timestamp);
                        }
                    }

                    if (HXR_OK == res)
                    {
                        m_bNeedStartTime = FALSE;

                        res = processUntimedPackets();
                    }
                }
            }
        }
        else
        {
            ogg_int64_t startGranulePos = m_pCodecInfo->CurrentGranulePos();
            
            res = m_pCodecInfo->OnPacket(pPkt);
            
            if (HXR_OK == res)
            {     
                DPRINTF(D_OGG_STR, 
                        ("COggStream::onPacket %p : %I64d %I64d %I64d\n",
                         this, 
                         startGranulePos, 
                         m_pCodecInfo->CurrentGranulePos(),
                         pPkt->granulepos));
                
                pPkt->granulepos = m_pCodecInfo->CurrentGranulePos();
                
                res = m_pPayload->OnPacket(pPkt);
            }
        }

        OggUtil::DestroyPacket(pCommentPkt);
    }

    DPRINTF(D_OGG_STR, 
            ("COggStream::onPacket %p : res %08x\n",
             this, res));

    return res;
}

HX_RESULT COggStream::processUntimedPackets()
{
    HX_RESULT res = HXR_OK;

    while(!m_untimedPkts.IsEmpty() && (HXR_OK == res))
    {
        ogg_packet* pPkt = (ogg_packet*)m_untimedPkts.RemoveHead();

        res = onPacket(pPkt);

        OggUtil::DestroyPacket(pPkt);
    }

    return res;
}

HX_RESULT COggStream::cachePacket(ogg_packet* pPkt)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (pPkt)
    {
        ogg_packet* pNewPkt = OggUtil::CopyPacket(pPkt);

        if (pNewPkt && m_untimedPkts.AddTail(pNewPkt))
        {
            res = HXR_OK;
        }
        else
        {
            OggUtil::DestroyPacket(pNewPkt);
            res = HXR_OUTOFMEMORY;
        }
    }

    return res;
}

void COggStream::flushUntimedPkts()
{
    while(!m_untimedPkts.IsEmpty())
    {
        ogg_packet* pPkt = (ogg_packet*)m_untimedPkts.RemoveHead();
        OggUtil::DestroyPacket(pPkt);
    }
}
