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

#include "debug.h"

#define D_STREAM_HDLR 0 //0x100000


COggStreamHandler::COggStreamHandler() :
    m_uNumAudioStreams(0),
    m_uNumVideoStreams(0),
    m_pCCF(NULL),
    m_pStreams(NULL),
    m_bNextStreamIDSet(FALSE),
    m_uNextStreamID(0)
{
#ifdef _DEBUG
    debug_level() |= D_STREAM_HDLR;
#endif // _DEBUG
}

COggStreamHandler::~COggStreamHandler()
{
    HX_RELEASE(m_pCCF);
}

HX_RESULT 
COggStreamHandler::Init(IUnknown* pContext)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

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

    return res;
}

HX_RESULT 
COggStreamHandler::SetStreamTypeCounts(UINT16 uNumAudioStreams, 
                                       UINT16 uNumVideoStreams)
{
    HX_RESULT res = HXR_UNEXPECTED;

    DPRINTF(D_STREAM_HDLR, 
            ("COggStreamHandler::SetStreamTypeCounts(%u, %u)\n",
             uNumAudioStreams, uNumVideoStreams));

    if (!uNumAudioStreams && !uNumVideoStreams)
    {
        res = HXR_INVALID_PARAMETER;
    }
    else if (!m_uNumAudioStreams && !m_uNumVideoStreams)
    {
        m_uNumAudioStreams = uNumAudioStreams;
        m_uNumVideoStreams = uNumVideoStreams;

        delete [] m_pStreams;

        m_pStreams = new COggStream[StreamCount()];

        if (m_pStreams)
        {
            res = HXR_OK;
            for (UINT16 i = 0; (HXR_OK == res) && (i < StreamCount()); i++)
            {
                OggStreamType type = 
                    ((i < m_uNumAudioStreams) ? ostAudioStream :
                     (i < (m_uNumAudioStreams + m_uNumVideoStreams)) ? ostVideoStream :
                     ostUnknown);

                res = m_pStreams[i].Init(i, type, m_pCCF);
            }
        }
        else
        {
            res = HXR_OUTOFMEMORY;
        }
    }

    return res;
}

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

    if (pCodecInfo)
    {
        OggCodecType type = pCodecInfo->Type();
        UINT32 uLower = 0;
        UINT32 uUpper = 0;

        if ((ctVorbis == type) || (ctSpeex == type))
        {
            // audio stream
            uUpper = m_uNumAudioStreams;
        }
        else if (ctTheora == type)
        {
            // video stream
            uLower = m_uNumAudioStreams;
            uUpper = uLower + m_uNumVideoStreams;
        }
        res = setupStream(uLower, uUpper, serialNum, pCodecInfo);
    }

    return res;
}

HX_RESULT 
COggStreamHandler::CreateFileHeader(REF(IHXValues*) pFileHdr)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (m_pCCF && StreamCount())
    {
        res = m_pCCF->CreateInstance(IID_IHXValues, (void**)&pFileHdr);

        if (HXR_OK == res)
        {
            res = pFileHdr->SetPropertyULONG32("StreamCount",
                                               StreamCount());
        }
    }

    return res;
}

HX_RESULT 
COggStreamHandler::CreateStreamHeader(UINT16 i, 
                                      REF(IHXValues*) pStreamHdr)
{
    HX_RESULT res = HXR_INVALID_PARAMETER;

    if (i < StreamCount())
    {
        res = m_pStreams[i].CreateStreamHeader(pStreamHdr);
    }

    return res;
}

HX_RESULT 
COggStreamHandler::NextPacketStreamID(REF(UINT16) uStreamID)
{
    HX_RESULT res = HXR_NO_DATA;

    if (!m_bNextStreamIDSet)
    {
        res = findNextStreamID();
    }

    if (m_bNextStreamIDSet)
    {
        uStreamID = m_uNextStreamID;
        res = HXR_OK;
    }

    return res;
}

HX_RESULT 
COggStreamHandler::GetNextPacket(REF(IHXPacket*) pPkt)
{
    HX_RESULT res = HXR_NO_DATA;

    if (!m_bNextStreamIDSet)
    {
        res = findNextStreamID();
    }

    if (m_bNextStreamIDSet)
    {
        res = m_pStreams[m_uNextStreamID].GetNextPacket(pPkt);

        if (HXR_OK == res)
        {
            m_bNextStreamIDSet = FALSE;
        }
    }

    return res;
}

BOOL COggStreamHandler::EndOfStream(UINT16 uStreamID) const
{
    BOOL bRet = FALSE;
    
    return bRet;
}

COggStream* COggStreamHandler::GetStream(int serialNum)
{
    COggStream* pRet = NULL;
    void* pTmp = NULL;

    if (m_serialToStreamMap.Lookup(serialNum, pTmp))
    {
        pRet = (COggStream*)pTmp;
    }

    return pRet;
}

