/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: smlpkt.cpp,v 1.4.14.1 2004/07/09 01:57:06 hubbe 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/stdlib.h"
#include "hlxclib/stdio.h"
#include "hlxclib/ctype.h"
#include "hxtypes.h"
#include "hxresult.h"
#include "hxassert.h"
#include "hxcom.h"
#include "debug.h"
#include "hxstrutl.h"
#include "hxstring.h"
#include "hxmap.h"
#include "hxslist.h"
#include "chxpckts.h"
#include "cbbqueue.h"
#include "hxstack.h"

#include "smlpkt.h"

#ifdef _WINCE
#include <charfs.h>
#endif

#include "hxheap.h"
#ifdef _DEBUG
#undef HX_THIS_FILE             
static char HX_THIS_FILE[] = __FILE__;
#endif

static const int MAX_ARGS = 32;
static const int MAX_STRING_LEN = 10000;

CSmilAddGroupPacket::CSmilAddGroupPacket():
    CSmilPacket(SMILAddGroup),
    m_nGroup(0),
    m_nTotalTracks(0),
    m_nInitTracks(0),
    m_ulDuration((UINT32)-1)
{
}

void
CSmilAddGroupPacket::assign(const char* pName, const char** pValues,
                            INT32 nValues)
{
    if(strcmp(pName, "ver") == 0 && nValues >= 1)
    {
        m_version = pValues[0];
    }
    else if(strcmp(pName, "id") == 0 && nValues >= 1)
    {
        m_id = pValues[0];
    }
    else if(strcmp(pName, "group") == 0 && nValues >= 1)
    {
        m_nGroup = (int)atol(pValues[0]);
    }
    else if(strcmp(pName, "total-tracks") == 0 && nValues >= 1)
    {
        m_nTotalTracks = (int)atol(pValues[0]);
    }
    else if(strcmp(pName, "init-tracks") == 0 && nValues >= 1)
    {
        m_nInitTracks = (int)atol(pValues[0]);
    }
    else if(strcmp(pName, "title") == 0 && nValues >= 1)
    {
        m_title = pValues[0];
    }
    else if(strcmp(pName, "dur") == 0 && nValues >= 1)
    {
        m_ulDuration = atol(pValues[0]);
    }
}

CSmilPlayGroupPacket::CSmilPlayGroupPacket():
    CSmilPacket(SMILPlayGroup),
    m_nGroup(0),
    m_ulDelay(0),
    m_ulDuration(0)
{
}

void
CSmilPlayGroupPacket::assign(const char* pName, const char** pValues,
                             INT32 nValues)
{
    if(strcmp(pName, "ver") == 0 && nValues >= 1)
    {
        m_version = pValues[0];
    }
    else if(strcmp(pName, "id") == 0 && nValues >= 1)
    {
        m_id = pValues[0];
    }
    else if(strcmp(pName, "group") == 0 && nValues >= 1)
    {
        m_nGroup = (int)atol(pValues[0]);
    }
    else if(strcmp(pName, "delay") == 0 && nValues >= 1)
    {
        m_ulDelay = atol(pValues[0]);
    }
    else if(strcmp(pName, "dur") == 0 && nValues >= 1)
    {
        m_ulDuration = atol(pValues[0]);
    }
}


CSmilMetaValuesPacket::CSmilMetaValuesPacket():
    CSmilPacket(SMILMetaValues)
{
    m_pValues = new CHXHeader;
    m_pValues->AddRef();
}

CSmilMetaValuesPacket::~CSmilMetaValuesPacket()
{
    HX_RELEASE(m_pValues);
}

void
CSmilMetaValuesPacket::assign(const char* pName, const char** pValues,
                              INT32 nValues)
{
    if(nValues >= 1)
    {
        CHXBuffer* pBuffer = new CHXBuffer;
        pBuffer->AddRef();
        pBuffer->Set((BYTE*)pValues[0], strlen(pValues[0])+1);

        m_pValues->SetPropertyCString(pName, pBuffer);
        pBuffer->Release();
    }
}

CSmilAddChannelPacket::CSmilAddChannelPacket():
    CSmilPacket(SMILAddChannel),
    m_ulLeft(0),
    m_ulTop(0),
    m_ulHeight(0),
    m_ulWidth(0),
    m_ulZIndex(0),
    m_ulBgColor(0)
{
}

