h261dec.c

来自「symbian 下的helix player源代码」· C语言 代码 · 共 1,645 行 · 第 1/5 页

C
1,645
字号
/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: h261dec.c,v 1.3.34.1 2004/07/09 01:56:22 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 "hxtypes.h"
#include "dllindex.h"
#include "h261defs.h"
#include "vldstate.h"
#include "h261func.h"
#include "hvscodes.h"        /* getImgParms can be called                    */
#include "dec_blk.h"        /* set the proper pragmas for decode_block      */
#include "vldecode.h"       /* set the proper pragmas for VLDecode          */
#include "h263plus.h"

//#define ANNOTATE_PICTURE    // Include diagnostic info in output picture
#ifdef TESTING
#include <stdio.h>
#include <stdlib.h>
#define BS_ERR_MSG(a)   a   // Generate messages on bitstream error (i.e., illegal 
                            // bitstream syntax) to simplify debugging
#define CHECKSYM(a)     a   // Check symbol types to verify decoder state tables

#else
#define BS_ERR_MSG(a)       // Suppress error messages 
#define CHECKSYM(a)         // Don't check symbol types
#endif


// Declarations of local functions
static int  findPSC( BS_PTR start[], int gn[], int num_sc, int *sc, H261Decoder *s );
static void savePSCpointer( BS_PTR *bsPSC, H261Decoder *s );
static void outputBsPointer( BS_PTR * start, BS_PTR * output, int codingMethod );
static int decodeBitstream( H261Decoder *s,
                            GOB_DESCR   *gob,
                            BS_PTR      start[2],
                            int         gn[2],
                            int         *structStatus,
                            int         *decStatus );
static int  doGobStructures( H261Decoder *s, GOB_DESCR *gob, MACROBLOCK_DESCR mb[],
                        BS_PTR start[2], int gn[2] );
static int  doGobDecoding( H261Decoder *s, GOB_DESCR *gob, MACROBLOCK_DESCR mb[],
                        BS_PTR start[2], SYMBOL sym[], int maxsym );
static void gobConcealment( H261Decoder *s, GOB_DESCR *gob, MACROBLOCK_DESCR mb[] );
static int build_gob_struct( S32 format, S32 gn, GOB_DESCR * gob);
static int build263gob( S32 format, S32 gn, int next_gn, GOB_DESCR * gob,
                        PICTURE_DESCR * pic );
/*static void update_decMB( GOB_DESCR * gob, MACROBLOCK_DESCR mb[], int mb_per_row, 
                        int codingMethod, MBMap * decMB, S32 * iFrame, int forcedUpdate );*/
static int  initializePicture( H261Decoder * s );
static int  decodePicLayer( BS_PTR * bs, int nbits, PICTURE_DESCR * pic,
                            SYMBOL sym[], int maxsym, int codingMethod, GOB_DESCR * gob,
                            int * ptype );
static int  decode_pic261( BS_PTR * bs, int nbits, PICTURE_DESCR * pic,
                            SYMBOL sym[], int maxsym);
static int  decode261gob(  BS_PTR * bs, int nbits, GOB_DESCR * gob,
                        MACROBLOCK_DESCR mb[], SYMBOL sym[], int maxsym);
static int  decode_mb( SYMBOL insym[], int * nextsym, int * quant,
                        GOB_DESCR * gob, MACROBLOCK_DESCR mb[], int mbnum,
                        SYMBOL outsym[]);
static int  decode_intra_block( SYMBOL insym[], int * nextsym,
                            BLOCK_DESCR * block, SYMBOL outsym[]);
static int  find_startcodes( BS_PTR * bs,   // Points to beginning of bitstream
                            int numbits,    // length of bitstream in bits
                            BS_PTR start[], // Returns positions for startcodes; size "max_start"
                            int gobnum[],   // Returns 4 bits after startcode (5 bits for H.263); size "max_start"
                            int max_start,  // Max number of start codes to be returned
                            int codingMethod );  // Indicate H.261 or H.263 syntax
static int  find_sc( BS_PTR * bs,       // Points to beginning of bitstream
                     int numbits,       // length of bitstream in bits
                     int startZeros,    // number of zeros in startcode
                     BS_PTR * start );   // Returns position for bit after startcode
#ifdef ANNOTATE_PICTURE
// saveOrRestoreReconPicture
static void saveOrRestoreReconPicture( PICTURE *pic,    // Picture to be saved or restored
                                       int  restore     // Save if 0, otherwise restore
                                     );
// annotatePicture - Draw motion vectors etc.
static void annotatePicture( PICTURE *pic, MACROBLOCK_DESCR mb[]);
// annotateMacroblock
static void annotateMacroblock( PIXEL data[], int xdim, MACROBLOCK_DESCR *mb,
                                int xMin, int xMax, int yMin, int yMax );
