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

Audio

开发平台:

Visual C++

  1. /*!
  2.  ***********************************************************************
  3.  *  mainpage
  4.  *     This is the H.264/AVC encoder reference software. For detailed documentation
  5.  *     see the comments in each file.
  6.  *
  7.  *     The JM software web site is located at:
  8.  *     http://iphome.hhi.de/suehring/tml
  9.  *
  10.  *     For bug reporting and known issues see:
  11.  *     https://ipbt.hhi.de
  12.  *
  13.  *  author
  14.  *     The main contributors are listed in contributors.h
  15.  *
  16.  *  version
  17.  *     JM 14.2 (FRExt)
  18.  *
  19.  *  note
  20.  *     tags are used for document system "doxygen"
  21.  *     available at http://www.doxygen.org
  22.  */
  23. /*!
  24.  *  file
  25.  *     lencod.c
  26.  *  brief
  27.  *     H.264/AVC reference encoder project main()
  28.  *  author
  29.  *   Main contributors (see contributors.h for copyright, address and affiliation details)
  30.  *   - Inge Lille-Langoy               <inge.lille-langoy@telenor.com>
  31.  *   - Rickard Sjoberg                 <rickard.sjoberg@era.ericsson.se>
  32.  *   - Stephan Wenger                  <stewe@cs.tu-berlin.de>
  33.  *   - Jani Lainema                    <jani.lainema@nokia.com>
  34.  *   - Byeong-Moon Jeon                <jeonbm@lge.com>
  35.  *   - Yoon-Seong Soh                  <yunsung@lge.com>
  36.  *   - Thomas Stockhammer              <stockhammer@ei.tum.de>
  37.  *   - Detlev Marpe                    <marpe@hhi.de>
  38.  *   - Guido Heising
  39.  *   - Valeri George                   <george@hhi.de>
  40.  *   - Karsten Suehring                <suehring@hhi.de>
  41.  *   - Alexis Michael Tourapis         <alexismt@ieee.org>
  42.  ***********************************************************************
  43.  */
  44. #include "contributors.h"
  45. #include <time.h>
  46. #include <math.h>
  47. #include <sys/timeb.h>
  48. #include "global.h"
  49. #include "cconv_yuv2rgb.h"
  50. #include "configfile.h"
  51. #include "context_ini.h"
  52. #include "explicit_gop.h"
  53. #include "filehandle.h"
  54. #include "image.h"
  55. #include "input.h"
  56. #include "slice.h"
  57. #include "intrarefresh.h"
  58. #include "leaky_bucket.h"
  59. #include "memalloc.h"
  60. #include "me_epzs.h"
  61. #include "me_umhex.h"
  62. #include "me_umhexsmp.h"
  63. #include "output.h"
  64. #include "parset.h"
  65. #include "q_matrix.h"
  66. #include "q_offsets.h"
  67. #include "ratectl.h"
  68. #include "report.h"
  69. #include "rdoq.h"
  70. #include "errdo.h"
  71. #include "rdopt.h"
  72. #include "wp_mcprec.h"
  73. InputParameters  inputs, *params = &inputs;
  74. ImageParameters  images, *img    = &images;
  75. Decoders       decoders, *decs   = &decoders;
  76. #ifdef _ADAPT_LAST_GROUP_
  77. int initial_Bframes = 0;
  78. #endif
  79. Boolean In2ndIGOP = FALSE;
  80. int    start_frame_no_in_this_IGOP = 0;
  81. int    start_tr_in_this_IGOP = 0;
  82. int    FirstFrameIn2ndIGOP=0;
  83. int    cabac_encoding = 0;
  84. int    frame_statistic_start;
  85. extern ColocatedParams *Co_located;
  86. extern ColocatedParams *Co_located_JV[MAX_PLANE];  //!< Co_located to be used during 4:4:4 independent mode encoding
  87. extern double *mb16x16_cost_frame;
  88. extern int FrameNumberInFile;
  89. extern void Init_Motion_Search_Module (void);
  90. extern void Clear_Motion_Search_Module (void);
  91. static void SetImgType(void);
  92. void SetLevelIndices(void);
  93. void chroma_mc_setup(void);
  94. int  get_mem_mv  (short*******);
  95. int  get_mem_bipred_mv (short********);
  96. void free_mem_bipred_mv (short*******);
  97. void free_mem_mv (short******);
  98. static void init_img( ImageParameters *img, InputParameters *params);
  99. static void init_poc(void);
  100. void init_stats (StatParameters *stats)
  101. {
  102.   memset(stats, 0, sizeof(StatParameters));
  103.   stats->successive_Bframe = params->successive_Bframe;
  104. }
  105. void init_dstats (DistortionParams *dist)
  106. {
  107.   dist->frame_ctr = 0;
  108.   memset(dist->metric, 0, TOTAL_DIST_TYPES * sizeof(DistMetric));
  109. }
  110. /*!
  111.  ***********************************************************************
  112.  * brief
  113.  *    Initialize encoding parameters.
  114.  ***********************************************************************
  115.  */
  116. void init_frame_params()
  117. {
  118.   int base_mul = 0;
  119.   if (params->idr_period)
  120.   {
  121.     if (!params->adaptive_idr_period && ( img->frm_number - img->lastIDRnumber ) % params->idr_period == 0 )
  122.       img->nal_reference_idc = NALU_PRIORITY_HIGHEST;
  123.     if (params->adaptive_idr_period == 1 && ( img->frm_number - imax(img->lastIntraNumber, img->lastIDRnumber) ) % params->idr_period == 0 )
  124.       img->nal_reference_idc = NALU_PRIORITY_HIGHEST;
  125.     else
  126.       img->nal_reference_idc = (params->DisposableP) ? (img->frm_number + 1)% 2 : NALU_PRIORITY_LOW;
  127.   }
  128.   else
  129.     img->nal_reference_idc = (img->frm_number && params->DisposableP) ? (img->frm_number + 1)% 2 : NALU_PRIORITY_LOW;
  130.   //much of this can go in init_frame() or init_field()?
  131.   //poc for this frame or field
  132.   if (params->idr_period)
  133.   {
  134.     if (!params->adaptive_idr_period)
  135.       base_mul = ( img->frm_number - img->lastIDRnumber ) % params->idr_period;
  136.     else if (params->adaptive_idr_period == 1)
  137.       base_mul = (( img->frm_number - imax(img->lastIntraNumber, img->lastIDRnumber) ) % params->idr_period == 0) ? 0 : ( img->frm_number - img->lastIDRnumber );
  138.   }
  139.   else 
  140.     base_mul = ( img->frm_number - img->lastIDRnumber );
  141.   if ((img->frm_number - img->lastIDRnumber) <= params->intra_delay)
  142.   {    
  143.     base_mul = -base_mul;
  144.   }
  145.   else
  146.   {
  147.     base_mul -= ( base_mul ? params->intra_delay :  0);    
  148.   }
  149.   img->toppoc = base_mul * (2 * (params->jumpd + 1));
  150.   if ((params->PicInterlace==FRAME_CODING) && (params->MbInterlace==FRAME_CODING))
  151.     img->bottompoc = img->toppoc;     //progressive
  152.   else
  153.     img->bottompoc = img->toppoc + 1;   //hard coded
  154.   img->framepoc = imin (img->toppoc, img->bottompoc);
  155.   //the following is sent in the slice header
  156.   img->delta_pic_order_cnt[0] = 0;
  157.   if ((params->BRefPictures == 1) && (img->frm_number))
  158.   {
  159.     img->delta_pic_order_cnt[0] = +2 * params->successive_Bframe;
  160.   }  
  161. }
  162. /*!
  163.  ***********************************************************************
  164.  * brief
  165.  *    Main function for encoder.
  166.  * param argc
  167.  *    number of command line arguments
  168.  * param argv
  169.  *    command line arguments
  170.  * return
  171.  *    exit code
  172.  ***********************************************************************
  173.  */
  174. int main(int argc,char **argv)
  175. {
  176.   int primary_disp = 0;
  177.   giRDOpt_B8OnlyFlag = 0;
  178.   p_dec = p_in = -1;
  179.   p_log = p_trace = NULL;
  180.   frame_statistic_start = 1;
  181.   Configure (argc, argv);
  182.   Init_QMatrix();
  183.   Init_QOffsetMatrix();
  184.   init_poc();
  185.   GenerateParameterSets();
  186.   SetLevelIndices();
  187.   init_img(img, params);
  188.   init_rdopt(params);
  189.   if (params->rdopt == 3)
  190.   {
  191.     init_error_conceal(params->ErrorConcealment); 
  192.   }
  193. #ifdef _LEAKYBUCKET_
  194.   Bit_Buffer = malloc((params->no_frames * (params->successive_Bframe + 1) + 1) * sizeof(long));
  195. #endif
  196.   // Prepare hierarchical coding structures. 
  197.   // Code could be extended in the future to allow structure adaptation.
  198.   if (params->HierarchicalCoding)
  199.   {
  200.     init_gop_structure();
  201.     if (params->successive_Bframe && params->HierarchicalCoding == 3)
  202.       interpret_gop_structure();
  203.     else
  204.       create_hierarchy();
  205.   }
  206.   dpb.init_done = 0;
  207.   init_dpb();
  208.   init_out_buffer();
  209.   init_stats (stats);
  210.   init_dstats(dist);
  211.   enc_picture = NULL;
  212.   init_global_buffers();
  213.   if ( params->WPMCPrecision )
  214.   {
  215.     wpxInitWPXPasses(params);
  216.   }
  217.   create_context_memory ();
  218.   Init_Motion_Search_Module ();
  219.   information_init(img, params, stats);
  220.   if(params->DistortionYUVtoRGB)
  221.     init_YUVtoRGB();
  222.   //Rate control
  223.   if (params->RCEnable)
  224.     rc_init_sequence();
  225.   img->last_valid_reference = 0;
  226.   tot_time = 0;                 // time for total encoding session
  227. #ifdef _ADAPT_LAST_GROUP_
  228.   if (params->last_frame > 0)
  229.     params->no_frames = 1 + (params->last_frame + params->jumpd) / (params->jumpd + 1);
  230.   initial_Bframes = params->successive_Bframe;
  231. #endif
  232.   PatchInputNoFrames();
  233.   // Write sequence header (with parameter sets)
  234.   stats->bit_ctr_parametersets = 0;
  235.   stats->bit_slice = start_sequence();
  236.   stats->bit_ctr_parametersets += stats->bit_ctr_parametersets_n;
  237.   start_frame_no_in_this_IGOP = 0;
  238.   if (params->UseRDOQuant)
  239.     precalculate_unary_exp_golomb_level();
  240.   for (img->number=0; img->number < params->no_frames; img->number++)
  241.   {
  242.     img->frm_number = img->number;    
  243.     FrameNumberInFile = CalculateFrameNumber();
  244.     SetImgType();
  245.     init_frame_params();
  246.     if (img->last_ref_idc)
  247.     {
  248.       img->frame_num++;                 //increment frame_num once for B-frames
  249.       img->frame_num %= max_frame_num;
  250.     }
  251.     //frame_num for this frame
  252.     if (params->idr_period && ((!params->adaptive_idr_period && ( img->frm_number - img->lastIDRnumber ) % params->idr_period == 0)
  253.       || (params->adaptive_idr_period == 1 && ( img->frm_number - imax(img->lastIntraNumber, img->lastIDRnumber) ) % params->idr_period == 0)) )
  254.     {
  255.       img->frame_num = 0;
  256.       primary_disp   = 0;   
  257.     }
  258.     if (params->ResendSPS == 1 && img->type == I_SLICE && img->frm_number != 0)
  259.     {
  260.       stats->bit_slice = rewrite_paramsets();
  261.       stats->bit_ctr_parametersets += stats->bit_ctr_parametersets_n;
  262.     }
  263. #ifdef _ADAPT_LAST_GROUP_
  264.     if (params->successive_Bframe && params->last_frame && (IMG_NUMBER + 1) == params->no_frames)
  265.     {
  266.       int bi = (int)((float)(params->jumpd + 1)/(params->successive_Bframe + 1.0) + 0.499999);
  267.       params->successive_Bframe = ((params->last_frame - (img->frm_number - 1)*(params->jumpd + 1)) / bi) - 1;
  268.       //about to code the last ref frame, adjust delta poc
  269.       img->delta_pic_order_cnt[0]= -2*(initial_Bframes - params->successive_Bframe);
  270.       img->toppoc    += img->delta_pic_order_cnt[0];
  271.       img->bottompoc += img->delta_pic_order_cnt[0];
  272.       img->framepoc   = imin (img->toppoc, img->bottompoc);
  273.     }
  274. #endif
  275.     //Rate control
  276.     if (params->RCEnable && img->type == I_SLICE)
  277.       rc_init_gop_params();
  278.     // which layer does the image belong to?
  279.     img->layer = (IMG_NUMBER % (params->NumFramesInELSubSeq + 1)) ? 0 : 1;
  280.     // redundant frame initialization and allocation
  281.     if (params->redundant_pic_flag)
  282.     {
  283.       Init_redundant_frame();
  284.       Set_redundant_frame();
  285.     }
  286.     encode_one_frame(); // encode one I- or P-frame
  287.     img->last_ref_idc = img->nal_reference_idc ? 1 : 0;
  288.     // if key frame is encoded, encode one redundant frame
  289.     if (params->redundant_pic_flag && key_frame)
  290.     {
  291.       encode_one_redundant_frame();
  292.     }
  293.     if (img->type == I_SLICE && params->EnableOpenGOP)
  294.       img->last_valid_reference = img->ThisPOC;
  295.     if (params->ReportFrameStats)
  296.       report_frame_statistic();
  297.     if (img->nal_reference_idc == 0)
  298.     {
  299.       primary_disp ++;
  300.     }
  301.     if (img->currentPicture->idr_flag)
  302.     {
  303.       img->idr_gop_number = 0;
  304.     }
  305.     else
  306.       img->idr_gop_number ++;
  307.     encode_enhancement_layer();    
  308.   }
  309.   // terminate sequence
  310.   free_encoder_memory(img);
  311.   return 0;
  312. }
  313. void free_encoder_memory(ImageParameters *img)
  314. {
  315.   int nplane;
  316.   terminate_sequence();
  317.   flush_dpb();
  318.   close(p_in);
  319.   if (-1 != p_dec)
  320.     close(p_dec);
  321.   if (p_trace)
  322.     fclose(p_trace);
  323.   Clear_Motion_Search_Module ();
  324.   RandomIntraUninit();
  325.   FmoUninit();
  326.   if (params->HierarchicalCoding)
  327.     clear_gop_structure ();
  328.   // free structure for rd-opt. mode decision
  329.   clear_rdopt (params);
  330. #ifdef _LEAKYBUCKET_
  331.   calc_buffer();
  332. #endif
  333.   // report everything
  334.   report(img, params, stats);
  335. #ifdef _LEAKYBUCKET_
  336.   if (Bit_Buffer)
  337.     free(Bit_Buffer);
  338. #endif
  339.   free_dpb();
  340.   if( IS_INDEPENDENT(params) )
  341.   {
  342.     for( nplane=0; nplane<MAX_PLANE; nplane++ )
  343.     {
  344.       free_colocated(Co_located_JV[nplane]);
  345.     }
  346.   }
  347.   else
  348.   {
  349.     free_colocated(Co_located);
  350.   }
  351.   uninit_out_buffer();
  352.   free_global_buffers();
  353.   // free image mem
  354.   free_img ();
  355.   free_context_memory ();
  356.   FreeParameterSets();
  357. }
  358. /*!
  359.  ***********************************************************************
  360.  * brief
  361.  *    Initializes the POC structure with appropriate parameters.
  362.  *
  363.  ***********************************************************************
  364.  */
  365. void init_poc()
  366. {
  367.   //the following should probably go in sequence parameters
  368.   // frame poc's increase by 2, field poc's by 1
  369.   img->pic_order_cnt_type=params->pic_order_cnt_type;
  370.   img->delta_pic_order_always_zero_flag = FALSE;
  371.   img->num_ref_frames_in_pic_order_cnt_cycle= 1;
  372.   if (params->BRefPictures == 1)
  373.   {
  374.     img->offset_for_non_ref_pic  =  0;
  375.     img->offset_for_ref_frame[0] =  2;
  376.   }
  377.   else
  378.   {
  379.     img->offset_for_non_ref_pic  = -2*(params->successive_Bframe);
  380.     img->offset_for_ref_frame[0] =  2*(params->successive_Bframe + 1);
  381.   }
  382.   if ((params->PicInterlace==FRAME_CODING) && (params->MbInterlace==FRAME_CODING))
  383.   {
  384.     img->offset_for_top_to_bottom_field = 0;
  385.     img->pic_order_present_flag = FALSE;
  386.     img->delta_pic_order_cnt_bottom = 0;
  387.   }
  388.   else
  389.   {
  390.     img->offset_for_top_to_bottom_field = 1;
  391.     img->pic_order_present_flag = TRUE;
  392.     img->delta_pic_order_cnt_bottom = 1;
  393.   }
  394. }
  395. /*!
  396.  ***********************************************************************
  397.  * brief
  398.  *    Initializes the img->nz_coeff
  399.  * par Input:
  400.  *    none
  401.  * par  Output:
  402.  *    none
  403.  *  side effects
  404.  *    sets omg->nz_coef[][][][] to -1
  405.  ***********************************************************************
  406.  */
  407. void CAVLC_init(void)
  408. {
  409.   unsigned int i, k, l;
  410.   for (i = 0; i < img->PicSizeInMbs; i++)
  411.     for (k = 0; k < 4; k++)
  412.       for (l = 0; l < (4 + (unsigned int)img->num_blk8x8_uv); l++)
  413.         img->nz_coeff[i][k][l] = 0;
  414. }
  415. /*!
  416.  ***********************************************************************
  417.  * brief
  418.  *    Initializes the Image structure with appropriate parameters.
  419.  * par Input:
  420.  *    Input Parameters struct inp_par *inp
  421.  * par  Output:
  422.  *    Image Parameters ImageParameters *img
  423.  ***********************************************************************
  424.  */
  425. static void init_img( ImageParameters *img, InputParameters *params)
  426. {
  427.   int i, j;
  428.   int byte_abs_range;
  429.   static int mb_width_cr[4] = {0,8, 8,16};
  430.   static int mb_height_cr[4]= {0,8,16,16};
  431.   // Color format
  432.   img->yuv_format = params->yuv_format;
  433.   img->P444_joined = (img->yuv_format == YUV444 && !IS_INDEPENDENT(params));  
  434.   //pel bitdepth init
  435.   img->bitdepth_luma            = params->output.bit_depth[0];
  436.   img->bitdepth_scale[0]        = 1 << (img->bitdepth_luma - 8);
  437.   img->bitdepth_lambda_scale    = 2 * (img->bitdepth_luma - 8);
  438.   img->bitdepth_luma_qp_scale   = 3 *  img->bitdepth_lambda_scale;
  439.   img->dc_pred_value_comp[0]    =  1<<(img->bitdepth_luma - 1);
  440.   img->max_imgpel_value_comp[0] = (1<<img->bitdepth_luma) - 1;
  441.   img->max_imgpel_value_comp_sq[0] = img->max_imgpel_value_comp[0] * img->max_imgpel_value_comp[0];
  442.   img->dc_pred_value            = img->dc_pred_value_comp[0]; // set defaults
  443.   img->max_imgpel_value         = img->max_imgpel_value_comp[0];
  444.   img->mb_size[0][0]            = img->mb_size[0][1] = MB_BLOCK_SIZE;
  445.   // Initialization for RC QP parameters (could be placed in ratectl.c)
  446.   img->RCMinQP                = params->RCMinQP[P_SLICE];
  447.   img->RCMaxQP                = params->RCMaxQP[P_SLICE];
  448.   // Set current residue & prediction array pointers
  449.   img->curr_res = img->mb_rres[0];
  450.   img->curr_prd = img->mb_pred[0];
  451.   if (img->yuv_format != YUV400)
  452.   {
  453.     img->bitdepth_chroma          = params->output.bit_depth[1];
  454.     img->bitdepth_scale[1]        = 1 << (img->bitdepth_chroma - 8);
  455.     img->dc_pred_value_comp[1]    = 1<<(img->bitdepth_chroma - 1);
  456.     img->dc_pred_value_comp[2]    = img->dc_pred_value_comp[1];
  457.     img->max_imgpel_value_comp[1] = (1<<img->bitdepth_chroma) - 1;
  458.     img->max_imgpel_value_comp[2] = img->max_imgpel_value_comp[1];
  459.     img->max_imgpel_value_comp_sq[1] = img->max_imgpel_value_comp[1] * img->max_imgpel_value_comp[1];
  460.     img->max_imgpel_value_comp_sq[2] = img->max_imgpel_value_comp[2] * img->max_imgpel_value_comp[2];
  461.     img->num_blk8x8_uv            = (1<<img->yuv_format)&(~(0x1));
  462.     img->num_cdc_coeff            = img->num_blk8x8_uv << 1;
  463.     img->mb_size[1][0] = img->mb_size[2][0] = img->mb_cr_size_x = (img->yuv_format == YUV420 || img->yuv_format == YUV422) ? 8 : 16;
  464.     img->mb_size[1][1] = img->mb_size[2][1] = img->mb_cr_size_y = (img->yuv_format == YUV444 || img->yuv_format == YUV422) ? 16 : 8;
  465.     img->bitdepth_chroma_qp_scale = 6*(img->bitdepth_chroma - 8);
  466.     img->chroma_qp_offset[0] = active_pps->cb_qp_index_offset;
  467.     img->chroma_qp_offset[1] = active_pps->cr_qp_index_offset;
  468.   }
  469.   else
  470.   {
  471.     img->bitdepth_chroma     = 0;
  472.     img->bitdepth_scale[1]   = 0;
  473.     img->max_imgpel_value_comp[1] = 0;
  474.     img->max_imgpel_value_comp[2] = img->max_imgpel_value_comp[1];
  475.     img->max_imgpel_value_comp_sq[1] = img->max_imgpel_value_comp[1] * img->max_imgpel_value_comp[1];
  476.     img->max_imgpel_value_comp_sq[2] = img->max_imgpel_value_comp[2] * img->max_imgpel_value_comp[2];
  477.     img->num_blk8x8_uv       = 0;
  478.     img->num_cdc_coeff       = 0;
  479.     img->mb_size[1][0] = img->mb_size[2][0] = img->mb_cr_size_x = 0;
  480.     img->mb_size[1][1] = img->mb_size[2][1] = img->mb_cr_size_y = 0;
  481.     img->bitdepth_chroma_qp_scale = 0;
  482.     img->bitdepth_chroma_qp_scale = 0;
  483.     img->chroma_qp_offset[0] = 0;
  484.     img->chroma_qp_offset[1] = 0;
  485.   }  
  486.   //img->pic_unit_size_on_disk = (imax(img->bitdepth_luma , img->bitdepth_chroma) > 8) ? 16 : 8;
  487.   img->pic_unit_size_on_disk = (imax(params->source.bit_depth[0], params->source.bit_depth[1]) > 8) ? 16 : 8;
  488.   img->out_unit_size_on_disk = (imax(params->output.bit_depth[0], params->output.bit_depth[1]) > 8) ? 16 : 8;
  489.   img->max_bitCount =  128 + 256 * img->bitdepth_luma + 2 * img->mb_cr_size_y * img->mb_cr_size_x * img->bitdepth_chroma;
  490.   //img->max_bitCount =  (128 + 256 * img->bitdepth_luma + 2 *img->mb_cr_size_y * img->mb_cr_size_x * img->bitdepth_chroma)*2;
  491.   img->max_qp_delta = (25 + (img->bitdepth_luma_qp_scale>>1));
  492.   img->min_qp_delta = img->max_qp_delta + 1;
  493.   img->num_ref_frames = active_sps->num_ref_frames;
  494.   img->max_num_references   = active_sps->frame_mbs_only_flag ? active_sps->num_ref_frames : 2 * active_sps->num_ref_frames;
  495.   img->buf_cycle = params->num_ref_frames;
  496.   img->base_dist = params->jumpd;  
  497.   // Intra/IDR related parameters
  498.   img->lastIntraNumber = 0;
  499.   img->lastINTRA       = 0;
  500.   img->lastIDRnumber   = 0;
  501.   img->last_ref_idc    = 0;
  502.   img->idr_refresh     = 0;
  503.   img->idr_gop_number  = 0;
  504.   img->rewind_frame    = 0;
  505.   img->DeblockCall     = 0;
  506.   img->framerate       = (float) params->FrameRate;   // The basic frame rate (of the original sequence)
  507.   // Allocate proper memory space for different parameters (i.e. MVs, coefficients, etc)
  508.   if (!params->IntraProfile)
  509.   {
  510.     get_mem_mv (&(img->pred_mv));
  511.     get_mem_mv (&(img->all_mv));
  512.     if (params->BiPredMotionEstimation)
  513.     {
  514.       get_mem_bipred_mv(&(img->bipred_mv)); 
  515.     }
  516.   }
  517.   get_mem_ACcoeff (&(img->cofAC));
  518.   get_mem_DCcoeff (&(img->cofDC));
  519.   if (params->AdaptiveRounding)
  520.   {
  521.     get_mem3Dint(&(img->fadjust4x4), 4, MB_BLOCK_SIZE, MB_BLOCK_SIZE);
  522.     get_mem3Dint(&(img->fadjust8x8), 3, MB_BLOCK_SIZE, MB_BLOCK_SIZE);
  523.     if (img->yuv_format != 0)
  524.     {
  525.       get_mem4Dint(&(img->fadjust4x4Cr), 2, 4, img->mb_cr_size_y, img->mb_cr_size_x);
  526.       get_mem4Dint(&(img->fadjust8x8Cr), 2, 3, img->mb_cr_size_y, img->mb_cr_size_x);
  527.     }
  528.   }
  529.   if(params->MbInterlace)
  530.   {
  531.     if (!params->IntraProfile)
  532.     {
  533.       get_mem_mv (&(rddata_top_frame_mb.pred_mv));
  534.       get_mem_mv (&(rddata_top_frame_mb.all_mv));
  535.       get_mem_mv (&(rddata_bot_frame_mb.pred_mv));
  536.       get_mem_mv (&(rddata_bot_frame_mb.all_mv));
  537.     }
  538.     get_mem_ACcoeff (&(rddata_top_frame_mb.cofAC));
  539.     get_mem_DCcoeff (&(rddata_top_frame_mb.cofDC));
  540.     get_mem_ACcoeff (&(rddata_bot_frame_mb.cofAC));
  541.     get_mem_DCcoeff (&(rddata_bot_frame_mb.cofDC));
  542.     if ( params->MbInterlace != FRAME_MB_PAIR_CODING )
  543.     {
  544.       if (!params->IntraProfile)
  545.       {      
  546.         get_mem_mv (&(rddata_top_field_mb.pred_mv));
  547.         get_mem_mv (&(rddata_top_field_mb.all_mv));
  548.         get_mem_mv (&(rddata_bot_field_mb.pred_mv));
  549.         get_mem_mv (&(rddata_bot_field_mb.all_mv));
  550.       }
  551.       get_mem_ACcoeff (&(rddata_top_field_mb.cofAC));
  552.       get_mem_DCcoeff (&(rddata_top_field_mb.cofDC));
  553.       get_mem_ACcoeff (&(rddata_bot_field_mb.cofAC));
  554.       get_mem_DCcoeff (&(rddata_bot_field_mb.cofDC));
  555.     }
  556.   }
  557.   if (params->UseRDOQuant && params->RDOQ_QP_Num > 1)
  558.   {
  559.     get_mem_ACcoeff (&(rddata_trellis_curr.cofAC));
  560.     get_mem_DCcoeff (&(rddata_trellis_curr.cofDC));
  561.     get_mem_ACcoeff (&(rddata_trellis_best.cofAC));
  562.     get_mem_DCcoeff (&(rddata_trellis_best.cofDC));
  563.     if (!params->IntraProfile)
  564.     {          
  565.       get_mem_mv (&(rddata_trellis_curr.pred_mv));
  566.       get_mem_mv (&(rddata_trellis_curr.all_mv));
  567.       get_mem_mv (&(rddata_trellis_best.pred_mv));
  568.       get_mem_mv (&(rddata_trellis_best.all_mv));
  569.       if (params->Transform8x8Mode && params->RDOQ_CP_MV)
  570.       {
  571.         get_mem5Dshort(&tmp_mv8, 2, img->max_num_references, 4, 4, 2);
  572.         get_mem5Dshort(&tmp_pmv8, 2, img->max_num_references, 4, 4, 2);
  573.         get_mem3Dint  (&motion_cost8, 2, img->max_num_references, 4);
  574.       }
  575.     }
  576.   }
  577.   byte_abs_range = (imax(img->max_imgpel_value_comp[0], img->max_imgpel_value_comp[1]) + 1) * 2;
  578.   if ((img->quad = (int*)calloc (byte_abs_range, sizeof(int))) == NULL)
  579.     no_mem_exit ("init_img: img->quad");
  580.   img->quad += byte_abs_range/2;
  581.   for (i=0; i < byte_abs_range/2; ++i)
  582.   {
  583.     img->quad[i] = img->quad[-i] = i * i;
  584.   }
  585.   img->width         = (params->output.width  + img->auto_crop_right);
  586.   img->height        = (params->output.height + img->auto_crop_bottom);
  587.   img->width_blk     = img->width  / BLOCK_SIZE;
  588.   img->height_blk    = img->height / BLOCK_SIZE;
  589.   img->width_padded  = img->width  + 2 * IMG_PAD_SIZE;
  590.   img->height_padded = img->height + 2 * IMG_PAD_SIZE;
  591.   if (img->yuv_format != YUV400)
  592.   {
  593.     img->width_cr = img->width  * mb_width_cr [img->yuv_format] / 16;
  594.     img->height_cr= img->height * mb_height_cr[img->yuv_format] / 16;
  595.   }
  596.   else
  597.   {
  598.     img->width_cr = 0;
  599.     img->height_cr= 0;
  600.   }
  601.   img->height_cr_frame = img->height_cr;
  602.   img->size = img->width * img->height;
  603.   img->size_cr = img->width_cr * img->height_cr;
  604.   img->PicWidthInMbs    = img->width  / MB_BLOCK_SIZE;
  605.   img->FrameHeightInMbs = img->height / MB_BLOCK_SIZE;
  606.   img->FrameSizeInMbs   = img->PicWidthInMbs * img->FrameHeightInMbs;
  607.   img->PicHeightInMapUnits = ( active_sps->frame_mbs_only_flag ? img->FrameHeightInMbs : img->FrameHeightInMbs/2 );
  608.   
  609.   if ((img->b8x8info = (Block8x8Info *) calloc(1, sizeof(Block8x8Info))) == NULL)
  610.      no_mem_exit("init_img: img->block8x8info");
  611.   if( IS_INDEPENDENT(params) )
  612.   {
  613.     for( i = 0; i < MAX_PLANE; i++ ){
  614.       if ((img->mb_data_JV[i] = (Macroblock *) calloc(img->FrameSizeInMbs,sizeof(Macroblock))) == NULL)
  615.         no_mem_exit("init_img: img->mb_data_JV");
  616.     }
  617.     img->mb_data = NULL;
  618.   }
  619.   else
  620.   {
  621.     if ((img->mb_data = (Macroblock *) calloc(img->FrameSizeInMbs, sizeof(Macroblock))) == NULL)
  622.       no_mem_exit("init_img: img->mb_data");
  623.   }
  624.   if (params->UseConstrainedIntraPred)
  625.   {
  626.     if ((img->intra_block = (int*)calloc(img->FrameSizeInMbs, sizeof(int))) == NULL)
  627.       no_mem_exit("init_img: img->intra_block");
  628.   }
  629.   if (params->CtxAdptLagrangeMult == 1)
  630.   {
  631.     if ((mb16x16_cost_frame = (double*)calloc(img->FrameSizeInMbs, sizeof(double))) == NULL)
  632.     {
  633.       no_mem_exit("init mb16x16_cost_frame");
  634.     }
  635.   }
  636.   get_mem2D((byte***)&(img->ipredmode), img->height_blk, img->width_blk);        //need two extra rows at right and bottom
  637.   get_mem2D((byte***)&(img->ipredmode8x8), img->height_blk, img->width_blk);     // help storage for ipredmode 8x8, inserted by YV
  638.   memset(&(img->ipredmode[0][0])   , -1, img->height_blk * img->width_blk *sizeof(char));
  639.   memset(&(img->ipredmode8x8[0][0]), -1, img->height_blk * img->width_blk *sizeof(char));
  640.   get_mem2D((byte***)&(rddata_top_frame_mb.ipredmode), img->height_blk, img->width_blk);
  641.   get_mem2D((byte***)&(rddata_trellis_curr.ipredmode), img->height_blk, img->width_blk);
  642.   get_mem2D((byte***)&(rddata_trellis_best.ipredmode), img->height_blk, img->width_blk);
  643.   if (params->MbInterlace)
  644.   {
  645.     get_mem2D((byte***)&(rddata_bot_frame_mb.ipredmode), img->height_blk, img->width_blk);
  646.     get_mem2D((byte***)&(rddata_top_field_mb.ipredmode), img->height_blk, img->width_blk);
  647.     get_mem2D((byte***)&(rddata_bot_field_mb.ipredmode), img->height_blk, img->width_blk);
  648.   }
  649.   // CAVLC mem
  650.   get_mem3Dint(&(img->nz_coeff), img->FrameSizeInMbs, 4, 4+img->num_blk8x8_uv);
  651.   CAVLC_init();
  652.   
  653.   get_mem2Dolm     (&(img->lambda), 10, 52 + img->bitdepth_luma_qp_scale, img->bitdepth_luma_qp_scale);
  654.   get_mem2Dodouble (&(img->lambda_md), 10, 52 + img->bitdepth_luma_qp_scale, img->bitdepth_luma_qp_scale);
  655.   get_mem3Dodouble (&(img->lambda_me), 10, 52 + img->bitdepth_luma_qp_scale, 3, img->bitdepth_luma_qp_scale);
  656.   get_mem3Doint    (&(img->lambda_mf), 10, 52 + img->bitdepth_luma_qp_scale, 3, img->bitdepth_luma_qp_scale);
  657.   if (params->CtxAdptLagrangeMult == 1)
  658.   {
  659.     get_mem2Dodouble(&(img->lambda_mf_factor), 10, 52 + img->bitdepth_luma_qp_scale, img->bitdepth_luma_qp_scale);
  660.   }
  661.   img->b_frame_to_code = 0;
  662.   img->GopLevels = (params->successive_Bframe) ? 1 : 0;
  663.   img->mb_y_upd=0;
  664.   RandomIntraInit (img->PicWidthInMbs, img->FrameHeightInMbs, params->RandomIntraMBRefresh);
  665.   InitSEIMessages(); 
  666.   initInput(&params->source, &params->output);
  667.   // Allocate I/O Frame memory
  668.   if (AllocateFrameMemory(img, params->source.size))
  669.     no_mem_exit("AllocateFrameMemory: buf");
  670.   // Initialize filtering parameters. If sending parameters, the offsets are
  671.   // multiplied by 2 since inputs are taken in "div 2" format.
  672.   // If not sending parameters, all fields are cleared
  673.   if (params->DFSendParameters)
  674.   {
  675.     for (j = 0; j < 2; j++)
  676.     {
  677.       for (i = 0; i < NUM_SLICE_TYPES; i++)
  678.       {
  679.         params->DFAlpha[j][i] <<= 1;
  680.         params->DFBeta [j][i] <<= 1;
  681.       }
  682.     }
  683.   }
  684.   else
  685.   {
  686.     for (j = 0; j < 2; j++)
  687.     {
  688.       for (i = 0; i < NUM_SLICE_TYPES; i++)
  689.       {
  690.         params->DFDisableIdc[j][i] = 0;
  691.         params->DFAlpha     [j][i] = 0;
  692.         params->DFBeta      [j][i] = 0;
  693.       }
  694.     }
  695.   }
  696.   img->ChromaArrayType = params->separate_colour_plane_flag ? 0 : params->yuv_format;
  697.   if (params->RDPictureDecision)
  698.     img->frm_iter = 3;
  699.   else
  700.     img->frm_iter = 1;
  701. }
  702. /*!
  703.  ***********************************************************************
  704.  * brief
  705.  *    Free the Image structures
  706.  * par Input:
  707.  *    Image Parameters ImageParameters *img
  708.  ***********************************************************************
  709.  */
  710. void free_img ()
  711. {
  712.   // Delete Frame memory 
  713.   DeleteFrameMemory();
  714.   CloseSEIMessages(); 
  715.   if (!params->IntraProfile)
  716.   {
  717.     free_mem_mv (img->pred_mv);
  718.     free_mem_mv (img->all_mv);
  719.     if (params->BiPredMotionEstimation)
  720.     {
  721.       free_mem_bipred_mv (img->bipred_mv);
  722.     }
  723.   }
  724.   free_mem_ACcoeff (img->cofAC);
  725.   free_mem_DCcoeff (img->cofDC);
  726.   if (params->AdaptiveRounding)
  727.   {
  728.     free_mem3Dint(img->fadjust4x4);
  729.     free_mem3Dint(img->fadjust8x8);
  730.     if (img->yuv_format != 0)
  731.     {
  732.       free_mem4Dint(img->fadjust4x4Cr);
  733.       free_mem4Dint(img->fadjust8x8Cr);
  734.     }
  735.   }
  736.   if (params->MbInterlace)
  737.   {
  738.     if (!params->IntraProfile)
  739.     {    
  740.       free_mem_mv (rddata_top_frame_mb.pred_mv);
  741.       free_mem_mv (rddata_top_frame_mb.all_mv);
  742.       free_mem_mv (rddata_bot_frame_mb.pred_mv);
  743.       free_mem_mv (rddata_bot_frame_mb.all_mv);
  744.     }
  745.     free_mem_ACcoeff (rddata_top_frame_mb.cofAC);
  746.     free_mem_DCcoeff (rddata_top_frame_mb.cofDC);
  747.     free_mem_ACcoeff (rddata_bot_frame_mb.cofAC);
  748.     free_mem_DCcoeff (rddata_bot_frame_mb.cofDC);
  749.     if ( params->MbInterlace != FRAME_MB_PAIR_CODING )
  750.     {
  751.       if (!params->IntraProfile)
  752.       {
  753.         free_mem_mv (rddata_top_field_mb.pred_mv);
  754.         free_mem_mv (rddata_top_field_mb.all_mv);
  755.         free_mem_mv (rddata_bot_field_mb.pred_mv);
  756.         free_mem_mv (rddata_bot_field_mb.all_mv);
  757.       }
  758.       free_mem_ACcoeff (rddata_top_field_mb.cofAC);
  759.       free_mem_DCcoeff (rddata_top_field_mb.cofDC);
  760.       free_mem_ACcoeff (rddata_bot_field_mb.cofAC);
  761.       free_mem_DCcoeff (rddata_bot_field_mb.cofDC);
  762.     }
  763.   }
  764.   if (params->UseRDOQuant && params->RDOQ_QP_Num > 1)
  765.   {
  766.     free_mem_ACcoeff (rddata_trellis_curr.cofAC);
  767.     free_mem_DCcoeff (rddata_trellis_curr.cofDC);
  768.     free_mem_ACcoeff (rddata_trellis_best.cofAC);
  769.     free_mem_DCcoeff (rddata_trellis_best.cofDC);
  770.     if (!params->IntraProfile)
  771.     {    
  772.       free_mem_mv (rddata_trellis_curr.pred_mv);
  773.       free_mem_mv (rddata_trellis_curr.all_mv);
  774.       free_mem_mv (rddata_trellis_best.pred_mv);
  775.       free_mem_mv (rddata_trellis_best.all_mv);
  776.       if (params->Transform8x8Mode && params->RDOQ_CP_MV)
  777.       {
  778.         free_mem5Dshort(tmp_mv8);
  779.         free_mem5Dshort(tmp_pmv8);
  780.         free_mem3Dint(motion_cost8);
  781.       }
  782.     }
  783.   }
  784.   free (img->quad - (imax(img->max_imgpel_value_comp[0],img->max_imgpel_value_comp[1]) + 1));
  785.   if (params->MbInterlace)
  786.   {
  787.     free_mem2D((byte**) rddata_bot_frame_mb.ipredmode);
  788.     free_mem2D((byte**) rddata_top_field_mb.ipredmode);
  789.     free_mem2D((byte**) rddata_bot_field_mb.ipredmode);
  790.   }
  791. }
  792. /*!
  793.  ************************************************************************
  794.  * brief
  795.  *    Allocates the picture structure along with its dependent
  796.  *    data structures
  797.  * return
  798.  *    Pointer to a Picture
  799.  ************************************************************************
  800.  */
  801. Picture *malloc_picture()
  802. {
  803.   Picture *pic;
  804.   if ((pic = calloc (1, sizeof (Picture))) == NULL) no_mem_exit ("malloc_picture: Picture structure");
  805.   //! Note: slice structures are allocated as needed in code_a_picture
  806.   return pic;
  807. }
  808. /*!
  809.  ************************************************************************
  810.  * brief
  811.  *    Frees a picture
  812.  * param
  813.  *    pic: POinter to a Picture to be freed
  814.  ************************************************************************
  815.  */
  816. void free_picture(Picture *pic)
  817. {
  818.   if (pic != NULL)
  819.   {
  820.     free_slice_list(pic);
  821.     free (pic);
  822.   }
  823. }
  824. /*!
  825.  ************************************************************************
  826.  * brief
  827.  *    memory allocation for original picture buffers
  828.  ************************************************************************
  829.  */
  830. int init_orig_buffers(void)
  831. {
  832.   int memory_size = 0;
  833.   int nplane;
  834.   // allocate memory for reference frame buffers: img_org_frm
  835.   if( IS_INDEPENDENT(params) )
  836.   {
  837.     for( nplane=0; nplane<MAX_PLANE; nplane++ )
  838.     {
  839.       memory_size += get_mem2Dpel(&img_org_frm[nplane], img->height, img->width);
  840.     }
  841.   }
  842.   else
  843.   {
  844.     memory_size += get_mem2Dpel(&img_org_frm[0], img->height, img->width);
  845.     if (img->yuv_format != YUV400)
  846.     {
  847.       int i, j, k;
  848.       memory_size += get_mem2Dpel(&img_org_frm[1], img->height_cr, img->width_cr);
  849.       memory_size += get_mem2Dpel(&img_org_frm[2], img->height_cr, img->width_cr);
  850.       for (k = 1; k < 3; k++)
  851.         for (j = 0; j < img->height_cr; j++)
  852.           for (i = 0; i < img->width_cr; i++)
  853.             img_org_frm[k][j][i] = 128;
  854.     }
  855.   }
  856.   if (!active_sps->frame_mbs_only_flag)
  857.   {
  858.     // allocate memory for field reference frame buffers
  859.     memory_size += init_top_bot_planes(img_org_frm[0], img->height, img->width, &img_org_top[0], &img_org_bot[0]);
  860.     if (img->yuv_format != YUV400)
  861.     {
  862.       memory_size += 4*(sizeof(imgpel**));
  863.       memory_size += init_top_bot_planes(img_org_frm[1], img->height_cr, img->width_cr, &(img_org_top[1]), &(img_org_bot[1]));
  864.       memory_size += init_top_bot_planes(img_org_frm[2], img->height_cr, img->width_cr, &(img_org_top[2]), &(img_org_bot[2]));
  865.     }
  866.   }
  867.   return memory_size;
  868. }
  869. /*!
  870.  ************************************************************************
  871.  * brief
  872.  *    Dynamic memory allocation of frame size related global buffers
  873.  *    buffers are defined in global.h, allocated memory must be freed in
  874.  *    void free_global_buffers()
  875.  * par Input:
  876.  *    Input Parameters struct inp_par *inp,                            n
  877.  *    Image Parameters ImageParameters *img
  878.  * return Number of allocated bytes
  879.  ************************************************************************
  880.  */
  881. int init_global_buffers(void)
  882. {
  883.   int j, memory_size=0;
  884. #ifdef _ADAPT_LAST_GROUP_
  885.   extern int *last_P_no_frm;
  886.   extern int *last_P_no_fld;
  887. //  if ((last_P_no_frm = (int*)malloc(2*img->max_num_references*sizeof(int))) == NULL)
  888.   if ((last_P_no_frm = (int*)malloc(32*sizeof(int))) == NULL)
  889.     no_mem_exit("init_global_buffers: last_P_no");
  890.   if (!active_sps->frame_mbs_only_flag)
  891. //    if ((last_P_no_fld = (int*)malloc(4*img->max_num_references*sizeof(int))) == NULL)
  892.     if ((last_P_no_fld = (int*)malloc(64*sizeof(int))) == NULL)
  893.       no_mem_exit("init_global_buffers: last_P_no");
  894. #endif
  895.   if ((enc_frame_picture = (StorablePicture**)malloc(6 * sizeof(StorablePicture*))) == NULL)
  896.     no_mem_exit("init_global_buffers: *enc_frame_picture");
  897.   for (j = 0; j < 6; j++)
  898.     enc_frame_picture[j] = NULL;
  899.   if ((enc_field_picture = (StorablePicture**)malloc(2 * sizeof(StorablePicture*))) == NULL)
  900.     no_mem_exit("init_global_buffers: *enc_field_picture");
  901.   for (j = 0; j < 2; j++)
  902.     enc_field_picture[j] = NULL;
  903.   if ((frame_pic = (Picture**)malloc(img->frm_iter * sizeof(Picture*))) == NULL)
  904.     no_mem_exit("init_global_buffers: *frame_pic");
  905.   for (j = 0; j < img->frm_iter; j++)
  906.     frame_pic[j] = malloc_picture();
  907.   if (params->si_frame_indicator || params->sp_periodicity)
  908.   {
  909.     si_frame_indicator=0; //indicates whether the frame is SP or SI
  910.     number_sp2_frames=0;
  911.     frame_pic_si = malloc_picture();//picture buffer for the encoded SI picture
  912.     //allocation of lrec and lrec_uv for SI picture
  913.     get_mem2Dint (&lrec, img->height, img->width);
  914.     get_mem3Dint (&lrec_uv, 2, img->height, img->width);
  915.   }
  916.   // Allocate memory for field picture coding
  917.   if (params->PicInterlace != FRAME_CODING)
  918.   { 
  919.     if ((field_pic = (Picture**)malloc(2 * sizeof(Picture*))) == NULL)
  920.       no_mem_exit("init_global_buffers: *field_pic");
  921.     for (j = 0; j < 2; j++)
  922.       field_pic[j] = malloc_picture();
  923.   }
  924.   memory_size += init_orig_buffers();
  925.   memory_size += get_mem2Dint(&PicPos, img->FrameSizeInMbs + 1, 2);
  926.   for (j = 0; j < (int) img->FrameSizeInMbs + 1; j++)
  927.   {
  928.     PicPos[j][0] = (j % img->PicWidthInMbs);
  929.     PicPos[j][1] = (j / img->PicWidthInMbs);
  930.   }
  931.   if (params->WeightedPrediction || params->WeightedBiprediction || params->GenerateMultiplePPS)
  932.   {
  933.     // Currently only use up to 32 references. Need to use different indicator such as maximum num of references in list
  934.     memory_size += get_mem3Dint(&wp_weight, 6, MAX_REFERENCE_PICTURES, 3);
  935.     memory_size += get_mem3Dint(&wp_offset, 6, MAX_REFERENCE_PICTURES, 3);
  936.     memory_size += get_mem4Dint(&wbp_weight, 6, MAX_REFERENCE_PICTURES, MAX_REFERENCE_PICTURES, 3);
  937.   }
  938.   // allocate memory for reference frames of each block: refFrArr
  939.   if ((params->successive_Bframe != 0) || (params->BRefPictures > 0) || (params->ProfileIDC != 66))
  940.   {
  941.     memory_size += get_mem3D((byte ****)(void*)(&direct_ref_idx), 2, img->height_blk, img->width_blk);
  942.     memory_size += get_mem2D((byte ***)(void*)&direct_pdir, img->height_blk, img->width_blk);
  943.   }
  944.   if (params->rdopt == 3)
  945.   {
  946.     decs->dec_mbY = NULL;
  947.     decs->dec_mbY8x8 = NULL;
  948.     memory_size += get_mem3Dpel(&decs->dec_mbY, params->NoOfDecoders, 16, 16);
  949.     memory_size += get_mem3Dpel(&decs->dec_mbY8x8, params->NoOfDecoders, 16, 16);
  950.   }
  951.   if (params->RestrictRef)
  952.   {
  953.     memory_size += get_mem2D(&pixel_map,   img->height,   img->width);
  954.     memory_size += get_mem2D(&refresh_map, img->height/8, img->width/8);
  955.   }
  956.   if (!active_sps->frame_mbs_only_flag)
  957.   {
  958.     memory_size += get_mem2Dpel(&imgY_com, img->height, img->width);
  959.     if (img->yuv_format != YUV400)
  960.     {
  961.       memory_size += get_mem3Dpel(&imgUV_com, 2, img->height_cr, img->width_cr);
  962.     }
  963.   }
  964.   // allocate and set memory relating to motion estimation
  965.   if (!params->IntraProfile)
  966.   {  
  967.     if (params->SearchMode == UM_HEX)
  968.     {
  969.       memory_size += UMHEX_get_mem();
  970.     }
  971.     else if (params->SearchMode == UM_HEX_SIMPLE)
  972.     {
  973.       smpUMHEX_init();
  974.       memory_size += smpUMHEX_get_mem();
  975.     }
  976.     else if (params->SearchMode == EPZS)
  977.       memory_size += EPZSInit(params, img);
  978.   }
  979.   if (params->RCEnable)
  980.     rc_allocate_memory();
  981.   if (params->redundant_pic_flag)
  982.   {
  983.     memory_size += get_mem2Dpel(&imgY_tmp, img->height, img->width);
  984.     memory_size += get_mem2Dpel(&imgUV_tmp[0], img->height_cr, img->width_cr);
  985.     memory_size += get_mem2Dpel(&imgUV_tmp[1], img->height_cr, img->width_cr);
  986.   }
  987.   memory_size += get_mem2Dint (&imgY_sub_tmp, img->height_padded, img->width_padded);
  988.   if ( params->ChromaMCBuffer )
  989.     chroma_mc_setup();
  990.   img_padded_size_x       = (img->width + 2 * IMG_PAD_SIZE);
  991.   img_padded_size_x2      = (img_padded_size_x << 1);
  992.   img_padded_size_x4      = (img_padded_size_x << 2);
  993.   img_padded_size_x_m8    = (img_padded_size_x - 8);
  994.   img_padded_size_x_m8x8  = (img_padded_size_x - BLOCK_SIZE_8x8);
  995.   img_padded_size_x_m4x4  = (img_padded_size_x - BLOCK_SIZE);
  996.   img_cr_padded_size_x    = (img->width_cr + 2 * img_pad_size_uv_x);
  997.   img_cr_padded_size_x2   = (img_cr_padded_size_x << 1);
  998.   img_cr_padded_size_x4   = (img_cr_padded_size_x << 2);
  999.   img_cr_padded_size_x_m8 = (img_cr_padded_size_x - 8);
  1000.   // RGB images for distortion calculation
  1001.   // Recommended to do this allocation (and de-allocation) in 
  1002.   // the appropriate file instead of here.
  1003.   if(params->DistortionYUVtoRGB)
  1004.   {
  1005.     memory_size += create_RGB_memory(img);
  1006.   }
  1007.   pWPX = NULL;
  1008.   if ( params->WPMCPrecision )
  1009.   {
  1010.     wpxInitWPXObject();
  1011.   }
  1012.   return memory_size;
  1013. }
  1014. /*!
  1015.  ************************************************************************
  1016.  * brief
  1017.  *    Free allocated memory of original picture buffers
  1018.  ************************************************************************
  1019.  */
  1020. void free_orig_planes(void)
  1021. {
  1022.   if( IS_INDEPENDENT(params) )
  1023.   {
  1024.     int nplane;
  1025.     for( nplane=0; nplane<MAX_PLANE; nplane++ )
  1026.     {
  1027.       free_mem2Dpel(img_org_frm[nplane]);      // free ref frame buffers
  1028.     }
  1029.   }
  1030.   else
  1031.   {
  1032.     free_mem2Dpel(img_org_frm[0]);      // free ref frame buffers
  1033.     if (img->yuv_format != YUV400)
  1034.     {
  1035.       free_mem2Dpel(img_org_frm[1]);
  1036.       free_mem2Dpel(img_org_frm[2]);
  1037.     }
  1038.   }
  1039.   if (!active_sps->frame_mbs_only_flag)
  1040.   {
  1041.     free_top_bot_planes(img_org_top[0], img_org_bot[0]);
  1042.     if (img->yuv_format != YUV400)
  1043.     {
  1044.       free_top_bot_planes(img_org_top[1], img_org_bot[1]);
  1045.       free_top_bot_planes(img_org_top[2], img_org_bot[2]);
  1046.     }
  1047.   }
  1048. }
  1049. /*!
  1050.  ************************************************************************
  1051.  * brief
  1052.  *    Free allocated memory of frame size related global buffers
  1053.  *    buffers are defined in global.h, allocated memory is allocated in
  1054.  *    int get_mem4global_buffers()
  1055.  * par Input:
  1056.  *    Input Parameters struct inp_par *inp,                             n
  1057.  *    Image Parameters ImageParameters *img
  1058.  * par Output:
  1059.  *    none
  1060.  ************************************************************************
  1061.  */
  1062. void free_global_buffers(void)
  1063. {
  1064.   int  i,j;
  1065. #ifdef _ADAPT_LAST_GROUP_
  1066.   extern int *last_P_no_frm;
  1067.   extern int *last_P_no_fld;
  1068.   free (last_P_no_frm);
  1069.   free (last_P_no_fld);
  1070. #endif
  1071.   if (enc_frame_picture)
  1072.     free (enc_frame_picture);
  1073.   if (frame_pic)
  1074.   {
  1075.     for (j = 0; j < img->frm_iter; j++)
  1076.     {
  1077.       if (frame_pic[j])
  1078.         free_picture (frame_pic[j]);
  1079.     }
  1080.     free (frame_pic);
  1081.   }
  1082.   if (enc_field_picture)
  1083.     free (enc_field_picture);
  1084.   if (field_pic)
  1085.   {
  1086.     for (j = 0; j < 2; j++)
  1087.     {
  1088.       if (field_pic[j])
  1089.         free_picture (field_pic[j]);
  1090.     }
  1091.     free (field_pic);
  1092.   }
  1093.   // Deallocation of SI picture related memory
  1094.   if (params->si_frame_indicator || params->sp_periodicity)
  1095.   {
  1096.     free_picture (frame_pic_si);
  1097.     //deallocation of lrec and lrec_uv for SI frames
  1098.     free_mem2Dint (lrec);
  1099.     free_mem3Dint (lrec_uv);
  1100.   }
  1101.   free_orig_planes();
  1102.   // free lookup memory which helps avoid divides with PicWidthInMbs
  1103.   free_mem2Dint(PicPos);
  1104.   // Free Qmatrices and offsets
  1105.   free_QMatrix();
  1106.   free_QOffsets();
  1107.   if ( params->WPMCPrecision )
  1108.   {
  1109.     wpxFreeWPXObject();
  1110.   }
  1111.   if (params->WeightedPrediction || params->WeightedBiprediction || params->GenerateMultiplePPS)
  1112.   {
  1113.     free_mem3Dint(wp_weight );
  1114.     free_mem3Dint(wp_offset );
  1115.     free_mem4Dint(wbp_weight);
  1116.   }
  1117.   if ((stats->successive_Bframe != 0) || (params->BRefPictures > 0)||(params->ProfileIDC != 66))
  1118.   {
  1119.     free_mem3D((byte ***)direct_ref_idx);
  1120.     free_mem2D((byte **) direct_pdir);
  1121.   } // end if B frame
  1122.   if (imgY_sub_tmp) // free temp quarter pel frame buffers
  1123.   {
  1124.     free_mem2Dint (imgY_sub_tmp);
  1125.     imgY_sub_tmp=NULL;
  1126.   }
  1127.   // free mem, allocated in init_img()
  1128.   // free intra pred mode buffer for blocks
  1129.   free_mem2D((byte**)img->ipredmode);
  1130.   free_mem2D((byte**)img->ipredmode8x8);
  1131.   free(img->b8x8info);
  1132.   if( IS_INDEPENDENT(params) )
  1133.   {
  1134.     for( i=0; i<MAX_PLANE; i++ ){
  1135.       free(img->mb_data_JV[i]);
  1136.     }
  1137.   }
  1138.   else
  1139.   {
  1140.     free(img->mb_data);
  1141.   }
  1142.   free_mem2D((byte**)rddata_top_frame_mb.ipredmode);
  1143.   free_mem2D((byte**)rddata_trellis_curr.ipredmode);
  1144.   free_mem2D((byte**)rddata_trellis_best.ipredmode);
  1145.   if(params->UseConstrainedIntraPred)
  1146.   {
  1147.     free (img->intra_block);
  1148.   }
  1149.   if (params->CtxAdptLagrangeMult == 1)
  1150.   {
  1151.     free(mb16x16_cost_frame);
  1152.   }
  1153.   if (params->rdopt == 3)
  1154.   {
  1155.     if (decs->dec_mbY)
  1156.     {
  1157.        free_mem3Dpel(decs->dec_mbY);
  1158.     }
  1159.     if (decs->dec_mbY8x8)
  1160.     {
  1161.        free_mem3Dpel(decs->dec_mbY8x8);
  1162.     }
  1163.   }
  1164.   if (params->RestrictRef)
  1165.   {
  1166.     free(pixel_map[0]);
  1167.     free(pixel_map);
  1168.     free(refresh_map[0]);
  1169.     free(refresh_map);
  1170.   }
  1171.   if (!active_sps->frame_mbs_only_flag)
  1172.   {
  1173.     free_mem2Dpel(imgY_com);
  1174.     if (img->yuv_format != YUV400)
  1175.     {
  1176.       free_mem3Dpel(imgUV_com);
  1177.     }
  1178.   }
  1179.   free_mem3Dint(img->nz_coeff);
  1180.   free_mem2Dolm     (img->lambda, img->bitdepth_luma_qp_scale);
  1181.   free_mem2Dodouble (img->lambda_md, img->bitdepth_luma_qp_scale);
  1182.   free_mem3Dodouble (img->lambda_me, 10, 52 + img->bitdepth_luma_qp_scale, img->bitdepth_luma_qp_scale);
  1183.   free_mem3Doint    (img->lambda_mf, 10, 52 + img->bitdepth_luma_qp_scale, img->bitdepth_luma_qp_scale);
  1184.   if (params->CtxAdptLagrangeMult == 1)
  1185.   {
  1186.     free_mem2Dodouble(img->lambda_mf_factor, img->bitdepth_luma_qp_scale);
  1187.   }
  1188.   if (!params->IntraProfile)
  1189.   {
  1190.     if (params->SearchMode == UM_HEX)
  1191.     {
  1192.       UMHEX_free_mem();
  1193.     }
  1194.     else if (params->SearchMode == UM_HEX_SIMPLE)
  1195.     {
  1196.       smpUMHEX_free_mem();
  1197.     }
  1198.     else if (params->SearchMode == EPZS)
  1199.     {
  1200.       EPZSDelete(params);
  1201.     }
  1202.   }
  1203.   if (params->RCEnable)
  1204.     rc_free_memory();
  1205.   if (params->redundant_pic_flag)
  1206.   {
  1207.     free_mem2Dpel(imgY_tmp);
  1208.     free_mem2Dpel(imgUV_tmp[0]);
  1209.     free_mem2Dpel(imgUV_tmp[1]);
  1210.   }
  1211.   // Again process should be moved into cconv_yuv2rgb.c file for cleanliness
  1212.   // These should not be globals but instead only be visible through that code.
  1213.   if(params->DistortionYUVtoRGB)
  1214.   {
  1215.     delete_RGB_memory();
  1216.   }
  1217. }
  1218. /*!
  1219.  ************************************************************************
  1220.  * brief
  1221.  *    Allocate memory for mv
  1222.  * par Input:
  1223.  *    Image Parameters ImageParameters *img                             n
  1224.  *    int****** mv
  1225.  * return memory size in bytes
  1226.  ************************************************************************
  1227.  */
  1228. int get_mem_mv (short ******* mv)
  1229. {
  1230.   // LIST, reference, block_type, block_y, block_x, component
  1231.   get_mem6Dshort(mv, 2, img->max_num_references, 9, 4, 4, 2);
  1232.   return 2 * img->max_num_references * 9 * 4 * 4 * 2 * sizeof(short);
  1233. }
  1234. /*!
  1235.  ************************************************************************
  1236.  * brief
  1237.  *    Allocate memory for bipredictive mv 
  1238.  * par Input:
  1239.  *    Image Parameters ImageParameters *img                             n
  1240.  *    int****** mv
  1241.  * return memory size in bytes
  1242.  ************************************************************************
  1243.  */
  1244. int get_mem_bipred_mv (short******** bipred_mv) 
  1245. {
  1246.   if(((*bipred_mv) = (short*******)calloc(2, sizeof(short******))) == NULL)
  1247.     no_mem_exit("get_mem_bipred_mv: bipred_mv");
  1248.   
  1249.   get_mem6Dshort(*bipred_mv, 2 * 2, img->max_num_references, 9, 4, 4, 2);
  1250.   (*bipred_mv)[1] =  (*bipred_mv)[0] + 2;
  1251.   
  1252.   return 2 * 2 * img->max_num_references * 9 * 4 * 4 * 2 * sizeof(short);
  1253. }
  1254. /*!
  1255.  ************************************************************************
  1256.  * brief
  1257.  *    Free memory from mv
  1258.  * par Input:
  1259.  *    int****** mv
  1260.  ************************************************************************
  1261.  */
  1262. void free_mem_mv (short****** mv)
  1263. {
  1264.   free_mem6Dshort(mv);
  1265. }
  1266. /*!
  1267.  ************************************************************************
  1268.  * brief
  1269.  *    Free memory from mv
  1270.  * par Input:
  1271.  *    int****** mv
  1272.  ************************************************************************
  1273.  */
  1274. void free_mem_bipred_mv (short******* bipred_mv) 
  1275. {
  1276.   if (bipred_mv)
  1277.   {
  1278.     free_mem6Dshort(*bipred_mv);
  1279.     free (bipred_mv);
  1280.   }
  1281.   else
  1282.   {
  1283.     error ("free_mem_bipred_mv: trying to free unused memory",100);
  1284.   }
  1285. }
  1286. /*!
  1287.  ************************************************************************
  1288.  * brief
  1289.  *    Allocate memory for AC coefficients
  1290.  ************************************************************************
  1291.  */
  1292. int get_mem_ACcoeff (int***** cofAC)
  1293. {
  1294.   int num_blk8x8 = 4 + img->num_blk8x8_uv;
  1295.   
  1296.   get_mem4Dint(cofAC, num_blk8x8, 4, 2, 65);
  1297.   return num_blk8x8*4*2*65*sizeof(int);// 18->65 for ABT
  1298. }
  1299. /*!
  1300.  ************************************************************************
  1301.  * brief
  1302.  *    Allocate memory for DC coefficients
  1303.  ************************************************************************
  1304.  */
  1305. int get_mem_DCcoeff (int**** cofDC)
  1306. {
  1307.   get_mem3Dint(cofDC, 3, 2, 18);
  1308.   return 3 * 2 * 18 * sizeof(int); 
  1309. }
  1310. /*!
  1311.  ************************************************************************
  1312.  * brief
  1313.  *    Free memory of AC coefficients
  1314.  ************************************************************************
  1315.  */
  1316. void free_mem_ACcoeff (int**** cofAC)
  1317. {
  1318.   free_mem4Dint(cofAC);
  1319. }
  1320. /*!
  1321.  ************************************************************************
  1322.  * brief
  1323.  *    Free memory of DC coefficients
  1324.  ************************************************************************
  1325.  */
  1326. void free_mem_DCcoeff (int*** cofDC)
  1327. {
  1328.   free_mem3Dint(cofDC);
  1329. }
  1330. /*!
  1331.  ************************************************************************
  1332.  * brief
  1333.  *    Set the image type for I,P and SP pictures (not B!)
  1334.  ************************************************************************
  1335.  */
  1336. static void SetImgType(void)
  1337. {
  1338.   int intra_refresh = (params->intra_period == 0) ? (IMG_NUMBER == 0) : (( ( img->frm_number - img->lastIntraNumber) % params->intra_period ) == 0);
  1339.   int idr_refresh;
  1340.   if ( params->idr_period && !params->adaptive_idr_period )
  1341.     idr_refresh = (( ( img->frm_number - img->lastIDRnumber  ) % params->idr_period   ) == 0);
  1342.   else if ( params->idr_period && params->adaptive_idr_period == 1 )
  1343.     idr_refresh = (( ( img->frm_number - imax(img->lastIntraNumber, img->lastIDRnumber)  ) % params->idr_period   ) == 0);
  1344.   else
  1345.     idr_refresh = (IMG_NUMBER == 0);
  1346.   if (intra_refresh || idr_refresh)
  1347.   {
  1348.     set_slice_type( I_SLICE );        // set image type for first image to I-frame
  1349.   }
  1350.   else
  1351.   {
  1352.     set_slice_type((params->sp_periodicity && ((IMG_NUMBER % params->sp_periodicity) == 0))
  1353.       ? SP_SLICE  : ((params->BRefPictures == 2) ? B_SLICE : P_SLICE) );
  1354.   }
  1355. }
  1356. /*!
  1357.  ************************************************************************
  1358.  * brief
  1359.  *    Sets indices to appropriate level constraints, depending on 
  1360.  *    current level_idc
  1361.  ************************************************************************
  1362.  */
  1363. void SetLevelIndices(void)
  1364. {
  1365.   switch(active_sps->level_idc)
  1366.   {
  1367.   case 9:
  1368.     img->LevelIndex=1;
  1369.     break;
  1370.   case 10:
  1371.     img->LevelIndex=0;
  1372.     break;
  1373.   case 11:
  1374.     if (!IS_FREXT_PROFILE(active_sps->profile_idc) && (active_sps->constrained_set3_flag == 0))
  1375.       img->LevelIndex=2;
  1376.     else
  1377.       img->LevelIndex=1;
  1378.     break;
  1379.   case 12:
  1380.     img->LevelIndex=3;
  1381.     break;
  1382.   case 13:
  1383.     img->LevelIndex=4;
  1384.     break;
  1385.   case 20:
  1386.     img->LevelIndex=5;
  1387.     break;
  1388.   case 21:
  1389.     img->LevelIndex=6;
  1390.     break;
  1391.   case 22:
  1392.     img->LevelIndex=7;
  1393.     break;
  1394.   case 30:
  1395.     img->LevelIndex=8;
  1396.     break;
  1397.   case 31:
  1398.     img->LevelIndex=9;
  1399.     break;
  1400.   case 32:
  1401.     img->LevelIndex=10;
  1402.     break;
  1403.   case 40:
  1404.     img->LevelIndex=11;
  1405.     break;
  1406.   case 41:
  1407.     img->LevelIndex=12;
  1408.     break;
  1409.   case 42:
  1410.     if (!IS_FREXT_PROFILE(active_sps->profile_idc))
  1411.       img->LevelIndex=13;
  1412.     else
  1413.       img->LevelIndex=14;
  1414.     break;
  1415.   case 50:
  1416.     img->LevelIndex=15;
  1417.     break;
  1418.   case 51:
  1419.     img->LevelIndex=16;
  1420.     break;
  1421.   default:
  1422.     fprintf ( stderr, "Warning: unknown LevelIDC, using maximum level 5.1 n" );
  1423.     img->LevelIndex=16;
  1424.     break;
  1425.   }
  1426. }
  1427. /*!
  1428.  ************************************************************************
  1429.  * brief
  1430.  *    initialize key frames and corresponding redundant frames.
  1431.  ************************************************************************
  1432.  */
  1433. void Init_redundant_frame()
  1434. {
  1435.   if (params->redundant_pic_flag)
  1436.   {
  1437.     if (params->successive_Bframe)
  1438.     {
  1439.       error("B frame not supported when redundant picture used!", 100);
  1440.     }
  1441.     if (params->PicInterlace)
  1442.     {
  1443.       error("Interlace not supported when redundant picture used!", 100);
  1444.     }
  1445.     if (params->num_ref_frames < params->PrimaryGOPLength)
  1446.     {
  1447.       error("NumberReferenceFrames must be no less than PrimaryGOPLength", 100);
  1448.     }
  1449.     if ((1<<params->NumRedundantHierarchy) > params->PrimaryGOPLength)
  1450.     {
  1451.       error("PrimaryGOPLength must be greater than 2^NumRedundantHeirarchy", 100);
  1452.     }
  1453.     if (params->Verbose != 1)
  1454.     {
  1455.       error("Redundant slices not supported when Verbose != 1", 100);
  1456.     }
  1457.   }
  1458.   key_frame = 0;
  1459.   redundant_coding = 0;
  1460.   img->redundant_pic_cnt = 0;
  1461.   frameNuminGOP = img->frm_number % params->PrimaryGOPLength;
  1462.   if (img->frm_number == 0)
  1463.   {
  1464.     frameNuminGOP = -1;
  1465.   }
  1466. }
  1467. /*!
  1468.  ************************************************************************
  1469.  * brief
  1470.  *    allocate redundant frames in a primary GOP.
  1471.  ************************************************************************
  1472.  */
  1473. void Set_redundant_frame()
  1474. {
  1475.   int GOPlength = params->PrimaryGOPLength;
  1476.   //start frame of GOP
  1477.   if (frameNuminGOP == 0)
  1478.   {
  1479.     redundant_coding = 0;
  1480.     key_frame = 1;
  1481.     redundant_ref_idx = GOPlength;
  1482.   }
  1483.   //1/2 position
  1484.   if (params->NumRedundantHierarchy > 0)
  1485.   {
  1486.     if (frameNuminGOP == GOPlength/2)
  1487.     {
  1488.       redundant_coding = 0;
  1489.       key_frame = 1;
  1490.       redundant_ref_idx = GOPlength/2;
  1491.     }
  1492.   }
  1493.   //1/4, 3/4 position
  1494.   if (params->NumRedundantHierarchy > 1)
  1495.   {
  1496.     if (frameNuminGOP == GOPlength/4 || frameNuminGOP == GOPlength*3/4)
  1497.     {
  1498.       redundant_coding = 0;
  1499.       key_frame = 1;
  1500.       redundant_ref_idx = GOPlength/4;
  1501.     }
  1502.   }
  1503.   //1/8, 3/8, 5/8, 7/8 position
  1504.   if (params->NumRedundantHierarchy > 2)
  1505.   {
  1506.     if (frameNuminGOP == GOPlength/8 || frameNuminGOP == GOPlength*3/8
  1507.       || frameNuminGOP == GOPlength*5/8 || frameNuminGOP == GOPlength*7/8)
  1508.     {
  1509.       redundant_coding = 0;
  1510.       key_frame = 1;
  1511.       redundant_ref_idx = GOPlength/8;
  1512.     }
  1513.   }
  1514.   //1/16, 3/16, 5/16, 7/16, 9/16, 11/16, 13/16 position
  1515.   if (params->NumRedundantHierarchy > 3)
  1516.   {
  1517.     if (frameNuminGOP == GOPlength/16 || frameNuminGOP == GOPlength*3/16
  1518.       || frameNuminGOP == GOPlength*5/16 || frameNuminGOP == GOPlength*7/16
  1519.       || frameNuminGOP == GOPlength*9/16 || frameNuminGOP == GOPlength*11/16
  1520.       || frameNuminGOP == GOPlength*13/16)
  1521.     {
  1522.       redundant_coding = 0;
  1523.       key_frame = 1;
  1524.       redundant_ref_idx = GOPlength/16;
  1525.     }
  1526.   }
  1527. }
  1528. /*!
  1529.  ************************************************************************
  1530.  * brief
  1531.  *    encode on redundant frame.
  1532.  ************************************************************************
  1533.  */
  1534. void encode_one_redundant_frame()
  1535. {
  1536.   key_frame = 0;
  1537.   redundant_coding = 1;
  1538.   img->redundant_pic_cnt = 1;
  1539.   if (img->type == I_SLICE)
  1540.   {
  1541.     set_slice_type( P_SLICE );
  1542.   }
  1543.   encode_one_frame();
  1544. }
  1545. /*!
  1546.  ************************************************************************
  1547.  * brief
  1548.  *    Setup Chroma MC Variables
  1549.  ************************************************************************
  1550.  */
  1551. void chroma_mc_setup(void)
  1552. {
  1553.   // initialize global variables used for chroma interpolation and buffering
  1554.   if ( img->yuv_format == YUV420 )
  1555.   {
  1556.     img_pad_size_uv_x = IMG_PAD_SIZE >> 1;
  1557.     img_pad_size_uv_y = IMG_PAD_SIZE >> 1;
  1558.     chroma_mask_mv_y = 7;
  1559.     chroma_mask_mv_x = 7;
  1560.     chroma_shift_x = 3;
  1561.     chroma_shift_y = 3;
  1562.   }
  1563.   else if ( img->yuv_format == YUV422 )
  1564.   {
  1565.     img_pad_size_uv_x = IMG_PAD_SIZE >> 1;
  1566.     img_pad_size_uv_y = IMG_PAD_SIZE;
  1567.     chroma_mask_mv_y = 3;
  1568.     chroma_mask_mv_x = 7;
  1569.     chroma_shift_y = 2;
  1570.     chroma_shift_x = 3;
  1571.   }
  1572.   else
  1573.   { // YUV444
  1574.     img_pad_size_uv_x = IMG_PAD_SIZE;
  1575.     img_pad_size_uv_y = IMG_PAD_SIZE;
  1576.     chroma_mask_mv_y = 3;
  1577.     chroma_mask_mv_x = 3;
  1578.     chroma_shift_y = 2;
  1579.     chroma_shift_x = 2;
  1580.   }
  1581.   shift_cr_y  = chroma_shift_y - 2;
  1582.   shift_cr_x  = chroma_shift_x - 2;
  1583. }