void
CSmilAddChannelPacket::assign(const char* pName, const char** pValues,
                              INT32 nValues)
{
    if(strcmp(pName, "ver") == 0 && nValues >= 1)
    {
        m_version = pValues[0];
    }
    else if(strcmp(pName, "id") == 0 && nValues >= 1)
    {
        m_id = pValues[0];
    }
    else if(strcmp(pName, "left") == 0 && nValues >= 1)
    {
        m_ulLeft = atol(pValues[0]);
    }
    else if(strcmp(pName, "top") == 0 && nValues >= 1)
    {
        m_ulTop = atol(pValues[0]);
    }
    else if(strcmp(pName, "height") == 0 && nValues >= 1)
    {
        m_ulHeight = atol(pValues[0]);
    }
    else if(strcmp(pName, "width") == 0 && nValues >= 1)
    {
        m_ulWidth = atol(pValues[0]);
    }
    else if(strcmp(pName, "z-index") == 0 && nValues >= 1)
    {
        m_ulZIndex = atol(pValues[0]);
    }
    else if(strcmp(pName, "bgcolor") == 0 && nValues >= 1)
    {
        m_ulBgColor = atol(pValues[0]);
    }
}

CSmilEndLayoutPacket::CSmilEndLayoutPacket():
    CSmilPacket(SMILEndLayout)
{
}

CSmilEndLayoutPacket::~CSmilEndLayoutPacket()
{
}

void
CSmilEndLayoutPacket::assign(const char* pName, const char** pValues,
                             INT32 nValues)
{
}


CSmilDocumentPacket::CSmilDocumentPacket():
    CSmilPacket(SMILDocument),
    m_ulPacketNumber(0),
    m_ulTotalPackets(0)
{
}

CSmilDocumentPacket::~CSmilDocumentPacket()
{
}

void
CSmilDocumentPacket::assign(const char* pName, const char** pValues,
                            INT32 nValues)
{
    if(strcmp(pName, "ver") == 0 && nValues >= 1)
    {
        m_version = pValues[0];
    }
    else if(strcmp(pName, "id") == 0 && nValues >= 1)
    {
        m_id = pValues[0];
    }
    else if(strcmp(pName, "doc") == 0 && nValues >= 1)
    {
        m_document = pValues[0];
    }
    else if(strcmp(pName, "npkt") == 0 && nValues >= 1)
    {
        m_ulPacketNumber = atol(pValues[0]);
    }
    else if(strcmp(pName, "ttlpkt") == 0 && nValues >= 1)
    {
        m_ulTotalPackets = atol(pValues[0]);
    }
}


CSmilAddSourcePacket::CSmilAddSourcePacket():
    CSmilPacket(SMILAddSource),
    m_ulDelay((UINT32)-1),
    m_ulDuration((UINT32)-1),
    m_ulClipStart((UINT32)-1),
    m_ulClipEnd((UINT32)-1)
{
}

void
CSmilAddSourcePacket::assign(const char* pName, const char** pValues,
                             INT32 nValues)
{
    if(strcmp(pName, "ver") == 0 && nValues >= 1)
    {
        m_version = pValues[0];
    }
    else if(strcmp(pName, "id") == 0 && nValues >= 1)
    {
        m_id = pValues[0];
    }
    else if(strcmp(pName, "src") == 0 && nValues >= 1)
    {
        m_src = pValues[0];
    }
    else if(strcmp(pName, "channel") == 0 && nValues >= 1)
    {
        m_channel = pValues[0];
    }
    else if(strcmp(pName, "group") == 0 && nValues >= 1)
    {
        m_nGroup = atol(pValues[0]);
    }
    else if(strcmp(pName, "delay") == 0 && nValues >= 1)
    {
        m_ulDelay = atol(pValues[0]);
    }
    else if(strcmp(pName, "dur") == 0 && nValues >= 1)
    {
        m_ulDuration = atol(pValues[0]);
    }
    else if(strcmp(pName, "start") == 0 && nValues >= 1)
    {
        m_ulClipStart = atol(pValues[0]);
    }
    else if(strcmp(pName, "end") == 0 && nValues >= 1)
    {
        m_ulClipEnd = atol(pValues[0]);
    }
    else if(strcmp(pName, "fill") == 0 && nValues >= 1)
    {
        m_fill = pValues[0];
    }
}

CSmilSourceAddedPacket::CSmilSourceAddedPacket():
    CSmilPacket(SMILSourceAdded),
    m_duration(0)
{
}

void
CSmilSourceAddedPacket::assign(const char* pName, const char** pValues,
                               INT32 nValues)
{
    if(strcmp(pName, "dur") == 0 && nValues >= 1)
    {
        m_duration = atol(pValues[0]);
    }
}