static void drawMv( PIXEL data[], int xdim, int mvX, int mvY,
                    int xMin, int xMax, int yMin, int yMax );
static void plusMb( PIXEL data[], int xdim );
static void crossMb( PIXEL data[], int xdim );
static void fillMb( PIXEL data[], int xdim );
static void markPixel( PIXEL *pixel );
static int  DrawVector( unsigned char data[], int xdim, int x1, int y1, int x2, int y2 );
static int  drawVec( unsigned char data[], int xdim, int x1, int y1 );
#endif


#define GN_END_OF_SEQUENCE  (31)    // GN=31 for EOS
#define H263_START_ZEROS    (16)
#define H263_GN_BITS        (5)
#define H261_START_ZEROS    (15)
#define H261_GN_BITS        (4)


//
//
//  ****************************************************
//  H261Decode - Decode one or several GOBs in a picture
//  ****************************************************
//
//
extern int  H261Decode( H261Decoder * s )
#define NUM_SC      0
#define NUMGOB      1
#define ERRGOB      2
#define IFRAME      3
{
    BS_PTR      *pStart;    // Position of startcodes ("start")
    int         *pGn;       // GOB numbers following each startcode ("gn")
    GOB_DESCR   *pGob;      // Can refer to several GOBs, if GOB headers are left out ("gob")
    int         *pNum_sc;   // Points to number of startcodes found ("num_sc")
    int         *pSc;       // Points to current startcode ("sc")
    BS_PTR      bsPSC;
    int         status, structStatus, decStatus;
    BS_ERR_MSG(char msg[120];) /* Flawfinder: ignore */

    s->state.actComp = 0;  // Init computation measure
    pStart  =  s->state.bspStartCode;
    pGn     =  s->state.gobNumber;
    pGob    = &s->state.currentGob;
    pNum_sc = &s->state.nStartCodes;
    pSc     = &s->state.currentStartCode;

    if (s->pic_layer.decodingInProgress) {
        // Restore internal state; we interrupted reconstruction with status=OK
        structStatus = decStatus = OK;
        s->pic_layer.decodingInProgress = FALSE;    // Set only if we time out again

    } else {    // We did not time out last time, so do the usual thing

        s->state.i = 0;     // Tell ReconGob to reset its state

        /* Find Picture and GOB Start Codes */
        *pNum_sc = find_startcodes( &s->bsStart, BsDiff(s->bsEnd, s->bsStart),
                                    pStart, pGn, SC_MAX, (int)s->codingMethod );
        /*{   // Print startcode positions
            int i;
            for (i = 0; i < *pNum_sc; i++) {
                printf("Startcode %d: gn = %d starts in byte %d, bit %d\n", i,
                    pGn[i], pStart[i].byteptr - s->bsStart.byteptr, pStart[i].bitptr);
            }
            printf("Continue? ");
            scanf("%d", &i);
        }*/
        s->status.dwStartcodes = *pNum_sc;
        s->status.dwGobs = 0;       // # GOBs processed
        s->status.dwBadgobs = 0;    // # erroneous GOBs
        s->status.dwUpdateGobs = 0; // # GOBs for fast updating
        s->status.dwFirstBadgob = 0; // First bad Gob
        s->status.dwPsc = FALSE;    // indicates that a picture layer was successfully decoded
        s->newBs = s->bsStart;      // Just in case...  (will be updated later)
        if (*pNum_sc < 2) {
            if (*pNum_sc == 1) {
                outputBsPointer( &pStart[0], &s->newBs, (int)s->codingMethod ); // If we exit, begin here next time
            } else if ((s->bsEnd.byteptr - s->bsStart.byteptr) < 4) {
                // No startcode found and bitstream is less than 4 bytes long
                s->newBs = s->bsStart;
            } else {
                // No startcode found; skip to end of bitstream
                s->newBs = s->bsEnd;
                s->newBs.byteptr -= 4;  // Back up 32 bits (22-bit PSC and one byte margin)
            }
            return( NO );
        }
        *pSc = 0;
        if (s->next_gob == 0) {   // Decode Picture Layer info
            do {
                if (findPSC( pStart, pGn, *pNum_sc, pSc, s ) != YES)   // Find Picture Start Code
                    return( NO );
                // Try to decode Picture Layer
                outputBsPointer( &pStart[*pSc], &bsPSC, (int)s->codingMethod ); // Save possible picture start code pointer
                status = decodePicLayer( &pStart[*pSc], BsDiff(pStart[*pSc + 1], pStart[*pSc]),
                                    &s->pic_layer, s->sym, s->maxSym, (int)s->codingMethod, pGob,
                                    &s->ptype );
                // H.263: pStart[*pSc] gets bumped by decodePicLayer; now pointing to MB layer
                if (status != OK) {
                    ++s->status.dwBadgobs;
                    BS_ERR_MSG( H261ErrMsg( "Bitstream error when decoding Picture Layer" ); )
                } else {    // Decoded Picture Layer successfully
                    savePSCpointer( &bsPSC, s );
                    // Initialize image structures according to received image format: QCIF or CIF
                    status = initializePicture ( s );   
                    if (status != OK)  H261ErrMsg("Decoder: illegal picture format");
                    s->status.dwIntraFrame = 1;  // Assume intraframe (set to zero if we encounter a non-INTRA MacroBlock)
#ifdef ANNOTATE_PICTURE
                    saveOrRestoreReconPicture( &s->oldOut, 1 ); // Restore prev. from local memory
#endif
                    if (s->codingMethod == H263_CODING  &&  status == OK) {
                        s->next_gob = 0;    // First GOB is gn=0 for H.263
                        break;  // Don't increment *pSc; decode GOB 0 first
                    } else if (status == OK) {  // H.261 decoding
                        s->next_gob = 1;    // Go on to decode first GOB (gn=1 for H.261)
                    }
                }
                ++(*pSc);
            } while (status != OK);
        }
    
        // Decode GOBs until we reach next to last startcode or until picture complete
        if (*pSc >= *pNum_sc - 1)  return NO;

        // Decode bitstream for the first GOB
        status = decodeBitstream( s, pGob, &pStart[*pSc], &pGn[*pSc], &structStatus, &decStatus );
        if (status == H261_ERROR)  return NO;   // Exit to resync on next PSC

    }   // end if !s->pic_layer.decodingInProgress

    while (1) {     // Process until next to last startcode
        // Reconstruct GOB
        if (structStatus == OK) {
            // decStatus!=OK means that we found bitstream errors
            if (decStatus == OK) {
                //printf("Calling ReconGob \n");
                ReconGob( pGob, s->mb, &s->oldOut, &s->newOut, &s->B_Out, 
                           s->pic_layer.advancedPred, s->pic_layer.PBframeMode, 
                           s->PBframeCap, s->pic_layer.reducedResUpdate, s->pic_layer.advancedIntraMode,
                           &s->state, s->maxComp );
                // Time to exit?
                if (s->state.i > 0) {   // ReconGob timed out
                    s->pic_layer.decodingInProgress = TRUE;
                    return NO;
                }
				/*// Update macroblock map to control RGB conversion
				// This is not very useful anymore; skipped blocks might change when
				// we use overlapped MC or deblocking filter /SE 4/4/97
                update_decMB( pGob, pGob->mb, (int)(s->newOut.y.nhor >> 4), 
                            (int)s->codingMethod, &s->decMB,
                            &s->status.dwIntraFrame, NO );*/
            } else {    //  Bitstream error
                gobConcealment( s, pGob, s->mb );
            }
            s->status.dwGobs += pGob->num_mb / max(1,pGob->mb_width);
            s->next_gob = pGob->next_gn;
        }
        (*pSc)++;
        outputBsPointer( &pStart[*pSc], &s->newBs, (int)s->codingMethod ); // If we exit, begin here next time
        if (s->next_gob == 0) {    // Completed picture
#ifdef DO_H263_PLUS
            // Perform deblocking filtering
            if(s->pic_layer.reducedResUpdate) {
                ReducedResDeblockingFilter( &s->newOut, s->mb );
            } else if(s->pic_layer.deblockingFilterMode) {
                ApplyDeblockingFilter(&s->newOut, s->mb, FALSE);
                if(s->pic_layer.PBframeMode && s->PBframeCap) 
                    ApplyDeblockingFilter(&s->B_Out, s->mb, TRUE);
            }
#endif
            //checkPicture( s->newOut );  // Very useful when chasing subtle encoder bugs
#ifdef ANNOTATE_PICTURE
            saveOrRestoreReconPicture( &s->newOut, 0 ); // Save new picture to local memory
            annotatePicture( &s->newOut, s->mb );  // Draw motion vectors etc.
            annotatePicture( &s->B_Out, s->mb );
#endif
            return (YES);
        }
        if (*pSc >= *pNum_sc - 1)  return NO;

        // Decode bitstream for the next GOB
        status = decodeBitstream( s, pGob, &pStart[*pSc], &pGn[*pSc],
                                  &structStatus, &decStatus );
        if (status == H261_ERROR)  return NO;   // Exit to resync on next PSC
    }
}


// findPSC - Search for Picture Start Code
static int  findPSC( BS_PTR start[], int gn[], int num_sc, int *sc, H261Decoder *s )
{
    do {
        if (*sc > num_sc - 2) { //  Reached last startcode?
            return (NO);
        }
        (*sc)++;
        outputBsPointer( &start[*sc], &s->newBs, (int)s->codingMethod ); // If we exit, begin here next time
    } while (gn[*sc - 1] != 0); // GN=0 indicates PSC
    *sc = *sc - 1;    // Back up to point at PSC
    return( YES );
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?