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

Audio

开发平台:

Visual C++

  1. /*!
  2.  ***********************************************************************
  3.  * file image.c
  4.  *
  5.  * brief
  6.  *    Decode a Slice
  7.  *
  8.  * author
  9.  *    Main contributors (see contributors.h for copyright, address and affiliation details)
  10.  *    - Inge Lille-Langoy               <inge.lille-langoy@telenor.com>
  11.  *    - Rickard Sjoberg                 <rickard.sjoberg@era.ericsson.se>
  12.  *    - Jani Lainema                    <jani.lainema@nokia.com>
  13.  *    - Sebastian Purreiter             <sebastian.purreiter@mch.siemens.de>
  14.  *    - Byeong-Moon Jeon                <jeonbm@lge.com>
  15.  *    - Thomas Wedi                     <wedi@tnt.uni-hannover.de>
  16.  *    - Gabi Blaettermann
  17.  *    - Ye-Kui Wang                     <wyk@ieee.org>
  18.  *    - Antti Hallapuro                 <antti.hallapuro@nokia.com>
  19.  *    - Alexis Tourapis                 <alexismt@ieee.org>
  20.  *    - Jill Boyce                      <jill.boyce@thomson.net>
  21.  *    - Saurav K Bandyopadhyay          <saurav@ieee.org>
  22.  *    - Zhenyu Wu                       <Zhenyu.Wu@thomson.net
  23.  *    - Purvin Pandit                   <Purvin.Pandit@thomson.net>
  24.  *
  25.  ***********************************************************************
  26.  */
  27. #include "contributors.h"
  28. #include <math.h>
  29. #include <limits.h>
  30. #include "global.h"
  31. #include "image.h"
  32. #include "fmo.h"
  33. #include "nalu.h"
  34. #include "parset.h"
  35. #include "header.h"
  36. #include "annexb.h"
  37. #include "rtp.h"
  38. #include "sei.h"
  39. #include "output.h"
  40. #include "mb_access.h"
  41. #include "memalloc.h"
  42. #include "macroblock.h"
  43. #include "loopfilter.h"
  44. #include "biaridecod.h"
  45. #include "context_ini.h"
  46. #include "cabac.h"
  47. #include "vlc.h"
  48. #include "quant.h"
  49. #include "errorconcealment.h"
  50. #include "erc_api.h"
  51. extern objectBuffer_t *erc_object_list;
  52. extern ercVariables_t *erc_errorVar;
  53. extern frame erc_recfr;
  54. extern int erc_mvperMB;
  55. extern ImageParameters *erc_img;
  56. //extern FILE *p_out2;
  57. extern StorablePicture **listX[6];
  58. extern ColocatedParams *Co_located;
  59. extern StorablePicture *no_reference_picture;
  60. int non_conforming_stream;
  61. StorablePicture *dec_picture;
  62. StorablePicture *dec_picture_JV[MAX_PLANE];  //!< dec_picture to be used during 4:4:4 independent mode decoding
  63. OldSliceParams old_slice;
  64. void MbAffPostProc(void)
  65. {
  66.   imgpel temp[32][16];
  67.   imgpel ** imgY  = dec_picture->imgY;
  68.   imgpel ***imgUV = dec_picture->imgUV;
  69.   int i, y, x0, y0, uv;
  70.   for (i=0; i<(int)dec_picture->PicSizeInMbs; i+=2)
  71.   {
  72.     if (dec_picture->motion.mb_field[i])
  73.     {
  74.       get_mb_pos(i, img->mb_size[IS_LUMA], &x0, &y0);
  75.       for (y=0; y<(2*MB_BLOCK_SIZE);y++)
  76.         memcpy(temp[y], &imgY[y0+y][x0], MB_BLOCK_SIZE * sizeof(imgpel));
  77.       for (y=0; y<MB_BLOCK_SIZE;y++)
  78.       {
  79.          memcpy(&imgY[y0+(2*y  )][x0], temp[y              ], MB_BLOCK_SIZE * sizeof(imgpel));
  80.          memcpy(&imgY[y0+(2*y+1)][x0], temp[y+MB_BLOCK_SIZE], MB_BLOCK_SIZE * sizeof(imgpel));
  81.       }
  82.        
  83.       if (dec_picture->chroma_format_idc != YUV400)
  84.       {
  85.         x0 = x0 / (16/img->mb_cr_size_x);
  86.         y0 = y0 / (16/img->mb_cr_size_y);
  87.         for (uv=0; uv<2; uv++)
  88.         {
  89.           for (y=0; y<(2*img->mb_cr_size_y);y++)
  90.             memcpy(temp[y], &imgUV[uv][y0+y][x0], img->mb_cr_size_x * sizeof(imgpel));
  91.           for (y=0; y<img->mb_cr_size_y;y++)
  92.           {
  93.             memcpy(&imgUV[uv][y0+(2*y  )][x0], temp[y                  ], img->mb_cr_size_x * sizeof(imgpel));
  94.             memcpy(&imgUV[uv][y0+(2*y+1)][x0], temp[y+img->mb_cr_size_y], img->mb_cr_size_x * sizeof(imgpel));
  95.           }
  96.         }
  97.       }
  98.     }
  99.   }
  100. }
  101. /*!
  102.  ***********************************************************************
  103.  * brief
  104.  *    decodes one I- or P-frame
  105.  *
  106.  ***********************************************************************
  107.  */
  108. int decode_one_frame(ImageParameters *img, struct inp_par *inp, struct snr_par *snr)
  109. {
  110.   int current_header;
  111.   Slice *currSlice = img->currentSlice;
  112.   int i;
  113.   img->current_slice_nr = 0;
  114.   img->current_mb_nr = -4711;     // initialized to an impossible value for debugging -- correct value is taken from slice header
  115.   currSlice->next_header = -8888; // initialized to an impossible value for debugging -- correct value is taken from slice header
  116.   img->num_dec_mb = 0;
  117.   img->newframe = 1;
  118.   while ((currSlice->next_header != EOS && currSlice->next_header != SOP))
  119.   {
  120.     current_header = read_new_slice();
  121.     // error tracking of primary and redundant slices.
  122.     Error_tracking();
  123.     // If primary and redundant are received and primary is correct, discard the redundant
  124.     // else, primary slice will be replaced with redundant slice.
  125.     if(img->frame_num == previous_frame_num && img->redundant_pic_cnt !=0
  126.       && Is_primary_correct !=0 && current_header != EOS)
  127.     {
  128.       continue;
  129.     }
  130.     // update reference flags and set current ref_flag
  131.     if(!(img->redundant_pic_cnt != 0 && previous_frame_num == img->frame_num))
  132.     {
  133.       for(i=16;i>0;i--)
  134.       {
  135.         ref_flag[i] = ref_flag[i-1];
  136.       }
  137.     }
  138.     ref_flag[0] = img->redundant_pic_cnt==0 ? Is_primary_correct : Is_redundant_correct;
  139.     previous_frame_num = img->frame_num;
  140.     if (current_header == EOS)
  141.     {
  142.       exit_picture();
  143.       return EOS;
  144.     }
  145.     decode_slice(img, inp, current_header);
  146.     img->newframe = 0;
  147.     img->current_slice_nr++;
  148.   }
  149.   exit_picture();
  150.   return (SOP);
  151. }
  152. /*!
  153.  ************************************************************************
  154.  * brief
  155.  *    Convert file read buffer to source picture structure
  156.  * param imgX
  157.  *    Pointer to image plane
  158.  * param buf
  159.  *    Buffer for file output
  160.  * param size_x
  161.  *    horizontal image size in pixel
  162.  * param size_y
  163.  *    vertical image size in pixel
  164.  * param symbol_size_in_bytes
  165.  *    number of bytes used per pel
  166.  ************************************************************************
  167.  */
  168. void buf2img (imgpel** imgX, unsigned char* buf, int size_x, int size_y, int symbol_size_in_bytes)
  169. {
  170.   int i,j;
  171.   unsigned short tmp16, ui16;
  172.   unsigned long  tmp32, ui32;
  173.   if (symbol_size_in_bytes> sizeof(imgpel))
  174.   {
  175.     error ("Source picture has higher bit depth than imgpel data type. nPlease recompile with larger data type for imgpel.", 500);
  176.   }
  177.   if (( sizeof(char) == sizeof (imgpel)) && ( sizeof(char) == symbol_size_in_bytes))
  178.   {
  179.     // imgpel == pixel_in_file == 1 byte -> simple copy
  180.     memcpy(&imgX[0][0], buf, size_x * size_y);
  181.     //for(j=0;j<size_y;j++)
  182.       //memcpy(&imgX[j][0], buf+j*size_x, size_x);
  183.   }
  184.   else
  185.   {
  186.     // sizeof (imgpel) > sizeof(char)
  187.     if (testEndian())
  188.     {
  189.       // big endian
  190.       switch (symbol_size_in_bytes)
  191.       {
  192.       case 1:
  193.         {
  194.           for(j=0;j<size_y;j++)
  195.             for(i=0;i<size_x;i++)
  196.             {
  197.               imgX[j][i]= buf[i+j*size_x];
  198.             }
  199.           break;
  200.         }
  201.       case 2:
  202.         {
  203.           for(j=0;j<size_y;j++)
  204.             for(i=0;i<size_x;i++)
  205.             {
  206.               memcpy(&tmp16, buf+((i+j*size_x)*2), 2);
  207.               ui16  = (unsigned short) ((tmp16 >> 8) | ((tmp16&0xFF)<<8));
  208.               imgX[j][i] = (imgpel) ui16;
  209.             }
  210.           break;
  211.         }
  212.       case 4:
  213.         {
  214.           for(j=0;j<size_y;j++)
  215.             for(i=0;i<size_x;i++)
  216.             {
  217.               memcpy(&tmp32, buf+((i+j*size_x)*4), 4);
  218.               ui32  = ((tmp32&0xFF00)<<8) | ((tmp32&0xFF)<<24) | ((tmp32&0xFF0000)>>8) | ((tmp32&0xFF000000)>>24);
  219.               imgX[j][i] = (imgpel) ui32;
  220.             }
  221.         }
  222.       default:
  223.         {
  224.            error ("reading only from formats of 8, 16 or 32 bit allowed on big endian architecture", 500);
  225.            break;
  226.         }
  227.       }
  228.     }
  229.     else
  230.     {
  231.       // little endian
  232.       if (symbol_size_in_bytes == 1)
  233.       {
  234.         for (j=0; j < size_y; j++)
  235.         {
  236.           for (i=0; i < size_x; i++)
  237.           {
  238.             imgX[j][i]=*(buf++);
  239.           }
  240.         }
  241.       }
  242.       else
  243.       {
  244.         for (j=0; j < size_y; j++)
  245.         {
  246.           int jpos = j*size_x;
  247.           for (i=0; i < size_x; i++)
  248.           {
  249.             imgX[j][i]=0;
  250.             memcpy(&(imgX[j][i]), buf +((i+jpos)*symbol_size_in_bytes), symbol_size_in_bytes);
  251.           }
  252.         }
  253.       }
  254.     }
  255.   }
  256. }
  257. /*!
  258.  ************************************************************************
  259.  * brief
  260.  *    Calculate the value of frame_no
  261.  ************************************************************************
  262. */
  263. void calculate_frame_no(StorablePicture *p)
  264. {
  265.   // calculate frame number
  266.   int  psnrPOC = active_sps->mb_adaptive_frame_field_flag ? p->poc /(params->poc_scale) : p->poc/(params->poc_scale);
  267.   if (psnrPOC==0)// && img->psnr_number)
  268.     img->idr_psnr_number = img->number*img->ref_poc_gap/(params->poc_scale);
  269.   img->psnr_number=imax(img->psnr_number,img->idr_psnr_number+psnrPOC);
  270.   frame_no = img->idr_psnr_number + psnrPOC;
  271. }
  272. /*!
  273. ************************************************************************
  274. * brief
  275. *    Find PSNR for all three components.Compare decoded frame with
  276. *    the original sequence. Read inp->jumpd frames to reflect frame skipping.
  277. ************************************************************************
  278. */
  279. void find_snr(
  280.               struct snr_par  *snr,   //!< pointer to snr parameters
  281.               StorablePicture *p,     //!< picture to be compared
  282.               int p_ref)              //!< open reference YUV file
  283. {
  284.   static const int SubWidthC  [4]= { 1, 2, 2, 1};
  285.   static const int SubHeightC [4]= { 1, 2, 1, 1};
  286.   int crop_left, crop_right, crop_top, crop_bottom;
  287.   int i,j, k;
  288.   int64 diff_comp[3] = {0};
  289.   int64  status;
  290.   int symbol_size_in_bytes = img->pic_unit_bitsize_on_disk/8;
  291.   int comp_size_x[3], comp_size_y[3];
  292.   int64 framesize_in_bytes;
  293.   unsigned int max_pix_value_sqd[3] = {iabs2(img->max_imgpel_value_comp[0]),  iabs2(img->max_imgpel_value_comp[1]), iabs2(img->max_imgpel_value_comp[2])};
  294.   Boolean rgb_output = (Boolean) (active_sps->vui_seq_parameters.matrix_coefficients==0);
  295.   unsigned char *buf;
  296.   imgpel **cur_ref[3]  = {imgY_ref, p->chroma_format_idc != YUV400 ? imgUV_ref[0] : NULL, p->chroma_format_idc != YUV400 ? imgUV_ref[1] : NULL};
  297.   imgpel **cur_comp[3] = {p->imgY,  p->chroma_format_idc != YUV400 ? p->imgUV[0]  : NULL , p->chroma_format_idc!= YUV400 ? p->imgUV[1]  : NULL}; 
  298.   // picture error concealment
  299.   char yuv_types[4][6]= {"4:0:0","4:2:0","4:2:2","4:4:4"};
  300.   // cropping for luma
  301.   if (p->frame_cropping_flag)
  302.   {
  303.     crop_left   = SubWidthC[p->chroma_format_idc] * p->frame_cropping_rect_left_offset;
  304.     crop_right  = SubWidthC[p->chroma_format_idc] * p->frame_cropping_rect_right_offset;
  305.     crop_top    = SubHeightC[p->chroma_format_idc]*( 2 - p->frame_mbs_only_flag ) *  p->frame_cropping_rect_top_offset;
  306.     crop_bottom = SubHeightC[p->chroma_format_idc]*( 2 - p->frame_mbs_only_flag ) *  p->frame_cropping_rect_bottom_offset;
  307.   }
  308.   else
  309.   {
  310.     crop_left = crop_right = crop_top = crop_bottom = 0;
  311.   }
  312.   comp_size_x[0] = p->size_x - crop_left - crop_right;
  313.   comp_size_y[0] = p->size_y - crop_top - crop_bottom;
  314.   // cropping for chroma
  315.   if (p->frame_cropping_flag)
  316.   {
  317.     crop_left   = p->frame_cropping_rect_left_offset;
  318.     crop_right  = p->frame_cropping_rect_right_offset;
  319.     crop_top    = ( 2 - p->frame_mbs_only_flag ) *  p->frame_cropping_rect_top_offset;
  320.     crop_bottom = ( 2 - p->frame_mbs_only_flag ) *   p->frame_cropping_rect_bottom_offset;
  321.   }
  322.   else
  323.   {
  324.     crop_left = crop_right = crop_top = crop_bottom = 0;
  325.   }
  326.   if ((p->chroma_format_idc==YUV400) && params->write_uv)
  327.   {
  328.     comp_size_x[1] = comp_size_x[2] = (p->size_x >> 1);
  329.     comp_size_y[1] = comp_size_y[2] = (p->size_y >> 1);
  330.   }
  331.   else
  332.   {
  333.     // These could be computed once and attached to the StorablePicture structure
  334.     comp_size_x[1] = comp_size_x[2] = (p->size_x_cr - crop_left - crop_right); 
  335.     comp_size_y[1] = comp_size_y[2] = (p->size_y_cr - crop_top  - crop_bottom);
  336.   }
  337.   framesize_in_bytes = (((int64) comp_size_x[0] * comp_size_y[0]) + ((int64) comp_size_x[1] * comp_size_y[1] ) * 2) * symbol_size_in_bytes;
  338.   // KS: this buffer should actually be allocated only once, but this is still much faster than the previous version
  339.   buf = malloc ( comp_size_x[0] * comp_size_y[0] * symbol_size_in_bytes );
  340.   if (NULL == buf)
  341.   {
  342.     no_mem_exit("find_snr: buf");
  343.   }
  344.   status = lseek (p_ref, framesize_in_bytes * frame_no, SEEK_SET);
  345.   if (status == -1)
  346.   {
  347.     fprintf(stderr, "Error in seeking frame number: %dn", frame_no);
  348.     free (buf);
  349.     return;
  350.   }
  351.   if(rgb_output)
  352.     lseek (p_ref, framesize_in_bytes/3, SEEK_CUR);
  353.   for (k = 0; k < ((p->chroma_format_idc != YUV400) ? 3 : 1); k++)
  354.   {
  355.     if(rgb_output && k == 2)
  356.       lseek (p_ref, -framesize_in_bytes, SEEK_CUR);
  357.     read(p_ref, buf, comp_size_x[k] * comp_size_y[k] * symbol_size_in_bytes);
  358.     buf2img(cur_ref[k], buf, comp_size_x[k], comp_size_y[k], symbol_size_in_bytes);
  359.     for (j=0; j < comp_size_y[k]; ++j)
  360.     {
  361.       for (i=0; i < comp_size_x[k]; ++i)
  362.       {
  363.         diff_comp[k] += iabs2(cur_comp[k][j][i] - cur_ref[k][j][i]);
  364.       }
  365.     }
  366.     // Collecting SNR statistics
  367.     snr->snr[k] = psnr( max_pix_value_sqd[k], comp_size_x[k] * comp_size_y[k], (float) diff_comp[k]);   
  368.     if (img->number == 0) // first
  369.     {
  370.       snr->snra[k] = snr->snr[k];                                                        // keep luma snr for first frame
  371.     }
  372.     else
  373.     {
  374.       snr->snra[k] = (float)(snr->snra[k]*(snr->frame_ctr)+snr->snr[k])/(snr->frame_ctr + 1); // average snr chroma for all frames
  375.     }
  376.   }
  377.    if(rgb_output)
  378.      lseek (p_ref, framesize_in_bytes*2/3, SEEK_CUR);
  379.   free (buf);
  380.   // picture error concealment
  381.   if(p->concealed_pic)
  382.   {
  383.       fprintf(stdout,"%04d(P)  %8d %5d %5d %7.4f %7.4f %7.4f  %s %5dn",
  384.           frame_no, p->frame_poc, p->pic_num, p->qp,
  385.           snr->snr[0], snr->snr[1], snr->snr[2], yuv_types[p->chroma_format_idc], 0);
  386.   }
  387. }
  388. void reorder_lists(int currSliceType, Slice * currSlice)
  389. {
  390.   if ((currSliceType != I_SLICE)&&(currSliceType != SI_SLICE))
  391.   {
  392.     if (currSlice->ref_pic_list_reordering_flag_l0)
  393.     {
  394.       reorder_ref_pic_list(listX[0], &listXsize[0],
  395.                            img->num_ref_idx_l0_active - 1,
  396.                            currSlice->reordering_of_pic_nums_idc_l0,
  397.                            currSlice->abs_diff_pic_num_minus1_l0,
  398.                            currSlice->long_term_pic_idx_l0);
  399.     }
  400.     if (no_reference_picture == listX[0][img->num_ref_idx_l0_active-1])
  401.     {
  402.       if (non_conforming_stream)
  403.         printf("RefPicList0[ num_ref_idx_l0_active_minus1 ] is equal to 'no reference picture'n");
  404.       else
  405.         error("RefPicList0[ num_ref_idx_l0_active_minus1 ] is equal to 'no reference picture', invalid bitstream",500);
  406.     }
  407.     // that's a definition
  408.     listXsize[0] = img->num_ref_idx_l0_active;
  409.   }
  410.   if (currSliceType == B_SLICE)
  411.   {
  412.     if (currSlice->ref_pic_list_reordering_flag_l1)
  413.     {
  414.       reorder_ref_pic_list(listX[1], &listXsize[1],
  415.                            img->num_ref_idx_l1_active - 1,
  416.                            currSlice->reordering_of_pic_nums_idc_l1,
  417.                            currSlice->abs_diff_pic_num_minus1_l1,
  418.                            currSlice->long_term_pic_idx_l1);
  419.     }
  420.     if (no_reference_picture == listX[1][img->num_ref_idx_l1_active-1])
  421.     {
  422.       if (non_conforming_stream)
  423.         printf("RefPicList1[ num_ref_idx_l1_active_minus1 ] is equal to 'no reference picture'n");
  424.       else
  425.         error("RefPicList1[ num_ref_idx_l1_active_minus1 ] is equal to 'no reference picture', invalid bitstream",500);
  426.     }
  427.     // that's a definition
  428.     listXsize[1] = img->num_ref_idx_l1_active;
  429.   }
  430.   free_ref_pic_list_reordering_buffer(currSlice);
  431. }
  432. /*!
  433.  ************************************************************************
  434.  * brief
  435.  *    initialize ref_pic_num array
  436.  ************************************************************************
  437.  */
  438. void set_ref_pic_num(void)
  439. {
  440.   int i,j;
  441.   int slice_id=img->current_slice_nr;
  442.   for (i=0;i<listXsize[LIST_0];i++)
  443.   {
  444.     dec_picture->ref_pic_num        [slice_id][LIST_0][i] = listX[LIST_0][i]->poc * 2 + ((listX[LIST_0][i]->structure==BOTTOM_FIELD)?1:0) ;
  445.     dec_picture->frm_ref_pic_num    [slice_id][LIST_0][i] = listX[LIST_0][i]->frame_poc * 2;
  446.     dec_picture->top_ref_pic_num    [slice_id][LIST_0][i] = listX[LIST_0][i]->top_poc * 2;
  447.     dec_picture->bottom_ref_pic_num [slice_id][LIST_0][i] = listX[LIST_0][i]->bottom_poc * 2 + 1;
  448.     //printf("POCS %d %d %d %d ",listX[LIST_0][i]->frame_poc,listX[LIST_0][i]->bottom_poc,listX[LIST_0][i]->top_poc,listX[LIST_0][i]->poc);
  449.     //printf("refid %d %d %d %dn",(int) dec_picture->frm_ref_pic_num[LIST_0][i],(int) dec_picture->top_ref_pic_num[LIST_0][i],(int) dec_picture->bottom_ref_pic_num[LIST_0][i],(int) dec_picture->ref_pic_num[LIST_0][i]);
  450.   }
  451.   for (i=0;i<listXsize[LIST_1];i++)
  452.   {
  453.     dec_picture->ref_pic_num        [slice_id][LIST_1][i] = listX[LIST_1][i]->poc  *2 + ((listX[LIST_1][i]->structure==BOTTOM_FIELD)?1:0);
  454.     dec_picture->frm_ref_pic_num    [slice_id][LIST_1][i] = listX[LIST_1][i]->frame_poc * 2;
  455.     dec_picture->top_ref_pic_num    [slice_id][LIST_1][i] = listX[LIST_1][i]->top_poc * 2;
  456.     dec_picture->bottom_ref_pic_num [slice_id][LIST_1][i] = listX[LIST_1][i]->bottom_poc * 2 + 1;
  457.   }
  458.   if (!active_sps->frame_mbs_only_flag)
  459.   {
  460.     if (img->structure==FRAME)
  461.     {
  462.       for (j=2;j<6;j++)
  463.       {
  464.         for (i=0;i<listXsize[j];i++)
  465.         {
  466.           dec_picture->ref_pic_num        [slice_id][j][i] = listX[j][i]->poc * 2 + ((listX[j][i]->structure==BOTTOM_FIELD)?1:0);
  467.           dec_picture->frm_ref_pic_num    [slice_id][j][i] = listX[j][i]->frame_poc * 2 ;
  468.           dec_picture->top_ref_pic_num    [slice_id][j][i] = listX[j][i]->top_poc * 2 ;
  469.           dec_picture->bottom_ref_pic_num [slice_id][j][i] = listX[j][i]->bottom_poc * 2 + 1;
  470.         }
  471.       }
  472.     }
  473.   }
  474. }
  475. /*!
  476.  ************************************************************************
  477.  * brief
  478.  *    Reads new slice from bit_stream
  479.  ************************************************************************
  480.  */
  481. int read_new_slice(void)
  482. {
  483.   NALU_t *nalu = AllocNALU(MAX_CODED_FRAME_SIZE);
  484.   int current_header = 0;
  485.   int BitsUsedByHeader;
  486.   Slice *currSlice = img->currentSlice;
  487.   Bitstream *currStream;
  488.   int slice_id_a, slice_id_b, slice_id_c;
  489.   int redundant_pic_cnt_b, redundant_pic_cnt_c;
  490.   long ftell_position;
  491.   
  492.   while (1)
  493.   {
  494.     ftell_position = ftell(bits);
  495.     if (0 == read_next_nalu(bits, nalu))
  496.       return EOS;
  497.     switch (nalu->nal_unit_type)
  498.     {
  499.       case NALU_TYPE_SLICE:
  500.       case NALU_TYPE_IDR:
  501.         if (img->recovery_point || nalu->nal_unit_type == NALU_TYPE_IDR)
  502.         {
  503.           if (img->recovery_point_found == 0)
  504.           {
  505.             if (nalu->nal_unit_type != NALU_TYPE_IDR)
  506.             {
  507.               printf("Warning: Decoding does not start with an IDR picture.n");
  508.               non_conforming_stream = 1;
  509.             }
  510.             else
  511.               non_conforming_stream = 0;
  512.           }
  513.           img->recovery_point_found = 1;
  514.         }
  515.         if (img->recovery_point_found == 0)
  516.           break;
  517.         img->idr_flag = (nalu->nal_unit_type == NALU_TYPE_IDR);
  518.         img->nal_reference_idc = nalu->nal_reference_idc;
  519.         currSlice->dp_mode = PAR_DP_1;
  520.         currSlice->max_part_nr = 1;
  521.         currSlice->ei_flag = 0;
  522.         currStream = currSlice->partArr[0].bitstream;
  523.         currStream->ei_flag = 0;
  524.         currStream->frame_bitoffset = currStream->read_len = 0;
  525.         memcpy (currStream->streamBuffer, &nalu->buf[1], nalu->len-1);
  526.         currStream->code_len = currStream->bitstream_length = RBSPtoSODB(currStream->streamBuffer, nalu->len-1);
  527.         // Some syntax of the Slice Header depends on the parameter set, which depends on
  528.         // the parameter set ID of the SLice header.  Hence, read the pic_parameter_set_id
  529.         // of the slice header first, then setup the active parameter sets, and then read
  530.         // the rest of the slice header
  531.         BitsUsedByHeader = FirstPartOfSliceHeader();
  532.         UseParameterSet (currSlice->pic_parameter_set_id);
  533.         BitsUsedByHeader+= RestOfSliceHeader ();
  534.         FmoInit (active_pps, active_sps);
  535.         AssignQuantParam (active_pps, active_sps);
  536.         // if primary slice is replaced with redundant slice, set the correct image type
  537.         if(img->redundant_pic_cnt && Is_primary_correct==0 && Is_redundant_correct)
  538.         {
  539.           dec_picture->slice_type=img->type;
  540.         }
  541.         if(is_new_picture())
  542.         {
  543.           init_picture(img, params);
  544.           current_header = SOP;
  545.           //check zero_byte if it is also the first NAL unit in the access unit
  546.           CheckZeroByteVCL(nalu);
  547.         }
  548.         else
  549.           current_header = SOS;
  550.         init_lists(img->type, img->currentSlice->structure);
  551.         reorder_lists (img->type, img->currentSlice);
  552.         if (img->structure==FRAME)
  553.         {
  554.           init_mbaff_lists();
  555.         }
  556.         // From here on, active_sps, active_pps and the slice header are valid
  557.         if (img->MbaffFrameFlag)
  558.           img->current_mb_nr = currSlice->start_mb_nr << 1;
  559.         else
  560.           img->current_mb_nr = currSlice->start_mb_nr;
  561.         if (active_pps->entropy_coding_mode_flag)
  562.         {
  563.           int ByteStartPosition = currStream->frame_bitoffset/8;
  564.           if (currStream->frame_bitoffset%8 != 0)
  565.           {
  566.             ByteStartPosition++;
  567.           }
  568.           arideco_start_decoding (&currSlice->partArr[0].de_cabac, currStream->streamBuffer, ByteStartPosition, &currStream->read_len);
  569.         }
  570. // printf ("read_new_slice: returning %sn", current_header == SOP?"SOP":"SOS");
  571.         FreeNALU(nalu);
  572.         img->recovery_point = 0;
  573.         return current_header;
  574.         break;
  575.       case NALU_TYPE_DPA:
  576.         // read DP_A
  577.         currSlice->dpB_NotPresent =1; 
  578.         currSlice->dpC_NotPresent =1; 
  579.         img->idr_flag          = FALSE;
  580.         img->nal_reference_idc = nalu->nal_reference_idc;
  581.         currSlice->dp_mode     = PAR_DP_3;
  582.         currSlice->max_part_nr = 3;
  583.         currSlice->ei_flag     = 0;
  584.         currStream             = currSlice->partArr[0].bitstream;
  585.         currStream->ei_flag    = 0;
  586.         currStream->frame_bitoffset = currStream->read_len = 0;
  587.         memcpy (currStream->streamBuffer, &nalu->buf[1], nalu->len-1);
  588.         currStream->code_len = currStream->bitstream_length = RBSPtoSODB(currStream->streamBuffer, nalu->len-1);
  589.         BitsUsedByHeader     = FirstPartOfSliceHeader();
  590.         UseParameterSet (currSlice->pic_parameter_set_id);
  591.         BitsUsedByHeader    += RestOfSliceHeader ();
  592.         FmoInit (active_pps, active_sps);
  593.         if(is_new_picture())
  594.         {
  595.           init_picture(img, params);
  596.           current_header = SOP;
  597.           CheckZeroByteVCL(nalu);
  598.         }
  599.         else
  600.           current_header = SOS;
  601.         init_lists(img->type, img->currentSlice->structure);
  602.         reorder_lists (img->type, img->currentSlice);
  603.         if (img->structure==FRAME)
  604.         {
  605.           init_mbaff_lists();
  606.         }
  607.         // From here on, active_sps, active_pps and the slice header are valid
  608.         if (img->MbaffFrameFlag)
  609.           img->current_mb_nr = currSlice->start_mb_nr << 1;
  610.         else
  611.           img->current_mb_nr = currSlice->start_mb_nr;
  612.         // Now I need to read the slice ID, which depends on the value of
  613.         // redundant_pic_cnt_present_flag
  614.         slice_id_a  = ue_v("NALU: DP_A slice_id", currStream);
  615.         if (active_pps->entropy_coding_mode_flag)
  616.           error ("received data partition with CABAC, this is not allowed", 500);
  617.         // continue with reading next DP
  618.         ftell_position = ftell(bits);
  619.         if (0 == read_next_nalu(bits, nalu))
  620.           return current_header;
  621.         
  622.         if ( NALU_TYPE_DPB == nalu->nal_unit_type)
  623.         {
  624.           // we got a DPB
  625.           currStream             = currSlice->partArr[1].bitstream;
  626.           currStream->ei_flag    = 0;
  627.           currStream->frame_bitoffset = currStream->read_len = 0;
  628.           memcpy (currStream->streamBuffer, &nalu->buf[1], nalu->len-1);
  629.           currStream->code_len = currStream->bitstream_length = RBSPtoSODB(currStream->streamBuffer, nalu->len-1);
  630.           slice_id_b  = ue_v("NALU: DP_B slice_id", currStream);
  631.           currSlice->dpB_NotPresent = 0; 
  632.           if ((slice_id_b != slice_id_a) || (nalu->lost_packets))
  633.           {
  634.             printf ("Waning: got a data partition B which does not match DP_A (DP loss!)n");
  635.             currSlice->dpB_NotPresent =1; 
  636.             currSlice->dpC_NotPresent =1; 
  637.           }
  638.           else
  639.           {
  640.             if (active_pps->redundant_pic_cnt_present_flag)
  641.               redundant_pic_cnt_b = ue_v("NALU: DP_B redudant_pic_cnt", currStream);
  642.             else
  643.               redundant_pic_cnt_b = 0;
  644.             // we're finished with DP_B, so let's continue with next DP
  645.             ftell_position = ftell(bits);
  646.             if (0 == read_next_nalu(bits, nalu))
  647.               return current_header;
  648.           }
  649.         }
  650.         else
  651.         {
  652.           currSlice->dpB_NotPresent =1; 
  653.         }
  654.         // check if we got DP_C
  655.         if ( NALU_TYPE_DPC == nalu->nal_unit_type)
  656.         {
  657.           currStream             = currSlice->partArr[2].bitstream;
  658.           currStream->ei_flag    = 0;
  659.           currStream->frame_bitoffset = currStream->read_len = 0;
  660.           memcpy (currStream->streamBuffer, &nalu->buf[1], nalu->len-1);
  661.           currStream->code_len = currStream->bitstream_length = RBSPtoSODB(currStream->streamBuffer, nalu->len-1);
  662.           currSlice->dpC_NotPresent = 0;
  663.           slice_id_c  = ue_v("NALU: DP_C slice_id", currStream);
  664.           if ((slice_id_c != slice_id_a)|| (nalu->lost_packets))
  665.           {
  666.             printf ("Warning: got a data partition C which does not match DP_A(DP loss!)n");
  667.             //currSlice->dpB_NotPresent =1;
  668.             currSlice->dpC_NotPresent =1;
  669.           }
  670.           if (active_pps->redundant_pic_cnt_present_flag)
  671.             redundant_pic_cnt_c = ue_v("NALU:SLICE_C redudand_pic_cnt", currStream);
  672.           else
  673.             redundant_pic_cnt_c = 0;
  674.         }
  675.         else
  676.         {
  677.           currSlice->dpC_NotPresent =1;
  678.         }
  679.         // check if we read anything else than the expected partitions
  680.         if ((nalu->nal_unit_type != NALU_TYPE_DPB) && (nalu->nal_unit_type != NALU_TYPE_DPC))
  681.         {
  682.           // reset bitstream position and read again in next call
  683.           fseek(bits, ftell_position, SEEK_SET);
  684.         }
  685.         FreeNALU(nalu);
  686.         return current_header;
  687.         break;
  688.       case NALU_TYPE_DPB:
  689.         printf ("found data partition B without matching DP A, discardingn");
  690.         break;
  691.       case NALU_TYPE_DPC:
  692.         printf ("found data partition C without matching DP A, discardingn");
  693.         break;
  694.       case NALU_TYPE_SEI:
  695.         //printf ("read_new_slice: Found NALU_TYPE_SEI, len %dn", nalu->len);
  696.         InterpretSEIMessage(nalu->buf,nalu->len,img);
  697.         break;
  698.       case NALU_TYPE_PPS:
  699.         ProcessPPS(nalu);
  700.         break;
  701.       case NALU_TYPE_SPS:
  702.         ProcessSPS(nalu);
  703.         break;
  704.       case NALU_TYPE_AUD:
  705. //        printf ("read_new_slice: Found 'Access Unit Delimiter' NAL unit, len %d, ignoredn", nalu->len);
  706.         break;
  707.       case NALU_TYPE_EOSEQ:
  708. //        printf ("read_new_slice: Found 'End of Sequence' NAL unit, len %d, ignoredn", nalu->len);
  709.         break;
  710.       case NALU_TYPE_EOSTREAM:
  711. //        printf ("read_new_slice: Found 'End of Stream' NAL unit, len %d, ignoredn", nalu->len);
  712.         break;
  713.       case NALU_TYPE_FILL:
  714.         printf ("read_new_slice: Found NALU_TYPE_FILL, len %dn", (int) nalu->len);
  715.         printf ("Skipping these filling bits, proceeding w/ next NALUn");
  716.         break;
  717.       default:
  718.         printf ("Found NALU type %d, len %d undefined, ignore NALU, moving onn", (int) nalu->nal_unit_type, (int) nalu->len);
  719.         break;
  720.     }
  721.   }
  722.   FreeNALU(nalu);
  723.   return  current_header;
  724. }
  725. /*!
  726.  ************************************************************************
  727.  * brief
  728.  *    Initializes the parameters for a new picture
  729.  ************************************************************************
  730.  */
  731. void init_picture(ImageParameters *img, struct inp_par *inp)
  732. {
  733.   int i,j,k,l;
  734.   Slice *currSlice = img->currentSlice;
  735.   int nplane;
  736.   if (dec_picture)
  737.   {
  738.     // this may only happen on slice loss
  739.     exit_picture();
  740.   }
  741.   if (img->recovery_point)
  742.     img->recovery_frame_num = (img->frame_num + img->recovery_frame_cnt) % img->MaxFrameNum;
  743.   if (img->idr_flag)
  744.     img->recovery_frame_num = img->frame_num;
  745.   if (img->recovery_point == 0 &&
  746.     img->frame_num != img->pre_frame_num &&
  747.     img->frame_num != (img->pre_frame_num + 1) % img->MaxFrameNum)
  748.   {
  749.     if (active_sps->gaps_in_frame_num_value_allowed_flag == 0)
  750.     {
  751.       // picture error concealment
  752.       if(inp->conceal_mode !=0)
  753.       {
  754.         if((img->frame_num) < ((img->pre_frame_num + 1) % img->MaxFrameNum))
  755.         {
  756.           /* Conceal lost IDR frames and any frames immediately
  757.              following the IDR. Use frame copy for these since
  758.              lists cannot be formed correctly for motion copy*/
  759.           img->conceal_mode = 1;
  760.           img->IDR_concealment_flag = 1;
  761.           conceal_lost_frames(img);
  762.           //reset to original concealment mode for future drops
  763.           img->conceal_mode = inp->conceal_mode;
  764.         }
  765.         else
  766.         {
  767.           //reset to original concealment mode for future drops
  768.           img->conceal_mode = inp->conceal_mode;
  769.           img->IDR_concealment_flag = 0;
  770.           conceal_lost_frames(img);
  771.         }
  772.       }
  773.       else
  774.       {   /* Advanced Error Concealment would be called here to combat unintentional loss of pictures. */
  775.         error("An unintentional loss of pictures occurs! Exitn", 100);
  776.       }
  777.     }
  778.     if(img->conceal_mode == 0)
  779.       fill_frame_num_gap(img);
  780.   }
  781.   if(img->nal_reference_idc)
  782.   {
  783.     img->pre_frame_num = img->frame_num;
  784.   }
  785.   img->num_dec_mb = 0;
  786.   //calculate POC
  787.   decode_poc(img);
  788.   if (img->recovery_frame_num == img->frame_num &&
  789.     img->recovery_poc == 0x7fffffff)
  790.     img->recovery_poc = img->framepoc;
  791.   if(img->nal_reference_idc)
  792.     img->last_ref_pic_poc = img->framepoc;
  793.   //  dumppoc (img);
  794.   if (img->structure==FRAME ||img->structure==TOP_FIELD)
  795.   {
  796.     gettime (&(img->start_time));             // start time
  797.   }
  798.   dec_picture = alloc_storable_picture ((PictureStructure) img->structure, img->width, img->height, img->width_cr, img->height_cr);
  799.   dec_picture->top_poc=img->toppoc;
  800.   dec_picture->bottom_poc=img->bottompoc;
  801.   dec_picture->frame_poc=img->framepoc;
  802.   dec_picture->qp = img->qp;
  803.   dec_picture->slice_qp_delta = currSlice->slice_qp_delta;
  804.   dec_picture->chroma_qp_offset[0] = active_pps->chroma_qp_index_offset;
  805.   dec_picture->chroma_qp_offset[1] = active_pps->second_chroma_qp_index_offset;
  806.   // reset all variables of the error concealment instance before decoding of every frame.
  807.   // here the third parameter should, if perfectly, be equal to the number of slices per frame.
  808.   // using little value is ok, the code will allocate more memory if the slice number is larger
  809.   ercReset(erc_errorVar, img->PicSizeInMbs, img->PicSizeInMbs, dec_picture->size_x);
  810.   erc_mvperMB = 0;
  811.   switch (img->structure )
  812.   {
  813.   case TOP_FIELD:
  814.     {
  815.       dec_picture->poc=img->toppoc;
  816.       img->number *= 2;
  817.       break;
  818.     }
  819.   case BOTTOM_FIELD:
  820.     {
  821.       dec_picture->poc=img->bottompoc;
  822.       img->number = img->number * 2 + 1;
  823.       break;
  824.     }
  825.   case FRAME:
  826.     {
  827.       dec_picture->poc=img->framepoc;
  828.       break;
  829.     }
  830.   default:
  831.     error("img->structure not initialized", 235);
  832.   }
  833.   img->current_slice_nr=0;
  834.   if (img->type > SI_SLICE)
  835.   {
  836.     set_ec_flag(SE_PTYPE);
  837.     img->type = P_SLICE;  // concealed element
  838.   }
  839.   // CAVLC init
  840.   if (active_pps->entropy_coding_mode_flag == UVLC)
  841.   {
  842.     for (i=0;i < (int)img->PicSizeInMbs; i++)    
  843.       for (j = 0; j < 3; j++)
  844.         for (l = 0; l < 4; l++)
  845.           for (k = 0; k < 4;k++)
  846.             img->nz_coeff[i][j][l][k]=-1;  // CAVLC
  847.   }
  848.   if(active_pps->constrained_intra_pred_flag)
  849.   {
  850.     for (i=0; i<(int)img->PicSizeInMbs; i++)
  851.     {
  852.       img->intra_block[i] = 1;
  853.     }
  854.   }
  855.   // Set the slice_nr member of each MB to -1, to ensure correct when packet loss occurs
  856.   // TO set Macroblock Map (mark all MBs as 'have to be concealed')
  857.   if( IS_INDEPENDENT(img) )
  858.   {
  859.     for( nplane=0; nplane<MAX_PLANE; nplane++ )
  860.     {      
  861.       for(i=0; i<(int)img->PicSizeInMbs; i++)
  862.       {
  863.         img->mb_data_JV[nplane][i].slice_nr = -1; 
  864.         img->mb_data_JV[nplane][i].ei_flag = 1;
  865.         img->mb_data_JV[nplane][i].dpl_flag = 0;
  866.       }
  867.     }
  868.   }
  869.   else
  870.   {
  871.     for(i=0; i<(int)img->PicSizeInMbs; i++)
  872.     {
  873.       img->mb_data[i].slice_nr = -1; 
  874.       img->mb_data[i].ei_flag = 1;
  875.       img->mb_data[i].dpl_flag = 0;
  876.     }
  877.   }
  878.   img->mb_y = img->mb_x = 0;
  879.   img->block_y_aff = img->block_y = img->pix_y = img->pix_c_y = 0; // define vertical positions
  880.   img->block_x = img->pix_x = img->pix_c_x = 0; // define horizontal positions
  881.   dec_picture->slice_type = img->type;
  882.   dec_picture->used_for_reference = (img->nal_reference_idc != 0);
  883.   dec_picture->idr_flag = img->idr_flag;
  884.   dec_picture->no_output_of_prior_pics_flag = img->no_output_of_prior_pics_flag;
  885.   dec_picture->long_term_reference_flag = img->long_term_reference_flag;
  886.   dec_picture->adaptive_ref_pic_buffering_flag = img->adaptive_ref_pic_buffering_flag;
  887.   dec_picture->dec_ref_pic_marking_buffer = img->dec_ref_pic_marking_buffer;
  888.   img->dec_ref_pic_marking_buffer = NULL;
  889.   dec_picture->MbaffFrameFlag = img->MbaffFrameFlag;
  890.   dec_picture->PicWidthInMbs = img->PicWidthInMbs;
  891.   get_mb_block_pos = dec_picture->MbaffFrameFlag ? get_mb_block_pos_mbaff : get_mb_block_pos_normal;
  892.   getNeighbour = dec_picture->MbaffFrameFlag ? getAffNeighbour : getNonAffNeighbour;
  893.   dec_picture->pic_num = img->frame_num;
  894.   dec_picture->frame_num = img->frame_num;
  895.   dec_picture->recovery_frame = (img->frame_num == img->recovery_frame_num);
  896.   dec_picture->coded_frame = (img->structure==FRAME);
  897.   dec_picture->chroma_format_idc = active_sps->chroma_format_idc;
  898.   dec_picture->frame_mbs_only_flag = active_sps->frame_mbs_only_flag;
  899.   dec_picture->frame_cropping_flag = active_sps->frame_cropping_flag;
  900.   if (dec_picture->frame_cropping_flag)
  901.   {
  902.     dec_picture->frame_cropping_rect_left_offset   = active_sps->frame_cropping_rect_left_offset;
  903.     dec_picture->frame_cropping_rect_right_offset  = active_sps->frame_cropping_rect_right_offset;
  904.     dec_picture->frame_cropping_rect_top_offset    = active_sps->frame_cropping_rect_top_offset;
  905.     dec_picture->frame_cropping_rect_bottom_offset = active_sps->frame_cropping_rect_bottom_offset;
  906.   }
  907. #if (ENABLE_OUTPUT_TONEMAPPING)
  908.   // store the necessary tone mapping sei into StorablePicture structure
  909.   dec_picture->seiHasTone_mapping = 0;
  910.   if (seiToneMapping.seiHasTone_mapping)
  911.   {
  912.     dec_picture->seiHasTone_mapping    = 1;
  913.     dec_picture->tone_mapping_model_id = seiToneMapping.model_id;
  914.     dec_picture->tonemapped_bit_depth  = seiToneMapping.sei_bit_depth;
  915.     dec_picture->tone_mapping_lut      = malloc(sizeof(int)*(1<<seiToneMapping.coded_data_bit_depth));
  916.     if (NULL == dec_picture->tone_mapping_lut)
  917.     {
  918.       no_mem_exit("init_picture: tone_mapping_lut");
  919.     }
  920.     memcpy(dec_picture->tone_mapping_lut, seiToneMapping.lut, sizeof(imgpel)*(1<<seiToneMapping.coded_data_bit_depth));
  921.     update_tone_mapping_sei();
  922.   }
  923. #endif
  924.   if( IS_INDEPENDENT(img) )
  925.   {
  926.     dec_picture_JV[0] = dec_picture;
  927.     dec_picture_JV[1] = alloc_storable_picture ((PictureStructure) img->structure, img->width, img->height, img->width_cr, img->height_cr);
  928.     copy_dec_picture_JV( dec_picture_JV[1], dec_picture_JV[0] );
  929.     dec_picture_JV[2] = alloc_storable_picture ((PictureStructure) img->structure, img->width, img->height, img->width_cr, img->height_cr);
  930.     copy_dec_picture_JV( dec_picture_JV[2], dec_picture_JV[0] );
  931.   }
  932. }
  933. /*!
  934.  ************************************************************************
  935.  * brief
  936.  *    finish decoding of a picture, conceal errors and store it
  937.  *    into the DPB
  938.  ************************************************************************
  939.  */
  940. void exit_picture(void)
  941. {
  942.   char yuv_types[4][6]= {"4:0:0","4:2:0","4:2:2","4:4:4"};
  943.   int ercStartMB;
  944.   int ercSegment;
  945.   frame recfr;
  946.   unsigned int i;
  947.   int structure, frame_poc, slice_type, refpic, qp, pic_num, chroma_format_idc, is_idr;
  948.   static char cslice_type[9];  
  949.   time_t tmp_time;                   // time used by decoding the last frame
  950.   char   yuvFormat[10];
  951.   int nplane;
  952.   // return if the last picture has already been finished
  953.   if (dec_picture==NULL)
  954.   {
  955.     return;
  956.   }
  957.   //deblocking for frame or field
  958.   if( IS_INDEPENDENT(img) )
  959.   {
  960.     int colour_plane_id = img->colour_plane_id;
  961.     for( nplane=0; nplane<MAX_PLANE; nplane++ )
  962.     {
  963.       change_plane_JV( nplane );
  964.       DeblockPicture( img, dec_picture );
  965.     }
  966.     img->colour_plane_id = colour_plane_id;
  967.     make_frame_picture_JV();
  968.   }
  969.   else
  970.   {
  971.     DeblockPicture( img, dec_picture );
  972.   }
  973.   if (dec_picture->MbaffFrameFlag)
  974.     MbAffPostProc();
  975.   recfr.yptr = &dec_picture->imgY[0][0];
  976.   if (dec_picture->chroma_format_idc != YUV400)
  977.   {
  978.     recfr.uptr = &dec_picture->imgUV[0][0][0];
  979.     recfr.vptr = &dec_picture->imgUV[1][0][0];
  980.   }
  981.   //! this is always true at the beginning of a picture
  982.   ercStartMB = 0;
  983.   ercSegment = 0;
  984.   //! mark the start of the first segment
  985.   if (!dec_picture->MbaffFrameFlag)
  986.   {
  987.     ercStartSegment(0, ercSegment, 0 , erc_errorVar);
  988.     //! generate the segments according to the macroblock map
  989.     for(i = 1; i<dec_picture->PicSizeInMbs; i++)
  990.     {
  991.       if(img->mb_data[i].ei_flag != img->mb_data[i-1].ei_flag)
  992.       {
  993.         ercStopSegment(i-1, ercSegment, 0, erc_errorVar); //! stop current segment
  994.         //! mark current segment as lost or OK
  995.         if(img->mb_data[i-1].ei_flag)
  996.           ercMarkCurrSegmentLost(dec_picture->size_x, erc_errorVar);
  997.         else
  998.           ercMarkCurrSegmentOK(dec_picture->size_x, erc_errorVar);
  999.         ercSegment++;  //! next segment
  1000.         ercStartSegment(i, ercSegment, 0 , erc_errorVar); //! start new segment
  1001.         ercStartMB = i;//! save start MB for this segment
  1002.       }
  1003.     }
  1004.     //! mark end of the last segment
  1005.     ercStopSegment(dec_picture->PicSizeInMbs-1, ercSegment, 0, erc_errorVar);
  1006.     if(img->mb_data[i-1].ei_flag)
  1007.       ercMarkCurrSegmentLost(dec_picture->size_x, erc_errorVar);
  1008.     else
  1009.       ercMarkCurrSegmentOK(dec_picture->size_x, erc_errorVar);
  1010.     //! call the right error concealment function depending on the frame type.
  1011.     erc_mvperMB /= dec_picture->PicSizeInMbs;
  1012.     erc_img = img;
  1013.     if(dec_picture->slice_type == I_SLICE || dec_picture->slice_type == SI_SLICE) // I-frame
  1014.       ercConcealIntraFrame(&recfr, dec_picture->size_x, dec_picture->size_y, erc_errorVar);
  1015.     else
  1016.       ercConcealInterFrame(&recfr, erc_object_list, dec_picture->size_x, dec_picture->size_y, erc_errorVar, dec_picture->chroma_format_idc);
  1017.   }
  1018.   if (img->structure == FRAME)         // buffer mgt. for frame mode
  1019.     frame_postprocessing(img);
  1020.   else
  1021.     field_postprocessing(img);   // reset all interlaced variables
  1022.   structure  = dec_picture->structure;
  1023.   slice_type = dec_picture->slice_type;
  1024.   frame_poc  = dec_picture->frame_poc;
  1025.   refpic     = dec_picture->used_for_reference;
  1026.   qp         = dec_picture->qp;
  1027.   pic_num    = dec_picture->pic_num;
  1028.   is_idr     = dec_picture->idr_flag;
  1029.   chroma_format_idc= dec_picture->chroma_format_idc;
  1030.   store_picture_in_dpb(dec_picture);
  1031.   dec_picture=NULL;
  1032.   if (img->last_has_mmco_5)
  1033.   {
  1034.     img->pre_frame_num = 0;
  1035.   }
  1036.   if (params->silent == FALSE)
  1037.   {
  1038.     if (structure==TOP_FIELD || structure==FRAME)
  1039.     {
  1040.       if(slice_type == I_SLICE && is_idr) // IDR picture
  1041.         strcpy(cslice_type,"IDR");
  1042.       else if(slice_type == I_SLICE) // I picture
  1043.         strcpy(cslice_type," I ");
  1044.       else if(slice_type == P_SLICE) // P pictures
  1045.         strcpy(cslice_type," P ");
  1046.       else if(slice_type == SP_SLICE) // SP pictures
  1047.         strcpy(cslice_type,"SP ");
  1048.       else if (slice_type == SI_SLICE)
  1049.         strcpy(cslice_type,"SI ");
  1050.       else if(refpic) // stored B pictures
  1051.         strcpy(cslice_type," B ");
  1052.       else // B pictures
  1053.         strcpy(cslice_type," b ");
  1054.       if (structure==FRAME)
  1055.       {
  1056.         strncat(cslice_type,")       ",8-strlen(cslice_type));
  1057.       }
  1058.     }
  1059.     else if (structure==BOTTOM_FIELD)
  1060.     {
  1061.       if(slice_type == I_SLICE && is_idr) // IDR picture
  1062.         strncat(cslice_type,"|IDR)",8-strlen(cslice_type));
  1063.       else if(slice_type == I_SLICE) // I picture
  1064.         strncat(cslice_type,"| I )",8-strlen(cslice_type));
  1065.       else if(slice_type == P_SLICE) // P pictures
  1066.         strncat(cslice_type,"| P )",8-strlen(cslice_type));
  1067.       else if(slice_type == SP_SLICE) // SP pictures
  1068.         strncat(cslice_type,"|SP )",8-strlen(cslice_type));
  1069.       else if (slice_type == SI_SLICE)
  1070.         strncat(cslice_type,"|SI )",8-strlen(cslice_type));
  1071.       else if(refpic) // stored B pictures
  1072.         strncat(cslice_type,"| B )",8-strlen(cslice_type));
  1073.       else // B pictures
  1074.         strncat(cslice_type,"| b )",8-strlen(cslice_type));   
  1075.     }
  1076.   }
  1077.   if ((structure==FRAME)||structure==BOTTOM_FIELD)
  1078.   {
  1079.     gettime (&(img->end_time));              // end time
  1080.     tmp_time= timediff(&(img->start_time), &(img->end_time));
  1081.     tot_time=tot_time + tmp_time;
  1082.     sprintf(yuvFormat,"%s", yuv_types[chroma_format_idc]);
  1083.     
  1084.     if (params->silent == FALSE)
  1085.     {
  1086.       if (p_ref != -1)
  1087.         fprintf(stdout,"%05d(%s%5d %5d %5d %8.4f %8.4f %8.4f  %s %7dn",
  1088.         frame_no, cslice_type, frame_poc, pic_num, qp, snr->snr[0], snr->snr[1], snr->snr[2], yuvFormat, (int)tmp_time);
  1089.     else
  1090.         fprintf(stdout,"%05d(%s%5d %5d %5d                             %s %7dn",
  1091.         frame_no, cslice_type, frame_poc, pic_num, qp, yuvFormat, (int)tmp_time);
  1092.     }
  1093.     else
  1094.       fprintf(stdout,"Completed Decoding frame %05d.r",snr->frame_ctr);
  1095.     fflush(stdout);
  1096.     if(slice_type == I_SLICE || slice_type == SI_SLICE || slice_type == P_SLICE || refpic)   // I or P pictures
  1097.       img->number++;
  1098.     else
  1099.       Bframe_ctr++;    // B pictures
  1100.     snr->frame_ctr++;
  1101.     g_nFrame++;
  1102.   }
  1103.   img->current_mb_nr = -4712;   // impossible value for debugging, StW
  1104.   img->current_slice_nr = 0;
  1105. }
  1106. /*!
  1107.  ************************************************************************
  1108.  * brief
  1109.  *    write the encoding mode and motion vectors of current
  1110.  *    MB to the buffer of the error concealment module.
  1111.  ************************************************************************
  1112.  */
  1113. void ercWriteMBMODEandMV(Macroblock *currMB, ImageParameters *img,struct inp_par *inp)
  1114. {
  1115.   extern objectBuffer_t *erc_object_list;
  1116.   int i, ii, jj, currMBNum = img->current_mb_nr;
  1117.   int mbx = xPosMB(currMBNum,dec_picture->size_x), mby = yPosMB(currMBNum,dec_picture->size_x);
  1118.   objectBuffer_t *currRegion, *pRegion;
  1119.   short***  mv;
  1120.   currRegion = erc_object_list + (currMBNum<<2);
  1121.   if(img->type != B_SLICE) //non-B frame
  1122.   {
  1123.     for (i=0; i<4; i++)
  1124.     {
  1125.       pRegion             = currRegion + i;
  1126.       pRegion->regionMode = (currMB->mb_type  ==I16MB  ? REGMODE_INTRA      :
  1127.                              currMB->b8mode[i]==IBLOCK ? REGMODE_INTRA_8x8  :
  1128.                              currMB->b8mode[i]==0      ? REGMODE_INTER_COPY :
  1129.                              currMB->b8mode[i]==1      ? REGMODE_INTER_PRED : REGMODE_INTER_PRED_8x8);
  1130.       if (currMB->b8mode[i]==0 || currMB->b8mode[i]==IBLOCK)  // INTRA OR COPY
  1131.       {
  1132.         pRegion->mv[0]    = 0;
  1133.         pRegion->mv[1]    = 0;
  1134.         pRegion->mv[2]    = 0;
  1135.       }
  1136.       else
  1137.       {
  1138.         ii              = 4*mbx + (i & 0x01)*2;// + BLOCK_SIZE;
  1139.         jj              = 4*mby + (i >> 1  )*2;
  1140.         if (currMB->b8mode[i]>=5 && currMB->b8mode[i]<=7)  // SMALL BLOCKS
  1141.         {
  1142.           pRegion->mv[0]  = (dec_picture->motion.mv[LIST_0][jj][ii][0] + dec_picture->motion.mv[LIST_0][jj][ii+1][0] + dec_picture->motion.mv[LIST_0][jj+1][ii][0] + dec_picture->motion.mv[LIST_0][jj+1][ii+1][0] + 2)/4;
  1143.           pRegion->mv[1]  = (dec_picture->motion.mv[LIST_0][jj][ii][1] + dec_picture->motion.mv[LIST_0][jj][ii+1][1] + dec_picture->motion.mv[LIST_0][jj+1][ii][1] + dec_picture->motion.mv[LIST_0][jj+1][ii+1][1] + 2)/4;
  1144.         }
  1145.         else // 16x16, 16x8, 8x16, 8x8
  1146.         {
  1147.           pRegion->mv[0]  = dec_picture->motion.mv[LIST_0][jj][ii][0];
  1148.           pRegion->mv[1]  = dec_picture->motion.mv[LIST_0][jj][ii][1];
  1149. //          pRegion->mv[0]  = dec_picture->motion.mv[LIST_0][4*mby+(i/2)*2][4*mbx+(i%2)*2+BLOCK_SIZE][0];
  1150. //          pRegion->mv[1]  = dec_picture->motion.mv[LIST_0][4*mby+(i/2)*2][4*mbx+(i%2)*2+BLOCK_SIZE][1];
  1151.         }
  1152.         erc_mvperMB      += iabs(pRegion->mv[0]) + iabs(pRegion->mv[1]);
  1153.         pRegion->mv[2]    = dec_picture->motion.ref_idx[LIST_0][jj][ii];
  1154.       }
  1155.     }
  1156.   }
  1157.   else  //B-frame
  1158.   {
  1159.     for (i=0; i<4; i++)
  1160.     {
  1161.       ii                  = 4*mbx + (i%2)*2;// + BLOCK_SIZE;
  1162.       jj                  = 4*mby + (i/2)*2;
  1163.       pRegion             = currRegion + i;
  1164.       pRegion->regionMode = (currMB->mb_type  ==I16MB  ? REGMODE_INTRA      :
  1165.                              currMB->b8mode[i]==IBLOCK ? REGMODE_INTRA_8x8  : REGMODE_INTER_PRED_8x8);
  1166.       if (currMB->mb_type==I16MB || currMB->b8mode[i]==IBLOCK)  // INTRA
  1167.       {
  1168.         pRegion->mv[0]    = 0;
  1169.         pRegion->mv[1]    = 0;
  1170.         pRegion->mv[2]    = 0;
  1171.       }
  1172.       else
  1173.       {
  1174.         int idx = (dec_picture->motion.ref_idx[0][jj][ii]<0)?1:0;
  1175. //        int idx = (currMB->b8mode[i]==0 && currMB->b8pdir[i]==2 ? LIST_0 : currMB->b8pdir[i]==1 ? LIST_1 : LIST_0);
  1176. //        int idx = currMB->b8pdir[i]==0 ? LIST_0 : LIST_1;
  1177.         mv                = dec_picture->motion.mv[idx];
  1178.         pRegion->mv[0]    = (mv[jj][ii][0] + mv[jj][ii+1][0] + mv[jj+1][ii][0] + mv[jj+1][ii+1][0] + 2)/4;
  1179.         pRegion->mv[1]    = (mv[jj][ii][1] + mv[jj][ii+1][1] + mv[jj+1][ii][1] + mv[jj+1][ii+1][1] + 2)/4;
  1180.         erc_mvperMB      += iabs(pRegion->mv[0]) + iabs(pRegion->mv[1]);
  1181.         pRegion->mv[2]  = (dec_picture->motion.ref_idx[idx][jj][ii]);
  1182. /*
  1183.         if (currMB->b8pdir[i]==0 || (currMB->b8pdir[i]==2 && currMB->b8mode[i]!=0)) // forward or bidirect
  1184.         {
  1185.           pRegion->mv[2]  = (dec_picture->motion.ref_idx[LIST_0][jj][ii]);
  1186.           ///???? is it right, not only "img->fw_refFrArr[jj][ii-4]"
  1187.         }
  1188.         else
  1189.         {
  1190.           pRegion->mv[2]  = (dec_picture->motion.ref_idx[LIST_1][jj][ii]);
  1191. //          pRegion->mv[2]  = 0;
  1192.         }
  1193.         */
  1194.       }
  1195.     }
  1196.   }
  1197. }
  1198. /*!
  1199.  ************************************************************************
  1200.  * brief
  1201.  *    set defaults for old_slice
  1202.  *    NAL unit of a picture"
  1203.  ************************************************************************
  1204.  */
  1205. void init_old_slice(void)
  1206. {
  1207.   old_slice.field_pic_flag = 0;
  1208.   old_slice.pps_id = INT_MAX;
  1209.   old_slice.frame_num = INT_MAX;
  1210.   old_slice.nal_ref_idc = INT_MAX;
  1211.   old_slice.idr_flag = FALSE;
  1212.   old_slice.pic_oder_cnt_lsb          = UINT_MAX;
  1213.   old_slice.delta_pic_oder_cnt_bottom = INT_MAX;
  1214.   old_slice.delta_pic_order_cnt[0] = INT_MAX;
  1215.   old_slice.delta_pic_order_cnt[1] = INT_MAX;
  1216. }
  1217. /*!
  1218.  ************************************************************************
  1219.  * brief
  1220.  *    save slice parameters that are needed for checking of "first VCL
  1221.  *    NAL unit of a picture"
  1222.  ************************************************************************
  1223.  */
  1224. void exit_slice(void)
  1225. {
  1226.   old_slice.pps_id = img->currentSlice->pic_parameter_set_id;
  1227.   old_slice.frame_num = img->frame_num;
  1228.   old_slice.field_pic_flag = img->field_pic_flag;
  1229.   if(img->field_pic_flag)
  1230.   {
  1231.     old_slice.bottom_field_flag = img->bottom_field_flag;
  1232.   }
  1233.   old_slice.nal_ref_idc   = img->nal_reference_idc;
  1234.   old_slice.idr_flag = img->idr_flag;
  1235.   if (img->idr_flag)
  1236.   {
  1237.     old_slice.idr_pic_id = img->idr_pic_id;
  1238.   }
  1239.   if (active_sps->pic_order_cnt_type == 0)
  1240.   {
  1241.     old_slice.pic_oder_cnt_lsb          = img->pic_order_cnt_lsb;
  1242.     old_slice.delta_pic_oder_cnt_bottom = img->delta_pic_order_cnt_bottom;
  1243.   }
  1244.   if (active_sps->pic_order_cnt_type == 1)
  1245.   {
  1246.     old_slice.delta_pic_order_cnt[0] = img->delta_pic_order_cnt[0];
  1247.     old_slice.delta_pic_order_cnt[1] = img->delta_pic_order_cnt[1];
  1248.   }
  1249. }
  1250. /*!
  1251.  ************************************************************************
  1252.  * brief
  1253.  *    detect if current slice is "first VCL NAL unit of a picture"
  1254.  ************************************************************************
  1255.  */
  1256. int is_new_picture(void)
  1257. {
  1258.   int result=0;
  1259.   result |= (NULL==dec_picture);
  1260.   result |= (old_slice.pps_id != img->currentSlice->pic_parameter_set_id);
  1261.   result |= (old_slice.frame_num != img->frame_num);
  1262.   result |= (old_slice.field_pic_flag != img->field_pic_flag);
  1263.   if(img->field_pic_flag && old_slice.field_pic_flag)
  1264.   {
  1265.     result |= (old_slice.bottom_field_flag != img->bottom_field_flag);
  1266.   }
  1267.   result |= (old_slice.nal_ref_idc != img->nal_reference_idc) && ((old_slice.nal_ref_idc == 0) || (img->nal_reference_idc == 0));
  1268.   result |= ( old_slice.idr_flag != img->idr_flag);
  1269.   if (img->idr_flag && old_slice.idr_flag)
  1270.   {
  1271.     result |= (old_slice.idr_pic_id != img->idr_pic_id);
  1272.   }
  1273.   if (active_sps->pic_order_cnt_type == 0)
  1274.   {
  1275.     result |=  (old_slice.pic_oder_cnt_lsb          != img->pic_order_cnt_lsb);
  1276.     result |=  (old_slice.delta_pic_oder_cnt_bottom != img->delta_pic_order_cnt_bottom);
  1277.   }
  1278.   if (active_sps->pic_order_cnt_type == 1)
  1279.   {
  1280.     result |= (old_slice.delta_pic_order_cnt[0] != img->delta_pic_order_cnt[0]);
  1281.     result |= (old_slice.delta_pic_order_cnt[1] != img->delta_pic_order_cnt[1]);
  1282.   }
  1283.   return result;
  1284. }
  1285. /*!
  1286.  ************************************************************************
  1287.  * brief
  1288.  *    decodes one slice
  1289.  ************************************************************************
  1290.  */
  1291. void decode_one_slice(ImageParameters *img,struct inp_par *inp)
  1292. {
  1293.   Boolean end_of_slice = FALSE;
  1294.   Macroblock *currMB = NULL;
  1295.   img->cod_counter=-1;
  1296.   set_interpret_mb_mode(img->type);
  1297.   if( IS_INDEPENDENT(img) )
  1298.   {
  1299.     change_plane_JV( img->colour_plane_id );
  1300.   }
  1301.   set_ref_pic_num();
  1302.   if (img->type == B_SLICE)
  1303.   {
  1304.     if( IS_INDEPENDENT(img) )
  1305.     {
  1306.       compute_colocated_JV(Co_located, listX);
  1307.     }
  1308.     else
  1309.     {
  1310.       compute_colocated(Co_located, listX);
  1311.     }
  1312.   }
  1313.   //reset_ec_flags();
  1314.   while (end_of_slice == FALSE) // loop over macroblocks
  1315.   {
  1316. #if TRACE
  1317.   fprintf(p_trace,"n*********** POC: %i (I/P) MB: %i Slice: %i Type %d **********n", img->ThisPOC, img->current_mb_nr, img->current_slice_nr, img->type);
  1318. #endif
  1319.     // Initializes the current macroblock
  1320.     start_macroblock(img, &currMB);
  1321.     // Get the syntax elements from the NAL
  1322.     read_one_macroblock(img, currMB);
  1323.     decode_one_macroblock(img, currMB, dec_picture);
  1324.     if(img->MbaffFrameFlag && dec_picture->motion.mb_field[img->current_mb_nr])
  1325.     {
  1326.       img->num_ref_idx_l0_active >>= 1;
  1327.       img->num_ref_idx_l1_active >>= 1;
  1328.     }
  1329.     ercWriteMBMODEandMV(currMB, img,inp);
  1330.     end_of_slice=exit_macroblock(img,(!img->MbaffFrameFlag||img->current_mb_nr%2));
  1331.   }
  1332.   exit_slice();
  1333.   //reset_ec_flags();
  1334. }
  1335. void decode_slice(ImageParameters *img,struct inp_par *inp, int current_header)
  1336. {
  1337.   Slice *currSlice = img->currentSlice;
  1338.   if (active_pps->entropy_coding_mode_flag)
  1339.   {
  1340.     init_contexts (img);
  1341.     cabac_new_slice();
  1342.   }
  1343.   if ( (active_pps->weighted_bipred_idc > 0  && (img->type == B_SLICE)) || (active_pps->weighted_pred_flag && img->type !=I_SLICE))
  1344.     fill_wp_params(img);
  1345.   //printf("frame picture %d %d %dn",img->structure,img->ThisPOC,img->direct_spatial_mv_pred_flag);
  1346.   // decode main slice information
  1347.   if ((current_header == SOP || current_header == SOS) && currSlice->ei_flag == 0)
  1348.     decode_one_slice(img,inp);
  1349.   // setMB-Nr in case this slice was lost
  1350.   // if(currSlice->ei_flag)
  1351.   //   img->current_mb_nr = currSlice->last_mb_nr + 1;
  1352. }
  1353. /*!
  1354.  ************************************************************************
  1355.  * brief
  1356.  *    Prepare field and frame buffer after frame decoding
  1357.  ************************************************************************
  1358.  */
  1359. void frame_postprocessing(ImageParameters *img)
  1360. {
  1361. }
  1362. /*!
  1363.  ************************************************************************
  1364.  * brief
  1365.  *    Prepare field and frame buffer after field decoding
  1366.  ************************************************************************
  1367.  */
  1368. void field_postprocessing(ImageParameters *img)
  1369. {
  1370.   img->number /= 2;
  1371. }
  1372. void reset_wp_params(ImageParameters *img)
  1373. {
  1374.   int i,comp;
  1375.   int log_weight_denom;
  1376.   for (i=0; i<MAX_REFERENCE_PICTURES; i++)
  1377.   {
  1378.     for (comp=0; comp<3; comp++)
  1379.     {
  1380.       log_weight_denom = (comp == 0) ? img->luma_log2_weight_denom : img->chroma_log2_weight_denom;
  1381.       img->wp_weight[0][i][comp] = 1 << log_weight_denom;
  1382.       img->wp_weight[1][i][comp] = 1 << log_weight_denom;
  1383.     }
  1384.   }
  1385. }
  1386. void fill_wp_params(ImageParameters *img)
  1387. {
  1388.   int i, j, k;
  1389.   int comp;
  1390.   int log_weight_denom;
  1391.   int tb, td;
  1392.   int bframe = (img->type==B_SLICE);
  1393.   int max_bwd_ref, max_fwd_ref;
  1394.   int tx,DistScaleFactor;
  1395.   max_fwd_ref = img->num_ref_idx_l0_active;
  1396.   max_bwd_ref = img->num_ref_idx_l1_active;
  1397.   if (active_pps->weighted_bipred_idc == 2 && bframe)
  1398.   {
  1399.     img->luma_log2_weight_denom = 5;
  1400.     img->chroma_log2_weight_denom = 5;
  1401.     img->wp_round_luma = 16;
  1402.     img->wp_round_chroma = 16;
  1403.     for (i=0; i<MAX_REFERENCE_PICTURES; i++)
  1404.     {
  1405.       for (comp=0; comp<3; comp++)
  1406.       {
  1407.         log_weight_denom = (comp == 0) ? img->luma_log2_weight_denom : img->chroma_log2_weight_denom;
  1408.         img->wp_weight[0][i][comp] = 1<<log_weight_denom;
  1409.         img->wp_weight[1][i][comp] = 1<<log_weight_denom;
  1410.         img->wp_offset[0][i][comp] = 0;
  1411.         img->wp_offset[1][i][comp] = 0;
  1412.       }
  1413.     }
  1414.   }
  1415.   if (bframe)
  1416.   {
  1417.     for (i=0; i<max_fwd_ref; i++)
  1418.     {
  1419.       for (j=0; j<max_bwd_ref; j++)
  1420.       {
  1421.         for (comp = 0; comp<3; comp++)
  1422.         {
  1423.           log_weight_denom = (comp == 0) ? img->luma_log2_weight_denom : img->chroma_log2_weight_denom;
  1424.           if (active_pps->weighted_bipred_idc == 1)
  1425.           {
  1426.             img->wbp_weight[0][i][j][comp] =  img->wp_weight[0][i][comp];
  1427.             img->wbp_weight[1][i][j][comp] =  img->wp_weight[1][j][comp];
  1428.           }
  1429.           else if (active_pps->weighted_bipred_idc == 2)
  1430.           {
  1431.             td = iClip3(-128,127,listX[LIST_1][j]->poc - listX[LIST_0][i]->poc);
  1432.             if (td == 0 || listX[LIST_1][j]->is_long_term || listX[LIST_0][i]->is_long_term)
  1433.             {
  1434.               img->wbp_weight[0][i][j][comp] =   32;
  1435.               img->wbp_weight[1][i][j][comp] =   32;
  1436.             }
  1437.             else
  1438.             {
  1439.               tb = iClip3(-128,127,img->ThisPOC - listX[LIST_0][i]->poc);
  1440.               tx = (16384 + iabs(td/2))/td;
  1441.               DistScaleFactor = iClip3(-1024, 1023, (tx*tb + 32 )>>6);
  1442.               img->wbp_weight[1][i][j][comp] = DistScaleFactor >> 2;
  1443.               img->wbp_weight[0][i][j][comp] = 64 - img->wbp_weight[1][i][j][comp];
  1444.               if (img->wbp_weight[1][i][j][comp] < -64 || img->wbp_weight[1][i][j][comp] > 128)
  1445.               {
  1446.                 img->wbp_weight[0][i][j][comp] = 32;
  1447.                 img->wbp_weight[1][i][j][comp] = 32;
  1448.                 img->wp_offset[0][i][comp] = 0;
  1449.                 img->wp_offset[1][j][comp] = 0;
  1450.               }
  1451.             }
  1452.           }
  1453.         }
  1454.       }
  1455.    }
  1456.  }
  1457.   if (bframe && img->MbaffFrameFlag)
  1458.   {
  1459.     for (i=0; i<2*max_fwd_ref; i++)
  1460.     {
  1461.       for (j=0; j<2*max_bwd_ref; j++)
  1462.       {
  1463.         for (comp = 0; comp<3; comp++)
  1464.         {
  1465.           for (k=2; k<6; k+=2)
  1466.           {
  1467.             img->wp_offset[k+0][i][comp] = img->wp_offset[0][i>>1][comp];
  1468.             img->wp_offset[k+1][j][comp] = img->wp_offset[1][j>>1][comp];
  1469.             log_weight_denom = (comp == 0) ? img->luma_log2_weight_denom : img->chroma_log2_weight_denom;
  1470.             if (active_pps->weighted_bipred_idc == 1)
  1471.             {
  1472.               img->wbp_weight[k+0][i][j][comp] =  img->wp_weight[0][i>>1][comp];
  1473.               img->wbp_weight[k+1][i][j][comp] =  img->wp_weight[1][j>>1][comp];
  1474.             }
  1475.             else if (active_pps->weighted_bipred_idc == 2)
  1476.             {
  1477.               td = iClip3(-128,127,listX[k+LIST_1][j]->poc - listX[k+LIST_0][i]->poc);
  1478.               if (td == 0 || listX[k+LIST_1][j]->is_long_term || listX[k+LIST_0][i]->is_long_term)
  1479.               {
  1480.                 img->wbp_weight[k+0][i][j][comp] =   32;
  1481.                 img->wbp_weight[k+1][i][j][comp] =   32;
  1482.               }
  1483.               else
  1484.               {
  1485.                 tb = iClip3(-128,127,((k==2)?img->toppoc:img->bottompoc) - listX[k+LIST_0][i]->poc);
  1486.                 tx = (16384 + iabs(td/2))/td;
  1487.                 DistScaleFactor = iClip3(-1024, 1023, (tx*tb + 32 )>>6);
  1488.                 img->wbp_weight[k+1][i][j][comp] = DistScaleFactor >> 2;
  1489.                 img->wbp_weight[k+0][i][j][comp] = 64 - img->wbp_weight[k+1][i][j][comp];
  1490.                 if (img->wbp_weight[k+1][i][j][comp] < -64 || img->wbp_weight[k+1][i][j][comp] > 128)
  1491.                 {
  1492.                   img->wbp_weight[k+1][i][j][comp] = 32;
  1493.                   img->wbp_weight[k+0][i][j][comp] = 32;
  1494.                   img->wp_offset[k+0][i][comp] = 0;
  1495.                   img->wp_offset[k+1][j][comp] = 0;
  1496.                 }
  1497.               }
  1498.             }
  1499.           }
  1500.         }
  1501.       }
  1502.     }
  1503.   }
  1504. }
  1505. /*!
  1506.  ************************************************************************
  1507.  * brief
  1508.  *    Error tracking: if current frame is lost or any reference frame of
  1509.  *                    current frame is lost, current frame is incorrect.
  1510.  ************************************************************************
  1511.  */
  1512. void Error_tracking(void)
  1513. {
  1514.   int i;
  1515.   if(img->redundant_pic_cnt == 0)
  1516.     {
  1517.       Is_primary_correct = Is_redundant_correct = 1;
  1518.     }
  1519.   if(img->redundant_pic_cnt == 0 && img->type != I_SLICE)
  1520.   {
  1521.     for(i=0;i<img->num_ref_idx_l0_active;i++)
  1522.     {
  1523.       if(ref_flag[i] == 0)  // any reference of primary slice is incorrect
  1524.       {
  1525.         Is_primary_correct = 0; // primary slice is incorrect
  1526.       }
  1527.     }
  1528.   }
  1529.   else if(img->redundant_pic_cnt != 0 && img->type != I_SLICE)
  1530.   {
  1531.     if(ref_flag[redundant_slice_ref_idx] == 0)  // reference of redundant slice is incorrect
  1532.     {
  1533.       Is_redundant_correct = 0;  // redundant slice is incorrect
  1534.     }
  1535.   }
  1536. }
  1537. /*!
  1538.  ************************************************************************
  1539.  * brief
  1540.  *    copy StorablePicture *src -> StorablePicture *dst
  1541.  *    for 4:4:4 Independent mode
  1542.  ************************************************************************
  1543.  */
  1544. void copy_dec_picture_JV( StorablePicture *dst, StorablePicture *src )
  1545. {
  1546.   dst->top_poc              = src->top_poc;
  1547.   dst->bottom_poc           = src->bottom_poc;
  1548.   dst->frame_poc            = src->frame_poc;
  1549.   dst->qp                   = src->qp;
  1550.   dst->slice_qp_delta       = src->slice_qp_delta;
  1551.   dst->chroma_qp_offset[0]  = src->chroma_qp_offset[0];
  1552.   dst->chroma_qp_offset[1]  = src->chroma_qp_offset[1];
  1553.   dst->poc                  = src->poc;
  1554.   dst->slice_type           = src->slice_type;
  1555.   dst->used_for_reference   = src->used_for_reference;
  1556.   dst->idr_flag             = src->idr_flag;
  1557.   dst->no_output_of_prior_pics_flag = src->no_output_of_prior_pics_flag;
  1558.   dst->long_term_reference_flag = src->long_term_reference_flag;
  1559.   dst->adaptive_ref_pic_buffering_flag = src->adaptive_ref_pic_buffering_flag;
  1560.   dst->dec_ref_pic_marking_buffer = src->dec_ref_pic_marking_buffer;
  1561.   dst->MbaffFrameFlag       = src->MbaffFrameFlag;
  1562.   dst->PicWidthInMbs        = src->PicWidthInMbs;
  1563.   dst->pic_num              = src->pic_num;
  1564.   dst->frame_num            = src->frame_num;
  1565.   dst->recovery_frame       = src->recovery_frame;
  1566.   dst->coded_frame          = src->coded_frame;
  1567.   dst->chroma_format_idc    = src->chroma_format_idc;
  1568.   dst->frame_mbs_only_flag  = src->frame_mbs_only_flag;
  1569.   dst->frame_cropping_flag  = src->frame_cropping_flag;
  1570.   dst->frame_cropping_rect_left_offset   = src->frame_cropping_rect_left_offset;
  1571.   dst->frame_cropping_rect_right_offset  = src->frame_cropping_rect_right_offset;
  1572.   dst->frame_cropping_rect_top_offset    = src->frame_cropping_rect_top_offset;
  1573.   dst->frame_cropping_rect_bottom_offset = src->frame_cropping_rect_bottom_offset;
  1574. #if (ENABLE_OUTPUT_TONEMAPPING)
  1575.   // store the necessary tone mapping sei into StorablePicture structure
  1576.   dst->seiHasTone_mapping = src->seiHasTone_mapping;
  1577.   dst->seiHasTone_mapping    = src->seiHasTone_mapping;
  1578.   dst->tone_mapping_model_id = src->tone_mapping_model_id;
  1579.   dst->tonemapped_bit_depth  = src->tonemapped_bit_depth;
  1580.   if( src->tone_mapping_lut )
  1581.   {
  1582.     dst->tone_mapping_lut      = malloc(sizeof(int)*(1<<seiToneMapping.coded_data_bit_depth));
  1583.     if (NULL == dst->tone_mapping_lut)
  1584.     {
  1585.       no_mem_exit("copy_dec_picture_JV: tone_mapping_lut");
  1586.     }
  1587.     memcpy(dst->tone_mapping_lut, src->tone_mapping_lut, sizeof(imgpel)*(1<<seiToneMapping.coded_data_bit_depth));
  1588.   }
  1589. #endif
  1590. }