CSmilPacketParser::CSmilPacketParser():
    m_pRootNode(0)
{
}

CSmilPacketParser::~CSmilPacketParser()
{
    deleteNode(m_pRootNode);
}

CSmilPacketParser::SMILPacketParseResult
CSmilPacketParser::getAtom(const char*& pBuf, UINT32 len, 
                           CSmilPacketTag*& pTag)
{
    CSmilPacketParser::SMILPacketParseResult retCode = SMILUnknown;
    const char* pEnd;
    const char* pCur;

    pTag = 0;
    pEnd = pBuf + len;
    pCur = pBuf;

    if(*pCur == '(')
    {
        pCur++;
        pBuf = pCur;
        retCode = SMILOpenList;
    }
    else if(*pCur == ')')
    {
        pCur++;
        pBuf = pCur;
        retCode = SMILCloseList;
    }
    else
    {
        // skip whitespace
        while(isspace(*pCur) && (pCur < pEnd))
        {
            pCur++;
        }
        if(pCur >= pEnd)
        {
            pBuf = pCur;
            retCode = SMILNoValue;
        }
        else if(*pCur == ')')
        {
            pCur++;
            pBuf = pCur;
            retCode = SMILCloseList;
        }
        else if(*pCur == '(')
        {
            pCur++;
            pBuf = pCur;
            retCode = SMILOpenList;
        }
        else
        {
            char* tmpBuf = new char [MAX_STRING_LEN + 2]; /* Flawfinder: ignore */ // one for null, one for luck
            char* pTmpBuf = tmpBuf;
            if(*pCur == '"')
            {
                pCur++;
                int iLen = 0;  
                while((*pCur != '"') && (pCur < pEnd) && (++iLen < MAX_STRING_LEN))
                {
                    if(*pCur == '\\')
                    {
                        pCur++;
                        *pTmpBuf++ = *pCur++;
                    }
                    else
                    {
                        *pTmpBuf++ = *pCur++;
                    }
                }
                if(*pCur != '"')
                {
                    pBuf = pCur;
                    retCode = SMILMissingQuote;
                }
                else
                {
                    *pTmpBuf = 0;
                    pCur++;
                }
            }
            else
            {
                while((pCur<pEnd) && !isspace(*pCur) && (*pCur != ')') && 
                      (*pCur != '(') )
                {
                    if(*pCur == '\\')
                    {
                        pCur++;
                        *pTmpBuf++ = *pCur++;
                    }
                    else
                    {
                        *pTmpBuf++ = *pCur++;
                    }
                }
                *pTmpBuf = 0;
            }
            if( retCode != SMILMissingQuote )
            {
                pTag = new CSmilPacketTag;
                pTag->m_name = tmpBuf;
                pBuf = pCur;
                retCode = SMILString;
            }
            HX_VECTOR_DELETE(tmpBuf);
        }
    }
    return retCode;
}

