slice.c
上传用户:hjq518
上传日期:2021-12-09
资源大小:5084k
文件大小:56k
源码类别:

Audio

开发平台:

Visual C++

  1. /*!
  2.  **************************************************************************************
  3.  * file
  4.  *    slice.c
  5.  * brief
  6.  *    generate the slice header, setup the bit buffer for slices,
  7.  *    and generates the slice NALU(s)
  8.  * author
  9.  *    Main contributors (see contributors.h for copyright, address and affiliation details)
  10.  *      - Thomas Stockhammer            <stockhammer@ei.tum.de>
  11.  *      - Detlev Marpe                  <marpe@hhi.de>
  12.  *      - Stephan Wenger                <stewe@cs.tu-berlin.de>
  13.  *      - Alexis Michael Tourapis       <alexismt@ieee.org>
  14.  ***************************************************************************************
  15.  */
  16. #include "contributors.h"
  17. #include <math.h>
  18. #include <float.h>
  19. #include "global.h"
  20. #include "header.h"
  21. #include "nal.h"
  22. #include "rtp.h"
  23. #include "fmo.h"
  24. #include "vlc.h"
  25. #include "image.h"
  26. #include "cabac.h"
  27. #include "elements.h"
  28. #include "macroblock.h"
  29. #include "symbol.h"
  30. #include "context_ini.h"
  31. #include "enc_statistics.h"
  32. #include "ratectl.h"
  33. #include "me_epzs.h"
  34. #include "wp.h"
  35. #include "slice.h"
  36. #include "rdoq.h"
  37. #include "wp_mcprec.h"
  38. #include "q_offsets.h"
  39. #include "conformance.h"
  40. #include "quant4x4.h"
  41. #include "quant8x8.h"
  42. #include "quantChroma.h"
  43. // Local declarations
  44. static Slice *malloc_slice();
  45. static void  free_slice(Slice *slice);
  46. static void  set_ref_pic_num();
  47. extern ColocatedParams *Co_located;
  48. extern StorablePicture **listX[6];
  49. //! convert from H.263 QP to H.264 quant given by: quant=pow(2,QP/6)
  50. const int QP2QUANT[40]=
  51. {
  52.    1, 1, 1, 1, 2, 2, 2, 2,
  53.    3, 3, 3, 4, 4, 4, 5, 6,
  54.    6, 7, 8, 9,10,11,13,14,
  55.   16,18,20,23,25,29,32,36,
  56.   40,45,51,57,64,72,81,91
  57. };
  58. /*!
  59.  ************************************************************************
  60.  * brief
  61.  *    init_ref_pic_list_reordering initializations should go here
  62.  ************************************************************************
  63.  */
  64. void init_ref_pic_list_reordering(Slice* currSlice)
  65. {
  66.   currSlice->ref_pic_list_reordering_flag_l0 = 0;
  67.   currSlice->ref_pic_list_reordering_flag_l1 = 0;
  68. }
  69. /*!
  70.  ************************************************************************
  71.  *  brief
  72.  *     This function generates the slice (and partition) header(s)
  73.  *
  74.  *  return number of bits used for the slice (and partition) header(s)
  75.  *
  76.  *  par Side effects:
  77.  *      Adds slice/partition header symbols to the symbol buffer
  78.  *      increments Picture->no_slices, allocates memory for the
  79.  *      slice, sets img->currSlice
  80.  ************************************************************************
  81. */
  82. static int start_slice(Slice *currSlice, StatParameters *cur_stats)
  83. {
  84.   EncodingEnvironmentPtr eep;
  85.   Bitstream *currStream;
  86.   int header_len = 0;
  87.   int i;
  88.   int NumberOfPartitions = (params->partition_mode == PAR_DP_1?1:3);
  89.   //one  partition for IDR img
  90.   if(img->currentPicture->idr_flag)
  91.   {
  92.      NumberOfPartitions = 1;
  93.   }
  94.   RTPUpdateTimestamp (img->tr);   // this has no side effects, just leave it for all NALs
  95.   for (i=0; i<NumberOfPartitions; i++)
  96.   {
  97.     currStream = (currSlice->partArr[i]).bitstream;
  98.     currStream->write_flag = 0;
  99.     if (i==0)     // First partition
  100.       header_len += SliceHeader ();
  101.     else          // Second/Third partition
  102.       header_len += Partition_BC_Header(i);
  103.     //! Initialize CABAC
  104.     if (currSlice->symbol_mode == CABAC)
  105.     {
  106.       eep = &((currSlice->partArr[i]).ee_cabac);
  107.       if (currStream->bits_to_go != 8)
  108.         header_len+=currStream->bits_to_go;
  109.       writeVlcByteAlign(currStream, cur_stats);
  110.       arienco_start_encoding(eep, currStream->streamBuffer, &(currStream->byte_pos));
  111.       arienco_reset_EC(eep);
  112.     }
  113.     else
  114.     {
  115.       // Initialize CA-VLC
  116.       CAVLC_init();
  117.     }
  118.   }
  119.   if(currSlice->symbol_mode == CABAC)
  120.   {
  121.     init_contexts();
  122.   }
  123.   return header_len;
  124. }
  125. /*!
  126. ************************************************************************
  127. * brief
  128. *    This creates a NAL unit structures for all data partition of the slice
  129. *
  130. ************************************************************************
  131. */
  132. void create_slice_nalus(Slice *currSlice)
  133. {
  134.   // KS: this is approx. max. allowed code picture size
  135.   const int buffer_size = 500 + img->FrameSizeInMbs * (128 + 256 * img->bitdepth_luma + 512 * img->bitdepth_chroma);
  136.   
  137.   int part;
  138.   NALU_t *nalu;
  139.   for (part=0; part< currSlice->max_part_nr; part++)
  140.   {
  141.     if (currSlice->partArr[part].bitstream->write_flag)
  142.     {
  143.       nalu = AllocNALU(buffer_size);
  144.       currSlice->partArr[part].nal_unit = nalu;
  145.       nalu->startcodeprefix_len = 1+ (currSlice->start_mb_nr == 0 && part == 0 ?ZEROBYTES_SHORTSTARTCODE+1:ZEROBYTES_SHORTSTARTCODE);
  146.       nalu->forbidden_bit = 0;
  147.       if (img->currentPicture->idr_flag)
  148.       {
  149.         nalu->nal_unit_type = NALU_TYPE_IDR;
  150.         nalu->nal_reference_idc = NALU_PRIORITY_HIGHEST;
  151.       }
  152.       else
  153.       {
  154.         //different nal header for different partitions
  155.         if(params->partition_mode == 0)
  156.         {
  157.           nalu->nal_unit_type = NALU_TYPE_SLICE;
  158.         }
  159.         else
  160.         {
  161.           nalu->nal_unit_type = (NaluType) (NALU_TYPE_DPA +  part);
  162.         }
  163.         if (img->nal_reference_idc !=0)
  164.         {
  165.           nalu->nal_reference_idc = NALU_PRIORITY_HIGH;
  166.         }
  167.         else
  168.         {
  169.           nalu->nal_reference_idc = NALU_PRIORITY_DISPOSABLE;
  170.         }
  171.       }
  172.     }
  173.     else
  174.     {
  175.       currSlice->partArr[part].nal_unit = NULL;
  176.     }
  177.   }
  178. }
  179. /*!
  180.  ************************************************************************
  181.  * brief
  182.  *    This function terminates a slice (but doesn't write it out),
  183.  *    the old terminate_slice (0)
  184.  * return
  185.  *    0 if OK,                                                         n
  186.  *    1 in case of error
  187.  *
  188.  ************************************************************************
  189.  */
  190. static int terminate_slice(Slice *currSlice, int lastslice, StatParameters *cur_stats )
  191. {
  192.   Bitstream *currStream;
  193.   NALU_t    *currNalu;
  194.   EncodingEnvironmentPtr eep;
  195.   int part;
  196.   int tmp_stuffingbits = img->mb_data[img->current_mb_nr].bitcounter[BITS_STUFFING];
  197.   if (currSlice->symbol_mode == CABAC)
  198.     write_terminating_bit (1);      // only once, not for all partitions
  199.   create_slice_nalus(currSlice);
  200.   for (part=0; part<currSlice->max_part_nr; part++)
  201.   {
  202.     currStream = (currSlice->partArr[part]).bitstream;
  203.     currNalu   = (currSlice->partArr[part]).nal_unit;
  204.     if (currStream->write_flag)
  205.     {
  206.       if (currSlice->symbol_mode == CAVLC)
  207.       {
  208.         SODBtoRBSP(currStream);
  209.         currNalu->len = RBSPtoEBSP(currNalu->buf, currStream->streamBuffer, currStream->byte_pos);
  210.       }
  211.       else     // CABAC
  212.       {
  213.         eep = &((currSlice->partArr[part]).ee_cabac);
  214.         // terminate the arithmetic code
  215.         arienco_done_encoding(eep);
  216.         set_pic_bin_count(eep);
  217.         currStream->bits_to_go = eep->Ebits_to_go;
  218.         currStream->byte_buf = 0;
  219.         currNalu->len = RBSPtoEBSP(currNalu->buf, currStream->streamBuffer, currStream->byte_pos);
  220.         // NumBytesInNALunit is: payload length + 1 byte header
  221.         img->bytes_in_picture += currNalu->len + 1;
  222.         if (lastslice && (part==(currSlice->max_part_nr-1)))
  223.         {
  224.           addCabacZeroWords(currNalu, cur_stats);
  225.         }
  226.       }           // CABAC
  227.     }
  228.   }           // partition loop
  229.   if( currSlice->symbol_mode == CABAC )
  230.   {
  231.     store_contexts();
  232.   }
  233.   cur_stats->bit_use_stuffingBits[img->type] += img->mb_data[img->current_mb_nr].bitcounter[BITS_STUFFING] - tmp_stuffingbits;
  234.   if (img->type != I_SLICE && img->type != SI_SLICE)
  235.     free_ref_pic_list_reordering_buffer (currSlice);
  236.   return 0;
  237. }
  238. /*!
  239. ************************************************************************
  240. * brief
  241. *    Encodes one slice
  242. * par
  243. *   returns the number of coded MBs in the SLice
  244. ************************************************************************
  245. */
  246. int encode_one_slice (int SliceGroupId, Picture *pic, int TotalCodedMBs)
  247. {
  248.   Boolean end_of_slice = FALSE;
  249.   Boolean recode_macroblock;
  250.   Boolean prev_recode_mb = FALSE;
  251.   int len;
  252.   int NumberOfCodedMBs = 0;
  253.   Macroblock* currMB      = NULL;
  254.   int CurrentMbAddr;
  255.   double FrameRDCost = DBL_MAX, FieldRDCost = DBL_MAX;
  256.   StatParameters *cur_stats = &enc_picture->stats;
  257.   Slice *currSlice = NULL;
  258.   Motion_Selected = 0;
  259.   if( IS_INDEPENDENT(params) )
  260.   {
  261.     change_plane_JV( img->colour_plane_id );
  262.   }
  263.   img->cod_counter = 0;
  264.   CurrentMbAddr = FmoGetFirstMacroblockInSlice (SliceGroupId);
  265.   // printf ("nnEncode_one_slice: PictureID %d SliceGroupId %d  SliceID %d  FirstMB %d n", img->tr, SliceGroupId, img->current_slice_nr, CurrentMbInScanOrder);
  266.   init_slice (&currSlice, CurrentMbAddr);
  267.   // Initialize quantization functions based on rounding/quantization method
  268.   // Done here since we may wish to disable adaptive rounding on occasional intervals (even at a frame or gop level).
  269.   init_quant_4x4(params, img, currSlice);
  270.   init_quant_8x8(params, img, currSlice);
  271.   init_quant_Chroma(params, img, currSlice);
  272.   SetLagrangianMultipliers();
  273.   if (currSlice->symbol_mode == CABAC)
  274.   {
  275.     SetCtxModelNumber ();
  276.   }
  277.   img->checkref = (params->rdopt && params->RestrictRef && (img->type==P_SLICE || img->type==SP_SLICE));
  278.   len = start_slice (currSlice, cur_stats);
  279.   // Rate control
  280.   if (params->RCEnable)
  281.     rc_store_slice_header_bits( len );
  282.   // Update statistics
  283.   stats->bit_slice += len;
  284.   cur_stats->bit_use_header[img->type] += len;
  285.   while (end_of_slice == FALSE) // loop over macroblocks
  286.   {
  287.     if (img->AdaptiveRounding && params->AdaptRndPeriod && (img->current_mb_nr % params->AdaptRndPeriod == 0))
  288.     {
  289.       CalculateOffsetParam();
  290.       if(params->Transform8x8Mode)
  291.       {
  292.         CalculateOffset8Param();
  293.       }
  294.     }
  295.     //sw paff
  296.     if (!img->MbaffFrameFlag)
  297.     {
  298.       recode_macroblock = FALSE;
  299.       if(params->UseRDOQuant) // This needs revisit
  300.         rdopt = &rddata_trellis_curr;
  301.       else
  302.         rdopt = &rddata_top_frame_mb;   // store data in top frame MB
  303.       start_macroblock (currSlice,  &currMB, CurrentMbAddr, FALSE);
  304.       if(params->UseRDOQuant)
  305.       {
  306.         trellis_coding(currMB, CurrentMbAddr, prev_recode_mb);   
  307.       }
  308.       else
  309.       {
  310.         img->masterQP = img->qp;
  311.         encode_one_macroblock (currMB);
  312.         write_one_macroblock (currMB, 1, prev_recode_mb);    
  313.       }
  314.       terminate_macroblock (currSlice, currMB, &end_of_slice, &recode_macroblock);
  315.       prev_recode_mb = recode_macroblock;
  316.       //       printf ("encode_one_slice: mb %d,  slice %d,   bitbuf bytepos %d EOS %dn",
  317.       //       img->current_mb_nr, img->current_slice_nr,
  318.       //       currSlice->partArr[0].bitstream->byte_pos, end_of_slice);
  319.       if (recode_macroblock == FALSE)       // The final processing of the macroblock has been done
  320.       {
  321.         img->SumFrameQP += currMB->qp;
  322.         CurrentMbAddr = FmoGetNextMBNr (CurrentMbAddr);
  323.         if (CurrentMbAddr == -1)   // end of slice
  324.         {
  325.           // printf ("FMO End of Slice Group detected, current MBs %d, force end of slicen", NumberOfCodedMBs+1);
  326.           end_of_slice = TRUE;
  327.         }
  328.         NumberOfCodedMBs++;       // only here we are sure that the coded MB is actually included in the slice
  329.         proceed2nextMacroblock (currMB);
  330.       }
  331.       else
  332.       {
  333.         //!Go back to the previous MB to recode it
  334.         img->current_mb_nr = FmoGetPreviousMBNr(img->current_mb_nr);
  335.         img->NumberofCodedMacroBlocks--;
  336.         if(img->current_mb_nr == -1 )   // The first MB of the slice group  is too big,
  337.           // which means it's impossible to encode picture using current slice bits restriction
  338.         {
  339.           snprintf (errortext, ET_SIZE, "Error encoding first MB with specified parameter, bits of current MB may be too big");
  340.           error (errortext, 300);
  341.         }
  342.       }
  343.     }
  344.     else                      // TBD -- Addition of FMO
  345.     {
  346.       //! This following ugly code breaks slices, at least for a slice mode that accumulates a certain
  347.       //! number of bits into one slice.
  348.       //! The suggested algorithm is as follows:
  349.       //!
  350.       //! SaveState (Bitstream, stats,  etc. etc.);
  351.       //! BitsForThisMBPairInFrameMode = CodeMB (Upper, FRAME_MODE) + CodeMB (Lower, FRAME_MODE);
  352.       //! DistortionForThisMBPairInFrameMode = CalculateDistortion(Upper) + CalculateDistortion (Lower);
  353.       //! RestoreState();
  354.       //! BitsForThisMBPairInFieldMode = CodeMB (Upper, FIELD_MODE) + CodeMB (Lower, FIELD_MODE);
  355.       //! DistortionForThisMBPairInFrameMode = CalculateDistortion(Upper) + CalculateDistortion (Lower);
  356.       //! FrameFieldMode = Decision (...)
  357.       //! RestoreState()
  358.       //! if (FrameFieldMode == FRAME) {
  359.       //!   CodeMB (Upper, FRAME); CodeMB (Lower, FRAME);
  360.       //! } else {
  361.       //!   CodeMB (Upper FIELD); CodeMB (Lower, FIELD);
  362.       //! }
  363.       //!
  364.       //! Open questions/issues:
  365.       //!   1. CABAC/CA-VLC state:  It seems that the CABAC/CA_VLC states are changed during the
  366.       //!      dummy encoding processes (for the R-D based selection), but that they are never
  367.       //!      reset, once the selection is made.  I believe that this breaks the MB-adaptive
  368.       //!      frame/field coding.  The necessary code for the state saves is readily available
  369.       //!      in macroblock.c, start_macroblock() and terminate_macroblock() (this code needs
  370.       //!      to be double checked that it works with CA-VLC as well
  371.       //!   2. would it be an option to allocate Bitstreams with zero data in them (or copy the
  372.       //!      already generated bitstream) for the "test coding"?
  373.       img->write_macroblock = FALSE;
  374.       if (params->MbInterlace == ADAPTIVE_CODING || params->MbInterlace == FRAME_MB_PAIR_CODING)
  375.       {
  376.         //================ code MB pair as frame MB ================
  377.         //----------------------------------------------------------
  378.         recode_macroblock = FALSE;
  379.         //set mv limits to frame type
  380.         update_mv_limits(img, FALSE);
  381.         img->field_mode = FALSE;  // MB coded as frame
  382.         img->top_field  = FALSE;   // Set top field to 0
  383.         //Rate control
  384.         img->write_macroblock = FALSE;
  385.         img->bot_MB = FALSE;
  386.         // save RC state only when it is going to change
  387.         if ( params->RCEnable && params->RCUpdateMode <= MAX_RC_MODE )
  388.         {
  389.           if ( params->MbInterlace == ADAPTIVE_CODING
  390.             && img->NumberofCodedMacroBlocks > 0 && (img->NumberofCodedMacroBlocks % img->BasicUnit) == 0 )
  391.             rc_copy_quadratic( quadratic_RC_init, quadratic_RC ); // save initial RC status
  392.           if ( params->MbInterlace == ADAPTIVE_CODING )
  393.             rc_copy_generic( generic_RC_init, generic_RC ); // save initial RC status
  394.         }
  395.         start_macroblock (currSlice, &currMB, CurrentMbAddr, FALSE);
  396.         rdopt = &rddata_top_frame_mb; // store data in top frame MB
  397.         img->masterQP = img->qp;
  398.         encode_one_macroblock (currMB);   // code the MB as frame
  399.         FrameRDCost = rdopt->min_rdcost;
  400.         //***   Top MB coded as frame MB ***//
  401.         //Rate control
  402.         img->bot_MB = TRUE; //for Rate control
  403.         // go to the bottom MB in the MB pair
  404.         img->field_mode = FALSE;  // MB coded as frame  //GB
  405.         start_macroblock (currSlice, &currMB, CurrentMbAddr + 1, FALSE);
  406.         rdopt = &rddata_bot_frame_mb; // store data in top frame MB
  407.         img->masterQP = img->qp;
  408.         encode_one_macroblock (currMB);         // code the MB as frame
  409.         if ( params->RCEnable && params->RCUpdateMode <= MAX_RC_MODE )
  410.         {
  411.           if ( params->MbInterlace == ADAPTIVE_CODING
  412.             && img->NumberofCodedMacroBlocks > 0 && (img->NumberofCodedMacroBlocks % img->BasicUnit) == 0 )
  413.             rc_copy_quadratic( quadratic_RC_best, quadratic_RC ); // restore initial RC status
  414.           if ( params->MbInterlace == ADAPTIVE_CODING )
  415.             rc_copy_generic( generic_RC_best, generic_RC ); // save frame RC stats
  416.         }
  417.         FrameRDCost += rdopt->min_rdcost;
  418.         //***   Bottom MB coded as frame MB ***//
  419.       }
  420.       if ((params->MbInterlace == ADAPTIVE_CODING) || (params->MbInterlace == FIELD_CODING))
  421.       {
  422.         //Rate control
  423.         img->bot_MB = FALSE;
  424.         //set mv limits to field type
  425.         update_mv_limits(img, TRUE);
  426.         //=========== start coding the MB pair as a field MB pair =============
  427.         //---------------------------------------------------------------------
  428.         img->field_mode = TRUE;  // MB coded as field
  429.         img->top_field = TRUE;   // Set top field to 1
  430.         img->buf_cycle <<= 1;
  431.         params->num_ref_frames <<= 1;
  432.         img->num_ref_idx_l0_active <<= 1;
  433.         img->num_ref_idx_l0_active += 1;
  434.         if ( params->RCEnable && params->RCUpdateMode <= MAX_RC_MODE )
  435.         {
  436.           if ( params->MbInterlace == ADAPTIVE_CODING
  437.             && img->NumberofCodedMacroBlocks > 0 && (img->NumberofCodedMacroBlocks % img->BasicUnit) == 0 )
  438.             rc_copy_quadratic( quadratic_RC, quadratic_RC_init ); // restore initial RC status
  439.           if ( params->MbInterlace == ADAPTIVE_CODING )
  440.             rc_copy_generic( generic_RC, generic_RC_init ); // reset RC stats
  441.         }
  442.         start_macroblock (currSlice, &currMB, CurrentMbAddr, TRUE);
  443.         rdopt = &rddata_top_field_mb; // store data in top frame MB
  444.         //        TopFieldIsSkipped = 0;        // set the top field MB skipped flag to 0
  445.         img->masterQP = img->qp;
  446.         encode_one_macroblock (currMB);         // code the MB as field
  447.         FieldRDCost = rdopt->min_rdcost;
  448.         //***   Top MB coded as field MB ***//
  449.         //Rate control
  450.         img->bot_MB = TRUE;//for Rate control
  451.         img->top_field = FALSE;   // Set top field to 0
  452.         start_macroblock (currSlice, &currMB, CurrentMbAddr+1, TRUE);
  453.         rdopt = &rddata_bot_field_mb; // store data in top frame MB
  454.         img->masterQP = img->qp;
  455.         encode_one_macroblock (currMB);         // code the MB as field
  456.         FieldRDCost += rdopt->min_rdcost;
  457.         //***   Bottom MB coded as field MB ***//
  458.       }
  459.       //Rate control
  460.       img->write_mbaff_frame = 0;  //Rate control
  461.       //=========== decide between frame/field MB pair ============
  462.       //-----------------------------------------------------------
  463.       if ( ((params->MbInterlace == ADAPTIVE_CODING) && (FrameRDCost < FieldRDCost)) || params->MbInterlace == FRAME_MB_PAIR_CODING )
  464.       {
  465.         img->field_mode = FALSE;
  466.         MBPairIsField = FALSE;
  467.         if ( params->MbInterlace != FRAME_MB_PAIR_CODING )
  468.         {
  469.           img->buf_cycle >>= 1;
  470.           params->num_ref_frames >>= 1;
  471.           img->num_ref_idx_l0_active -= 1;
  472.           img->num_ref_idx_l0_active >>= 1;
  473.         }
  474.         if ( params->RCEnable && params->RCUpdateMode <= MAX_RC_MODE )
  475.         {
  476.           if ( params->MbInterlace == ADAPTIVE_CODING
  477.             && img->NumberofCodedMacroBlocks > 0 && (img->NumberofCodedMacroBlocks % img->BasicUnit) == 0 )
  478.             rc_copy_quadratic( quadratic_RC, quadratic_RC_best ); // restore initial RC status
  479.           if ( params->MbInterlace == ADAPTIVE_CODING )
  480.             rc_copy_generic( generic_RC, generic_RC_best ); // restore frame RC stats
  481.         }
  482.         //Rate control
  483.         img->write_mbaff_frame = 1;  //for Rate control
  484.       }
  485.       else
  486.       {
  487.         img->field_mode = TRUE;
  488.         MBPairIsField = TRUE;
  489.       }
  490.       //Rate control
  491.       img->write_macroblock = TRUE;//Rate control
  492.       if (MBPairIsField)
  493.         img->top_field = TRUE;
  494.       else
  495.         img->top_field = FALSE;
  496.       //Rate control
  497.       img->bot_MB = FALSE;// for Rate control
  498.       // go back to the Top MB in the MB pair
  499.       start_macroblock (currSlice, &currMB, CurrentMbAddr, img->field_mode);
  500.       rdopt =  img->field_mode ? &rddata_top_field_mb : &rddata_top_frame_mb;
  501.       copy_rdopt_data (currMB, 0);  // copy the MB data for Top MB from the temp buffers
  502.       write_one_macroblock (currMB, 1, prev_recode_mb);     // write the Top MB data to the bitstream
  503.       terminate_macroblock (currSlice, currMB, &end_of_slice, &recode_macroblock);     // done coding the Top MB
  504.       prev_recode_mb = recode_macroblock;
  505.       if (recode_macroblock == FALSE)       // The final processing of the macroblock has been done
  506.       {
  507.         img->SumFrameQP += currMB->qp;
  508.         CurrentMbAddr = FmoGetNextMBNr (CurrentMbAddr);
  509.         if (CurrentMbAddr == -1)   // end of slice
  510.         {
  511.           end_of_slice = TRUE;
  512.         }
  513.         NumberOfCodedMBs++;       // only here we are sure that the coded MB is actually included in the slice
  514.         proceed2nextMacroblock (currMB);
  515.         //Rate control
  516.         img->bot_MB = TRUE;//for Rate control
  517.         // go to the Bottom MB in the MB pair
  518.         img->top_field = FALSE;
  519.         start_macroblock (currSlice, &currMB, CurrentMbAddr, img->field_mode);
  520.         rdopt = img->field_mode ? &rddata_bot_field_mb : &rddata_bot_frame_mb;
  521.         copy_rdopt_data (currMB, 1);  // copy the MB data for Bottom MB from the temp buffers
  522.         write_one_macroblock (currMB, 0, prev_recode_mb);     // write the Bottom MB data to the bitstream
  523.         terminate_macroblock (currSlice, currMB, &end_of_slice, &recode_macroblock);     // done coding the Top MB
  524.         prev_recode_mb = recode_macroblock;
  525.         if (recode_macroblock == FALSE)       // The final processing of the macroblock has been done
  526.         {
  527.           img->SumFrameQP += currMB->qp;
  528.           CurrentMbAddr = FmoGetNextMBNr (CurrentMbAddr);
  529.           if (CurrentMbAddr == -1)   // end of slice
  530.           {
  531.             end_of_slice = TRUE;
  532.           }
  533.           NumberOfCodedMBs++;       // only here we are sure that the coded MB is actually included in the slice
  534.           proceed2nextMacroblock (currMB);
  535.         }
  536.         else
  537.         {
  538.           //Go back to the beginning of the macroblock pair to recode it
  539.           img->current_mb_nr = FmoGetPreviousMBNr(img->current_mb_nr);
  540.           img->current_mb_nr = FmoGetPreviousMBNr(img->current_mb_nr);
  541.           img->NumberofCodedMacroBlocks -= 2;
  542.           if(img->current_mb_nr == -1 )   // The first MB of the slice group  is too big,
  543.             // which means it's impossible to encode picture using current slice bits restriction
  544.           {
  545.             snprintf (errortext, ET_SIZE, "Error encoding first MB with specified parameter, bits of current MB may be too big");
  546.             error (errortext, 300);
  547.           }
  548.         }
  549.       }
  550.       else
  551.       {
  552.         //!Go back to the previous MB to recode it
  553.         img->current_mb_nr = FmoGetPreviousMBNr(img->current_mb_nr);
  554.         img->NumberofCodedMacroBlocks--;
  555.         if(img->current_mb_nr == -1 )   // The first MB of the slice group  is too big,
  556.           // which means it's impossible to encode picture using current slice bits restriction
  557.         {
  558.           snprintf (errortext, ET_SIZE, "Error encoding first MB with specified parameter, bits of current MB may be too big");
  559.           error (errortext, 300);
  560.         }
  561.       }
  562.       if (MBPairIsField)    // if MB Pair was coded as field the buffer size variables back to frame mode
  563.       {
  564.         img->buf_cycle >>= 1;
  565.         params->num_ref_frames >>= 1;
  566.         img->num_ref_idx_l0_active -= 1;
  567.         img->num_ref_idx_l0_active >>= 1;
  568.       }
  569.       img->field_mode = img->top_field = FALSE; // reset to frame mode
  570.       if ( !end_of_slice )
  571.       {
  572.         assert( CurrentMbAddr < (int)img->PicSizeInMbs );
  573.         assert( CurrentMbAddr >= 0 );
  574.         if (CurrentMbAddr == FmoGetLastCodedMBOfSliceGroup (FmoMB2SliceGroup (CurrentMbAddr)))
  575.           end_of_slice = TRUE;        // just in case it doesn't get set in terminate_macroblock
  576.       }
  577.     }
  578.   }
  579.   terminate_slice (currSlice, (NumberOfCodedMBs + TotalCodedMBs >= (int)img->PicSizeInMbs), cur_stats );
  580.   return NumberOfCodedMBs;
  581. }
  582. /*!
  583.  ************************************************************************
  584.  * brief
  585.  *    Initializes the parameters for a new slice and
  586.  *     allocates the memory for the coded slice in the Picture structure
  587.  *  par Side effects:
  588.  *      Adds slice/partition header symbols to the symbol buffer
  589.  *      increments Picture->no_slices, allocates memory for the
  590.  *      slice, sets img->currSlice
  591.  ************************************************************************
  592.  */
  593. void init_slice (Slice **currSlice, int start_mb_addr)
  594. {
  595.   int i,j;
  596.   Picture *currPic = img->currentPicture;
  597.   DataPartition *dataPart;
  598.   Bitstream *currStream;
  599.   int active_ref_lists = (img->MbaffFrameFlag) ? 6 : 2;
  600.   img->current_mb_nr = start_mb_addr;
  601.   // Allocate new Slice in the current Picture, and set img->currentSlice
  602.   assert (currPic != NULL);
  603.   currPic->no_slices++;
  604.   if (currPic->no_slices >= MAXSLICEPERPICTURE)
  605.     error ("Too many slices per picture, increase MAXSLICEPERPICTURE in global.h.", -1);
  606.   currPic->slices[currPic->no_slices-1] = malloc_slice();
  607.   *currSlice = currPic->slices[currPic->no_slices-1];
  608.   img->currentSlice = *currSlice;
  609.   (*currSlice)->picture_id    = img->tr % 256;
  610.   (*currSlice)->qp            = img->qp;
  611.   (*currSlice)->start_mb_nr   = start_mb_addr;
  612.   (*currSlice)->slice_too_big = dummy_slice_too_big;
  613.   for (i = 0; i < (*currSlice)->max_part_nr; i++)
  614.   {
  615.     dataPart = &(*currSlice)->partArr[i];
  616.     currStream = dataPart->bitstream;
  617.     currStream->bits_to_go = 8;
  618.     currStream->byte_pos = 0;
  619.     currStream->byte_buf = 0;
  620.   }
  621.   img->num_ref_idx_l0_active = active_pps->num_ref_idx_l0_active_minus1 + 1;
  622.   img->num_ref_idx_l1_active = active_pps->num_ref_idx_l1_active_minus1 + 1;
  623.   // primary and redundant slices: number of references overriding.
  624.   if(params->redundant_pic_flag)
  625.   {
  626.     if(!redundant_coding)
  627.     {
  628.       img->num_ref_idx_l0_active = imin(img->number,params->NumRefPrimary);
  629.     }
  630.     else
  631.     {
  632.       // 1 reference picture for redundant slices
  633.       img->num_ref_idx_l0_active = 1;
  634.     }
  635.   }
  636.   // code now also considers fields. Issue whether we should account this within the appropriate input params directly
  637.   if ((img->type == P_SLICE || img->type == SP_SLICE) && params->P_List0_refs)
  638.   {
  639.     img->num_ref_idx_l0_active = imin(img->num_ref_idx_l0_active, params->P_List0_refs * ((img->structure !=0) + 1));
  640.   }
  641.   if (img->type == B_SLICE )
  642.   {
  643.     if (params->B_List0_refs)
  644.     {
  645.       img->num_ref_idx_l0_active = imin(img->num_ref_idx_l0_active, params->B_List0_refs * ((img->structure !=0) + 1));
  646.     }
  647.     if (params->B_List1_refs)
  648.     {
  649.       img->num_ref_idx_l1_active = imin(img->num_ref_idx_l1_active, params->B_List1_refs * ((img->structure !=0) + 1));
  650.     }
  651.   }
  652.   // generate reference picture lists
  653.   init_lists(img->type, (PictureStructure) img->structure);
  654.   // assign list 0 size from list size
  655.   img->num_ref_idx_l0_active = listXsize[0];
  656.   img->num_ref_idx_l1_active = listXsize[1];
  657.   if ( params->WPMCPrecision && params->WPMCPrecFullRef )
  658.   {
  659.     wpxAdaptRefNum(img);
  660.   }
  661.   //Perform memory management based on poc distances  
  662.   if (img->nal_reference_idc && params->PocMemoryManagement)
  663.   {
  664.     if (img->structure == FRAME && dpb.ref_frames_in_buffer==active_sps->num_ref_frames)
  665.     {
  666.       poc_based_ref_management_frame_pic(img->frame_num);
  667.     }
  668.     else if (img->structure == TOP_FIELD && dpb.ref_frames_in_buffer==active_sps->num_ref_frames)
  669.     {
  670.       poc_based_ref_management_field_pic((img->frame_num << 1) + 1);      
  671.     }
  672.     else if (img->structure == BOTTOM_FIELD)
  673.       poc_based_ref_management_field_pic((img->frame_num << 1) + 1);
  674.   }
  675.   if (params->EnableOpenGOP)
  676.   {
  677.     for (i = 0; i<listXsize[0]; i++)
  678.     {
  679.       if (listX[0][i]->poc < img->last_valid_reference && img->ThisPOC > img->last_valid_reference)
  680.       {
  681.         listXsize[0] = img->num_ref_idx_l0_active = imax(1, i);
  682.         break;
  683.       }
  684.     }
  685.     for (i = 0; i<listXsize[1]; i++)
  686.     {
  687.       if (listX[1][i]->poc < img->last_valid_reference && img->ThisPOC > img->last_valid_reference)
  688.       {
  689.         listXsize[1] = img->num_ref_idx_l1_active = imax(1,i);
  690.         break;
  691.       }
  692.     }
  693.   }
  694.   init_ref_pic_list_reordering(*currSlice);
  695.  
  696.   // reference list reordering 
  697.   if ( (img->type == P_SLICE || img->type == B_SLICE) && 
  698.     params->WPMCPrecision && pWPX->curr_wp_rd_pass->algorithm != WP_REGULAR )
  699.   {
  700.     wpxReorderLists( img, *currSlice );
  701.   }
  702.   else
  703.   {
  704.     // Perform reordering based on poc distances for HierarchicalCoding
  705.     if ( img->type == P_SLICE && params->ReferenceReorder)
  706.     {
  707.       int i, num_ref;
  708.       alloc_ref_pic_list_reordering_buffer(*currSlice);
  709.       for (i = 0; i < img->num_ref_idx_l0_active + 1; i++)
  710.       {
  711.         (*currSlice)->reordering_of_pic_nums_idc_l0[i] = 3;
  712.         (*currSlice)->abs_diff_pic_num_minus1_l0[i] = 0;
  713.         (*currSlice)->long_term_pic_idx_l0[i] = 0;
  714.       }
  715.       num_ref = img->num_ref_idx_l0_active;
  716.       if ( img->structure == FRAME )
  717.         poc_ref_pic_reorder_frame(listX[LIST_0], num_ref,
  718.         (*currSlice)->reordering_of_pic_nums_idc_l0,
  719.         (*currSlice)->abs_diff_pic_num_minus1_l0,
  720.         (*currSlice)->long_term_pic_idx_l0, LIST_0);
  721.       else
  722.       {
  723.         poc_ref_pic_reorder_field(listX[LIST_0], num_ref,
  724.           (*currSlice)->reordering_of_pic_nums_idc_l0,
  725.           (*currSlice)->abs_diff_pic_num_minus1_l0,
  726.           (*currSlice)->long_term_pic_idx_l0, LIST_0);
  727.       }
  728.       //reference picture reordering
  729.       reorder_ref_pic_list(listX[LIST_0], &listXsize[LIST_0],
  730.         img->num_ref_idx_l0_active - 1,
  731.         (*currSlice)->reordering_of_pic_nums_idc_l0,
  732.         (*currSlice)->abs_diff_pic_num_minus1_l0,
  733.         (*currSlice)->long_term_pic_idx_l0);
  734.     }
  735.   }
  736.   //if (img->MbaffFrameFlag)
  737.   if (img->structure==FRAME)
  738.     init_mbaff_lists();
  739.   InitWP(params);
  740.   if (img->type != I_SLICE && (active_pps->weighted_pred_flag == 1 || (active_pps->weighted_bipred_idc > 0 && (img->type == B_SLICE))))
  741.   {
  742.     if (img->type==P_SLICE || img->type==SP_SLICE)
  743.     {
  744.       int wp_type = (params->GenerateMultiplePPS && params->RDPictureDecision) && (enc_picture != enc_frame_picture[1]);
  745.       EstimateWPPSlice (img, params, wp_type);
  746.     }
  747.     else
  748.       EstimateWPBSlice (img, params);
  749.   }
  750.   set_ref_pic_num();
  751.   if (img->type == B_SLICE)
  752.   {
  753.     if( IS_INDEPENDENT(params) )
  754.     {
  755.       compute_colocated_JV(Co_located, listX);
  756.     }
  757.     else
  758.     {
  759.       compute_colocated(Co_located, listX);
  760.     }
  761.   }
  762.   if (img->type != I_SLICE && params->SearchMode == EPZS)
  763.     EPZSSliceInit(params, img, EPZSCo_located, listX);
  764.   if ((*currSlice)->symbol_mode == CAVLC)
  765.   {
  766.     writeMB_typeInfo       = writeSE_UVLC;
  767.     writeIntraPredMode     = writeIntraPredMode_CAVLC;
  768.     writeB8_typeInfo       = writeSE_UVLC;
  769.     for (i=0; i<6; i++)
  770.     {
  771.       switch (listXsize[i])
  772.       {
  773.       case 0:
  774.         writeRefFrame[i]   = NULL;
  775.         break;
  776.       case 1:
  777.         writeRefFrame[i]   = writeSE_Dummy;
  778.         break;
  779.       case 2:
  780.         writeRefFrame[i]   = writeSE_invFlag;
  781.         break;
  782.       default:
  783.         writeRefFrame[i]   = writeSE_UVLC;
  784.         break;
  785.       }
  786.     }
  787.     writeMVD               = writeSE_SVLC;
  788.     writeCBP               = writeCBP_VLC;
  789.     writeDquant            = writeSE_SVLC;
  790.     writeCIPredMode        = writeSE_UVLC;
  791.     writeFieldModeInfo     = writeSE_Flag;
  792.     writeMB_transform_size = writeSE_Flag;
  793.   }
  794.   else
  795.   {
  796.     writeMB_typeInfo       = writeMB_typeInfo_CABAC;
  797.     writeIntraPredMode     = writeIntraPredMode_CABAC;
  798.     writeB8_typeInfo       = writeB8_typeInfo_CABAC;
  799.     for (i=0; i<6; i++)
  800.     {
  801.       switch (listXsize[i])
  802.       {
  803.       case 0:
  804.         writeRefFrame[i]   = NULL;
  805.       case 1:
  806.         writeRefFrame[i]   = writeSE_Dummy;
  807.         break;
  808.       default:
  809.         writeRefFrame[i]   = writeRefFrame_CABAC;
  810.       }
  811.     }
  812.     writeMVD               = writeMVD_CABAC;
  813.     writeCBP               = writeCBP_CABAC;
  814.     writeDquant            = writeDquant_CABAC;
  815.     writeCIPredMode        = writeCIPredMode_CABAC;
  816.     writeFieldModeInfo     = writeFieldModeInfo_CABAC;
  817.     writeMB_transform_size = writeMB_transform_size_CABAC;
  818.   }
  819.   // assign luma common reference picture pointers to be used for ME/sub-pel interpolation
  820.   for(i = 0; i < active_ref_lists; i++)
  821.   {
  822.     for(j = 0; j < listXsize[i]; j++)
  823.     {
  824.       if( listX[i][j] )
  825.       {
  826.         listX[i][j]->p_curr_img     = listX[i][j]->p_img    [img->colour_plane_id];
  827.         listX[i][j]->p_curr_img_sub = listX[i][j]->p_img_sub[img->colour_plane_id];
  828.       }
  829.     }
  830.   }
  831.   if (params->UseRDOQuant)
  832.     init_rdoq_slice(img->type, (*currSlice)->symbol_mode);
  833. }
  834. /*!
  835.  ************************************************************************
  836.  * brief
  837.  *    Allocates a slice structure along with its dependent data structures
  838.  * return
  839.  *    Pointer to a Slice
  840.  ************************************************************************
  841.  */
  842. static Slice *malloc_slice()
  843. {
  844.   int i;
  845.   DataPartition *dataPart;
  846.   Slice *slice;
  847.   int cr_size = IS_INDEPENDENT( params ) ? 0 : 512;
  848. //  const int buffer_size = (img->size * 4); // AH 190202: There can be data expansion with
  849.                                                           // low QP values. So, we make sure that buffer
  850.                                                           // does not overflow. 4 is probably safe multiplier.
  851.   int buffer_size;
  852.   switch (params->slice_mode)
  853.   {
  854.   case 2:
  855.     //buffer_size = imax(2 * params->slice_argument, 500 + (128 + 256 * img->bitdepth_luma + 512 * img->bitdepth_chroma));
  856.     buffer_size = imax(2 * params->slice_argument, 764);
  857.     break;
  858.   case 1:
  859.     buffer_size = 500 + params->slice_argument * (128 + 256 * img->bitdepth_luma + cr_size * img->bitdepth_chroma);
  860.     break;
  861.   default:
  862.     buffer_size = 500 + img->FrameSizeInMbs * (128 + 256 * img->bitdepth_luma + cr_size * img->bitdepth_chroma);
  863.     break;
  864.   }
  865.   // KS: this is approx. max. allowed code picture size
  866.   if ((slice = (Slice *) calloc(1, sizeof(Slice))) == NULL) no_mem_exit ("malloc_slice: slice structure");
  867.   slice->symbol_mode  = params->symbol_mode;
  868.   cs_mb->symbol_mode  = params->symbol_mode;
  869.   cs_b8->symbol_mode  = params->symbol_mode;
  870.   cs_cm->symbol_mode  = params->symbol_mode;
  871.   cs_ib8->symbol_mode = params->symbol_mode;
  872.   cs_ib4->symbol_mode = params->symbol_mode;
  873.   if (slice->symbol_mode == CABAC)
  874.   {
  875.     // create all context models
  876.     slice->mot_ctx = create_contexts_MotionInfo();
  877.     slice->tex_ctx = create_contexts_TextureInfo();
  878.   }
  879.   slice->max_part_nr = params->partition_mode==0?1:3;
  880.   //for IDR img there should be only one partition
  881.   if(img->currentPicture->idr_flag)
  882.     slice->max_part_nr = 1;
  883.   assignSE2partition[0] = assignSE2partition_NoDP;
  884.   //ZL
  885.   //for IDR img all the syntax element should be mapped to one partition
  886.   if(!img->currentPicture->idr_flag && params->partition_mode == 1)
  887.     assignSE2partition[1] =  assignSE2partition_DP;
  888.   else
  889.     assignSE2partition[1] =  assignSE2partition_NoDP;
  890.   slice->num_mb = 0;          // no coded MBs so far
  891.   if ((slice->partArr = (DataPartition *) calloc(slice->max_part_nr, sizeof(DataPartition))) == NULL) 
  892.     no_mem_exit ("malloc_slice: partArr");
  893.   for (i=0; i<slice->max_part_nr; i++) // loop over all data partitions
  894.   {
  895.     dataPart = &(slice->partArr[i]);
  896.     if ((dataPart->bitstream = (Bitstream *) calloc(1, sizeof(Bitstream))) == NULL) 
  897.       no_mem_exit ("malloc_slice: Bitstream");
  898.     if ((dataPart->bitstream->streamBuffer = (byte *) calloc(buffer_size, sizeof(byte))) == NULL) 
  899.       no_mem_exit ("malloc_slice: StreamBuffer");
  900.     // Initialize storage of bitstream parameters
  901.   }
  902.   return slice;
  903. }
  904. /*!
  905.  ************************************************************************
  906.  * brief
  907.  *    This function frees nal units
  908.  *
  909.  ************************************************************************
  910.  */
  911. static void free_nal_unit(Picture *pic)
  912. {
  913.   int partition, slice;
  914.   Slice  *currSlice;
  915.   // loop over all slices of the picture
  916.   for (slice=0; slice < pic->no_slices; slice++)
  917.   {
  918.     currSlice = pic->slices[slice];
  919.     // loop over the partitions
  920.     if (currSlice != NULL)
  921.     {
  922.       for (partition=0; partition < currSlice->max_part_nr; partition++)
  923.       {
  924.         // free only if the partition has content
  925.         if (currSlice->partArr[partition].bitstream->write_flag )
  926.         {
  927.           if (currSlice->partArr[partition].nal_unit != NULL)
  928.           {
  929.             FreeNALU(currSlice->partArr[partition].nal_unit);
  930.             currSlice->partArr[partition].nal_unit = NULL;
  931.           }
  932.         }
  933.       }
  934.     }
  935.   }
  936. }
  937. /*!
  938.  ************************************************************************
  939.  * brief
  940.  *    Memory frees of all Slice structures and of its dependent
  941.  *    data structures
  942.  * par Input:
  943.  *    Image Parameters struct struct img_par *img
  944.  ************************************************************************
  945.  */
  946. void free_slice_list(Picture *currPic)
  947. {
  948.   int i;
  949.   free_nal_unit(currPic);
  950.   for (i = 0; i < currPic->no_slices; i++)
  951.   {
  952.     free_slice (currPic->slices[i]);
  953.     currPic->slices[i]=NULL;
  954.   }
  955. }
  956. /*!
  957.  ************************************************************************
  958.  * brief
  959.  *    Memory frees of the Slice structure and of its dependent
  960.  *    data structures
  961.  * param slice:
  962.  *    Slice to be freed
  963.  ************************************************************************
  964.  */
  965. static void free_slice(Slice *slice)
  966. {
  967.   int i;
  968.   DataPartition *dataPart;
  969.   if (slice != NULL)
  970.   {
  971.     for (i=0; i<slice->max_part_nr; i++) // loop over all data partitions
  972.     {
  973.       dataPart = &(slice->partArr[i]);
  974.       if (dataPart != NULL)
  975.       {
  976.          if (dataPart->bitstream != NULL)
  977.          {
  978.            if (dataPart->bitstream->streamBuffer != NULL)
  979.              free(dataPart->bitstream->streamBuffer);       
  980.            free(dataPart->bitstream);
  981.          }
  982.       }
  983.     }
  984.     if (slice->partArr != NULL)
  985.       free(slice->partArr);
  986.     
  987.     if (slice->symbol_mode == CABAC)
  988.     {
  989.       delete_contexts_MotionInfo(slice->mot_ctx);
  990.       delete_contexts_TextureInfo(slice->tex_ctx);
  991.     }
  992.     free(slice);
  993.   }
  994. }
  995. static void set_ref_pic_num()
  996. {
  997.   int i,j;
  998.   StorablePicture *this_ref;
  999.   //! need to add field ref_pic_num that handles field pair.
  1000.   for (i=0;i<listXsize[LIST_0];i++)
  1001.   {
  1002.     this_ref = listX[LIST_0][i];
  1003.     enc_picture->ref_pic_num        [LIST_0][i] = this_ref->poc * 2 + ((this_ref->structure==BOTTOM_FIELD)?1:0) ;
  1004.     enc_picture->frm_ref_pic_num    [LIST_0][i] = this_ref->frame_poc * 2;
  1005.     enc_picture->top_ref_pic_num    [LIST_0][i] = this_ref->top_poc * 2;
  1006.     enc_picture->bottom_ref_pic_num [LIST_0][i] = this_ref->bottom_poc * 2 + 1;
  1007.   }
  1008.   for (i=0;i<listXsize[LIST_1];i++)
  1009.   {
  1010.     this_ref = listX[LIST_1][i];
  1011.     enc_picture->ref_pic_num        [LIST_1][i] = this_ref->poc * 2 + ((this_ref->structure==BOTTOM_FIELD)?1:0);
  1012.     enc_picture->frm_ref_pic_num    [LIST_1][i] = this_ref->frame_poc * 2;
  1013.     enc_picture->top_ref_pic_num    [LIST_1][i] = this_ref->top_poc * 2;
  1014.     enc_picture->bottom_ref_pic_num [LIST_1][i] = this_ref->bottom_poc * 2 + 1;
  1015.   }
  1016.   if (!active_sps->frame_mbs_only_flag && img->structure==FRAME)
  1017.   {
  1018.     for (j=2;j<6;j++)
  1019.       for (i=0;i<listXsize[j];i++)
  1020.       {
  1021.         this_ref = listX[j][i];
  1022.         enc_picture->ref_pic_num[j][i] = this_ref->poc * 2 + ((this_ref->structure==BOTTOM_FIELD)?1:0);
  1023.         enc_picture->frm_ref_pic_num[j][i] = this_ref->frame_poc * 2 ;
  1024.         enc_picture->top_ref_pic_num[j][i] = this_ref->top_poc * 2 ;
  1025.         enc_picture->bottom_ref_pic_num[j][i] = this_ref->bottom_poc * 2 + 1;
  1026.       }
  1027.   }
  1028. }
  1029. /*!
  1030. ************************************************************************
  1031. * brief
  1032. *    decide reference picture reordering, Frame only
  1033. ************************************************************************
  1034. */
  1035. void poc_ref_pic_reorder_frame(StorablePicture **list, unsigned num_ref_idx_lX_active, int *reordering_of_pic_nums_idc, int *abs_diff_pic_num_minus1, int *long_term_pic_idx, int list_no)
  1036. {
  1037.   unsigned int i,j,k;
  1038.   int currPicNum, picNumLXPred;
  1039.   int default_order[32];
  1040.   int re_order[32];
  1041.   int tmp_reorder[32];
  1042.   int list_sign[32];
  1043.   int reorder_stop, no_reorder;
  1044.   int poc_diff[32];
  1045.   int tmp_value, diff;
  1046.   int abs_poc_dist;
  1047.   int maxPicNum;
  1048.   unsigned int numRefs;
  1049.   maxPicNum  = max_frame_num;
  1050.   currPicNum = img->frame_num;
  1051.   picNumLXPred = currPicNum;
  1052.   // First assign default list order.
  1053.   for (i=0; i<num_ref_idx_lX_active; i++)
  1054.   {
  1055.     default_order[i] = list[i]->pic_num;
  1056.   }
  1057.   // Now access all references in buffer and assign them
  1058.   // to a potential reordering list. For each one of these
  1059.   // references compute the poc distance compared to current
  1060.   // frame.
  1061.   numRefs = dpb.ref_frames_in_buffer;
  1062.   for (i=0; i<dpb.ref_frames_in_buffer; i++)
  1063.   {
  1064.     poc_diff[i] = 0xFFFF;
  1065.     re_order[i] = dpb.fs_ref[i]->frame->pic_num;
  1066.     if (dpb.fs_ref[i]->is_used==3 && (dpb.fs_ref[i]->frame->used_for_reference)&&(!dpb.fs_ref[i]->frame->is_long_term))
  1067.     {
  1068.       abs_poc_dist = iabs(dpb.fs_ref[i]->frame->poc - enc_picture->poc) ;
  1069.       poc_diff[i] = abs_poc_dist;
  1070.       if (list_no == LIST_0)
  1071.       {
  1072.         list_sign[i] = (enc_picture->poc < dpb.fs_ref[i]->frame->poc) ? +1 : -1;
  1073.       }
  1074.       else
  1075.       {
  1076.         list_sign[i] = (enc_picture->poc > dpb.fs_ref[i]->frame->poc) ? +1 : -1;
  1077.       }
  1078.     }
  1079.   }
  1080.   // now sort these references based on poc (temporal) distance
  1081.   for (i = 0; i< numRefs - 1; i++)
  1082.   {
  1083.     for (j = i + 1; j < numRefs; j++)
  1084.     {
  1085.       if (poc_diff[i]>poc_diff[j] || (poc_diff[i] == poc_diff[j] && list_sign[j] > list_sign[i]))
  1086.       {
  1087.         tmp_value = poc_diff[i];
  1088.         poc_diff[i] = poc_diff[j];
  1089.         poc_diff[j] = tmp_value;
  1090.         tmp_value  = re_order[i];
  1091.         re_order[i] = re_order[j];
  1092.         re_order[j] = tmp_value ;
  1093.         tmp_value  = list_sign[i];
  1094.         list_sign[i] = list_sign[j];
  1095.         list_sign[j] = tmp_value ;
  1096.       }
  1097.     }
  1098.   }
  1099.   // populate list with selections from the pre-analysis stage
  1100.   if ( params->WPMCPrecision 
  1101.     && pWPX->curr_wp_rd_pass->algorithm != WP_REGULAR
  1102.     && pWPX->num_wp_ref_list[list_no] )
  1103.   {
  1104.     for (i=0; i<num_ref_idx_lX_active; i++)
  1105.     {
  1106.       re_order[i] = pWPX->wp_ref_list[list_no][i].PicNum;
  1107.     }
  1108.   }
  1109.   // Check versus default list to see if any
  1110.   // change has happened
  1111.   no_reorder = 1;
  1112.   for (i=0; i<num_ref_idx_lX_active; i++)
  1113.   {
  1114.     if (default_order[i] != re_order[i])
  1115.     {
  1116.       no_reorder = 0;
  1117.     }
  1118.   }
  1119.   // If different, then signal reordering
  1120.   if (no_reorder==0)
  1121.   {
  1122.     for (i=0; i<num_ref_idx_lX_active; i++)
  1123.     {
  1124.       diff = re_order[i]-picNumLXPred;
  1125.       if (diff <= 0)
  1126.       {
  1127.         reordering_of_pic_nums_idc[i] = 0;
  1128.         abs_diff_pic_num_minus1[i] = iabs(diff)-1;
  1129.         if (abs_diff_pic_num_minus1[i] < 0)
  1130.           abs_diff_pic_num_minus1[i] = maxPicNum -1;
  1131.       }
  1132.       else
  1133.       {
  1134.         reordering_of_pic_nums_idc[i] = 1;
  1135.         abs_diff_pic_num_minus1[i] = iabs(diff)-1;
  1136.       }
  1137.       picNumLXPred = re_order[i];
  1138.       tmp_reorder[i] = re_order[i];
  1139.       k = i;
  1140.       for (j=i; j<num_ref_idx_lX_active; j++)
  1141.       {
  1142.         if (default_order[j] != re_order[i])
  1143.         {
  1144.           ++k;
  1145.           tmp_reorder[k] = default_order[j];
  1146.         }
  1147.       }
  1148.       reorder_stop = 1;
  1149.       for(j=i+1; j<num_ref_idx_lX_active; j++)
  1150.       {
  1151.         if (tmp_reorder[j] != re_order[j])
  1152.         {
  1153.           reorder_stop = 0;
  1154.           break;
  1155.         }
  1156.       }
  1157.       if (reorder_stop==1)
  1158.       {
  1159.         ++i;
  1160.         break;
  1161.       }
  1162.       memcpy ( default_order, tmp_reorder, num_ref_idx_lX_active * sizeof(int));
  1163.     }
  1164.     reordering_of_pic_nums_idc[i] = 3;
  1165.     memcpy ( default_order, tmp_reorder, num_ref_idx_lX_active * sizeof(int));
  1166.     if (list_no==0)
  1167.     {
  1168.       img->currentSlice->ref_pic_list_reordering_flag_l0=1;
  1169.     }
  1170.     else
  1171.     {
  1172.       img->currentSlice->ref_pic_list_reordering_flag_l1=1;
  1173.     }
  1174.   }
  1175. }
  1176. /*!
  1177. ************************************************************************
  1178. * brief
  1179. *    decide reference picture reordering, Field only
  1180. ************************************************************************
  1181. */
  1182. void poc_ref_pic_reorder_field(StorablePicture **list, unsigned num_ref_idx_lX_active, int *reordering_of_pic_nums_idc, int *abs_diff_pic_num_minus1, int *long_term_pic_idx, int list_no)
  1183. {
  1184.   unsigned int i,j,k;
  1185.   int currPicNum, picNumLXPred;
  1186.   int default_order[32];
  1187.   int re_order[32];
  1188.   int tmp_reorder[32];
  1189.   int list_sign[32];  
  1190.   int poc_diff[32];
  1191.   int fld_type[32];
  1192.   int reorder_stop, no_reorder;
  1193.   int tmp_value, diff;
  1194.   int abs_poc_dist;
  1195.   int maxPicNum;
  1196.   unsigned int numRefs;
  1197.   int field_used[2] = {1, 2};
  1198.   int fld, idx, num_flds;
  1199.   unsigned int top_idx = 0;
  1200.   unsigned int bot_idx = 0;
  1201.   unsigned int list_size = 0;
  1202.   StorablePicture *pField[2]; // 0: TOP_FIELD, 1: BOTTOM_FIELD
  1203.   FrameStore      *pFrameStore; 
  1204.   maxPicNum  = 2 * max_frame_num;
  1205.   currPicNum = 2 * img->frame_num + 1;
  1206.   picNumLXPred = currPicNum;
  1207.   // First assign default list order.
  1208.   for (i=0; i<num_ref_idx_lX_active; i++)
  1209.   {
  1210.     default_order[i] = list[i]->pic_num;
  1211.   }
  1212.   // Now access all references in buffer and assign them
  1213.   // to a potential reordering list. For each one of these
  1214.   // references compute the poc distance compared to current
  1215.   // frame.  
  1216.   // look for eligible fields
  1217.   idx = 0;
  1218.   for (i=0; i<dpb.ref_frames_in_buffer; i++)
  1219.   {
  1220.     pFrameStore = dpb.fs_ref[i];
  1221.     pField[0]   = pFrameStore->top_field;
  1222.     pField[1]   = pFrameStore->bottom_field;
  1223.     num_flds    = (img->structure == BOTTOM_FIELD && (enc_picture->poc == (pField[0]->poc + 1) ) ) ? 1 : 2;
  1224.     poc_diff[2*i    ] = 0xFFFF;
  1225.     poc_diff[2*i + 1] = 0xFFFF;
  1226.     for ( fld = 0; fld < num_flds; fld++ )
  1227.     {
  1228.       if ( (pFrameStore->is_used & field_used[fld]) && pField[fld]->used_for_reference && !(pField[fld]->is_long_term) )
  1229.       {
  1230.         abs_poc_dist = iabs(pField[fld]->poc - enc_picture->poc) ;
  1231.         poc_diff[idx] = abs_poc_dist;
  1232.         re_order[idx] = pField[fld]->pic_num;
  1233.         fld_type[idx] = fld + 1;
  1234.         if (list_no == LIST_0)
  1235.         {
  1236.           list_sign[idx] = (enc_picture->poc < pField[fld]->poc) ? +1 : -1;
  1237.         }
  1238.         else
  1239.         {
  1240.           list_sign[idx] = (enc_picture->poc > pField[fld]->poc) ? +1 : -1;
  1241.         }
  1242.         idx++;
  1243.       }
  1244.     }
  1245.   }
  1246.   numRefs = idx;
  1247.   // now sort these references based on poc (temporal) distance
  1248.   for (i=0; i < numRefs-1; i++)
  1249.   {
  1250.     for (j = (i + 1); j < numRefs; j++)
  1251.     {
  1252.       if (poc_diff[i] > poc_diff[j] || (poc_diff[i] == poc_diff[j] && list_sign[j] > list_sign[i]))
  1253.       {
  1254.         // poc_diff
  1255.         tmp_value   = poc_diff[i];
  1256.         poc_diff[i] = poc_diff[j];
  1257.         poc_diff[j] = tmp_value;
  1258.         // re_order (PicNum)
  1259.         tmp_value   = re_order[i];
  1260.         re_order[i] = re_order[j];
  1261.         re_order[j] = tmp_value;
  1262.         // list_sign
  1263.         tmp_value    = list_sign[i];
  1264.         list_sign[i] = list_sign[j];
  1265.         list_sign[j] = tmp_value;
  1266.         // fld_type
  1267.         tmp_value   = fld_type[i];
  1268.         fld_type[i] = fld_type[j];
  1269.         fld_type[j] = tmp_value ;
  1270.       }
  1271.     }
  1272.   }
  1273.   if (img->structure == TOP_FIELD)
  1274.   {
  1275.     while ((top_idx < numRefs)||(bot_idx < numRefs))
  1276.     {
  1277.       for ( ; top_idx < numRefs; top_idx++)
  1278.       {
  1279.         if ( fld_type[top_idx] == TOP_FIELD )
  1280.         {
  1281.           tmp_reorder[list_size] = re_order[top_idx];
  1282.           list_size++;
  1283.           top_idx++;
  1284.           break;
  1285.         }
  1286.       }
  1287.       for ( ; bot_idx < numRefs; bot_idx++)
  1288.       {
  1289.         if ( fld_type[bot_idx] == BOTTOM_FIELD )
  1290.         {
  1291.           tmp_reorder[list_size] = re_order[bot_idx];
  1292.           list_size++;
  1293.           bot_idx++;
  1294.           break;
  1295.         }
  1296.       }
  1297.     }
  1298.   }
  1299.   if (img->structure == BOTTOM_FIELD)
  1300.   {
  1301.     while ((top_idx < numRefs)||(bot_idx < numRefs))
  1302.     {
  1303.       for ( ; bot_idx < numRefs; bot_idx++)
  1304.       {
  1305.         if ( fld_type[bot_idx] == BOTTOM_FIELD )
  1306.         {
  1307.           tmp_reorder[list_size] = re_order[bot_idx];
  1308.           list_size++;
  1309.           bot_idx++;
  1310.           break;
  1311.         }
  1312.       }
  1313.       for ( ; top_idx < numRefs; top_idx++)
  1314.       {
  1315.         if ( fld_type[top_idx] == TOP_FIELD )
  1316.         {
  1317.           tmp_reorder[list_size] = re_order[top_idx];
  1318.           list_size++;
  1319.           top_idx++;
  1320.           break;
  1321.         }
  1322.       }
  1323.     }
  1324.   }
  1325.   // copy to final matrix
  1326.   list_size = imin( list_size, 32 );
  1327.   for ( i = 0; i < list_size; i++ )
  1328.   {
  1329.     re_order[i] = tmp_reorder[i];
  1330.   }
  1331.   // Check versus default list to see if any
  1332.   // change has happened
  1333.   no_reorder = 1;
  1334.   for (i=0; i<num_ref_idx_lX_active; i++)
  1335.   {
  1336.     if (default_order[i] != re_order[i])
  1337.     {
  1338.       no_reorder = 0;
  1339.     }
  1340.   }
  1341.   // If different, then signal reordering
  1342.   if (no_reorder == 0)
  1343.   {
  1344.     for (i=0; i<num_ref_idx_lX_active; i++)
  1345.     {
  1346.       diff = re_order[i] - picNumLXPred;
  1347.       if (diff <= 0)
  1348.       {
  1349.         reordering_of_pic_nums_idc[i] = 0;
  1350.         abs_diff_pic_num_minus1[i] = iabs(diff)-1;
  1351.         if (abs_diff_pic_num_minus1[i] < 0)
  1352.           abs_diff_pic_num_minus1[i] = maxPicNum -1;
  1353.       }
  1354.       else
  1355.       {
  1356.         reordering_of_pic_nums_idc[i] = 1;
  1357.         abs_diff_pic_num_minus1[i] = iabs(diff)-1;
  1358.       }
  1359.       picNumLXPred = re_order[i];
  1360.       tmp_reorder[i] = re_order[i];
  1361.       k = i;
  1362.       for (j = i; j < num_ref_idx_lX_active; j++)
  1363.       {
  1364.         if (default_order[j] != re_order[i])
  1365.         {
  1366.           ++k;
  1367.           tmp_reorder[k] = default_order[j];
  1368.         }
  1369.       }
  1370.       reorder_stop = 1;
  1371.       for(j=i+1; j<num_ref_idx_lX_active; j++)
  1372.       {
  1373.         if (tmp_reorder[j] != re_order[j])
  1374.         {
  1375.           reorder_stop = 0;
  1376.           break;
  1377.         }
  1378.       }
  1379.       if (reorder_stop==1)
  1380.       {
  1381.         ++i;
  1382.         break;
  1383.       }
  1384.       memcpy ( default_order, tmp_reorder, num_ref_idx_lX_active * sizeof(int));
  1385.     }
  1386.     reordering_of_pic_nums_idc[i] = 3;
  1387.     memcpy ( default_order, tmp_reorder, num_ref_idx_lX_active * sizeof(int));
  1388.     if (list_no==0)
  1389.     {
  1390.       img->currentSlice->ref_pic_list_reordering_flag_l0 = 1;
  1391.     }
  1392.     else
  1393.     {
  1394.       img->currentSlice->ref_pic_list_reordering_flag_l1 = 1;
  1395.     }
  1396.   }
  1397. }
  1398. void UpdateMELambda(ImageParameters *img)
  1399. {
  1400.   int j, k, qp;
  1401.   if (params->UpdateLambdaChromaME)
  1402.   {
  1403.     for (j = 0; j < 6; j++)
  1404.     {
  1405.       for (qp = -img->bitdepth_luma_qp_scale; qp < 52; qp++)
  1406.       { 
  1407.         for (k = 0; k < 3; k++)
  1408.         {
  1409.           if ((params->MEErrorMetric[k] == ERROR_SAD) && (params->ChromaMEEnable))
  1410.           {
  1411.             switch(params->yuv_format)
  1412.             {
  1413.             case YUV420:
  1414.               img->lambda_mf[j][qp][k] = (3 * img->lambda_mf[j][qp][k] + 1) >> 1;
  1415.               img->lambda_me[j][qp][k] *= 1.5;
  1416.               break;
  1417.             case YUV422:
  1418.               img->lambda_mf[j][qp][k] *= 2;
  1419.               img->lambda_me[j][qp][k] *= 2.0;
  1420.               break;
  1421.             case YUV444:
  1422.               img->lambda_mf[j][qp][k] *= 3;
  1423.               img->lambda_me[j][qp][k] *= 3.0;
  1424.               break;
  1425.             default:
  1426.               break;
  1427.             }
  1428.           }
  1429.         }
  1430.       }
  1431.     }
  1432.   }
  1433. }
  1434. void SetLambda(int j, int qp, double lambda_scale)
  1435. {
  1436.   int k;
  1437.   img->lambda_md[j][qp] *= lambda_scale;
  1438.   for (k = F_PEL; k <= Q_PEL; k++)
  1439.   {
  1440.     img->lambda_me[j][qp][k] =  (params->MEErrorMetric[k] == ERROR_SSE) ? img->lambda_md[j][qp] : sqrt(img->lambda_md[j][qp]);
  1441.     img->lambda_mf[j][qp][k] = LAMBDA_FACTOR (img->lambda_me[j][qp][k]);
  1442.   }
  1443. }
  1444. void SetLagrangianMultipliersOn()
  1445. {
  1446.   int qp, j;
  1447.   double qp_temp;
  1448.   double lambda_scale = 1.0 - dClip3(0.0,0.5,0.05 * (double) params->jumpd);;
  1449.   if (params->UseExplicitLambdaParams == 1) // consideration of explicit lambda weights.
  1450.   {
  1451.     for (j = 0; j < 6; j++)
  1452.     {
  1453.       for (qp = -img->bitdepth_luma_qp_scale; qp < 52; qp++)
  1454.       {
  1455.         qp_temp = (double)qp + img->bitdepth_luma_qp_scale - SHIFT_QP;
  1456.         img->lambda_md[j][qp] = params->LambdaWeight[j] * pow (2, qp_temp/3.0);
  1457.         SetLambda(j, qp, ((params->MEErrorMetric[H_PEL] == ERROR_SATD && params->MEErrorMetric[Q_PEL] == ERROR_SATD) ? 1.00 : 0.95));
  1458.       }
  1459.     }
  1460.   }
  1461.   else if (params->UseExplicitLambdaParams == 2) // consideration of fixed lambda values.
  1462.   {
  1463.     for (j = 0; j < 6; j++)
  1464.     {
  1465.       for (qp = -img->bitdepth_luma_qp_scale; qp < 52; qp++)
  1466.       {
  1467.         qp_temp = (double)qp + img->bitdepth_luma_qp_scale - SHIFT_QP;
  1468.         img->lambda_md[j][qp] = params->FixedLambda[j];
  1469.         SetLambda(j, qp, ((params->MEErrorMetric[H_PEL] == ERROR_SATD && params->MEErrorMetric[Q_PEL] == ERROR_SATD) ? 1.00 : 0.95));
  1470.       }
  1471.     }
  1472.   }
  1473.   else
  1474.   {
  1475.     for (j = 0; j < 5; j++)
  1476.     {
  1477.       for (qp = -img->bitdepth_luma_qp_scale; qp < 52; qp++)
  1478.       {
  1479.         qp_temp = (double)qp + img->bitdepth_luma_qp_scale - SHIFT_QP;
  1480.         if (params->successive_Bframe > 0)
  1481.           img->lambda_md[j][qp] = 0.68 * pow (2, qp_temp/3.0)
  1482.           * (j == B_SLICE && img->b_frame_to_code != 0 ? dClip3(2.00, 4.00, (qp_temp / 6.0)) : (j == SP_SLICE) ? dClip3(1.4,3.0,(qp_temp / 12.0)) : 1.0);
  1483.         else
  1484.           img->lambda_md[j][qp] = 0.85 * pow (2, qp_temp/3.0) * ((j == SP_SLICE) ? dClip3(1.4, 3.0,(qp_temp / 12.0)) : 1.0);
  1485.         // Scale lambda due to hadamard qpel only consideration
  1486.         img->lambda_md[j][qp] = ((params->MEErrorMetric[H_PEL] == ERROR_SATD && params->MEErrorMetric[Q_PEL] == ERROR_SATD) ? 1.00 : 0.95) * img->lambda_md[j][qp];
  1487.         //img->lambda_md[j][qp] = (j == B_SLICE && params->BRefPictures == 2 && img->b_frame_to_code == 0 ? 0.50 : 1.00) * img->lambda_md[j][qp];
  1488.         if (j == B_SLICE)
  1489.         {
  1490.           img->lambda_md[5][qp] = img->lambda_md[j][qp];
  1491.           if (img->b_frame_to_code != 0)
  1492.           {
  1493.             if (params->HierarchicalCoding == 2)
  1494.               img->lambda_md[5][qp] *= (1.0 - dmin(0.4, 0.2 * (double) gop_structure[img->b_frame_to_code-1].hierarchy_layer));
  1495.             else
  1496.               img->lambda_md[5][qp] *= 0.80;
  1497.           }
  1498.           SetLambda(5, qp, lambda_scale);
  1499.         }
  1500.         else
  1501.           img->lambda_md[j][qp] *= lambda_scale;
  1502.         SetLambda(j, qp, 1.0);
  1503.         if (params->CtxAdptLagrangeMult == 1)
  1504.         {
  1505.           int lambda_qp = (qp >= 32 && !params->RCEnable) ? imax(0, qp - 4) : imax(0, qp - 6);
  1506.           img->lambda_mf_factor[j][qp] = log (img->lambda_me[j][lambda_qp][Q_PEL] + 1.0) / log (2.0);
  1507.         }
  1508.       }
  1509.     }
  1510.   }
  1511.   UpdateMELambda(img);
  1512. }
  1513. void SetLagrangianMultipliersOff()
  1514. {
  1515.   int qp, j, k;
  1516.   double qp_temp;
  1517.   for (j = 0; j < 6; j++)
  1518.   {
  1519.     for (qp = -img->bitdepth_luma_qp_scale; qp < 52; qp++)
  1520.     {
  1521.       qp_temp = (double)qp + img->bitdepth_luma_qp_scale - SHIFT_QP;
  1522.       switch (params->UseExplicitLambdaParams)
  1523.       {
  1524.       case 1:  // explicit lambda weights
  1525.         img->lambda_md[j][qp] = sqrt(params->LambdaWeight[j] * pow (2, qp_temp/3.0));
  1526.         break;
  1527.       case 2: // explicit lambda
  1528.         img->lambda_md[j][qp] = sqrt(params->FixedLambda[j]);
  1529.         break;
  1530.       default:
  1531.         img->lambda_md[j][qp] = QP2QUANT[imax(0,qp - SHIFT_QP)];
  1532.         break;
  1533.       }
  1534.       for (k = F_PEL; k <= Q_PEL; k++)
  1535.       {
  1536.         img->lambda_me[j][qp][k]  = (params->MEErrorMetric[k] == ERROR_SSE) ? (img->lambda_md[j][qp] * img->lambda_md[j][qp]) : img->lambda_md[j][qp];
  1537.         img->lambda_mf[j][qp][k]  = LAMBDA_FACTOR (img->lambda_me[j][qp][k]);
  1538.       }
  1539.       if (params->CtxAdptLagrangeMult == 1)
  1540.       {
  1541.         int lambda_qp = (qp >= 32 && !params->RCEnable) ? imax(0, qp-4) : imax(0, qp-6);
  1542.         img->lambda_mf_factor[j][qp] = log (img->lambda_me[j][lambda_qp][Q_PEL] + 1.0) / log (2.0);
  1543.       }
  1544.     }
  1545.   }
  1546.   UpdateMELambda(img);
  1547. }