videoeditorengine/avcedit/src/sequence.cpp
branchRCL_3
changeset 3 e0b5df5c0969
parent 0 951a5db380a0
child 5 4c409de21d23
equal deleted inserted replaced
0:951a5db380a0 3:e0b5df5c0969
     1 /*
       
     2 * Copyright (c) 2010 Ixonos Plc.
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of the "Eclipse Public License v1.0"
       
     6 * which accompanies this distribution, and is available
       
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Nokia Corporation - Initial contribution
       
    11 *
       
    12 * Contributors:
       
    13 * Ixonos Plc
       
    14 *
       
    15 * Description:
       
    16 *
       
    17 */
       
    18 
       
    19 
       
    20 #include "globals.h"
       
    21 #include "bitbuffer.h"
       
    22 #include "vld.h"
       
    23 #include "framebuffer.h"
       
    24 #include "avcdapi.h"
       
    25 #include "parameterset.h"
       
    26 #include "dpb.h"
       
    27 #include "sequence.h"
       
    28 
       
    29 
       
    30 #define SEQ_OK                      0
       
    31 #define SEQ_ERROR                  -1
       
    32 #define SEQ_ERR_MEM                -2
       
    33 #define SEQ_ERR_GAPS_IN_FRAME_NUM  -3
       
    34 #define SEQ_ERR_DPB_CORRUPTED      -4
       
    35 
       
    36 // Definitions of SEI types
       
    37 #define SEI_TYPE_SCENE_INFO       9
       
    38 
       
    39 
       
    40 #ifdef CHECK_MV_RANGE
       
    41 int maxVerticalMvRange;
       
    42 #endif
       
    43 
       
    44 
       
    45 void GenerateEmptyFrame(sequence_s *seq, bitbuffer_s *bitbuf, TUint aFrameNumber);
       
    46 
       
    47 
       
    48 
       
    49 /*
       
    50  * setLower4Bits:
       
    51  *
       
    52  * Parameters:
       
    53  *      value               the destination to store the 4 bits
       
    54  *      bits                the 4 bits to be copied
       
    55  *
       
    56  * Function:
       
    57  *      Assign the value to the lowest 4 bits
       
    58  *
       
    59  *  Return:
       
    60  *      -
       
    61  */
       
    62 #define setLower4Bits(value, bits) (value) = ((value) & ~0xF) | ((bits))
       
    63 
       
    64 
       
    65 /*
       
    66  *
       
    67  * avcdOpen:
       
    68  *
       
    69  * Parameters:
       
    70  *      -
       
    71  *
       
    72  * Function:
       
    73  *      Open AVC decoder.
       
    74  *      
       
    75  * Returns:
       
    76  *      Pointer to initialized avcdDecoder_t object
       
    77  */
       
    78 avcdDecoder_t *avcdOpen()
       
    79 {
       
    80   sequence_s *seq;
       
    81 
       
    82 
       
    83   // Allocate sequence object
       
    84   if ((seq = (sequence_s *)User::Alloc(sizeof(sequence_s))) == NULL)
       
    85     return NULL;
       
    86 
       
    87   memset(seq, 0, sizeof(sequence_s));
       
    88   
       
    89   // Open bitbuffer
       
    90   if ((seq->bitbuf = bibOpen()) == NULL)
       
    91     return NULL;
       
    92 
       
    93   seq->isFirstSliceOfSeq       = 1;
       
    94   seq->unusedShortTermFrameNum = -1;
       
    95 
       
    96 #ifdef VIDEOEDITORENGINE_AVC_EDITING
       
    97   // Open slices
       
    98   if ((seq->currSlice = sliceOpen()) == NULL)
       
    99     return NULL;
       
   100 
       
   101   if ((seq->nextSlice = sliceOpen()) == NULL)
       
   102     return NULL;
       
   103 
       
   104   // Open dpb
       
   105   if ((seq->dpb = dpbOpen()) == NULL)
       
   106     return NULL;
       
   107 
       
   108 	seq->iFrameNumber = 0;
       
   109 	seq->iFromEncoder = 0;
       
   110 	seq->iEncodeUntilIDR = 0;
       
   111 	seq->iBitShiftInSlice = 0;
       
   112 	seq->iPreviousPPSId = 0;
       
   113 	seq->iNumSPS = 0;
       
   114 	seq->iNumPPS = 0;
       
   115 
       
   116 	seq->iTotalFrameNumber = 0;
       
   117 
       
   118 #endif  // VIDEOEDITORENGINE_AVC_EDITING
       
   119 	
       
   120   return seq;
       
   121 }
       
   122 
       
   123 
       
   124 /*
       
   125  *
       
   126  * avcdClose:
       
   127  *
       
   128  * Parameters:
       
   129  *      seq                   Sequence object
       
   130  *
       
   131  * Function:
       
   132  *      Close sequence.
       
   133  *      
       
   134  * Returns:
       
   135  *      -
       
   136  */
       
   137 void avcdClose(avcdDecoder_t *dec)
       
   138 {
       
   139   sequence_s *seq = (sequence_s *)dec;
       
   140   
       
   141   /* Close bitbuffer */
       
   142   bibClose(seq->bitbuf);
       
   143   
       
   144   /* Close parameter sets */
       
   145   psCloseParametersSets(seq->spsList, seq->ppsList);
       
   146 
       
   147 #ifdef VIDEOEDITORENGINE_AVC_EDITING
       
   148   /* Close current frame */
       
   149   frmClose(seq->recoBuf, seq->mbData);
       
   150 
       
   151   /* Close decoded picture buffer */
       
   152   dpbClose(seq->dpb);
       
   153 
       
   154   /* Close slices */
       
   155   sliceClose(seq->currSlice);
       
   156   sliceClose(seq->nextSlice);
       
   157 
       
   158 #endif  // VIDEOEDITORENGINE_AVC_EDITING
       
   159 
       
   160   User::Free(seq);
       
   161 }
       
   162 
       
   163 
       
   164 /*
       
   165  *
       
   166  * initSPSParsing
       
   167  *
       
   168  * Parameters:
       
   169  *      dec                   Sequence object
       
   170  *      nauUnitBits           Buffer containing SPS NAL unit
       
   171  *      nalUnitLen            Length of buffer
       
   172  *
       
   173  * Function:
       
   174  *      Initialises bit buffer for parsing, checks
       
   175  *      nal_unit_type
       
   176  *      
       
   177  * Returns:
       
   178  *      KErrNone for no error, negative value for error
       
   179  */
       
   180 TInt initSPSParsing(avcdDecoder_t *dec, void *nalUnitBits, TUint* nalUnitLen)
       
   181 {
       
   182     sequence_s *seq = (sequence_s *)dec;
       
   183 
       
   184     TInt nalHeaderByte;
       
   185     TInt nalType;
       
   186     TUint nalUnitLength = *nalUnitLen;
       
   187     
       
   188     // tempData allocation
       
   189     TUint8* tempData = (TUint8*) User::Alloc(nalUnitLength);
       
   190   	
       
   191   	if (!tempData)
       
   192   	    return KErrNoMemory;
       
   193   	
       
   194   	Mem::Copy(tempData, nalUnitBits, nalUnitLength);  	  	
       
   195 
       
   196     if (bibInit(seq->bitbuf, tempData, nalUnitLength) < 0)
       
   197     {
       
   198         User::Free(seq->bitbuf->data);
       
   199         return AVCD_ERROR;
       
   200     }
       
   201     
       
   202     if (bibGetByte(seq->bitbuf, &nalHeaderByte))
       
   203     {
       
   204         User::Free(seq->bitbuf->data);
       
   205         return AVCD_ERROR;
       
   206     }
       
   207     
       
   208     // Decode NAL unit type
       
   209     nalType   = nalHeaderByte & 0x1F;    
       
   210     
       
   211     if (nalType != NAL_TYPE_SPS)
       
   212     {
       
   213         User::Free(seq->bitbuf->data);
       
   214         return AVCD_ERROR;
       
   215     }
       
   216     
       
   217     return KErrNone;
       
   218 }
       
   219 
       
   220 /*
       
   221  *
       
   222  * avcdParseLevel
       
   223  *
       
   224  * Parameters:
       
   225  *      dec                   Sequence object
       
   226  *      nauUnitBits           Buffer containing SPS NAL unit
       
   227  *      nalUnitLen            Length of buffer
       
   228  *      aLevel                [output]Parsed level
       
   229  *
       
   230  * Function:
       
   231  *      Parses AVC level from SPS
       
   232  *      
       
   233  * Returns:
       
   234  *      KErrNone for no error, negative value for error
       
   235  */
       
   236 TInt avcdParseLevel(avcdDecoder_t *dec, void *nalUnitBits, TUint* nalUnitLen, TInt& aLevel)                    
       
   237 {
       
   238 
       
   239     TInt error = initSPSParsing(dec, nalUnitBits, nalUnitLen);
       
   240     
       
   241     if (error < 0)
       
   242     	return AVCD_ERROR;
       
   243 
       
   244     sequence_s *seq = (sequence_s *)dec;
       
   245 
       
   246     error = psParseLevelFromSPS(seq->bitbuf, aLevel);
       
   247 
       
   248     User::Free(seq->bitbuf->data);
       
   249     
       
   250     if (error < 0)
       
   251     	return AVCD_ERROR;
       
   252     
       
   253     return KErrNone;    	    
       
   254 
       
   255 }
       
   256 
       
   257 /*
       
   258  *
       
   259  * avcdParseResolution
       
   260  *
       
   261  * Parameters:
       
   262  *      dec                   Sequence object
       
   263  *      nauUnitBits           Buffer containing SPS NAL unit
       
   264  *      nalUnitLen            Length of buffer
       
   265  *      aResolution           [output]Parsed resolution
       
   266  *
       
   267  * Function:
       
   268  *      Parses resolution from SPS
       
   269  *      
       
   270  * Returns:
       
   271  *      KErrNone for no error, negative value for error
       
   272  */
       
   273 TInt avcdParseResolution(avcdDecoder_t *dec, void *nalUnitBits, TUint* nalUnitLen, 
       
   274                          TInt& aWidth, TInt& aHeight)
       
   275 {
       
   276 
       
   277     TInt error = initSPSParsing(dec, nalUnitBits, nalUnitLen);
       
   278     
       
   279     if (error < 0)
       
   280     	return AVCD_ERROR;
       
   281 
       
   282     sequence_s *seq = (sequence_s *)dec;
       
   283 
       
   284     error = psDecodeSPS(seq->bitbuf, seq->spsList, aWidth, aHeight);
       
   285 
       
   286     User::Free(seq->bitbuf->data);
       
   287     
       
   288     if (error < 0)
       
   289     	return AVCD_ERROR;
       
   290     
       
   291     return KErrNone;    	    
       
   292     
       
   293 }
       
   294 
       
   295 
       
   296 
       
   297 #ifdef VIDEOEDITORENGINE_AVC_EDITING
       
   298 
       
   299 /*
       
   300  *
       
   301  * slidingWindowDecRefPicMarking:
       
   302  *
       
   303  * Parameters:
       
   304  *      seq                   Sequence object
       
   305  *
       
   306  * Function:
       
   307  *      Sliding window decoded reference picture marking. Reference pictures
       
   308  *      in dpb are marked based on first in first out principle.
       
   309  *      
       
   310  * Returns:
       
   311  *      SEQ_OK for no error, negative value for error
       
   312  */
       
   313 static int slidingWindowDecRefPicMarking(sequence_s *seq)
       
   314 {
       
   315   dpb_s *dpb;
       
   316   int numRefPics;
       
   317 
       
   318   dpb = seq->dpb;
       
   319 
       
   320   numRefPics = dpb->numShortTermPics + dpb->numLongTermPics;
       
   321 
       
   322   /* If dpb contains maximum number of reference pitures allowed, short */
       
   323   /*  term reference picture with lowest picture number is removed.     */
       
   324   if (numRefPics == dpb->maxNumRefFrames) {
       
   325     if (dpb->numShortTermPics == 0) {
       
   326       PRINT((_L("numShortTerm must be greater than zero\n")));
       
   327       return SEQ_ERR_DPB_CORRUPTED;
       
   328     }
       
   329 
       
   330     dpbMarkLowestShortTermPicAsNonRef(dpb);
       
   331   }
       
   332 
       
   333   return SEQ_OK;
       
   334 }
       
   335 
       
   336 
       
   337 /*
       
   338  *
       
   339  * adaptiveDecRefPicMarking:
       
   340  *
       
   341  * Parameters:
       
   342  *      seq                   Sequence object
       
   343  *
       
   344  * Function:
       
   345  *      Adaptive decoded reference picture marking. Reference pictures in dpb
       
   346  *      are marked based on memory management command operations that were
       
   347  *      decoded in slice header earlier.
       
   348  *      
       
   349  * Returns:
       
   350  *      SEQ_OK for no error, SEQ_ERR_DPB_CORRUPTED for error in DPB
       
   351  */
       
   352 static int adaptiveDecRefPicMarking(sequence_s *seq)
       
   353 {
       
   354   dpb_s *dpb;
       
   355   sliceMMCO_s *mmcoCmdList;
       
   356   int32 currPicNum, picNumX;
       
   357   int i;
       
   358 
       
   359   dpb = seq->dpb;
       
   360   currPicNum = seq->currSlice->frame_num;
       
   361   mmcoCmdList = seq->currSlice->mmcoCmdList;
       
   362 
       
   363   i = 0;
       
   364   do {
       
   365     switch (mmcoCmdList[i].memory_management_control_operation) {
       
   366       case 1:
       
   367         picNumX = currPicNum - (mmcoCmdList[i].difference_of_pic_nums_minus1 + 1);
       
   368         if (dpbMarkShortTermPicAsNonRef(dpb, picNumX) < 0)
       
   369           return SEQ_ERR_DPB_CORRUPTED;
       
   370         break;
       
   371       case 2:
       
   372         if (dpbMarkLongTermPicAsNonRef(dpb, mmcoCmdList[i].long_term_pic_num) < 0)
       
   373           return SEQ_ERR_DPB_CORRUPTED;
       
   374         break;
       
   375       case 3:
       
   376         picNumX = currPicNum - (mmcoCmdList[i].difference_of_pic_nums_minus1 + 1);
       
   377         if (dpbMarkShortTermPicAsLongTerm(dpb, picNumX, mmcoCmdList[i].long_term_frame_idx) < 0)
       
   378           return SEQ_ERR_DPB_CORRUPTED;
       
   379         break;
       
   380       case 4:
       
   381         dpbSetMaxLongTermFrameIdx(dpb, mmcoCmdList[i].max_long_term_frame_idx_plus1);
       
   382         break;
       
   383       case 5:
       
   384         dpbMarkAllPicsAsNonRef(dpb);
       
   385         dpb->maxLongTermFrameIdx = -1;
       
   386         break;
       
   387       case 6:
       
   388         /* To avoid duplicate of longTermFrmIdx */
       
   389         dpbVerifyLongTermFrmIdx(dpb, mmcoCmdList[i].long_term_frame_idx);
       
   390 
       
   391         seq->recoBuf->refType        = FRM_LONG_TERM_PIC;
       
   392         seq->recoBuf->longTermFrmIdx = mmcoCmdList[i].long_term_frame_idx;
       
   393         break;
       
   394     }
       
   395     i++;
       
   396   } while (mmcoCmdList[i].memory_management_control_operation != 0 && i < MAX_NUM_OF_MMCO_OPS);
       
   397 
       
   398   return SEQ_OK;
       
   399 }
       
   400 
       
   401 
       
   402 /*
       
   403  *
       
   404  * decRefPicMarking:
       
   405  *
       
   406  * Parameters:
       
   407  *      seq                   Sequence object
       
   408  *
       
   409  * Function:
       
   410  *      Decoded reference picture marking. Reference pictures in dpb are marked
       
   411  *      differently depending on whether current picture is IDR picture or not
       
   412  *      and whether it is reference picture or non-reference picture.
       
   413  *      If current picture is non-IDR reference picture, reference pictures are
       
   414  *      marked with either sliding window marking process or adaptive marking
       
   415  *      process depending on the adaptiveRefPicMarkingModeFlag flag.
       
   416  *      
       
   417  * Returns:
       
   418  *      -
       
   419  */
       
   420 static int decRefPicMarking(sequence_s *seq)
       
   421 {
       
   422   slice_s *slice;
       
   423   frmBuf_s *recoBuf;
       
   424 
       
   425   slice = seq->currSlice;
       
   426   recoBuf = seq->recoBuf;
       
   427 
       
   428   recoBuf->refType  = FRM_SHORT_TERM_PIC;
       
   429   recoBuf->frameNum = slice->frame_num;
       
   430   recoBuf->hasMMCO5 = slice->picHasMMCO5;
       
   431   recoBuf->isIDR    = slice->isIDR;
       
   432 
       
   433   if (slice->isIDR) {
       
   434     recoBuf->idrPicID = slice->idr_pic_id;
       
   435 
       
   436     /* All reference frames are marked as non-reference frames */
       
   437     dpbMarkAllPicsAsNonRef(seq->dpb);
       
   438 
       
   439     /* Set reference type for current picture */
       
   440     if (!slice->long_term_reference_flag) {
       
   441       seq->dpb->maxLongTermFrameIdx = -1;
       
   442     }
       
   443     else {
       
   444       recoBuf->refType         = FRM_LONG_TERM_PIC;
       
   445       recoBuf->longTermFrmIdx  = 0;
       
   446       seq->dpb->maxLongTermFrameIdx = 0;
       
   447     }
       
   448   }
       
   449   else if (slice->nalRefIdc != 0) {
       
   450     if (!slice->adaptive_ref_pic_marking_mode_flag)
       
   451       return slidingWindowDecRefPicMarking(seq);
       
   452     else
       
   453       return adaptiveDecRefPicMarking(seq);
       
   454   }
       
   455   else
       
   456     recoBuf->refType  = FRM_NON_REF_PIC;
       
   457 
       
   458   return SEQ_OK;
       
   459 } 
       
   460 
       
   461 
       
   462 /*
       
   463  *
       
   464  * buildSliceGroups:
       
   465  *
       
   466  * Parameters:
       
   467  *      seq                   Sequence object
       
   468  *      slice                 Slice object
       
   469  *      sps                   Sequence parameter set
       
   470  *      pps                   Picture parameter set
       
   471  *
       
   472  * Function:
       
   473  *      Build slice group map. Syntax elements for slice groups are
       
   474  *      in active picture parameter set.
       
   475  *      
       
   476  * Returns:
       
   477  *      -
       
   478  *
       
   479  */
       
   480 static void buildSliceGroups(sequence_s* seq, slice_s *slice,
       
   481                              seq_parameter_set_s *sps, pic_parameter_set_s *pps)
       
   482 {
       
   483   int xTopLeft, yTopLeft;
       
   484   int xBottomRight, yBottomRight;
       
   485   int x, y;
       
   486   int leftBound, topBound;
       
   487   int rightBound, bottomBound;
       
   488   int xDir, yDir;
       
   489   int mapUnitsInSliceGroup0;
       
   490   int mapUnitVacant;
       
   491   int sizeOfUpperLeftGroup;
       
   492   int iGroup, picSizeInMapUnits;
       
   493   int picWidthInMbs, picHeightInMapUnits;
       
   494   int i, j, k;
       
   495   int *sliceMap;
       
   496 
       
   497   sliceMap = seq->mbData->sliceMap;
       
   498 
       
   499   picWidthInMbs = sps->pic_width_in_mbs_minus1+1;
       
   500   picHeightInMapUnits = sps->pic_height_in_map_units_minus1+1;
       
   501 
       
   502   picSizeInMapUnits = picWidthInMbs * picHeightInMapUnits;
       
   503 
       
   504   if (pps->num_slice_groups_minus1 == 0) {
       
   505     /* Only one slice group */
       
   506     for (i = 0; i < picSizeInMapUnits; i++)
       
   507       sliceMap[i] = 0;
       
   508   }
       
   509   else {
       
   510     /* There are more than one slice groups in this picture */
       
   511 
       
   512     switch (pps->slice_group_map_type) {
       
   513 
       
   514     case PS_SLICE_GROUP_MAP_TYPE_INTERLEAVED:
       
   515       i = 0;
       
   516       do {
       
   517         for (iGroup = 0; iGroup <= (int)pps->num_slice_groups_minus1 && i < picSizeInMapUnits;
       
   518           i += pps->run_length_minus1[iGroup++] + 1)
       
   519         {
       
   520           for (j = 0; j <= (int)pps->run_length_minus1[iGroup] && i+j < picSizeInMapUnits; j++)
       
   521             sliceMap[i+j] = iGroup;   /* Only the group number */
       
   522         }
       
   523       } while (i < picSizeInMapUnits);
       
   524       break;
       
   525 
       
   526     case PS_SLICE_GROUP_MAP_TYPE_DISPERSED:
       
   527       for ( i = 0; i < picSizeInMapUnits; i++ )
       
   528         sliceMap[i] = ( ( i % picWidthInMbs ) + 
       
   529         ( ( ( i / picWidthInMbs ) * ( pps->num_slice_groups_minus1 + 1 ) ) / 2 ) )
       
   530         % ( pps->num_slice_groups_minus1 + 1 );
       
   531       break;
       
   532 
       
   533     case PS_SLICE_GROUP_MAP_TYPE_FOREGROUND:
       
   534       for (i = 0; i < picSizeInMapUnits; i++)
       
   535         setLower4Bits(sliceMap[i], pps->num_slice_groups_minus1);
       
   536       for (iGroup = pps->num_slice_groups_minus1 - 1; iGroup >= 0; iGroup--) {
       
   537         yTopLeft = pps->top_left[iGroup] / picWidthInMbs;
       
   538         xTopLeft = pps->top_left[iGroup] % picWidthInMbs;
       
   539         yBottomRight = pps->bottom_right[iGroup] / picWidthInMbs;
       
   540         xBottomRight = pps->bottom_right[iGroup] % picWidthInMbs;
       
   541         for (y = yTopLeft; y <= yBottomRight; y++)
       
   542           for (x = xTopLeft; x <= xBottomRight; x++)
       
   543             sliceMap[y * picWidthInMbs + x] = iGroup;
       
   544       }
       
   545       break;
       
   546 
       
   547     case PS_SLICE_GROUP_MAP_TYPE_CHANGING_3:
       
   548       /* mapUnitsInSliceGroup0 */
       
   549       mapUnitsInSliceGroup0 =	min((int)(slice->slice_group_change_cycle * (pps->slice_group_change_rate_minus1+1)), picSizeInMapUnits);
       
   550 
       
   551       for (i = 0; i < picSizeInMapUnits; i++)
       
   552         sliceMap[i] = 1; // mapUnitToSliceGroupMap[ i ] = 1;
       
   553 
       
   554       x = (picWidthInMbs - pps->slice_group_change_direction_flag) / 2;
       
   555       y = (picHeightInMapUnits - pps->slice_group_change_direction_flag ) / 2;
       
   556       // ( leftBound, topBound ) = ( x, y )
       
   557       leftBound = x; 
       
   558       topBound = y;
       
   559       // ( rightBound, bottomBound ) = ( x, y )
       
   560       rightBound = x; 
       
   561       bottomBound = y;
       
   562       // ( xDir, yDir ) = ( slice_group_change_direction_flag - 1, slice_group_change_direction_flag )
       
   563       xDir = pps->slice_group_change_direction_flag - 1;
       
   564       yDir = pps->slice_group_change_direction_flag;
       
   565       for (i = 0; i < mapUnitsInSliceGroup0; i += mapUnitVacant) {
       
   566         mapUnitVacant = ( (sliceMap[y * picWidthInMbs + x] & 0xF) == 1);
       
   567         if (mapUnitVacant)
       
   568           setLower4Bits(sliceMap[y * picWidthInMbs + x], 0);
       
   569         if (xDir == -1 && x == leftBound) {
       
   570           leftBound = max(leftBound - 1, 0);
       
   571           x = leftBound;
       
   572           //( xDir, yDir ) = ( 0, 2 * slice_group_change_direction_flag - 1 )
       
   573           xDir = 0;
       
   574           yDir = 2 * pps->slice_group_change_direction_flag - 1;
       
   575         } 
       
   576         else if (xDir == 1 && x == rightBound) {
       
   577           rightBound = min(rightBound + 1, picWidthInMbs - 1);
       
   578           x = rightBound;
       
   579           //( xDir, yDir ) = ( 0, 1 - 2 * slice_group_change_direction_flag )
       
   580           xDir = 0;
       
   581           yDir = 1 - 2 * pps->slice_group_change_direction_flag;
       
   582         } 
       
   583         else if (yDir == -1 && y == topBound) {
       
   584           topBound = max(topBound - 1, 0);
       
   585           y = topBound;
       
   586           //( xDir, yDir ) = ( 1 - 2 * slice_group_change_direction_flag, 0 )
       
   587           xDir = 1 - 2 * pps->slice_group_change_direction_flag;
       
   588           yDir = 0;
       
   589         } 
       
   590         else if (yDir == 1 && y == bottomBound) {
       
   591           bottomBound = min(bottomBound + 1, picHeightInMapUnits - 1);
       
   592           y = bottomBound;
       
   593           //( xDir, yDir ) = ( 2 * slice_group_change_direction_flag - 1, 0 )
       
   594           xDir = 2 * pps->slice_group_change_direction_flag - 1;
       
   595           yDir = 0;
       
   596         } 
       
   597         else {
       
   598           //( x, y ) = ( x + xDir, y + yDir )
       
   599           x = x + xDir;
       
   600           y = y + yDir;
       
   601         }
       
   602       }
       
   603       break;
       
   604 
       
   605     case PS_SLICE_GROUP_MAP_TYPE_CHANGING_4:
       
   606       /* mapUnitsInSliceGroup0 */
       
   607       mapUnitsInSliceGroup0 =	min((int)(slice->slice_group_change_cycle * (pps->slice_group_change_rate_minus1+1)), picSizeInMapUnits);
       
   608 
       
   609       sizeOfUpperLeftGroup = ( pps->slice_group_change_direction_flag ? 
       
   610 			                        ( picSizeInMapUnits - mapUnitsInSliceGroup0 ) : mapUnitsInSliceGroup0 );
       
   611 
       
   612       for( i = 0; i < picSizeInMapUnits; i++ )
       
   613         if( i < sizeOfUpperLeftGroup )
       
   614           sliceMap[ i ] = pps->slice_group_change_direction_flag;
       
   615         else
       
   616           sliceMap[ i ] = 1 - pps->slice_group_change_direction_flag;
       
   617       break;
       
   618 
       
   619     case PS_SLICE_GROUP_MAP_TYPE_CHANGING_5:
       
   620       /* mapUnitsInSliceGroup0 */
       
   621       mapUnitsInSliceGroup0 =	min((int)(slice->slice_group_change_cycle * (pps->slice_group_change_rate_minus1+1)), picSizeInMapUnits);
       
   622 
       
   623       sizeOfUpperLeftGroup = ( pps->slice_group_change_direction_flag ? 
       
   624 			                        ( picSizeInMapUnits - mapUnitsInSliceGroup0 ) : mapUnitsInSliceGroup0 );
       
   625 
       
   626       k = 0;
       
   627       for( j = 0; j < picWidthInMbs; j++ )
       
   628         for( i = 0; i < picHeightInMapUnits; i++ )
       
   629           if( k++ < sizeOfUpperLeftGroup )
       
   630             sliceMap[ i * picWidthInMbs + j ] = pps->slice_group_change_direction_flag;
       
   631           else
       
   632             sliceMap[ i * picWidthInMbs + j ] = 1 - pps->slice_group_change_direction_flag;
       
   633       break;
       
   634 
       
   635     case PS_SLICE_GROUP_MAP_TYPE_EXPLICIT:
       
   636       for (i = 0; i < picSizeInMapUnits; i++)
       
   637         sliceMap[i] = pps->slice_group_id[i];
       
   638       break;
       
   639 
       
   640     default:
       
   641       break;
       
   642     }
       
   643   }
       
   644 
       
   645 }
       
   646 
       
   647 
       
   648 /*
       
   649  *
       
   650  * isPicBoundary:
       
   651  *
       
   652  * Parameters:
       
   653  *      seq                   Sequence object
       
   654  *
       
   655  * Function:
       
   656  *      Check if current slice and next slice belong to different pictures.
       
   657  *      
       
   658  * Returns:
       
   659  *      1: slices belong to different pictures (picture boundary detected)
       
   660  *      0: slices belong to the same picture
       
   661  *
       
   662  */
       
   663 static int isPicBoundary(sequence_s *seq)
       
   664 {
       
   665   slice_s *currSlice, *nextSlice;
       
   666   seq_parameter_set_s *prevSps, *currSps;
       
   667 
       
   668   currSlice = seq->currSlice;
       
   669   nextSlice = seq->nextSlice;
       
   670 
       
   671   /* frame_num differs in value. */
       
   672   if (currSlice->frame_num != nextSlice->frame_num)
       
   673     return 1;
       
   674 
       
   675   /* nal_ref_idc differs in value with one of the nal_ref_idc values being equal to 0. */
       
   676   if ((currSlice->nalRefIdc != nextSlice->nalRefIdc) &&
       
   677       (currSlice->nalRefIdc == 0 || nextSlice->nalRefIdc == 0))
       
   678     return 1;
       
   679 
       
   680   /* nal_unit_type is equal to 5 for one coded slice NAL unit and */
       
   681   /* is not equal to 5 in the other coded slice NAL unit */
       
   682   if ((currSlice->nalType == NAL_TYPE_CODED_SLICE_IDR || nextSlice->nalType == NAL_TYPE_CODED_SLICE_IDR) &&
       
   683       (currSlice->nalType != nextSlice->nalType))
       
   684     return 1;
       
   685 
       
   686   /* nal_unit_type is equal to 5 for both and idr_pic_id differs in value. */
       
   687   if (currSlice->nalType == NAL_TYPE_CODED_SLICE_IDR &&
       
   688       nextSlice->nalType == NAL_TYPE_CODED_SLICE_IDR &&
       
   689       (currSlice->idr_pic_id != nextSlice->idr_pic_id))
       
   690     return 1;
       
   691 
       
   692   prevSps = seq->spsList[seq->ppsList[currSlice->pic_parameter_set_id]->seq_parameter_set_id];
       
   693   currSps = seq->spsList[seq->ppsList[nextSlice->pic_parameter_set_id]->seq_parameter_set_id];
       
   694 
       
   695   /* pic_order_cnt_type is equal to 0 for both and */
       
   696   /* either pic_order_cnt_lsb differs in value, or delta_pic_order_cnt_bottom differs in value. */
       
   697   if ((prevSps->pic_order_cnt_type == 0 && currSps->pic_order_cnt_type == 0) &&
       
   698     ((currSlice->pic_order_cnt_lsb != nextSlice->pic_order_cnt_lsb) ||
       
   699     (currSlice->delta_pic_order_cnt_bottom != nextSlice->delta_pic_order_cnt_bottom)))
       
   700     return 1;
       
   701 
       
   702   /* pic_order_cnt_type is equal to 1 for both and */
       
   703   /* either delta_pic_order_cnt[ 0 ] differs in value, or delta_pic_order_cnt[ 1 ] differs in value. */
       
   704   if ((prevSps->pic_order_cnt_type == 1 && currSps->pic_order_cnt_type == 1) &&
       
   705       ((currSlice->delta_pic_order_cnt_0 != nextSlice->delta_pic_order_cnt_0) ||
       
   706        (currSlice->delta_pic_order_cnt_1 != nextSlice->delta_pic_order_cnt_1)))
       
   707     return 1;
       
   708 
       
   709   return 0;
       
   710 }
       
   711 
       
   712 
       
   713 /*
       
   714  *
       
   715  * decodePictureOrderCount:
       
   716  *
       
   717  * Parameters:
       
   718  *      seq                   Sequence object
       
   719  *      slice                 Slice object
       
   720  *      sps                   Sequence parameter set
       
   721  *
       
   722  * Function:
       
   723  *      Decode picture order count using syntax elements in slice object.
       
   724  *      
       
   725  * Returns:
       
   726  *      poc
       
   727  *
       
   728  */
       
   729 static int decodePictureOrderCount(sequence_s* seq, slice_s *slice,
       
   730                                    seq_parameter_set_s *sps)
       
   731 {
       
   732   int i;
       
   733   int32 maxPocLsb;
       
   734   int32 expectedPicOrderCnt, picOrderCntCycleCnt = 0;
       
   735   int32 expectedDeltaPerPicOrderCntCycle, frameNumInPicOrderCntCycle = 0, absFrameNum;
       
   736   int32 tempPicOrderCnt;
       
   737   int32 poc = 0;
       
   738 
       
   739   /* POC */
       
   740   if (sps->pic_order_cnt_type == 0) {
       
   741     /* Reset prevPocMsb, prevPocLsb if needed */
       
   742     if (slice->isIDR || seq->prevPicHasMMCO5) {
       
   743       seq->prevPocMsb = seq->prevPocLsb = 0;
       
   744     }
       
   745     /* PicOrderCntMsb is derived: */
       
   746     maxPocLsb = (u_int32)1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4);
       
   747     if ( (int32)slice->pic_order_cnt_lsb < seq->prevPocLsb &&  (seq->prevPocLsb - (int32)slice->pic_order_cnt_lsb ) >= (maxPocLsb / 2) )
       
   748       seq->pocMsb = seq->prevPocMsb + maxPocLsb;
       
   749     else if ( (int32)slice->pic_order_cnt_lsb > seq->prevPocLsb && ((int32)slice->pic_order_cnt_lsb - seq->prevPocLsb) > (maxPocLsb / 2) )
       
   750       seq->pocMsb = seq->prevPocMsb - maxPocLsb;
       
   751     else
       
   752       seq->pocMsb = seq->prevPocMsb;
       
   753     /* poc */
       
   754     poc = seq->pocMsb + slice->pic_order_cnt_lsb;
       
   755   }
       
   756 
       
   757   else if (sps->pic_order_cnt_type == 1) {
       
   758     /* Reset prevFrameNumOffset if needed */
       
   759     if (!slice->isIDR && seq->prevPicHasMMCO5)  /* : prevPicHasMMCO5 has not been tested. */
       
   760       seq->prevFrameNumOffset = 0;
       
   761 
       
   762     /* frameNumOffset is derived as follows: */
       
   763     if (slice->isIDR)
       
   764       seq->frameNumOffset = 0;
       
   765     else if (seq->prevFrameNum > (int32)slice->frame_num)
       
   766       seq->frameNumOffset = seq->prevFrameNumOffset + slice->maxFrameNum;
       
   767     else
       
   768       seq->frameNumOffset = seq->prevFrameNumOffset;
       
   769 
       
   770     /* absFrameNum is derived as follows: */
       
   771     if (sps->num_ref_frames_in_pic_order_cnt_cycle != 0)
       
   772       absFrameNum = seq->frameNumOffset + slice->frame_num;
       
   773     else
       
   774       absFrameNum = 0;
       
   775     if (slice->nalRefIdc == 0 && absFrameNum > 0)
       
   776       absFrameNum = absFrameNum - 1;
       
   777 
       
   778     /* When absFrameNum > 0, picOrderCntCycleCnt and frameNumInPicOrderCntCycle are derived as follows */
       
   779     if (absFrameNum > 0) {
       
   780       picOrderCntCycleCnt = (absFrameNum - 1) / sps->num_ref_frames_in_pic_order_cnt_cycle;
       
   781       frameNumInPicOrderCntCycle = (absFrameNum - 1) % sps->num_ref_frames_in_pic_order_cnt_cycle;
       
   782     }
       
   783 
       
   784     /* expectedDeltaPerPicOrderCntCycle */
       
   785     expectedDeltaPerPicOrderCntCycle = 0;
       
   786     for (i = 0; i < (int)sps->num_ref_frames_in_pic_order_cnt_cycle; i++)
       
   787       expectedDeltaPerPicOrderCntCycle += sps->offset_for_ref_frame[i];
       
   788 
       
   789     /* expectedPicOrderCnt */
       
   790     if (absFrameNum > 0) {
       
   791       expectedPicOrderCnt = picOrderCntCycleCnt * expectedDeltaPerPicOrderCntCycle;
       
   792       for (i = 0; i <= frameNumInPicOrderCntCycle; i++)
       
   793         expectedPicOrderCnt = expectedPicOrderCnt + sps->offset_for_ref_frame[i];
       
   794     }
       
   795     else
       
   796       expectedPicOrderCnt = 0;
       
   797     if (slice->nalRefIdc == 0)
       
   798       expectedPicOrderCnt = expectedPicOrderCnt + sps->offset_for_non_ref_pic;
       
   799 
       
   800     /* poc */
       
   801     poc = expectedPicOrderCnt + slice->delta_pic_order_cnt_0;
       
   802   }
       
   803 
       
   804   else if (sps->pic_order_cnt_type == 2) {
       
   805     /* prevFrameNumOffset is derived as follows */
       
   806     if (!slice->isIDR && seq->prevPicHasMMCO5)
       
   807       seq->prevFrameNumOffset = 0;
       
   808 
       
   809     /* FrameNumOffset is derived as follows. */
       
   810     if (slice->isIDR)
       
   811       seq->frameNumOffset = 0;
       
   812     else if (seq->prevFrameNum > (int32)slice->frame_num)
       
   813       seq->frameNumOffset = seq->prevFrameNumOffset + slice->maxFrameNum;
       
   814     else
       
   815       seq->frameNumOffset = seq->prevFrameNumOffset;
       
   816 
       
   817     /* tempPicOrderCnt is derived as follows */
       
   818     if (slice->isIDR)
       
   819       tempPicOrderCnt = 0;
       
   820     else if (slice->nalRefIdc == 0)
       
   821       tempPicOrderCnt = 2 * (seq->frameNumOffset + slice->frame_num) - 1;
       
   822     else
       
   823       tempPicOrderCnt = 2 * (seq->frameNumOffset + slice->frame_num);
       
   824 
       
   825     /* poc */
       
   826     poc = tempPicOrderCnt;
       
   827   }
       
   828 
       
   829   return poc;
       
   830 }
       
   831 
       
   832 
       
   833 /*
       
   834  *
       
   835  * getOutputPic:
       
   836  *
       
   837  * Parameters:
       
   838  *      seq                   Sequence object
       
   839  *
       
   840  * Function:
       
   841  *      Get one output picture. Pictures are output from output queue and
       
   842  *      if queue is empty pictures are ouput from dpb. Ouput from dpb can only
       
   843  *      happen if sequence is finished (i.e there are not more bits to decode).
       
   844  *
       
   845  * Returns:
       
   846  *      1: output picture is available
       
   847  *      0: output picture is not available
       
   848  */
       
   849 static int getOutputPic(sequence_s *seq)
       
   850 {
       
   851   frmBuf_s *srcBuf;
       
   852   seq_parameter_set_s *sps;
       
   853 
       
   854   /* If no slices have been decoded, there are no pictures available */
       
   855   if (seq->isFirstSliceOfSeq)
       
   856     return 0;
       
   857 
       
   858   /* Check if there are pictures in output queue */
       
   859   if (seq->numQueuedOutputPics == 0) 
       
   860   {
       
   861 
       
   862     /* Get active sequence parameter set */
       
   863     sps = seq->spsList[seq->ppsList[seq->currSlice->pic_parameter_set_id]->seq_parameter_set_id];
       
   864 
       
   865     /*
       
   866      * There are no queued pictures, but we can still output a picture if
       
   867      * at least one of the following conditions is true:
       
   868      * - we have decoded all NAL units
       
   869      * - num_reorder_frames in VUI parameters is zero
       
   870      * - POC type is 2
       
   871      */
       
   872     if (seq->isSeqFinished ||
       
   873         sps->vui_parameters.num_reorder_frames == 0 ||
       
   874         sps->pic_order_cnt_type == 2)
       
   875     {
       
   876       int dummy;
       
   877 
       
   878       /* Check if there are pictures in dpb */
       
   879       srcBuf = dpbGetNextOutputPic(seq->dpb, &dummy);
       
   880       if (!srcBuf)
       
   881         return 0;   /* There were no pictures to output */
       
   882     }
       
   883     else
       
   884       return 0;   /* None of the conditions were true */
       
   885   }
       
   886   else 
       
   887   {
       
   888     /* Take next picture from queue. */
       
   889     srcBuf = seq->outputQueue[seq->outputQueuePos];
       
   890 
       
   891     seq->numQueuedOutputPics--;
       
   892     if (seq->numQueuedOutputPics == 0)
       
   893       seq->outputQueuePos = 0;
       
   894     else
       
   895       seq->outputQueuePos++;
       
   896   }
       
   897 
       
   898   srcBuf->forOutput          = 0;
       
   899 
       
   900   return 1;
       
   901 }
       
   902 
       
   903 
       
   904 /*
       
   905  *
       
   906  * finishCurrentPic:
       
   907  *
       
   908  * Parameters:
       
   909  *      seq                   Sequence object
       
   910  *
       
   911  * Function:
       
   912  *      Finish decoding of current picture. Call loopfilter for the picture
       
   913  *      and try to store picture in dpb. Function also updates variables
       
   914  *      for previous decoded frame and previous decoded reference frame.
       
   915  *
       
   916  * Returns:
       
   917  *       0 : no frames were output
       
   918  *      >0 : the number of frames output
       
   919  *      <0 : error
       
   920  */
       
   921 static int finishCurrentPic(sequence_s *seq)
       
   922 {
       
   923   slice_s *slice;
       
   924   frmBuf_s *currPic;
       
   925   int numOutput;
       
   926   int retVal;
       
   927 
       
   928   slice   = seq->currSlice;
       
   929   currPic = seq->recoBuf;
       
   930 
       
   931   if ((retVal = decRefPicMarking(seq)) < 0)
       
   932     return retVal;
       
   933 
       
   934   /* After the decoding of the current picture and the processing of the     */
       
   935   /* memory management control operations a picture including                */
       
   936   /* a memory_management_control_operation equal to 5 shall be inferred      */
       
   937   /* to have had frame_num equal to 0 for all subsequent use in the decoding */
       
   938   /* process.                                                                */
       
   939   if (slice->picHasMMCO5)
       
   940     currPic->frameNum = slice->frame_num = 0;
       
   941 
       
   942   /* Try to store current picture to dpb */
       
   943   numOutput = dpbStorePicture(seq->dpb, currPic, seq->outputQueue);
       
   944   /* If numOutput != 0, picture was not stored */
       
   945 
       
   946   if (numOutput != 0) 
       
   947   {
       
   948 
       
   949     /* numOutput != 0 implies that pictures were output from dpb */
       
   950     seq->outputQueuePos      = 0;
       
   951     seq->numQueuedOutputPics = numOutput;
       
   952 
       
   953     /* Picture was not stored so we have to store it later */
       
   954     seq->isDpbStorePending   = 1;
       
   955   }
       
   956   else
       
   957     seq->isDpbStorePending = 0;
       
   958 
       
   959   seq->prevFrameNum       = slice->frame_num;
       
   960   seq->prevFrameNumOffset = seq->frameNumOffset;
       
   961 
       
   962   seq->prevPicHasMMCO5 = slice->picHasMMCO5;
       
   963 
       
   964   /* prevRefFrameNum, prevPocLsb and prevPocMsb for latest reference picture */
       
   965   if (slice->nalRefIdc != 0) 
       
   966   {
       
   967     seq->prevRefFrameNum = slice->frame_num;
       
   968     seq->prevPocLsb      = slice->pic_order_cnt_lsb;
       
   969     seq->prevPocMsb      = seq->pocMsb;
       
   970   }
       
   971 
       
   972   seq->isCurrPicFinished = 1;
       
   973 
       
   974   return numOutput;
       
   975 }
       
   976 
       
   977 
       
   978 /*
       
   979  *
       
   980  * generateNonExistingFrames:
       
   981  *
       
   982  * Parameters:
       
   983  *      seq                   Sequence object
       
   984  *
       
   985  * Function:
       
   986  *      Generate non-existing frame for each unused frame number between
       
   987  *      two closest existing frames in decoding order. Generated frames
       
   988  *      are stored to dpb in finishCurrentPic function.
       
   989  *
       
   990  * Returns:
       
   991  *       0 : no frames were output
       
   992  *      >0 : the number of frames output
       
   993  *      <0 : error
       
   994  */
       
   995 static int generateNonExistingFrames(sequence_s *seq)
       
   996 {
       
   997   slice_s *slice;
       
   998   frmBuf_s *currPic;
       
   999   int32 nextFrameNum;
       
  1000   int numOutput;
       
  1001 
       
  1002   slice   = seq->currSlice;
       
  1003   currPic = seq->recoBuf;
       
  1004 
       
  1005   slice->picHasMMCO5                        = 0;
       
  1006   slice->isIDR                              = 0;
       
  1007   slice->adaptive_ref_pic_marking_mode_flag = 0;
       
  1008   slice->nalType                            = NAL_TYPE_CODED_SLICE;
       
  1009   slice->nalRefIdc                          = 1;
       
  1010 
       
  1011   currPic->forOutput   = 0;
       
  1012   currPic->nonExisting = 1;
       
  1013 
       
  1014   do {
       
  1015     slice->frame_num = seq->unusedShortTermFrameNum;
       
  1016 
       
  1017     dpbUpdatePicNums(seq->dpb, slice->frame_num, slice->maxFrameNum);
       
  1018 
       
  1019     numOutput = finishCurrentPic(seq);
       
  1020 
       
  1021     nextFrameNum = (seq->unusedShortTermFrameNum + 1) % seq->nextSlice->maxFrameNum;
       
  1022 
       
  1023     if (nextFrameNum == (int)seq->nextSlice->frame_num)
       
  1024       seq->unusedShortTermFrameNum = -1;
       
  1025     else
       
  1026       seq->unusedShortTermFrameNum = nextFrameNum;
       
  1027 
       
  1028   } while (numOutput == 0 && seq->unusedShortTermFrameNum >= 0);
       
  1029 
       
  1030   return numOutput;
       
  1031 }
       
  1032 
       
  1033 
       
  1034 /*
       
  1035  *
       
  1036  * initializeCurrentPicture:
       
  1037  *
       
  1038  * Parameters:
       
  1039  *      seq                   Sequence object
       
  1040  *      sps                   Active sequence parameter set
       
  1041  *      pps                   Active picture parameter set
       
  1042  *      width                 Picture width
       
  1043  *      height                Picture height
       
  1044  *
       
  1045  * Function:
       
  1046  *      Current frame and dpb are initialized according to active
       
  1047  *      parameter sets.
       
  1048  *
       
  1049  * Returns:
       
  1050  *      SEQ_OK for no error, negative value for error
       
  1051  */
       
  1052 static int initializeCurrentPicture(sequence_s *seq, seq_parameter_set_s *sps,
       
  1053                                     pic_parameter_set_s *pps,
       
  1054                                     int width, int height)
       
  1055 
       
  1056 {
       
  1057   frmBuf_s *currPic;
       
  1058   slice_s *slice;
       
  1059   int i;
       
  1060 
       
  1061 #ifdef CHECK_MV_RANGE
       
  1062   if (sps->level_idc <= 10)
       
  1063     maxVerticalMvRange = 64;
       
  1064   else if (sps->level_idc <= 20)
       
  1065     maxVerticalMvRange = 128;
       
  1066   else if (sps->level_idc <= 30)
       
  1067     maxVerticalMvRange = 256;
       
  1068   else
       
  1069     maxVerticalMvRange = 512;
       
  1070 #endif
       
  1071 
       
  1072   currPic = seq->recoBuf;
       
  1073   slice   = seq->currSlice;
       
  1074 
       
  1075   /*
       
  1076     * (Re)initialize frame buffer for current picture if picture size has changed
       
  1077     */
       
  1078 
       
  1079   if (!currPic || width != currPic->width || height != currPic->height) {
       
  1080     frmClose(currPic, seq->mbData);
       
  1081     if ((currPic = frmOpen(&seq->mbData, width, height)) == NULL)
       
  1082       return SEQ_ERR_MEM;
       
  1083     seq->recoBuf = currPic;
       
  1084   }
       
  1085 
       
  1086   for (i = 0; i < MAX_SLICE_GROUP_NUM; i++)
       
  1087     seq->sliceNums[i] = 0;
       
  1088 
       
  1089   /* Build slice group map */
       
  1090   buildSliceGroups(seq, slice, sps, pps);
       
  1091 
       
  1092   /* Parameter from SPS */
       
  1093   currPic->constraintSet0flag = sps->constraint_set0_flag;
       
  1094   currPic->constraintSet1flag = sps->constraint_set1_flag;
       
  1095   currPic->constraintSet2flag = sps->constraint_set2_flag;
       
  1096   currPic->profile            = sps->profile_idc;
       
  1097   currPic->level              = sps->level_idc;
       
  1098   currPic->maxFrameNum        = slice->maxFrameNum;
       
  1099 
       
  1100   /* Parameter from PPS */
       
  1101   currPic->qp = pps->pic_init_qp_minus26 + 26;
       
  1102 
       
  1103   /* By default picture will be output */
       
  1104   currPic->forOutput   = 1;
       
  1105   currPic->nonExisting = 0;
       
  1106   currPic->picType     = slice->slice_type;
       
  1107   currPic->isIDR       = slice->isIDR;
       
  1108 
       
  1109   psGetAspectRatio(sps, &currPic->aspectRatioNum, &currPic->aspectRatioDenom);
       
  1110   currPic->overscanInfo        = sps->vui_parameters.overscan_appropriate_flag;
       
  1111   currPic->videoFormat         = sps->vui_parameters.video_format;
       
  1112   currPic->videoFullRangeFlag  = sps->vui_parameters.video_full_range_flag;
       
  1113   currPic->matrixCoefficients  = sps->vui_parameters.matrix_coefficients;
       
  1114   currPic->chromaSampleLocType = sps->vui_parameters.chroma_sample_loc_type_top_field;
       
  1115   currPic->numReorderFrames    = sps->vui_parameters.num_reorder_frames;
       
  1116 
       
  1117   if (sps->frame_cropping_flag) {
       
  1118     currPic->cropLeftOff   = sps->frame_crop_left_offset;
       
  1119     currPic->cropRightOff  = sps->frame_crop_right_offset;
       
  1120     currPic->cropTopOff    = sps->frame_crop_top_offset;
       
  1121     currPic->cropBottomOff = sps->frame_crop_bottom_offset;
       
  1122   }
       
  1123   else {
       
  1124     currPic->cropLeftOff   = 0;
       
  1125     currPic->cropRightOff  = 0;
       
  1126     currPic->cropTopOff    = 0;
       
  1127     currPic->cropBottomOff = 0;
       
  1128   }
       
  1129 
       
  1130   if (sps->vui_parameters_present_flag &&
       
  1131       sps->vui_parameters.timing_info_present_flag &&
       
  1132       sps->vui_parameters.num_units_in_tick != 0)
       
  1133     currPic->frameRate = (float)(0.5 * (float)sps->vui_parameters.time_scale/(float)sps->vui_parameters.num_units_in_tick);
       
  1134   else
       
  1135     currPic->frameRate = 0.0;
       
  1136 
       
  1137   /* Get poc for current picture */
       
  1138   currPic->poc = decodePictureOrderCount(seq, slice, sps);
       
  1139 
       
  1140   /* Set chroma qp index offset */
       
  1141   currPic->chromaQpIndexOffset = pps->chroma_qp_index_offset;
       
  1142 
       
  1143   currPic->pictureStructure = 0;
       
  1144 
       
  1145   currPic->lossy = 0;
       
  1146   seq->isCurrPicFinished = 0;
       
  1147   seq->redundantPicCnt = slice->redundant_pic_cnt;
       
  1148 
       
  1149   return SEQ_OK;
       
  1150 }
       
  1151 
       
  1152 // parseSliceData
       
  1153 // Reads and parses slice data
       
  1154 static TInt parseSliceData(sequence_s *seq)
       
  1155 {
       
  1156   	slice_s *slice;
       
  1157   	pic_parameter_set_s *pps;
       
  1158   	seq_parameter_set_s *sps;
       
  1159   	TInt width, height;
       
  1160   	TInt sliceGroupNum, sliceID;
       
  1161   	TInt retCode;
       
  1162 
       
  1163   	// New slice becomes current slice 
       
  1164   	slice = seq->nextSlice;
       
  1165   	seq->nextSlice = seq->currSlice;
       
  1166   	seq->currSlice = slice;
       
  1167 
       
  1168   	// Get current parameter sets 
       
  1169   	pps = seq->ppsList[slice->pic_parameter_set_id];
       
  1170   	sps = seq->spsList[pps->seq_parameter_set_id];
       
  1171 
       
  1172   	// Get picture size 
       
  1173   	width  = (sps->pic_width_in_mbs_minus1+1)*16;
       
  1174   	height = (sps->pic_height_in_map_units_minus1+1)*16;
       
  1175 
       
  1176   	// If this is the first slice of a picture, initialize picture 
       
  1177   	if (seq->isFirstSliceOfSeq || seq->isPicBoundary) 
       
  1178   	{
       
  1179 
       
  1180     	if (slice->isIDR || seq->isFirstSliceOfSeq) 
       
  1181     	{
       
  1182 
       
  1183       		// Set dpb according to level
       
  1184       		dpbSetSize(seq->dpb, sps->vui_parameters.max_dec_frame_buffering);
       
  1185 
       
  1186       		seq->dpb->maxNumRefFrames = sps->num_ref_frames;
       
  1187     	}
       
  1188 
       
  1189     	retCode = initializeCurrentPicture(seq, sps, pps, width, height);
       
  1190 
       
  1191     	if (retCode < 0)
       
  1192       		return retCode;
       
  1193   	}
       
  1194   	else 
       
  1195   	{
       
  1196     	if (IS_SLICE_P(slice->slice_type))
       
  1197       	// If there is a P-slice in the picture, mark picture as P-picture 
       
  1198       		seq->recoBuf->picType = slice->slice_type;
       
  1199   	}
       
  1200 
       
  1201   	// Compute picture numbers for all reference frames 
       
  1202   	if (!slice->isIDR)
       
  1203     	dpbUpdatePicNums(seq->dpb, slice->frame_num, slice->maxFrameNum);
       
  1204 
       
  1205   	// Get slice group number if there are more than 1 slice groups 
       
  1206   	if (pps->num_slice_groups_minus1 == 0)
       
  1207     	sliceGroupNum = 0;
       
  1208   	else
       
  1209     	sliceGroupNum = seq->mbData->sliceMap[slice->first_mb_in_slice] & 0xF;
       
  1210 
       
  1211   	// Increment slice number for current slice group (slice numbers start from 1) 
       
  1212   	seq->sliceNums[sliceGroupNum]++;
       
  1213 
       
  1214   	// sliceID for current slice 
       
  1215   	sliceID = seq->sliceNums[sliceGroupNum]*16 | sliceGroupNum;
       
  1216 
       
  1217 
       
  1218   	// Parse the macroblocks in the slice
       
  1219   	retCode = sliceParseMacroblocks(slice, seq->recoBuf, seq->dpb,
       
  1220     	                            pps, seq->mbData, sliceID, seq->bitbuf, 
       
  1221                                     seq->iBitShiftInSlice);
       
  1222 
       
  1223   	// Update sequence variables 
       
  1224   	seq->isFirstSliceOfSeq        = 0;
       
  1225   	seq->isPicBoundary            = 0;
       
  1226 
       
  1227   	if (retCode < 0)
       
  1228     	return SEQ_ERROR;
       
  1229   	else
       
  1230     	return SEQ_OK;
       
  1231 }
       
  1232 
       
  1233 
       
  1234 // parseSlice
       
  1235 // Parses the slice header and calls parseSliceData to parse the slice data if necessary
       
  1236 static TInt parseSlice(sequence_s *seq, int nalType, int nalRefIdc)
       
  1237 {
       
  1238   	slice_s *slice;
       
  1239   	TInt nextFrameNum;
       
  1240   	TInt numOutput;
       
  1241   	TInt retCode;
       
  1242   
       
  1243 
       
  1244   	slice = seq->nextSlice;
       
  1245 
       
  1246   	slice->nalType   = nalType;
       
  1247   	slice->nalRefIdc = nalRefIdc;
       
  1248   	slice->isIDR     = (nalType == NAL_TYPE_CODED_SLICE_IDR);
       
  1249   
       
  1250   	slice->sliceDataModified = 0;
       
  1251   
       
  1252   	// Reset the bit shift flag
       
  1253   	seq->iBitShiftInSlice = EFalse;
       
  1254 
       
  1255 	// Parse the slice header
       
  1256   	retCode = ParseSliceHeader(slice, seq->spsList, seq->ppsList, seq->bitbuf, &seq->iFrameNumber, seq->iFromEncoder);
       
  1257   
       
  1258   	if (slice->sliceDataModified)
       
  1259   		seq->sliceDataModified = 1;
       
  1260   
       
  1261   	if ( retCode != SLICE_STOP_PARSING )
       
  1262   		seq->iBitShiftInSlice = ETrue;
       
  1263 
       
  1264   	if (retCode < 0)
       
  1265     	return SEQ_ERROR;
       
  1266 
       
  1267   	// Check if next slice belongs to next picture 
       
  1268   	if (seq->isFirstSliceOfSeq)
       
  1269     	seq->isPicBoundary = 0;
       
  1270   	else
       
  1271     	seq->isPicBoundary = isPicBoundary(seq);
       
  1272 
       
  1273   	if (!seq->isPicBoundary) 
       
  1274   	{	
       
  1275     	// There is no picture boundary. Decode new slice if redundant 
       
  1276     	// picture count is same as in previous slice                  
       
  1277     	if (seq->isFirstSliceOfSeq || slice->redundant_pic_cnt == seq->redundantPicCnt)
       
  1278       		return parseSliceData(seq);
       
  1279     	else
       
  1280       		return SEQ_OK;
       
  1281   	}
       
  1282   	else 
       
  1283   	{
       
  1284     	// Picture boundary reached or all MBs of current picture were decoded. 
       
  1285     	if (!seq->isCurrPicFinished) 
       
  1286     	{
       
  1287       		// Finish decoding of current picture 
       
  1288       		numOutput = finishCurrentPic(seq);
       
  1289 
       
  1290       		// numOutput is the number of pictures in output queue 
       
  1291       		// If numOutput < 0, error occured 
       
  1292       		if (numOutput < 0)
       
  1293         		return numOutput;
       
  1294     	}
       
  1295     	else
       
  1296       		numOutput = 0;
       
  1297 
       
  1298     	// Compute expected next frame number 
       
  1299     	nextFrameNum = (seq->prevRefFrameNum + 1) % slice->maxFrameNum;
       
  1300 
       
  1301     	// Check if there is a gap in frame numbers 
       
  1302     	if (!slice->isIDR && (TInt)slice->frame_num != seq->prevRefFrameNum &&
       
  1303         	(TInt)slice->frame_num != nextFrameNum)
       
  1304     	{
       
  1305        		// Start filling in gaps in frame numbers 
       
  1306        		seq->unusedShortTermFrameNum = nextFrameNum;
       
  1307 
       
  1308 	        // If dpb was not full (i.e. we did not have to output any pictures), 
       
  1309        		// we can generate non-existing frames.                               
       
  1310        		if (numOutput == 0) 
       
  1311        			numOutput = generateNonExistingFrames(seq);
       
  1312     	}
       
  1313 
       
  1314     	if (numOutput == 0)
       
  1315     	{
       
  1316       		// If there are no pictures in output queue we can decode next slice 
       
  1317       		return parseSliceData(seq);
       
  1318     	}
       
  1319     	else 
       
  1320     	{
       
  1321       		// Don't decode slice since it belongs to next picture 
       
  1322       		return SEQ_OK;
       
  1323     	}
       
  1324   	}
       
  1325 }
       
  1326 
       
  1327 
       
  1328 // avcdParseParameterSet
       
  1329 // Parses SPS / PPS parameter sets from the input NAL unit
       
  1330 TInt avcdParseParameterSet(avcdDecoder_t *dec, void *nalUnitBits, TUint* nalUnitLen)
       
  1331 {
       
  1332     sequence_s *seq = (sequence_s *)dec;
       
  1333     TInt nalHeaderByte;
       
  1334     TInt nalType;
       
  1335 //    TInt nalRefIdc;
       
  1336     TInt retCode;
       
  1337     TUint nalUnitLength = *nalUnitLen;
       
  1338     
       
  1339 		
       
  1340 	PRINT((_L("Sequence::avcdParseParameterSet() in, frame # %d, total # %d"), seq->iFrameNumber, seq->iTotalFrameNumber));
       
  1341 
       
  1342   	// Check for end of stream 
       
  1343   	if (nalUnitBits == 0 || nalUnitLen == 0) 
       
  1344   	{
       
  1345   		return AVCD_OK;
       
  1346   	}
       
  1347 
       
  1348   	// Allocate memory for the bitbuffer data, add 10 to nal length in case SPS/PPS sets are modified
       
  1349   	seq->bitbuf->data = (TUint8*) User::Alloc(nalUnitLength+10);
       
  1350   	
       
  1351   	if (seq->bitbuf->data == 0)
       
  1352   	    return KErrNoMemory;
       
  1353   	
       
  1354 	Mem::FillZ(seq->bitbuf->data, (nalUnitLength+10)*sizeof(TUint8) );
       
  1355 	
       
  1356   	TUint8* tpD = (TUint8*)nalUnitBits;
       
  1357   	 
       
  1358 	Mem::Copy(seq->bitbuf->data, tpD, nalUnitLength*sizeof(TUint8));
       
  1359 
       
  1360   	// Initialize bitbuffer and get first byte containing NAL type and NAL ref idc 
       
  1361   	if (bibInit(seq->bitbuf, seq->bitbuf->data, nalUnitLength) < 0)
       
  1362   	{
       
  1363 		User::Free(seq->bitbuf->data);
       
  1364     
       
  1365     	return AVCD_ERROR;
       
  1366   	}
       
  1367 
       
  1368   	if (bibGetByte(seq->bitbuf, &nalHeaderByte))
       
  1369   	{
       
  1370 		User::Free(seq->bitbuf->data);
       
  1371     
       
  1372     	return AVCD_ERROR;
       
  1373   	}
       
  1374   
       
  1375   	// Decode NAL unit type and reference indicator 
       
  1376   	nalType   = nalHeaderByte & 0x1F;
       
  1377 //  	nalRefIdc = (nalHeaderByte & 0x60) >> 5;
       
  1378 
       
  1379   	// Decode NAL unit data 
       
  1380   	switch (nalType)
       
  1381   	{
       
  1382   		case NAL_TYPE_SPS:              // 7
       
  1383 			retCode = psParseSPS(seq->bitbuf, seq->spsList, seq->iFromEncoder, &seq->iEncodeUntilIDR, &seq->iNumSPS);
       
  1384     		if ( retCode == KErrNotSupported)
       
  1385     		{
       
  1386 				User::Free(seq->bitbuf->data);
       
  1387       		
       
  1388       			return KErrNotSupported;
       
  1389     		}
       
  1390     		else if (retCode < 0)
       
  1391 		  	{
       
  1392 				User::Free(seq->bitbuf->data);
       
  1393     		
       
  1394     			return AVCD_ERROR;
       
  1395   			}
       
  1396     		break;
       
  1397   		case NAL_TYPE_PPS:              // 8
       
  1398 			retCode = psParsePPS(seq->bitbuf, seq->ppsList, seq->spsList, seq->iFromEncoder, &seq->iNumPPS);
       
  1399     		if (retCode == KErrNotSupported)
       
  1400     		{
       
  1401 				User::Free(seq->bitbuf->data);
       
  1402       		
       
  1403       			return KErrNotSupported;
       
  1404     		}
       
  1405     		else if (retCode < 0)
       
  1406 	  		{
       
  1407 				User::Free(seq->bitbuf->data);
       
  1408     		
       
  1409     			return AVCD_ERROR;
       
  1410   			}
       
  1411     		break;
       
  1412   		default:
       
  1413    			PRINT((_L("Not a parameter set NAL type: (%i)\n"), nalType));    
       
  1414     		break;
       
  1415   		}
       
  1416 
       
  1417 	// Take care of emulation prevention bytes
       
  1418 	int error = bibEnd(seq->bitbuf);	
       
  1419 
       
  1420 	// Free the bitbuffer data
       
  1421 	User::Free(seq->bitbuf->data);
       
  1422 
       
  1423 	if (error != 0)
       
  1424         return error;
       
  1425 
       
  1426 	return AVCD_OK;  
       
  1427 }
       
  1428 
       
  1429 
       
  1430 // avcdParseOneNal
       
  1431 // Parses one input NAL unit
       
  1432 TInt avcdParseOneNal(avcdDecoder_t *dec, void *nalUnitBits, TUint* nalUnitLen)
       
  1433 {
       
  1434     sequence_s *seq = (sequence_s *)dec;
       
  1435     TInt nalHeaderByte;
       
  1436     TInt nalType;
       
  1437     TInt nalRefIdc;
       
  1438     TInt retCode;
       
  1439     TUint nalUnitLength = *nalUnitLen;
       
  1440 		
       
  1441 	PRINT((_L("Sequence::avcdParseOneNal() in, frame # %d, total # %d"), seq->iFrameNumber, seq->iTotalFrameNumber));
       
  1442 	
       
  1443   /*
       
  1444    * The following conditions are tested to see what is the current decoder state
       
  1445    * and to act upon that state:
       
  1446    *
       
  1447    * - Check if picture can be output from output queue without further decoding.
       
  1448    * - Check if dpb store is pending (i.e current picture was not be
       
  1449    *   stored to dpb during previous call because dpb was full).
       
  1450    * - Check any non-existing frames should be generated (i.e there were gaps in
       
  1451    *   frame number). If non-existing frame(s) were generated, check output
       
  1452    *   queue again.
       
  1453    * - Check for end of stream. If end of stream was reached then current picture
       
  1454    *   is finished if not yet finished. Check again whether picture can be output
       
  1455    *   from either output queue or dpb (check is internal to getOutputPic(...)).
       
  1456    * - Check if slice decode is pending (i.e only header of the latest slice was
       
  1457    *   decoded during previous call and we now need to decode slice data) and if
       
  1458    *   so, decode slice data.
       
  1459    * - Check any lost frames being recovered (i.e there were ref frames lost)
       
  1460    *   If lost frames were rescued, check output queue again.
       
  1461    */
       
  1462 
       
  1463   	// We can return immediately if there are queued output pics 
       
  1464   	if (seq->numQueuedOutputPics > 0) 
       
  1465   	{
       
  1466   		// "Flush" all output pictures 
       
  1467   		while (seq->numQueuedOutputPics > 0)
       
  1468   		{
       
  1469 	    	getOutputPic(seq);
       
  1470   		}
       
  1471   	}
       
  1472 
       
  1473   	// Is current picture waiting to be moved to DPB? 
       
  1474   	if (seq->isDpbStorePending) 
       
  1475   	{
       
  1476     	if (dpbStorePicture(seq->dpb, seq->recoBuf, seq->outputQueue) != 0) 
       
  1477     	{
       
  1478       		PRINT((_L("Error: dpb store failed\n")));
       
  1479       		return AVCD_ERROR;
       
  1480     	}
       
  1481     	
       
  1482     	seq->isDpbStorePending = 0;
       
  1483   	}
       
  1484 
       
  1485   	// Check for end of stream 
       
  1486   	if (nalUnitBits == 0 || nalUnitLen == 0) 
       
  1487   	{
       
  1488     	if (!seq->isSeqFinished && !seq->isCurrPicFinished && seq->recoBuf != NULL) 
       
  1489     	{
       
  1490       		if (finishCurrentPic(seq) < 0)
       
  1491         		return AVCD_ERROR;
       
  1492     	}
       
  1493     	
       
  1494     	seq->isSeqFinished = 1;
       
  1495       	
       
  1496 		getOutputPic(seq);
       
  1497       	return AVCD_OK;
       
  1498   	}
       
  1499 
       
  1500   	// Reset the sliceDataModified flag
       
  1501   	seq->sliceDataModified = 0;
       
  1502 
       
  1503 	// Initialize bitbuffer and get first byte containing NAL type and NAL ref idc 
       
  1504   	if (bibInit(seq->bitbuf, (TUint8 *)nalUnitBits, nalUnitLength) < 0)
       
  1505     	return AVCD_ERROR;
       
  1506 
       
  1507   	if (bibGetByte(seq->bitbuf, &nalHeaderByte))
       
  1508     	return AVCD_ERROR;
       
  1509 
       
  1510   	// Decode NAL unit type and reference indicator 
       
  1511   	nalType   = nalHeaderByte & 0x1F;
       
  1512   	nalRefIdc = (nalHeaderByte & 0x60) >> 5;
       
  1513 
       
  1514   	// Decode NAL unit data 
       
  1515   	switch (nalType)
       
  1516   	{
       
  1517   		case NAL_TYPE_CODED_SLICE:      // 1
       
  1518     		parseSlice(seq, nalType, nalRefIdc);
       
  1519 			seq->iTotalFrameNumber++;
       
  1520     		break;
       
  1521   		case NAL_TYPE_CODED_SLICE_P_A:  // 2
       
  1522   		case NAL_TYPE_CODED_SLICE_P_B:  // 3
       
  1523   		case NAL_TYPE_CODED_SLICE_P_C:  // 4
       
  1524     		PRINT((_L("Slice data partition NAL type (%i) not supported.\n"), nalType));    
       
  1525     		break;
       
  1526   		case NAL_TYPE_CODED_SLICE_IDR:  // 5
       
  1527     		parseSlice(seq, nalType, nalRefIdc);
       
  1528 			seq->iTotalFrameNumber++;
       
  1529     		break;
       
  1530   		case NAL_TYPE_SEI:              // 6
       
  1531     		PRINT((_L("SEI NAL unit (6) skipped.\n")));
       
  1532     		break;
       
  1533   		case NAL_TYPE_SPS:              // 7
       
  1534 			retCode = psParseSPS(seq->bitbuf, seq->spsList, seq->iFromEncoder, &seq->iEncodeUntilIDR, &seq->iNumSPS);
       
  1535     		if ( retCode == KErrNotSupported)
       
  1536       			return KErrNotSupported;
       
  1537     		else if (retCode < 0)
       
  1538     			return AVCD_ERROR;
       
  1539     		break;
       
  1540   		case NAL_TYPE_PPS:              // 8
       
  1541 			retCode = psParsePPS(seq->bitbuf, seq->ppsList, seq->spsList, seq->iFromEncoder, &seq->iNumPPS);
       
  1542     		if (retCode == KErrNotSupported)
       
  1543       			return KErrNotSupported;
       
  1544     		else if (retCode < 0)
       
  1545       			return AVCD_ERROR;
       
  1546     		break;
       
  1547   		case NAL_TYPE_PIC_DELIMITER:    // 9
       
  1548     		PRINT((_L("Picture Delimiter NAL unit (9) skipped.\n")));
       
  1549     		break;
       
  1550   		case NAL_TYPE_END_SEQ:          // 10
       
  1551     		PRINT((_L("End of Sequence NAL unit (10) skipped.\n")));
       
  1552     		break;
       
  1553   		case NAL_TYPE_END_STREAM:       // 11
       
  1554     		PRINT((_L("End of Stream NAL unit (11) skipped.\n")));
       
  1555     		break;
       
  1556   		case NAL_TYPE_FILLER_DATA:      // 12
       
  1557     		PRINT((_L("Filler Data NAL unit (12) skipped.\n")));
       
  1558     		break;
       
  1559   		default:
       
  1560     		// Unspecied NAL types 0 and 24-31 
       
  1561     		if (nalType == 0 || (nalType >= 24 && nalType <= 31))
       
  1562     		{
       
  1563       			PRINT((_L("Unspecified NAL type: (%i)\n"), nalType));    
       
  1564     		}
       
  1565     		// Reserved NAL types 13-23 
       
  1566     		else
       
  1567     		{
       
  1568       			PRINT((_L("Reserved NAL type (%i)\n"), nalType));    
       
  1569     		}
       
  1570     		break;
       
  1571   	}
       
  1572 
       
  1573 
       
  1574   	// Check the output queue once again
       
  1575   	if (getOutputPic(seq)) 
       
  1576   	{
       
  1577   		// If current slice has not been parsed yet, parse it not
       
  1578     	if (seq->isPicBoundary)
       
  1579     	{
       
  1580 			parseSliceData(seq);
       
  1581     		getOutputPic(seq);
       
  1582     	}
       
  1583   	}
       
  1584 
       
  1585 	// Take care of emulation prevention bytes
       
  1586 	bibEndSlice(seq->bitbuf);
       
  1587 
       
  1588 	// If slice data was modified, copy the modified data back to the nal data buffer
       
  1589 	if (seq->sliceDataModified)
       
  1590 	{
       
  1591 		// If buffer length has been modified, change nalUnitLen
       
  1592 		if (seq->bitbuf->dataLen != nalUnitLength)
       
  1593 		{	
       
  1594 			(*nalUnitLen) = seq->bitbuf->dataLen;
       
  1595 		}
       
  1596 	}
       
  1597 
       
  1598 	return AVCD_OK;  
       
  1599 }
       
  1600 
       
  1601 
       
  1602 // FrameIsFromEncoder
       
  1603 // Stores information about the origin of next frame (if it is generated by the encoder)
       
  1604 void FrameIsFromEncoder(avcdDecoder_t *dec, TUint aFromEncoder)
       
  1605 {
       
  1606     sequence_s *seq = (sequence_s *)dec;
       
  1607 	
       
  1608 	seq->iFromEncoder = aFromEncoder;
       
  1609 }
       
  1610 
       
  1611 
       
  1612 // ReturnPPSSet
       
  1613 // This function returns the aIndex'th PPS set stored
       
  1614 TUint8* ReturnPPSSet(avcdDecoder_t *dec, TUint aIndex, TUint* aPPSLength)
       
  1615 {
       
  1616 	TUint i=0;
       
  1617 	TUint j;
       
  1618     sequence_s *seq = (sequence_s *)dec;
       
  1619 	
       
  1620 	for (j=0; j<PS_MAX_NUM_OF_PPS; j++)
       
  1621 	{
       
  1622 		if (seq->ppsList[j])
       
  1623 		{
       
  1624 			if ( i == aIndex )
       
  1625 			{
       
  1626 				*aPPSLength = seq->ppsList[j]->PPSlength;			
       
  1627 				return seq->ppsList[j]->codedPPSBuffer;
       
  1628 			}
       
  1629 			
       
  1630 			i++;
       
  1631 		}
       
  1632 	}
       
  1633 	
       
  1634 	// No PPS set found with that index
       
  1635 	return NULL;
       
  1636 }
       
  1637 
       
  1638 
       
  1639 // ReturnNumPPS
       
  1640 // Returns the number of PPS units stored 
       
  1641 TUint ReturnNumPPS(avcdDecoder_t *dec)
       
  1642 {
       
  1643 	TUint i=0;
       
  1644 	TUint j;
       
  1645     sequence_s *seq = (sequence_s *)dec;
       
  1646 	
       
  1647 	for (j=0; j<PS_MAX_NUM_OF_PPS; j++)
       
  1648 	{
       
  1649 		if (seq->ppsList[j])
       
  1650 		{
       
  1651 			i++;
       
  1652 		}
       
  1653 	}
       
  1654 	
       
  1655 	return i;
       
  1656 }
       
  1657 
       
  1658 
       
  1659 // ReturnSPSSet
       
  1660 // This function returns the aIndex'th PPS set stored
       
  1661 TUint8* ReturnSPSSet(avcdDecoder_t *dec, TUint aIndex, TUint* aSPSLength)
       
  1662 {
       
  1663 	TUint i=0;
       
  1664 	TUint j;
       
  1665     sequence_s *seq = (sequence_s *)dec;
       
  1666 	
       
  1667 	for (j=0; j<PS_MAX_NUM_OF_SPS; j++)
       
  1668 	{
       
  1669 		if (seq->spsList[j])
       
  1670 		{
       
  1671 			if ( i == aIndex )
       
  1672 			{
       
  1673 				*aSPSLength = seq->spsList[j]->SPSlength;			
       
  1674 				return seq->spsList[j]->codedSPSBuffer;
       
  1675 			}
       
  1676 			
       
  1677 			i++;
       
  1678 		}
       
  1679 		
       
  1680 	}
       
  1681 	
       
  1682 	// No SPS set found with that index
       
  1683 	return NULL;
       
  1684 }
       
  1685 
       
  1686 
       
  1687 // ReturnNumSPS
       
  1688 // Returns the number of SPS units stored 
       
  1689 TUint ReturnNumSPS(avcdDecoder_t *dec)
       
  1690 {
       
  1691 	TUint i=0;
       
  1692 	TUint j;
       
  1693     sequence_s *seq = (sequence_s *)dec;
       
  1694 	
       
  1695 	for (j=0; j<PS_MAX_NUM_OF_SPS; j++)
       
  1696 	{
       
  1697 		if (seq->spsList[j])
       
  1698 		{
       
  1699 			i++;
       
  1700 		}
       
  1701 	}
       
  1702 	
       
  1703 	return i;
       
  1704 }
       
  1705 
       
  1706 
       
  1707 // ReturnEncodeUntilIDR
       
  1708 // Returns information whether frames should be encoded until the next IDR
       
  1709 TBool ReturnEncodeUntilIDR(avcdDecoder_t *dec)
       
  1710 {
       
  1711     sequence_s *seq = (sequence_s *)dec;
       
  1712 
       
  1713 	return (seq->iEncodeUntilIDR);
       
  1714 }
       
  1715 
       
  1716 
       
  1717 // EncodeZeroValueWithVariableLength
       
  1718 // Encodes zero (which is encoded with a single one bit) to the bitbuffer
       
  1719 void EncodeZeroValueWithVariableLength(bitbuffer_s *aBitBuffer)
       
  1720 {
       
  1721 	// If bit position is zero, move to next byte
       
  1722 	if(aBitBuffer->bitpos == 0)
       
  1723 	{
       
  1724 		// Get the next byte
       
  1725 		aBitBuffer->currentBits = aBitBuffer->data[aBitBuffer->bytePos];
       
  1726 		aBitBuffer->bytePos++;
       
  1727 		aBitBuffer->bitpos = 8;
       
  1728 	}
       
  1729 		
       
  1730 	// Change the bitpos bit's value to one
       
  1731 	aBitBuffer->data[aBitBuffer->bytePos-1] |= 1 << (aBitBuffer->bitpos-1);
       
  1732 	aBitBuffer->bitpos--;
       
  1733 		
       
  1734 	if(aBitBuffer->bitpos == 0)
       
  1735 	{
       
  1736 		// Get the next byte
       
  1737 		aBitBuffer->currentBits = aBitBuffer->data[aBitBuffer->bytePos];
       
  1738 		aBitBuffer->bytePos++;
       
  1739 		aBitBuffer->bitpos = 8;
       
  1740 	}
       
  1741 	
       
  1742 	// Make sure the bit buffer currentBits is up-to-date
       
  1743 	aBitBuffer->currentBits = aBitBuffer->data[aBitBuffer->bytePos-1];
       
  1744 }
       
  1745 
       
  1746 
       
  1747 // GenerateEmptyFrame
       
  1748 // Generates an empty frame (a not coded frame) by generating the slice header and slice body
       
  1749 // Slice body contains only a value to skip all the macroblocks in the slice.
       
  1750 void GenerateEmptyFrame(sequence_s *seq, bitbuffer_s *bitbuf, TUint aFrameNumber)
       
  1751 {
       
  1752   	seq_parameter_set_s *sps;
       
  1753   	pic_parameter_set_s *pps;
       
  1754 	TUint8 bitMask;
       
  1755 	TUint picSizeInMapUnits;
       
  1756 	TUint ppsId;
       
  1757   	
       
  1758   	
       
  1759   	pps = seq->ppsList[seq->iPreviousPPSId];
       
  1760 
       
  1761   	if (pps->indexChanged)
       
  1762   	{
       
  1763 	  	// Since we generate empty frames for original clips only, 
       
  1764 	  	// find out what is the original PPS id
       
  1765   		ppsId = pps->origPPSId;
       
  1766   		
       
  1767   		pps = seq->ppsList[ppsId];
       
  1768   	}
       
  1769   		
       
  1770   	sps = seq->spsList[pps->seq_parameter_set_id];
       
  1771   	
       
  1772   	// Compute the number of macroblocks
       
  1773 	picSizeInMapUnits = (sps->pic_width_in_mbs_minus1+1) * (sps->pic_height_in_map_units_minus1+1);
       
  1774 
       
  1775 	// Generate the not coded frame
       
  1776 	// Set the first byte as zero
       
  1777 	bitbuf->bytePos = 0;
       
  1778 	bitbuf->data[bitbuf->bytePos] = 0;
       
  1779 	bitbuf->bitpos = 8;
       
  1780 	
       
  1781 	// Generate the NAL header, with nal type as 1 and nal_ref_idc as 1
       
  1782 	bitbuf->data[0] = 0x21;
       
  1783 	bitbuf->bytePos = 1;
       
  1784 
       
  1785 	// Set the first_mb_in_slice & slice_type to be zero (coded as 1), advance bitpos by two
       
  1786 	bitbuf->data[bitbuf->bytePos] = 0xc0;	// First two bits == 1
       
  1787 	bitbuf->bitpos -= 2;
       
  1788 	bitbuf->bytePos = 2;
       
  1789 	
       
  1790 	// Encode the PPS index
       
  1791 	EncodeUnsignedExpGolombCode(bitbuf, 0);
       
  1792 	
       
  1793  	// Encode the new frame number here
       
  1794  	// If the max frame num was changed use original value since empty clips are generated for original clips
       
  1795   	if (sps->maxFrameNumChanged)
       
  1796 	  	EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->origMaxFrameNum+4);
       
  1797   	else
       
  1798 	  	EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->log2_max_frame_num_minus4+4);
       
  1799   
       
  1800   	// POC parameters 
       
  1801 	if (sps->pic_order_cnt_type == 0) 
       
  1802   	{
       
  1803 	  	// For now encode the POC as the frame number
       
  1804  		// If the max frame num was changed use original value since empty clips are generated 
       
  1805  		// for original clips
       
  1806 	  	if (sps->maxPOCNumChanged)
       
  1807 	  		EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->origMaxPOCNum+4);
       
  1808 	  	else
       
  1809 	  		EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->log2_max_pic_order_cnt_lsb_minus4+4);
       
  1810   	}
       
  1811   	else if (sps->pic_order_cnt_type == 1) 
       
  1812   	{
       
  1813     	if (!sps->delta_pic_order_always_zero_flag) 
       
  1814     	{
       
  1815       		EncodeZeroValueWithVariableLength(bitbuf);
       
  1816       		if (pps->pic_order_present_flag) 
       
  1817       		{
       
  1818 	      		EncodeZeroValueWithVariableLength(bitbuf);
       
  1819       		}
       
  1820     	}
       
  1821   	}
       
  1822   	
       
  1823   	// Redundant picture count
       
  1824   	if (pps->redundant_pic_cnt_present_flag) 
       
  1825   	{
       
  1826   		EncodeZeroValueWithVariableLength(bitbuf);
       
  1827   	}
       
  1828   	
       
  1829   	// Encode num_ref_idx_active:override_flag with zero value
       
  1830 	EncodeUnsignedNBits(bitbuf, 0, 1);
       
  1831 	
       
  1832   	// Encode reference picture list reordering with single zero value
       
  1833 	EncodeUnsignedNBits(bitbuf, 0, 1);
       
  1834 	
       
  1835 	// Since nal_ref_idc == 1, encode zero value for decoded reference picture marking
       
  1836 	EncodeUnsignedNBits(bitbuf, 0, 1);
       
  1837   	
       
  1838   	// Encode slice_qp_delta with zero value
       
  1839 	EncodeZeroValueWithVariableLength(bitbuf);
       
  1840 	
       
  1841   	if (pps->deblocking_filter_parameters_present_flag == 1) 
       
  1842   	{
       
  1843   		// Encode value of 1 which is 010, i.e. two with three bits
       
  1844   		EncodeUnsignedNBits(bitbuf, 2, 3);
       
  1845   	}
       
  1846 
       
  1847   	if (pps->num_slice_groups_minus1 > 0 && pps->slice_group_map_type >= 3 &&
       
  1848         pps->slice_group_map_type <= 5)
       
  1849   	{
       
  1850   		TUint temp, temp2, len1;
       
  1851   		
       
  1852     	// len = Ceil( Log2( PicSizeInMapUnits / SliceGroupChangeRate + 1 ) ) 
       
  1853 	    // PicSizeInMapUnits / SliceGroupChangeRate 
       
  1854     	temp = picSizeInMapUnits / (pps->slice_group_change_rate_minus1+1);
       
  1855 
       
  1856     	// Calculate Log2 
       
  1857     	temp2 = (temp + 1) >> 1;
       
  1858     	for (len1 = 0; len1 < 16 && temp2 != 0; len1++)
       
  1859       		temp2 >>= 1;
       
  1860 
       
  1861     	// Calculate Ceil 
       
  1862     	if ( (((unsigned)1) << len1) < (temp + 1) )
       
  1863       		len1++;
       
  1864     	
       
  1865 		// Encode zero value with len1 bits
       
  1866 		EncodeUnsignedNBits(bitbuf, 0, len1);
       
  1867   	}
       
  1868   	
       
  1869   	// Now encode the slice data
       
  1870   	// Encode the mb_skip_run to indicate all macroblocks to be skipped
       
  1871   	// For example in CIF we have 22x18 = 396 macroblocks
       
  1872   	// 396 = 00000000 1 10001101
       
  1873 	EncodeUnsignedExpGolombCode(bitbuf, picSizeInMapUnits);
       
  1874   	
       
  1875   	// Take care of the trailing bits, i.e. encode the rest of the bits in this byte to zero
       
  1876   	bitMask = 1 << (bitbuf->bitpos - 1);
       
  1877 	bitbuf->data[bitbuf->bytePos-1] = bitbuf->data[bitbuf->bytePos-1] | bitMask;
       
  1878 	
       
  1879 	bitbuf->bitpos--;
       
  1880 	if(bitbuf->bitpos != 0)
       
  1881 	{
       
  1882 		bitMask = 255 << (bitbuf->bitpos);	// Mask the 8-bitPos upper bits
       
  1883 		bitbuf->data[bitbuf->bytePos-1] = bitbuf->data[bitbuf->bytePos-1] & bitMask;
       
  1884 	}
       
  1885   	
       
  1886   	bitbuf->dataLen = bitbuf->bytePos;
       
  1887 }
       
  1888 
       
  1889 
       
  1890 // avcdGenerateNotCodedFrame
       
  1891 // Generates an empty frame
       
  1892 TInt avcdGenerateNotCodedFrame(avcdDecoder_t *dec, void *aNalUnitBits, TUint aNalUnitLen, TUint aFrameNumber)
       
  1893 {
       
  1894     sequence_s *seq = (sequence_s *)dec;
       
  1895 	
       
  1896 	// Initialize bitbuffer
       
  1897   	if (bibInit(seq->bitbuf, (TUint8 *)aNalUnitBits, aNalUnitLen) < 0)
       
  1898     	return AVCD_ERROR;
       
  1899   	
       
  1900   	GenerateEmptyFrame(seq, seq->bitbuf, aFrameNumber);
       
  1901 
       
  1902   	return (seq->bitbuf->dataLen);
       
  1903 }
       
  1904 
       
  1905 
       
  1906 // avcdStoreCurrentPPSId
       
  1907 // Stores the value of PPS Id from the input NAL unit (if that unit is a coded slice). 
       
  1908 // The Id value is used in the generation of an empty frame. 
       
  1909 TInt avcdStoreCurrentPPSId(avcdDecoder_t *dec, TUint8 *nalUnitBits, TUint aNalUnitLen)
       
  1910 {
       
  1911     sequence_s *seq = (sequence_s *)dec;
       
  1912     TInt nalHeaderByte;
       
  1913     TInt nalType;
       
  1914 //    TInt nalRefIdc;
       
  1915 //    TUint temp;
       
  1916 		
       
  1917 	// Initialize bitbuffer and get first byte containing NAL type and NAL ref idc 
       
  1918   	if (bibInit(seq->bitbuf, nalUnitBits, aNalUnitLen) < 0)
       
  1919     	return AVCD_ERROR;
       
  1920 
       
  1921   	if (bibGetByte(seq->bitbuf, &nalHeaderByte))
       
  1922     	return AVCD_ERROR;
       
  1923 
       
  1924   	// Decode NAL unit type and reference indicator 
       
  1925   	nalType   = nalHeaderByte & 0x1F;
       
  1926 //  	nalRefIdc = (nalHeaderByte & 0x60) >> 5;
       
  1927 
       
  1928   	// Decode NAL unit data 
       
  1929   	if (nalType == NAL_TYPE_CODED_SLICE || nalType == NAL_TYPE_CODED_SLICE_IDR)
       
  1930   	{
       
  1931   		// Parse the slice haeder until the PPS id
       
  1932   		// First macroblock in slice 
       
  1933 //  		temp = vldGetUVLC(seq->bitbuf);
       
  1934 	  		
       
  1935 	  	// Slice type 
       
  1936 //  		temp = vldGetUVLC(seq->bitbuf);
       
  1937 
       
  1938 		// PPS id 
       
  1939   		seq->iPreviousPPSId = vldGetUVLC(seq->bitbuf);
       
  1940   	}
       
  1941 
       
  1942 	return AVCD_OK;  
       
  1943 }
       
  1944 
       
  1945 
       
  1946 // ue_v
       
  1947 // Returns unsigned UVLC code from the bitbuffer
       
  1948 static int ue_v(bitbuffer_s *bitbuf, unsigned int *val, unsigned int maxVal)
       
  1949 {
       
  1950   *val = vldGetUVLC(bitbuf);
       
  1951 
       
  1952   if (bibGetStatus(bitbuf) < 0)
       
  1953     return SLICE_ERROR;
       
  1954 
       
  1955   if (*val > maxVal)
       
  1956     return SLICE_ERR_ILLEGAL_VALUE;
       
  1957 
       
  1958   return SLICE_OK;
       
  1959 }
       
  1960 
       
  1961 
       
  1962 // ModifyFrameNumber
       
  1963 // Modifies the frame numbering from the input bit buffer. The bit buffer must be positioned 
       
  1964 // at the start of the slice header when this function is called.
       
  1965 void ModifyFrameNumber(sequence_s *seq, bitbuffer_s *bitbuf, TUint aFrameNumber, TInt aNalType)
       
  1966 {
       
  1967   	seq_parameter_set_s *sps;
       
  1968   	pic_parameter_set_s *pps;
       
  1969 	TUint tempValue;
       
  1970 	TUint firstMbInSlice;
       
  1971 	TUint ppsId;
       
  1972 //	TInt spsId;
       
  1973   	
       
  1974   	
       
  1975   	// First macroblock in slice 
       
  1976   	ue_v(bitbuf, &firstMbInSlice, 65535);
       
  1977 
       
  1978   	// Slice type 
       
  1979   	ue_v(bitbuf, &tempValue, SLICE_MAX);
       
  1980 
       
  1981   	// PPS id 
       
  1982   	ue_v(bitbuf, &ppsId, PS_MAX_NUM_OF_PPS-1);
       
  1983   
       
  1984   	pps = seq->ppsList[ppsId];
       
  1985 
       
  1986   	if (pps->indexChanged)
       
  1987   	{
       
  1988 	  	// Since we generate empty frames for original clips only, 
       
  1989 	  	// find out what is the original PPS id
       
  1990   		ppsId = pps->origPPSId;
       
  1991   		
       
  1992   		pps = seq->ppsList[ppsId];
       
  1993   	}
       
  1994   		
       
  1995 /*
       
  1996   	if (pps == NULL) 
       
  1997   	{
       
  1998 		// Use zero for SPS id
       
  1999 		spsId = 0;
       
  2000   	}
       
  2001   	else
       
  2002   	{
       
  2003 	  	spsId = pps->seq_parameter_set_id;
       
  2004   	}
       
  2005 */
       
  2006 
       
  2007 	syncBitBufferBitpos(bitbuf);
       
  2008 	
       
  2009   	sps = seq->spsList[pps->seq_parameter_set_id];
       
  2010   	
       
  2011   	if (sps == NULL) 
       
  2012   	{
       
  2013     	PRINT((_L("Error: referring to non-existing SPS.\n")));     
       
  2014 		return;
       
  2015   	}
       
  2016 
       
  2017   	if (sps->maxFrameNumChanged)
       
  2018   	{
       
  2019 	  	// Encode the new frame number here
       
  2020   		EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->origMaxFrameNum+4);
       
  2021   	}
       
  2022   	else
       
  2023   	{
       
  2024 	  	// Encode the new frame number here
       
  2025   		EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->log2_max_frame_num_minus4+4);
       
  2026   	}
       
  2027   	
       
  2028   	// IDR picture 
       
  2029   	if (aNalType == NAL_TYPE_CODED_SLICE_IDR) 
       
  2030   	{
       
  2031     	ue_v(bitbuf, &tempValue, 65535);
       
  2032   	}
       
  2033 
       
  2034 	syncBitBufferBitpos(bitbuf);
       
  2035 	
       
  2036   	// POC parameters 
       
  2037 	if (sps->pic_order_cnt_type == 0) 
       
  2038   	{
       
  2039 	  	if (sps->maxPOCNumChanged)
       
  2040   		{
       
  2041 		  	// For now encode the POC as the frame number
       
  2042 	  		EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->origMaxPOCNum+4);
       
  2043   		}
       
  2044   		else
       
  2045   		{
       
  2046 		  	// For now encode the POC as the frame number
       
  2047 	  		EncodeUnsignedNBits(bitbuf, aFrameNumber, sps->log2_max_pic_order_cnt_lsb_minus4+4);
       
  2048   		}
       
  2049   	}
       
  2050 }
       
  2051 
       
  2052 
       
  2053 // avcdModifyFrameNumber
       
  2054 // Modifies the input NAL unit's frame numbering
       
  2055 void avcdModifyFrameNumber(avcdDecoder_t *dec, void *aNalUnitBits, TUint aNalUnitLen, TUint aFrameNumber)
       
  2056 {
       
  2057     sequence_s *seq = (sequence_s *)dec;
       
  2058     TInt nalHeaderByte;
       
  2059     TInt nalType;
       
  2060 	
       
  2061 	// Initialize bitbuffer
       
  2062   	bibInit(seq->bitbuf, (TUint8 *)aNalUnitBits, aNalUnitLen);
       
  2063   	
       
  2064   	// Read the nalHeaderByte
       
  2065   	bibGetByte(seq->bitbuf, &nalHeaderByte);
       
  2066   	
       
  2067   	nalType   = nalHeaderByte & 0x1F;
       
  2068 
       
  2069   	if (nalType == NAL_TYPE_CODED_SLICE || nalType == NAL_TYPE_CODED_SLICE_IDR)
       
  2070 	  	ModifyFrameNumber(seq, seq->bitbuf, aFrameNumber, nalType);
       
  2071 }
       
  2072 
       
  2073 
       
  2074 #endif  // VIDEOEDITORENGINE_AVC_EDITING