HX_RESULT 
COggStreamHandler::OnEndOfGroup()
{
    HX_RESULT res = HXR_OK;

    for (UINT16 i = 0; (i < StreamCount()) && (HXR_OK == res); i++)
    {
        res = m_pStreams[i].OnEndOfGroup();
    }

    // Remove all serialNum to stream mappings
    m_serialToStreamMap.RemoveAll();

    return res;
}

HX_RESULT 
COggStreamHandler::OnEndOfFile()
{
    HX_RESULT res = HXR_OK;

    for (UINT16 i = 0; (i < StreamCount()) && (HXR_OK == res); i++)
    {
        res = m_pStreams[i].OnEndOfFile();
    }

    return res;
}

HX_RESULT 
COggStreamHandler::OnSeek(UINT32 uRequestedTime)
{
    HX_RESULT res = HXR_OK;

    m_bNextStreamIDSet = FALSE;

    for (UINT16 i = 0; (i < StreamCount()) && (HXR_OK == res); i++)
    {
        res = m_pStreams[i].OnSeek(uRequestedTime);
    }

    // Remove all serialNum to stream mappings
    m_serialToStreamMap.RemoveAll();

    return res;
}

HX_RESULT 
COggStreamHandler::GetStartTimestamp(COggTimestamp& timestamp)
{
    HX_RESULT res = HXR_OK;

    COggTimestamp highest;
    BOOL bHighestSet = FALSE;

    for (UINT16 i = 0; i < StreamCount(); i++)
    {
        COggTimestamp tmp;
        res = m_pStreams[i].GetStartTimestamp(tmp);

        tmp.SetSampleRate(1000);

        if ((HXR_OK == res) && 
            (!bHighestSet || 
             (tmp.Samples() > highest.Samples())))
        {
            highest = tmp;
            
            bHighestSet = TRUE;
        }
    }

    if ((HXR_OK == res) && bHighestSet)
    {
        timestamp = highest; 
    }
    else
    {
        res = HXR_UNEXPECTED;
    }

    return res;
}

UINT16 COggStreamHandler::StreamCount() const
{
    return m_uNumAudioStreams + m_uNumVideoStreams;
}

HX_RESULT 
COggStreamHandler::setupStream(UINT32 uLower, UINT32 uUpper,
                               int serialNum, const COggCodecInfo* pCodecInfo)
{
    HX_RESULT res = HXR_OK;

    COggStream* pStream = NULL;
    for (UINT32 i = uLower; !pStream && (i < uUpper); i++)
    {
        if (!m_pStreams[i].IsActive())
        {
            pStream = &m_pStreams[i];
            res = pStream->SetCodecInfo(serialNum, pCodecInfo);

            if ((HXR_OK == res) &&
                m_serialToStreamMap.GetCount() == 0)
            {
                pStream->SetIsFirstStream();
            }
        }
    }

    if (!pStream)
    {
        // If we couldn't find a free stream, then assign the 
        // null stream object. This should only happen for 
        // chained live streams where a group in the stream
        // has more streams than the first group
        pStream = &m_nullStream;
    }

    if (HXR_OK == res)
    {
        // Store the serialNum to COggStream mapping
        if (m_serialToStreamMap.SetAt(serialNum, pStream))
        {
            res = HXR_OK;
        }
        else
        {
            res = HXR_OUTOFMEMORY;
        }
    }

    return res;
}

HX_RESULT 
COggStreamHandler::findNextStreamID()
{
    HX_RESULT res = HXR_OK;
    BOOL bNextStreamIDSet = FALSE;
    UINT16 uNextStreamID = 0;
    UINT32 uLowestTS = 0;
    UINT32 uStreamDoneCount = 0;
    UINT32 uActiveStreamCount = 0;

    for (UINT16 i = 0; (i < StreamCount()) && (HXR_OK == res); i++)
    {
        if (m_pStreams[i].IsActive())
        {
            UINT32 uTmpTS;
            HX_RESULT tmpRes = m_pStreams[i].NextPacketTimestamp(uTmpTS);

            uActiveStreamCount++;

            if (HXR_OK == tmpRes)
            {
                if (!bNextStreamIDSet || (uTmpTS < uLowestTS))
                {
                    bNextStreamIDSet = TRUE;
                    uNextStreamID = i;
                    uLowestTS = uTmpTS;
                }
            }
            else if (HXR_STREAM_DONE == tmpRes)
            {
                uStreamDoneCount++;
            }
            else
            {
                // We want to report all errors
                // other than HXR_STREAM_DONE
                res = tmpRes;
            }
        }
    }

    if (HXR_OK == res)
    {
        if (bNextStreamIDSet)
        {
            m_bNextStreamIDSet = TRUE;
            m_uNextStreamID = uNextStreamID;
        }
        else if (uStreamDoneCount &&
                 (uStreamDoneCount == uActiveStreamCount))
        {
            res = HXR_STREAM_DONE;
        }
        else
        {
            res = HXR_NO_DATA;
        }
    }

    return res;
}
