/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: decoder-h261.cpp,v 1.1.8.1 2004/07/09 01:50:08 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 ***** */

/*
 * Copyright (c) 1993-1994 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the University of
 *      California, Berkeley and the Network Research Group at
 *      Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

static const char rcsid[] =
    "@(#) $Header: /cvsroot/datatype/h261/renderer/decoder-h261.cpp,v 1.1.8.1 2004/07/09 01:50:08 hubbe Exp $ (LBL)";

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "inet.h"
#include "rtp.h"
#include "p64.h"
#include "decoder.h"

#ifdef _MACINTOSH
 #include "hxtypes.h"
 #include "hxresult.h"
 #include "hxcom.h"
 #include "mac_net.h"
#endif

#include "hxheap.h"
#ifdef _DEBUG
    #undef HX_THIS_FILE		
    static char HX_THIS_FILE[] = __FILE__;
#endif
//
// Following is bare minimum to get the VIC decoder to run in place...
//

Decoder::Decoder(int hdrlen) : 
	hdrlen_(hdrlen), delvar_(0),
	inw_(0), inh_(0), color_(1), decimation_(422),
	nstat_(0), rvts_(NULL), nblk_(0), ndblk_(0)
{
	/*XXX*/
	now_ = 1;

	for (int i = 0; i < MAXSTAT; ++i)
		stat_[i].cnt = 0;
}


H261Decoder::H261Decoder() :
	Decoder(4), codec_(0), h261_rtp_bug_(0), 
	frame_needs_rendering_(0), frame_needs_resizing_(0)
{
	stat_[STAT_BAD_PSC].name = "H261-Bad-PSC";
	stat_[STAT_BAD_GOB].name = "H261-Bad-GOB";
	stat_[STAT_BAD_SYNTAX].name = "H261-Bad-Syntax";
	stat_[STAT_BAD_FMT].name = "H261-Bad-fmt";
	stat_[STAT_FMT_CHANGE].name = "H261-Fmt-change";
	stat_[STAT_BAD_HEADER].name = "H261-Bad-Header";
	nstat_ = 6;

	decimation_ = 411;
	/*
	 * Assume CIF.  Picture header will trigger a resize if
	 * we encounter QCIF instead.
	 */
	inw_ = 352;
	inh_ = 288;

	/*XXX*/
	resize(inw_, inh_);
}

H261Decoder::~H261Decoder()
{
	if (codec_) 
	    delete codec_;
}

void H261Decoder::info(char* wrk) const
{
	if (codec_ == 0)
		*wrk = 0;
	else
		sprintf(wrk, "[q=%d]", codec_->gobquant()); /* Flawfinder: ignore */
}

void H261Decoder::resize(int width, int height)
{
	inw_ = width;
	inh_ = height;
	nblk_ = (width * height) / 64;
	if(rvts_)
	{
	    delete rvts_;
	}
	rvts_ = new u_char[nblk_];
	memset(rvts_, 0, nblk_);
}

void H261Decoder::stats(char* wrk)
{
    if (codec_)
    {
    	/* pull stats out of vic indepdendent P64Decoder */
    	setstat(STAT_BAD_PSC, codec_->bad_psc());
    	setstat(STAT_BAD_GOB, codec_->bad_GOBno());
    	setstat(STAT_BAD_SYNTAX, codec_->bad_bits());
    	setstat(STAT_BAD_FMT, codec_->bad_fmt());
    	Decoder::stats(wrk);
    }    	
}

void H261Decoder::recv(BOOL bMarker, const u_char* bp, int cc)
{	
	if (codec_ == 0) {
	    u_char* vh = (u_char*)(bp);
	    if ((vh[0] & 2) != 0)
		    codec_ = new IntraP64Decoder();
	    else
		    codec_ = new FullP64Decoder();
	    
	    codec_->marks(rvts_);
	}
	/*XXX*/
	u_int v = ntohl(*(u_int*)(bp));
	int sbit = v >> 29;
	int ebit = (v >> 26) & 7;
	int quant = (v >> 10) & 0x1f;
	int mvdh = (v >> 5) & 0x1f;
	int mvdv = v & 0x1f;
	int mba, gob;
	/*
	 * vic-2.7 swapped the GOB and MBA fields in the RTP packet header
	 * with respect to the spec.  To maintain backward compat, whenever
	 * we see an out of range gob, we change our assumption about the
	 * stream and continue.
	 */
	if (!h261_rtp_bug_) {
		mba = (v >> 15) & 0x1f;
		gob = (v >> 20) & 0xf;
		if (gob > 12) {
			h261_rtp_bug_ = 1;
			mba = (v >> 19) & 0x1f;
			gob = (v >> 15) & 0xf;
		}
	} else {
		mba = (v >> 19) & 0x1f;
		gob = (v >> 15) & 0xf;
		if (gob > 12) {
			h261_rtp_bug_ = 0;
			mba = (v >> 15) & 0x1f;
			gob = (v >> 20) & 0xf;
		}
	}

	if (gob > 12) {
		count(STAT_BAD_HEADER);
		return;
	}
	codec_->mark(now_);
	(void)codec_->decode(bp+4, cc-4, sbit, ebit, mba, gob, quant, mvdh, mvdv);
	/*
	 * If the stream changes format, issue a resize.
	 */
	if (codec_->width() != inw_) {
		resize(codec_->width(), codec_->height());
		frame_needs_resizing_ = 1;
		codec_->marks(rvts_);
		count(STAT_FMT_CHANGE);
	}

	/*XXX*/
	if (bMarker) {
		codec_->sync();
		ndblk_ = codec_->ndblk();
		frame_needs_rendering_ = 1;
		codec_->resetndblk();
	}
}

Decoder::~Decoder()
{
    if(rvts_)
	delete rvts_;
}

void Decoder::stats(char* bp)
{
	if (nstat_ == 0) {
		*bp = 0;
		return;
	}
	for (int i = 0; i < nstat_; ++i) {
		sprintf(bp, "%s %d ", stat_[i].name, stat_[i].cnt); /* Flawfinder: ignore */
		bp += strlen(bp);
	}
	bp[-1] = 0;
}