CSmilPacket*
CSmilPacketParser::parse(IHXBuffer* pBuffer,
                         REF(CSmilPacketParser::SMILPacketParseResult) pktPrsRslt)
{
    BOOL bErrorOccurred = FALSE;

    CSmilPacketTag* pTag = 0;

    HX_RESULT pnr = HXR_OK;

    if(m_pRootNode)
    {
        deleteNode(m_pRootNode);
    }
    m_pRootNode = new Node;
    Node* pCurNode = m_pRootNode;
    Node* pCurList = m_pRootNode;

    CHXStack* pStack = new CHXStack;

    CBigByteQueue* pQueue = new CBigByteQueue(pBuffer->GetSize());
    pQueue->EnQueue((void*)pBuffer->GetBuffer(), pBuffer->GetSize());

    BOOL bFirst = TRUE;
    for(;;)
    {
        UINT32 bytesUsed;
        UINT32 bytesAvail = pQueue->GetQueuedItemCount();
        if(bytesAvail <= 0)
        {
            break;
        }

        BYTE* pBuf = new BYTE[bytesAvail];
        BYTE* p = pBuf;
        pQueue->DeQueue(pBuf, bytesAvail);
        bytesUsed = bytesAvail;

        if(pTag)
        {
            delete pTag;
            pTag = 0;
        }

        SMILPacketParseResult rc = getAtom((const char*&)p, bytesAvail, pTag);
        // /Fixes PR 32297 (release-build-only crash):
        // In case rc is SMILMissingQuote, quit and return an error,
        // otherwise a 0-sized buffer gets created later on that is the
        // subject of an access violation:
        INT32 lSizeToEnqueue = bytesAvail - (p - pBuf);
        HX_ASSERT(lSizeToEnqueue >= 0); // /If < 0, something is messed up.
        if (0 == lSizeToEnqueue  &&  SMILMissingQuote == rc)
        {
            pktPrsRslt = rc;
            bErrorOccurred = TRUE;
            goto cleanup;
        }
        pQueue->EnQueue(p, (UINT32)(bytesAvail - (p - pBuf)));
        switch(rc)
        {
           case SMILOpenList:
           {
               Node* pNode = new Node;
               if(pCurNode == m_pRootNode)
               {
                   pCurNode->car = pNode;
               }
               else
               {
                   pCurNode->cdr = pNode;
               }
               pStack->Push(pNode);
               pCurNode = pNode;
           }
           break;

           case SMILString:
           {
               if(bFirst)
               {
                   bFirst = FALSE;
               }
               else
               {
                   Node* pNode = new Node;
                   if(!pCurNode->m_bIsSymbol)
                   {
                       if(!pCurNode->car)
                           pCurNode->car = pNode;
                       else
                           pCurNode->cdr = pNode;
                   }
                   else
                   {
                       pCurNode->cdr = pNode;
                   }
                   pCurNode = pNode;
               }
               pCurNode->m_name = pTag->m_name;
               pCurNode->m_bIsSymbol = TRUE;
           }
           break;

           case SMILCloseList:
           {
               pCurNode = (Node*)pStack->Pop();
           }
           break;

           default:
               break;
        }
        HX_VECTOR_DELETE(pBuf);
    }

  cleanup:
    if(pTag)
    {
        delete pTag;
    }

    delete pQueue;
    delete pStack;

    if (bErrorOccurred)
    {
        return NULL;
    }
    return evalNode(getRoot());
}

void
CSmilPacketParser::deleteNode(Node* pNode)
{
    if(!pNode)
    {
        return;
    }
    deleteNode(pNode->car);
    deleteNode(pNode->cdr);
    delete pNode;
}

void
CSmilPacketParser::eval(Node* pNode, CSmilPacket* pPacket)
{
    if(!pNode)
        return;

    BOOL bFirst = TRUE;
    const char* pName = 0;
    const char* pValue[MAX_ARGS] = {0};
    int i = 0;
    while(pNode && i < MAX_ARGS)
    {
        if(pNode->m_bIsSymbol)
        {
            if(bFirst)
            {
                pName = (const char*)pNode->m_name;
                bFirst = FALSE;
                i = 0;
            }
            else
            {
                pValue[i] = (const char*)pNode->m_name;
                i++;
            }
        }
        else
        {
            eval(pNode->car, pPacket);
        }
        pNode = pNode->cdr;
    }
    if(pName)
    {
        pPacket->assign(pName, pValue, i);
    }
}

CSmilPacket*
CSmilPacketParser::evalNode(Node* pNode)
{
    if(!pNode || !pNode->m_bIsSymbol)
    {
        return 0;
    }

    CSmilPacket* pPacket = 0;
    // const char* pID = 0;
    const char* pName = 0;

    pName = (const char*)pNode->m_name;
    pNode = pNode->cdr;
    if(pNode)
    {
//      if(pNode->m_bIsSymbol)
//      {
//          pID = (const char*)pNode->m_name;
//          pNode = pNode->cdr;
//      }
//      else
//      {
//          pID = "<anonymous>";
//      }

        if(strcmp(pName, "smil-document") == 0)
        {
            pPacket = new CSmilDocumentPacket;
        }
        else if(strcmp(pName, "add-channel") == 0)
        {
            pPacket = new CSmilAddChannelPacket;
        }
        else if(strcmp(pName, "add-group") == 0)
        {
            pPacket = new CSmilAddGroupPacket;
        }
        else if(strcmp(pName, "play-group") == 0)
        {
            pPacket = new CSmilPlayGroupPacket;
        }
        else if(strcmp(pName, "add-source") == 0)
        {
            pPacket = new CSmilAddSourcePacket;
        }
        else if(strcmp(pName, "source-added") == 0)
        {
            pPacket = new CSmilSourceAddedPacket;
        }
        else if(strcmp(pName, "end-layout") == 0)
        {
            pPacket = new CSmilEndLayoutPacket;
        }
        else if(strcmp(pName, "meta") == 0)
        {
            pPacket = new CSmilMetaValuesPacket;
        }

        if(pPacket)
        {
            eval(pNode, pPacket);
        }
        return pPacket;
    }
    return 0;
}
