source: SHVCSoftware/trunk/source/Lib/TLibEncoder/TEncCavlc.cpp @ 462

Last change on this file since 462 was 442, checked in by seregin, 11 years ago

reintegrate SHM-3.1-dev branch

  • Property svn:eol-style set to native
File size: 81.0 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license. 
5 *
6 * Copyright (c) 2010-2013, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncCavlc.cpp
35    \brief    CAVLC encoder class
36*/
37
38#include "../TLibCommon/CommonDef.h"
39#include "TEncCavlc.h"
40#include "SEIwrite.h"
41
42//! \ingroup TLibEncoder
43//! \{
44
45#if ENC_DEC_TRACE
46
47Void  xTraceSPSHeader (TComSPS *pSPS)
48{
49  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
50}
51
52Void  xTracePPSHeader (TComPPS *pPPS)
53{
54  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
55}
56
57Void  xTraceSliceHeader (TComSlice *pSlice)
58{
59  fprintf( g_hTrace, "=========== Slice ===========\n");
60}
61
62#endif
63
64
65
66// ====================================================================================================================
67// Constructor / destructor / create / destroy
68// ====================================================================================================================
69
70TEncCavlc::TEncCavlc()
71{
72  m_pcBitIf           = NULL;
73  m_uiCoeffCost       = 0;
74}
75
76TEncCavlc::~TEncCavlc()
77{
78}
79
80
81// ====================================================================================================================
82// Public member functions
83// ====================================================================================================================
84
85Void TEncCavlc::resetEntropy()
86{
87}
88
89
90Void TEncCavlc::codeDFFlag(UInt uiCode, const Char *pSymbolName)
91{
92  WRITE_FLAG(uiCode, pSymbolName);
93}
94Void TEncCavlc::codeDFSvlc(Int iCode, const Char *pSymbolName)
95{
96  WRITE_SVLC(iCode, pSymbolName);
97}
98
99Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps, Bool calledFromSliceHeader, Int idx)
100{
101#if PRINT_RPS_INFO
102  Int lastBits = getNumberOfWrittenBits();
103#endif
104  if (idx > 0)
105  {
106  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
107  }
108  if (rps->getInterRPSPrediction())
109  {
110    Int deltaRPS = rps->getDeltaRPS();
111    if(calledFromSliceHeader)
112    {
113      WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
114    }
115
116    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
117    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
118
119    for(Int j=0; j < rps->getNumRefIdc(); j++)
120    {
121      Int refIdc = rps->getRefIdc(j);
122      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
123      if (refIdc != 1) 
124      {
125        WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
126      }
127    }
128  }
129  else
130  {
131    WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
132    WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
133    Int prev = 0;
134    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
135    {
136      WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
137      prev = rps->getDeltaPOC(j);
138      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag"); 
139    }
140    prev = 0;
141    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
142    {
143      WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
144      prev = rps->getDeltaPOC(j);
145      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" ); 
146    }
147  }
148
149#if PRINT_RPS_INFO
150  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
151  rps->printDeltaPOC();
152#endif
153}
154
155
156Void TEncCavlc::codePPS( TComPPS* pcPPS )
157{
158#if ENC_DEC_TRACE 
159  xTracePPSHeader (pcPPS);
160#endif
161 
162  WRITE_UVLC( pcPPS->getPPSId(),                             "pps_pic_parameter_set_id" );
163  WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
164  WRITE_FLAG( pcPPS->getDependentSliceSegmentsEnabledFlag()    ? 1 : 0, "dependent_slice_segments_enabled_flag" );
165  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,     "output_flag_present_flag" );
166  WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3,        "num_extra_slice_header_bits");
167  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
168  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
169  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
170  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
171
172  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "init_qp_minus26");
173  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
174  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" ); 
175  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
176  if ( pcPPS->getUseDQP() )
177  {
178    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
179  }
180  WRITE_SVLC( pcPPS->getChromaCbQpOffset(),                   "pps_cb_qp_offset" );
181  WRITE_SVLC( pcPPS->getChromaCrQpOffset(),                   "pps_cr_qp_offset" );
182  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
183
184  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
185  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
186  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
187  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
188  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
189  if( pcPPS->getTilesEnabledFlag() )
190  {
191    WRITE_UVLC( pcPPS->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
192    WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
193    WRITE_FLAG( pcPPS->getUniformSpacingFlag(),                                  "uniform_spacing_flag" );
194    if( pcPPS->getUniformSpacingFlag() == 0 )
195    {
196      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
197      {
198        WRITE_UVLC( pcPPS->getColumnWidth(i)-1,                                  "column_width_minus1" );
199      }
200      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
201      {
202        WRITE_UVLC( pcPPS->getRowHeight(i)-1,                                    "row_height_minus1" );
203      }
204    }
205    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=0)
206    {
207      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
208    }
209  }
210  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
211  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
212  if(pcPPS->getDeblockingFilterControlPresentFlag())
213  {
214    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" ); 
215    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
216    if(!pcPPS->getPicDisableDeblockingFilterFlag())
217    {
218      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
219      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
220    }
221  }
222  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
223
224#if IL_SL_SIGNALLING_N0371
225  pcPPS->setPPS( pcPPS->getLayerId(), pcPPS ); 
226#endif
227
228  if( pcPPS->getScalingListPresentFlag() )
229  {
230#if SCALING_LIST_OUTPUT_RESULT
231    printf("PPS\n");
232#endif
233
234#if IL_SL_SIGNALLING_N0371
235    m_pcSlice->getScalingList()->setLayerId( pcPPS->getLayerId() );
236
237    if( pcPPS->getLayerId() > 0 )
238    {
239      WRITE_FLAG( pcPPS->getPredScalingListFlag() ? 1 : 0,                          "pps_pred_scaling_list_flag" );
240      m_pcSlice->getScalingList()->setPredScalingListFlag( pcPPS->getPredScalingListFlag() );
241
242      if( pcPPS->getPredScalingListFlag() )
243      {
244        // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
245        assert( /*pcPPS->getScalingListRefLayerId() >= 0 &&*/ pcPPS->getScalingListRefLayerId() <= 62 );
246
247        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of pps_scaling_list_ref_layer_id shall be greater than 0
248        if( pcPPS->getSPS()->getVPS()->getAvcBaseLayerFlag() )
249        {
250          assert( pcPPS->getScalingListRefLayerId() > 0 );
251        }
252
253        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
254        // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
255        assert( pcPPS->getPPS( pcPPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
256
257        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
258        // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
259        assert( pcPPS->getSPS()->getVPS()->getScalingListLayerDependency( pcPPS->getLayerId(), pcPPS->getScalingListRefLayerId() ) == true );
260       
261        WRITE_UVLC( pcPPS->getScalingListRefLayerId(),                            "scaling_list_pps_ref_layer_id" );
262        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcPPS->getScalingListRefLayerId() );
263        codeScalingList( m_pcSlice->getScalingList() );
264      }
265      else
266      {
267        codeScalingList( m_pcSlice->getScalingList() );
268      }
269    }
270    else
271    {
272      codeScalingList( m_pcSlice->getScalingList() );
273    }
274#else
275    codeScalingList( m_pcSlice->getScalingList() );
276#endif
277
278  }
279  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
280  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
281  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
282  WRITE_FLAG( 0, "pps_extension_flag" );
283}
284
285Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
286{
287#if ENC_DEC_TRACE
288  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
289#endif
290  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
291  if (pcVUI->getAspectRatioInfoPresentFlag())
292  {
293    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
294    if (pcVUI->getAspectRatioIdc() == 255)
295    {
296      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
297      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
298    }
299  }
300  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
301  if (pcVUI->getOverscanInfoPresentFlag())
302  {
303    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
304  }
305  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
306  if (pcVUI->getVideoSignalTypePresentFlag())
307  {
308    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
309    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
310    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
311    if (pcVUI->getColourDescriptionPresentFlag())
312    {
313      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
314      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
315      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
316    }
317  }
318
319  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
320  if (pcVUI->getChromaLocInfoPresentFlag())
321  {
322    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
323    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
324  }
325
326  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
327  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
328  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
329
330  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
331  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
332  if( defaultDisplayWindow.getWindowEnabledFlag() )
333  {
334    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset(),      "def_disp_win_left_offset");
335    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset(),     "def_disp_win_right_offset");
336    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset(),       "def_disp_win_top_offset");
337    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset(),    "def_disp_win_bottom_offset");
338  }
339  TimingInfo *timingInfo = pcVUI->getTimingInfo();
340  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
341  if(timingInfo->getTimingInfoPresentFlag())
342  {
343    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
344    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
345    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
346    if(timingInfo->getPocProportionalToTimingFlag())
347    {
348      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
349    }
350  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
351  if( pcVUI->getHrdParametersPresentFlag() )
352  {
353    codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
354  }
355  }
356
357  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
358  if (pcVUI->getBitstreamRestrictionFlag())
359  {
360    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
361#if M0464_TILE_BOUNDARY_ALIGNED_FLAG
362    if ( pcSPS->getLayerId() > 0 )
363    {
364      WRITE_FLAG( pcVUI->getTileBoundariesAlignedFlag( ) ? 1 : 0 , "tile_boundaries_aligned_flag" );
365    }
366#endif
367    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
368    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
369    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
370    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
371    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
372    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
373    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
374  }
375}
376
377Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
378{
379  if( commonInfPresentFlag )
380  {
381    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
382    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
383    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
384    {
385      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
386      if( hrd->getSubPicCpbParamsPresentFlag() )
387      {
388        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
389        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
390        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
391        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
392      }
393      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
394      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
395      if( hrd->getSubPicCpbParamsPresentFlag() )
396      {
397        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" ); 
398      }
399      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
400      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
401      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
402    }
403  }
404  Int i, j, nalOrVcl;
405  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
406  {
407    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
408    if( !hrd->getFixedPicRateFlag( i ) )
409    {
410      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
411    }
412    else
413    {
414      hrd->setFixedPicRateWithinCvsFlag( i, true );
415    }
416    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
417    {
418      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
419    }
420    else
421    {
422      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
423    }
424    if (!hrd->getLowDelayHrdFlag( i ))
425    {
426      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
427    }
428   
429    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
430    {
431      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
432          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
433      {
434        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
435        {
436          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
437          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
438          if( hrd->getSubPicCpbParamsPresentFlag() )
439          {
440            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1"); 
441            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
442          }
443          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
444        }
445      }
446    }
447  }
448}
449
450Void TEncCavlc::codeSPS( TComSPS* pcSPS )
451{
452#if ENC_DEC_TRACE 
453  xTraceSPSHeader (pcSPS);
454#endif
455  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
456#if SPS_SUB_LAYER_INFO
457  if(pcSPS->getLayerId() == 0)
458  {
459#endif
460    WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
461    WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
462#if SPS_SUB_LAYER_INFO
463  }
464#endif
465#ifdef SPS_PTL_FIX
466  if (pcSPS->getLayerId() == 0)
467  {
468    codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
469  }
470#else
471  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
472#endif
473  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
474#if REPN_FORMAT_IN_VPS
475  if( pcSPS->getLayerId() > 0 )
476  {
477    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
478  }
479  if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
480  {
481#endif
482    WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
483    assert(pcSPS->getChromaFormatIdc () == 1);
484    // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
485    if( pcSPS->getChromaFormatIdc () == 3 )
486    {
487      WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
488    }
489
490    WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
491    WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
492#if REPN_FORMAT_IN_VPS
493  }
494#endif
495  Window conf = pcSPS->getConformanceWindow();
496
497  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
498  if (conf.getWindowEnabledFlag())
499  {
500    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
501    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
502    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
503    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
504  }
505
506#if REPN_FORMAT_IN_VPS
507  if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
508  {
509    assert( pcSPS->getBitDepthY() >= 8 );
510    assert( pcSPS->getBitDepthC() >= 8 );
511#endif
512    WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
513    WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
514#if REPN_FORMAT_IN_VPS
515  }
516#endif
517  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
518
519  const Bool subLayerOrderingInfoPresentFlag = 1;
520  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
521  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
522  {
523    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
524    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
525    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
526    if (!subLayerOrderingInfoPresentFlag)
527    {
528      break;
529    }
530  }
531  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
532 
533  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
534  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
535  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
536  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
537  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
538  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
539  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
540
541#if IL_SL_SIGNALLING_N0371
542  pcSPS->setSPS( pcSPS->getLayerId(), pcSPS );
543#endif
544
545  if(pcSPS->getScalingListFlag())
546  {
547    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
548    if(pcSPS->getScalingListPresentFlag())
549    {
550#if SCALING_LIST_OUTPUT_RESULT
551    printf("SPS\n");
552#endif
553
554#if IL_SL_SIGNALLING_N0371
555    m_pcSlice->getScalingList()->setLayerId( pcSPS->getLayerId() );
556
557    if( pcSPS->getLayerId() > 0 )
558    {
559      WRITE_FLAG( pcSPS->getPredScalingListFlag() ? 1 : 0,                          "sps_pred_scaling_list_flag" );
560      m_pcSlice->getScalingList()->setPredScalingListFlag( pcSPS->getPredScalingListFlag() );
561
562      if( pcSPS->getPredScalingListFlag() )
563      {
564
565        // The value of sps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
566        assert( /*pcSPS->getScalingListRefLayerId() >= 0 &&*/ pcSPS->getScalingListRefLayerId() <= 62 );
567       
568        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
569        if( pcSPS->getVPS()->getAvcBaseLayerFlag() )
570        {
571          assert( pcSPS->getScalingListRefLayerId() > 0 );
572        }
573
574        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
575        // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
576        assert( pcSPS->getSPS( pcSPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
577
578        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
579        // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
580        assert( pcSPS->getVPS()->getScalingListLayerDependency( pcSPS->getLayerId(), pcSPS->getScalingListRefLayerId() ) == true );
581
582        WRITE_UVLC( pcSPS->getScalingListRefLayerId(),                            "scaling_list_sps_ref_layer_id" );
583        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcSPS->getScalingListRefLayerId() );
584        codeScalingList( m_pcSlice->getScalingList() );
585      }
586      else
587      {
588        codeScalingList( m_pcSlice->getScalingList() );
589      }
590    }
591    else
592    {
593      codeScalingList( m_pcSlice->getScalingList() );
594    }
595#else
596      codeScalingList( m_pcSlice->getScalingList() );
597#endif
598
599    }
600  }
601  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
602  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
603
604  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
605  if( pcSPS->getUsePCM() )
606  {
607    WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,                                  "pcm_sample_bit_depth_luma_minus1" );
608    WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4,                                "pcm_sample_bit_depth_chroma_minus1" );
609    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
610    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
611    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
612  }
613
614  assert( pcSPS->getMaxTLayers() > 0 );         
615
616  TComRPSList* rpsList = pcSPS->getRPSList();
617  TComReferencePictureSet*      rps;
618 
619  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
620  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
621  {
622    rps = rpsList->getReferencePictureSet(i);
623    codeShortTermRefPicSet(pcSPS,rps,false, i);
624  }
625  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
626  if (pcSPS->getLongTermRefsPresent()) 
627  {
628    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
629    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
630    {
631      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
632      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
633    }
634  }
635  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
636#if REF_IDX_MFM
637#if !M0457_COL_PICTURE_SIGNALING
638  if( pcSPS->getLayerId() > 0 )
639  {
640    WRITE_FLAG( pcSPS->getMFMEnabledFlag() ? 1 : 0,          "sps_enh_mfm_enable_flag" );
641  }
642#endif
643#endif
644  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
645
646  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
647  if (pcSPS->getVuiParametersPresentFlag())
648  {
649      codeVUI(pcSPS->getVuiParameters(), pcSPS);
650  }
651
652#if SPS_EXTENSION
653  WRITE_FLAG( 1, "sps_extension_flag" );
654  if( 1 )   // if( sps_extension_flag )
655  {
656    codeSPSExtension( pcSPS );
657    WRITE_FLAG( 0, "sps_extension2_flag" );
658  }
659#else
660  WRITE_FLAG( 0, "sps_extension_flag" );
661#endif
662}
663#if SPS_EXTENSION
664Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
665{
666  // more syntax elements to be written here
667
668#if VERT_MV_CONSTRAINT
669  // Vertical MV component restriction is not used in SHVC CTC
670  WRITE_FLAG( 0, "inter_view_mv_vert_constraint_flag" );
671#endif
672#if SCALED_REF_LAYER_OFFSETS
673  if( pcSPS->getLayerId() > 0 )
674  {
675    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
676    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
677    {
678      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
679      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
680      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
681      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
682      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
683    }
684  }
685#endif
686#if M0463_VUI_EXT_ILP_REF
687  ////   sps_extension_vui_parameters( )
688  if( pcSPS->getVuiParameters()->getBitstreamRestrictionFlag() )
689  { 
690    WRITE_UVLC( pcSPS->getNumIlpRestrictedRefLayers( ),           "num_ilp_restricted_ref_layers" ); 
691    for( Int i = 0; i < pcSPS->getNumIlpRestrictedRefLayers( ); i++ ) 
692    { 
693      WRITE_UVLC( pcSPS->getMinSpatialSegmentOffsetPlus1( i ),    "min_spatial_segment_offset_plus1" ); 
694      if( pcSPS->getMinSpatialSegmentOffsetPlus1( i ) > 0 ) 
695      { 
696        WRITE_FLAG( pcSPS->getCtuBasedOffsetEnabledFlag( i ),      "ctu_based_offset_enabled_flag[ i ]"); 
697        if( pcSPS->getCtuBasedOffsetEnabledFlag( i ) ) 
698        {
699          WRITE_UVLC( pcSPS->getMinHorizontalCtuOffsetPlus1( i ), "min_horizontal_ctu_offset_plus1[ i ]"); 
700        }
701      } 
702    } 
703  } 
704  ////   sps_extension_vui_parameters( ) END
705#endif
706}
707#endif
708Void TEncCavlc::codeVPS( TComVPS* pcVPS )
709{
710  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
711  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
712#if VPS_RENAME
713  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );           
714#else
715  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
716#endif
717  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
718  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
719  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
720#if VPS_EXTN_OFFSET
721  WRITE_CODE( pcVPS->getExtensionOffset(),         16,        "vps_extension_offset" );
722#else
723  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
724#endif
725  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
726  const Bool subLayerOrderingInfoPresentFlag = 1;
727  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
728  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
729  {
730    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
731    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
732    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
733    if (!subLayerOrderingInfoPresentFlag)
734    {
735      break;
736    }
737  }
738
739#if VPS_RENAME
740  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
741  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_ID_PLUS1 );
742#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
743  pcVPS->setNumLayerSets(1);
744#endif
745  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
746  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
747  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getNumLayerSets() - 1 ); opsIdx ++ )
748  {
749    // Operation point set
750    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
751#else
752  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
753  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
754  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
755  pcVPS->setMaxOpSets(1);
756  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
757  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
758  {
759    // Operation point set
760    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
761#endif
762    {
763#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
764      // Only applicable for version 1
765      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
766#endif
767      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
768    }
769  }
770#if DERIVE_LAYER_ID_LIST_VARIABLES
771  pcVPS->deriveLayerIdListVariables();
772#endif
773  TimingInfo *timingInfo = pcVPS->getTimingInfo();
774  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
775  if(timingInfo->getTimingInfoPresentFlag())
776  {
777    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
778    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
779    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
780    if(timingInfo->getPocProportionalToTimingFlag())
781    {
782      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
783    }
784    pcVPS->setNumHrdParameters( 0 );
785    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
786
787    if( pcVPS->getNumHrdParameters() > 0 )
788    {
789      pcVPS->createHrdParamBuffer();
790    }
791    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
792    {
793      // Only applicable for version 1
794      pcVPS->setHrdOpSetIdx( 0, i );
795      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
796      if( i > 0 )
797      {
798        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
799      }
800      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
801    }
802  }
803#if !VPS_EXTNS
804  WRITE_FLAG( 0,                     "vps_extension_flag" );
805#else
806  WRITE_FLAG( 1,                     "vps_extension_flag" );
807  if(1) // Should be conditioned on the value of vps_extension_flag
808  {
809    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
810    {
811      WRITE_FLAG(1,                  "vps_extension_alignment_bit_equal_to_one");
812    }
813    codeVPSExtension(pcVPS);
814    WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
815  }
816#endif 
817  //future extensions here..
818 
819  return;
820}
821
822#if VPS_EXTNS
823Void TEncCavlc::codeVPSExtension (TComVPS *vps)
824{
825  // ... More syntax elements to be written here
826#if VPS_EXTN_MASK_AND_DIM_INFO
827  UInt i = 0, j = 0;
828
829  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
830  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
831
832  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
833  {
834    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
835  }
836
837#if VPS_SPLIT_FLAG
838  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
839#else
840  for(j = 0; j < vps->getNumScalabilityTypes(); j++)
841#endif
842  {
843    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
844  }
845
846#if SPL_FLG_CHK
847  if(vps->getSplittingFlag())
848  {
849    UInt splDimSum=0;
850    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
851    {
852      splDimSum+=(vps->getDimensionIdLen(j));
853    }
854    assert(splDimSum<=6);
855  }
856#endif
857
858  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
859  for(i = 1; i < vps->getMaxLayers(); i++)
860  {
861    if( vps->getNuhLayerIdPresentFlag() )
862    {
863      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
864    }
865#if VPS_SPLIT_FLAG
866    if(!vps->getSplittingFlag())
867#endif
868    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
869    {
870      UInt bits = vps->getDimensionIdLen(j);
871      WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
872    }
873  }
874#endif
875#if VIEW_ID_RELATED_SIGNALING
876  // if ( pcVPS->getNumViews() > 1 ) 
877  //   However, this is a bug in the text since, view_id_len_minus1 is needed to parse view_id_val.
878  {
879    WRITE_CODE( vps->getViewIdLenMinus1( ), 4, "view_id_len_minus1" );
880  }
881
882  for(  i = 0; i < vps->getNumViews(); i++ )
883  {
884    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLenMinus1( ) + 1, "view_id_val[i]" );
885  }
886#endif
887#if VPS_MOVE_DIR_DEPENDENCY_FLAG
888#if VPS_EXTN_DIRECT_REF_LAYERS
889  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
890  {
891    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
892    {
893      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
894    }
895  }
896#endif
897#endif
898#if JCTVC_M0203_INTERLAYER_PRED_IDC
899#if N0120_MAX_TID_REF_PRESENT_FLAG
900   WRITE_FLAG( vps->getMaxTidRefPresentFlag(), "max_tid_ref_present_flag");
901   if (vps->getMaxTidRefPresentFlag())
902   {
903     for( i = 0; i < vps->getMaxLayers() - 1; i++)
904     {
905       WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
906     }
907   }
908#else
909  for( i = 0; i < vps->getMaxLayers() - 1; i++)
910  {
911    WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
912  }
913#endif
914#endif
915#if ILP_SSH_SIG
916    WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
917#endif
918#if VPS_EXTN_PROFILE_INFO
919  // Profile-tier-level signalling
920#if VPS_PROFILE_OUTPUT_LAYERS
921  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
922  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
923  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
924#else
925  for(Int idx = 1; idx <= vps->getNumLayerSets() - 1; idx++)
926#endif
927  {
928    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
929    if( !vps->getProfilePresentFlag(idx) )
930    {
931#if VPS_PROFILE_OUTPUT_LAYERS
932      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
933#else
934      WRITE_UVLC( vps->getProfileLayerSetRef(idx) - 1, "vps_profile_layer_set_ref_minus1[i]" );
935#endif
936    }
937    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
938  }
939#endif
940
941#if VPS_PROFILE_OUTPUT_LAYERS
942  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
943  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
944  if(numOutputLayerSets > vps->getNumLayerSets())
945  {
946    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
947  }
948  if( numOutputLayerSets > 1 )
949  {
950    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
951  }
952
953  for(i = 1; i < numOutputLayerSets; i++)
954  {
955    if( i > (vps->getNumLayerSets() - 1) )
956    {
957      Int numBits = 1;
958      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
959      {
960        numBits++;
961      }
962      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "output_layer_set_idx_minus1"); 
963      Int lsIdx = vps->getOutputLayerSetIdx(i);
964      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
965      {
966        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
967      }
968    }
969    Int numBits = 1;
970    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
971    {
972      numBits++;
973    }
974    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
975  }
976#else
977#if VPS_EXTN_OP_LAYER_SETS
978  // Target output layer signalling
979  WRITE_UVLC( vps->getNumOutputLayerSets(),            "vps_num_output_layer_sets");
980  for(i = 0; i < vps->getNumOutputLayerSets(); i++)
981  {
982#if VPS_OUTPUT_LAYER_SET_IDX
983    assert(vps->getOutputLayerSetIdx(i) > 0);
984    WRITE_UVLC( vps->getOutputLayerSetIdx(i) - 1,           "vps_output_layer_set_idx_minus1[i]");
985#else
986    WRITE_UVLC( vps->getOutputLayerSetIdx(i),           "vps_output_layer_set_idx[i]");
987#endif
988    Int lsIdx = vps->getOutputLayerSetIdx(i);
989    for(j = 0; j <= vps->getMaxLayerId(); j++)
990    {
991      if(vps->getLayerIdIncludedFlag(lsIdx, j))
992      {
993        WRITE_FLAG( vps->getOutputLayerFlag(lsIdx, j), "vps_output_layer_flag[lsIdx][j]");
994      }
995    }
996  }
997#endif
998#endif
999
1000#if REPN_FORMAT_IN_VPS
1001  WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
1002
1003  if( vps->getRepFormatIdxPresentFlag() )
1004  {
1005    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
1006  }
1007  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
1008  {
1009    // Read rep_format_structures
1010    codeRepFormat( vps->getVpsRepFormat(i) );
1011  }
1012 
1013  if( vps->getRepFormatIdxPresentFlag() )
1014  {
1015    for(i = 1; i < vps->getMaxLayers(); i++)
1016    {
1017      if( vps->getVpsNumRepFormats() > 1 )
1018      {
1019        WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
1020      }
1021    }
1022  }
1023#endif
1024
1025#if JCTVC_M0458_INTERLAYER_RPS_SIG
1026      WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
1027#endif
1028#if N0147_IRAP_ALIGN_FLAG
1029      WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
1030#endif
1031#if !VPS_MOVE_DIR_DEPENDENCY_FLAG
1032#if VPS_EXTN_DIRECT_REF_LAYERS
1033  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
1034  {
1035    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
1036    {
1037      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
1038    }
1039  }
1040#endif
1041#endif
1042#if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
1043  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
1044  for(i = 1; i < vps->getMaxLayers(); i++)
1045  {
1046    for(j = 0; j < i; j++)
1047    {
1048      if (vps->getDirectDependencyFlag(i, j))
1049      {
1050        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
1051      }
1052    }
1053  }
1054
1055#if IL_SL_SIGNALLING_N0371
1056  for(i = 1; i < vps->getMaxLayers(); i++)
1057  {
1058    for(j = 0; j < i; j++)
1059    {
1060      vps->setScalingListLayerDependency( i, j, vps->checkLayerDependency( i,j ) );
1061    }
1062  }
1063#endif
1064
1065#endif
1066#if M0040_ADAPTIVE_RESOLUTION_CHANGE
1067  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
1068#endif
1069
1070#if !VPS_VUI
1071  WRITE_FLAG( 0,                     "vps_vui_present_flag" );
1072#else
1073  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
1074  if(1)   // Should be conditioned on the value of vps_vui_present_flag
1075  {
1076    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
1077    {
1078      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
1079    }
1080    codeVPSVUI(vps); 
1081  }
1082#endif
1083}
1084#endif
1085#if REPN_FORMAT_IN_VPS
1086Void  TEncCavlc::codeRepFormat      ( RepFormat *repFormat )
1087{
1088  WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
1089 
1090  if( repFormat->getChromaFormatVpsIdc() == 3 )
1091  {
1092    WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");     
1093  }
1094
1095  WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );   
1096  WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );   
1097 
1098  assert( repFormat->getBitDepthVpsLuma() >= 8 );
1099  assert( repFormat->getBitDepthVpsChroma() >= 8 );
1100  WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
1101  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );         
1102
1103}
1104#endif
1105#if VPS_VUI
1106Void TEncCavlc::codeVPSVUI (TComVPS *vps)
1107{
1108  Int i,j;
1109#if VPS_VUI_BITRATE_PICRATE
1110  WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
1111  WRITE_FLAG( vps->getPicRatePresentVpsFlag(),        "pic_rate_present_vps_flag" );
1112
1113  if( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
1114  {
1115    for( i = 0; i < vps->getNumLayerSets(); i++ )
1116    {
1117      for( j = 0; j < vps->getMaxTLayers(); j++ )
1118      {
1119        if( vps->getBitRatePresentVpsFlag() )
1120        {
1121          WRITE_FLAG( vps->getBitRatePresentFlag( i, j),        "bit_rate_present_vps_flag[i][j]" );
1122        }
1123        if( vps->getPicRatePresentVpsFlag() )
1124        {
1125          WRITE_FLAG( vps->getPicRatePresentFlag( i, j),        "pic_rate_present_vps_flag[i][j]" );
1126        }
1127        if( vps->getBitRatePresentFlag(i, j) )
1128        {
1129          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "avg_bit_rate[i][j]" );
1130          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "max_bit_rate[i][j]" );
1131        }
1132        if( vps->getPicRatePresentFlag(i, j) )
1133        {
1134          WRITE_CODE( vps->getConstPicRateIdc( i, j), 2 , "constant_pic_rate_idc[i][j]" ); 
1135          WRITE_CODE( vps->getConstPicRateIdc( i, j), 16, "avg_pic_rate[i][j]"          ); 
1136        }
1137      }
1138    }
1139  }
1140#endif
1141#if TILE_BOUNDARY_ALIGNED_FLAG
1142  for(i = 1; i < vps->getMaxLayers(); i++)
1143  {
1144    for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
1145    {
1146      WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
1147    }
1148  } 
1149#endif
1150#if N0160_VUI_EXT_ILP_REF
1151  WRITE_FLAG( vps->getNumIlpRestrictedRefLayers() ? 1 : 0 , "num_ilp_restricted_ref_layers" );   
1152  if( vps->getNumIlpRestrictedRefLayers())
1153  {
1154    for(i = 1; i < vps->getMaxLayers(); i++)
1155    {
1156      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
1157      {       
1158        WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
1159       
1160        if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
1161        { 
1162          WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );   
1163         
1164          if(vps->getCtuBasedOffsetEnabledFlag(i,j)) 
1165          {
1166            WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");           
1167          }
1168        } 
1169      } 
1170    }
1171  }
1172#endif
1173}
1174#endif
1175
1176Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
1177{
1178#if ENC_DEC_TRACE 
1179  xTraceSliceHeader (pcSlice);
1180#endif
1181
1182  //calculate number of bits required for slice address
1183  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumCUsInFrame();
1184  Int bitsSliceSegmentAddress = 0;
1185  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress)) 
1186  {
1187    bitsSliceSegmentAddress++;
1188  }
1189  Int ctuAddress;
1190  if (pcSlice->isNextSlice())
1191  {
1192    // Calculate slice address
1193    ctuAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
1194  }
1195  else
1196  {
1197    // Calculate slice address
1198    ctuAddress = (pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
1199  }
1200  //write slice address
1201  Int sliceSegmentAddress = pcSlice->getPic()->getPicSym()->getCUOrderMap(ctuAddress);
1202
1203  WRITE_FLAG( sliceSegmentAddress==0, "first_slice_segment_in_pic_flag" );
1204  if ( pcSlice->getRapPicFlag() )
1205  {
1206    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
1207  }
1208  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
1209  pcSlice->setDependentSliceSegmentFlag(!pcSlice->isNextSlice());
1210  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentAddress!=0) )
1211  {
1212    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
1213  }
1214  if(sliceSegmentAddress>0)
1215  {
1216    WRITE_CODE( sliceSegmentAddress, bitsSliceSegmentAddress, "slice_segment_address" );
1217  }
1218  if ( !pcSlice->getDependentSliceSegmentFlag() )
1219  {
1220
1221#if POC_RESET_FLAG
1222    Int iBits = 0;
1223    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1224    {
1225      WRITE_FLAG( pcSlice->getPocResetFlag(), "poc_reset_flag" );
1226      iBits++;
1227    }
1228    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1229    {
1230      assert(!!"discardable_flag");
1231      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1232      iBits++;
1233    }
1234    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1235    {
1236      assert(!!"slice_reserved_undetermined_flag[]");
1237      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1238    }
1239#else
1240#if SH_DISCARDABLE_FLAG
1241    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
1242    {
1243      assert(!!"discardable_flag");
1244      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1245    }
1246    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1247    {
1248      assert(!!"slice_reserved_undetermined_flag[]");
1249      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1250    }
1251#else
1252    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1253    {
1254      assert(!!"slice_reserved_undetermined_flag[]");
1255      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1256    }
1257#endif
1258#endif
1259
1260    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1261
1262    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1263    {
1264      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1265    }
1266
1267#if REPN_FORMAT_IN_VPS
1268    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1269    assert( pcSlice->getChromaFormatIdc() == 1 );
1270#else
1271    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1272    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
1273#endif
1274    // if( separate_colour_plane_flag  ==  1 )
1275    //   colour_plane_id                                      u(2)
1276
1277#if N0065_LAYER_POC_ALIGNMENT
1278    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
1279#else
1280    if( !pcSlice->getIdrPicFlag() )
1281#endif
1282    {
1283#if POC_RESET_FLAG
1284      Int picOrderCntLSB;
1285      if( !pcSlice->getPocResetFlag() )
1286      {
1287        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1288      }
1289      else
1290      {
1291        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1292      }
1293#else
1294      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1295#endif
1296      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
1297
1298#if N0065_LAYER_POC_ALIGNMENT
1299      if( !pcSlice->getIdrPicFlag() )
1300      {
1301#endif
1302      TComReferencePictureSet* rps = pcSlice->getRPS();
1303     
1304#if FIX1071
1305      // check for bitstream restriction stating that:
1306      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1307      // Ideally this process should not be repeated for each slice in a picture
1308#if SVC_EXTENSION
1309      if( pcSlice->getLayerId() == 0 )
1310#endif
1311      if (pcSlice->isIRAP())
1312      {
1313        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1314        {
1315          assert (!rps->getUsed(picIdx));
1316        }
1317      }
1318#endif
1319
1320      if(pcSlice->getRPSidx() < 0)
1321      {
1322        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1323        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1324      }
1325      else
1326      {
1327        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1328        Int numBits = 0;
1329        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1330        {
1331          numBits++;
1332        }
1333        if (numBits > 0)
1334        {
1335          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );         
1336        }
1337      }
1338      if(pcSlice->getSPS()->getLongTermRefsPresent())
1339      {
1340        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1341        Int ltrpInSPS[MAX_NUM_REF_PICS];
1342        Int numLtrpInSPS = 0;
1343        UInt ltrpIndex;
1344        Int counter = 0;
1345        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
1346        {
1347          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
1348          {
1349            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1350            numLtrpInSPS++;
1351          }
1352          else
1353          {
1354            counter++;
1355          }
1356        }
1357        numLtrpInSH -= numLtrpInSPS;
1358
1359        Int bitsForLtrpInSPS = 0;
1360        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1361        {
1362          bitsForLtrpInSPS++;
1363        }
1364        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
1365        {
1366          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1367        }
1368        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1369        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1370        // Not sorted here because LT ref indices will be used in setRefPicList()
1371        Int prevDeltaMSB = 0, prevLSB = 0;
1372        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1373        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
1374        {
1375          if (counter < numLtrpInSPS)
1376          {
1377            if (bitsForLtrpInSPS > 0)
1378            {
1379              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");             
1380            }
1381          }
1382          else 
1383          {
1384            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1385            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
1386          }
1387          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1388
1389          if(rps->getDeltaPocMSBPresentFlag(i))
1390          {
1391            Bool deltaFlag = false;
1392            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1393            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1394            {
1395              deltaFlag = true;
1396            }
1397            if(deltaFlag)
1398            {
1399              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1400            }
1401            else
1402            {             
1403              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1404              assert(differenceInDeltaMSB >= 0);
1405              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1406            }
1407            prevLSB = rps->getPocLSBLT(i);
1408            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1409          }
1410        }
1411      }
1412      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1413      {
1414        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
1415      }
1416#if N0065_LAYER_POC_ALIGNMENT
1417      }
1418#endif
1419    }
1420
1421#if JCTVC_M0458_INTERLAYER_RPS_SIG
1422#if ILP_SSH_SIG
1423    if((pcSlice->getSPS()->getLayerId() > 0) && pcSlice->getVPS()->getIlpSshSignalingEnabledFlag() && (pcSlice->getNumILRRefIdx() > 0) )
1424#else
1425    if((pcSlice->getSPS()->getLayerId() > 0)  &&  (pcSlice->getNumILRRefIdx() > 0) )
1426#endif
1427    {
1428      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
1429      if( pcSlice->getInterLayerPredEnabledFlag())
1430      {
1431        if(pcSlice->getNumILRRefIdx() > 1)
1432        {
1433          Int numBits = 1;
1434          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
1435          {
1436            numBits++;
1437          }
1438          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
1439          {
1440            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
1441          }       
1442#if ILP_NUM_REF_CHK
1443          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
1444          {
1445#endif
1446          for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1447          {
1448            WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
1449          }
1450#if ILP_NUM_REF_CHK
1451          }
1452#endif
1453        }
1454      }
1455    }     
1456#if M0457_IL_SAMPLE_PRED_ONLY_FLAG
1457    if( pcSlice->getNumSamplePredRefLayers() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 )
1458    {
1459      WRITE_FLAG( pcSlice->getInterLayerSamplePredOnlyFlag(), "inter_layer_sample_pred_only_flag" );
1460    }
1461#endif
1462#endif
1463
1464    if(pcSlice->getSPS()->getUseSAO())
1465    {
1466      if (pcSlice->getSPS()->getUseSAO())
1467      {
1468         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
1469         {
1470           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
1471          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
1472         }
1473      }
1474    }
1475
1476    //check if numrefidxes match the defaults. If not, override
1477
1478    if (!pcSlice->isIntra())
1479    {
1480      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
1481      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
1482      if (overrideFlag) 
1483      {
1484        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
1485        if (pcSlice->isInterB())
1486        {
1487          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
1488        }
1489        else
1490        {
1491          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1492        }
1493      }
1494    }
1495    else
1496    {
1497      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
1498      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1499    }
1500
1501    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
1502    {
1503      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1504      if(!pcSlice->isIntra())
1505      {
1506        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
1507        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
1508        {
1509          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
1510          if (numRpsCurrTempList0 > 1)
1511          {
1512            Int length = 1;
1513            numRpsCurrTempList0 --;
1514            while ( numRpsCurrTempList0 >>= 1) 
1515            {
1516              length ++;
1517            }
1518            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
1519            {
1520              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
1521            }
1522          }
1523        }
1524      }
1525      if(pcSlice->isInterB())
1526      {   
1527        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
1528        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
1529        {
1530          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
1531          if ( numRpsCurrTempList1 > 1 )
1532          {
1533            Int length = 1;
1534            numRpsCurrTempList1 --;
1535            while ( numRpsCurrTempList1 >>= 1)
1536            {
1537              length ++;
1538            }
1539            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
1540            {
1541              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
1542            }
1543          }
1544        }
1545      }
1546    }
1547   
1548    if (pcSlice->isInterB())
1549    {
1550      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
1551    }
1552
1553    if(!pcSlice->isIntra())
1554    {
1555      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1556      {
1557        SliceType sliceType   = pcSlice->getSliceType();
1558        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
1559        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1560        pcSlice->setCabacInitFlag( encCabacInitFlag );
1561        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1562      }
1563    }
1564
1565    if ( pcSlice->getEnableTMVPFlag() )
1566    {
1567#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1568      if ( !pcSlice->getIdrPicFlag() && pcSlice->getLayerId() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 && pcSlice->getNumMotionPredRefLayers() > 0 )
1569      {
1570        WRITE_FLAG( pcSlice->getAltColIndicationFlag() ? 1 : 0, "alt_collocated_indication_flag" );
1571        if (pcSlice->getAltColIndicationFlag() && pcSlice->getNumMotionPredRefLayers() > 1)
1572        {
1573          WRITE_UVLC(0, "collocated_ref_layer_idx");
1574        }
1575      }
1576      else
1577      {
1578#endif
1579      if ( pcSlice->getSliceType() == B_SLICE )
1580      {
1581        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1582      }
1583
1584      if ( pcSlice->getSliceType() != I_SLICE &&
1585        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1586        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1587      {
1588        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1589      }
1590#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1591      }
1592#endif
1593    }
1594    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1595    {
1596      xCodePredWeightTable( pcSlice );
1597    }
1598    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1599    if (!pcSlice->isIntra())
1600    {
1601      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1602    }
1603    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1604    WRITE_SVLC( iCode, "slice_qp_delta" ); 
1605    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1606    {
1607      iCode = pcSlice->getSliceQpDeltaCb();
1608      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
1609      iCode = pcSlice->getSliceQpDeltaCr();
1610      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
1611    }
1612    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1613    {
1614      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1615      {
1616        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1617      }
1618      if (pcSlice->getDeblockingFilterOverrideFlag())
1619      {
1620        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1621        if(!pcSlice->getDeblockingFilterDisable())
1622        {
1623          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
1624          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
1625        }
1626      }
1627    }
1628
1629    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
1630    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1631
1632    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1633    {
1634      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1635    }
1636  }
1637  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1638  {
1639    WRITE_UVLC(0,"slice_header_extension_length");
1640  }
1641}
1642
1643Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1644{
1645  if(profilePresentFlag)
1646  {
1647    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1648  }
1649  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
1650
1651  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
1652  {
1653    if(profilePresentFlag)
1654    {
1655      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1656    }
1657   
1658    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1659  }
1660 
1661  if (maxNumSubLayersMinus1 > 0)
1662  {
1663    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
1664    {
1665      WRITE_CODE(0, 2, "reserved_zero_2bits");
1666    }
1667  }
1668 
1669  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1670  {
1671    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1672    {
1673      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1674    }
1675    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1676    {
1677      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
1678    }
1679  }
1680}
1681Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1682{
1683  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1684  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
1685  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
1686  for(Int j = 0; j < 32; j++)
1687  {
1688    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
1689  }
1690
1691  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
1692  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
1693  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
1694  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
1695 
1696  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[0..15]");
1697  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
1698  WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
1699}
1700
1701/**
1702 - write wavefront substreams sizes for the slice header.
1703 .
1704 \param pcSlice Where we find the substream size information.
1705 */
1706Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1707{
1708  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1709  {
1710    return;
1711  }
1712  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
1713  Int  numZeroSubstreamsAtStartOfSlice  = 0;
1714  UInt *entryPointOffset = NULL;
1715  if ( pSlice->getPPS()->getTilesEnabledFlag() )
1716  {
1717    numEntryPointOffsets = pSlice->getTileLocationCount();
1718    entryPointOffset     = new UInt[numEntryPointOffsets];
1719    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
1720    {
1721      if ( idx == 0 )
1722      {
1723        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
1724      }
1725      else
1726      {
1727        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
1728      }
1729
1730      if ( entryPointOffset[ idx ] > maxOffset )
1731      {
1732        maxOffset = entryPointOffset[ idx ];
1733      }
1734    }
1735  }
1736  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
1737  {
1738    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
1739    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
1740    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceSegmentCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1741    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceSegmentCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1742    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
1743    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
1744    entryPointOffset           = new UInt[numEntryPointOffsets];
1745    for (Int idx=0; idx<numEntryPointOffsets; idx++)
1746    {
1747      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
1748      if ( entryPointOffset[ idx ] > maxOffset )
1749      {
1750        maxOffset = entryPointOffset[ idx ];
1751      }
1752    }
1753  }
1754  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1755  offsetLenMinus1 = 0;
1756  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1757  {
1758    offsetLenMinus1++;
1759    assert(offsetLenMinus1 + 1 < 32);   
1760  }
1761
1762  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
1763  if (numEntryPointOffsets>0)
1764  {
1765    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1766  }
1767
1768  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
1769  {
1770    WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
1771  }
1772
1773  delete [] entryPointOffset;
1774}
1775
1776Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1777{
1778}
1779
1780Void TEncCavlc::codeSliceFinish ()
1781{
1782}
1783
1784Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1785{
1786  assert(0);
1787}
1788
1789Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1790{
1791  assert(0);
1792}
1793
1794Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1795{
1796  assert(0);
1797}
1798
1799Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1800{
1801  assert(0);
1802}
1803
1804Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1805{
1806  assert(0);
1807}
1808
1809Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1810{
1811  assert(0);
1812}
1813
1814Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1815{
1816  assert(0);
1817}
1818
1819Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1820{
1821  assert(0);
1822}
1823
1824Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1825{
1826  assert(0);
1827}
1828
1829Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1830{
1831  assert(0);
1832}
1833
1834Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1835{
1836  assert(0);
1837}
1838
1839Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1840{
1841  assert(0);
1842}
1843
1844Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
1845{
1846  assert(0);
1847}
1848Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
1849{
1850  assert(0);
1851}
1852
1853Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
1854{
1855  assert(0);
1856}
1857
1858/** Code I_PCM information.
1859 * \param pcCU pointer to CU
1860 * \param uiAbsPartIdx CU index
1861 * \returns Void
1862 */
1863Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
1864{
1865  assert(0);
1866}
1867
1868Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1869{
1870  assert(0);
1871}
1872
1873Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
1874{
1875  assert(0);
1876}
1877
1878Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
1879{
1880  assert(0);
1881}
1882
1883Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1884{
1885  assert(0);
1886}
1887
1888Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1889{
1890  assert(0);
1891}
1892
1893Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
1894{
1895  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
1896
1897#if REPN_FORMAT_IN_VPS
1898  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
1899#else
1900  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
1901#endif
1902  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
1903
1904  xWriteSvlc( iDQp );
1905 
1906  return;
1907}
1908
1909Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
1910{
1911  assert(0);
1912}
1913
1914Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
1915{
1916  // printf("error : no VLC mode support in this version\n");
1917  return;
1918}
1919
1920// ====================================================================================================================
1921// Protected member functions
1922// ====================================================================================================================
1923
1924/** code explicit wp tables
1925 * \param TComSlice* pcSlice
1926 * \returns Void
1927 */
1928Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
1929{
1930  wpScalingParam  *wp;
1931  Bool            bChroma     = true; // color always present in HEVC ?
1932  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
1933  Bool            bDenomCoded  = false;
1934  UInt            uiMode = 0;
1935  UInt            uiTotalSignalledWeightFlags = 0;
1936  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
1937  {
1938    uiMode = 1; // explicit
1939  }
1940  if(uiMode == 1)
1941  {
1942
1943    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
1944    {
1945      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1946
1947      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1948      {
1949        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1950        if ( !bDenomCoded ) 
1951        {
1952          Int iDeltaDenom;
1953          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
1954
1955          if( bChroma )
1956          {
1957            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
1958            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
1959          }
1960          bDenomCoded = true;
1961        }
1962        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
1963        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
1964      }
1965      if (bChroma) 
1966      {
1967        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1968        {
1969          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1970          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1971          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
1972        }
1973      }
1974
1975      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1976      {
1977        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1978        if ( wp[0].bPresentFlag ) 
1979        {
1980          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
1981          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
1982          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
1983        }
1984
1985        if ( bChroma ) 
1986        {
1987          if ( wp[1].bPresentFlag )
1988          {
1989            for ( Int j=1 ; j<3 ; j++ ) 
1990            {
1991              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
1992              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
1993
1994              Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
1995              Int iDeltaChroma = (wp[j].iOffset - pred);
1996              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
1997            }
1998          }
1999        }
2000      }
2001    }
2002    assert(uiTotalSignalledWeightFlags<=24);
2003  }
2004}
2005
2006/** code quantization matrix
2007 *  \param scalingList quantization matrix information
2008 */
2009Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
2010{
2011  UInt listId,sizeId;
2012  Bool scalingListPredModeFlag;
2013
2014#if SCALING_LIST_OUTPUT_RESULT
2015  Int startBit;
2016  Int startTotalBit;
2017  startBit = m_pcBitIf->getNumberOfWrittenBits();
2018  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
2019#endif
2020
2021    //for each size
2022    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2023    {
2024      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
2025      {
2026#if SCALING_LIST_OUTPUT_RESULT
2027        startBit = m_pcBitIf->getNumberOfWrittenBits();
2028#endif
2029
2030#if IL_SL_SIGNALLING_N0371
2031        if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
2032        {
2033          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2034          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2035          if(!scalingListPredModeFlag)// Copy Mode
2036          {
2037            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2038          }
2039          else// DPCM Mode
2040          {
2041            xCodeScalingList(scalingList, sizeId, listId);
2042          }
2043        }
2044        else
2045        {
2046          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2047          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2048          if(!scalingListPredModeFlag)// Copy Mode
2049          {
2050            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2051          }
2052          else// DPCM Mode
2053          {
2054            xCodeScalingList(scalingList, sizeId, listId);
2055          }
2056        }
2057#else
2058        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2059        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2060        if(!scalingListPredModeFlag)// Copy Mode
2061        {
2062          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2063        }
2064        else// DPCM Mode
2065        {
2066          xCodeScalingList(scalingList, sizeId, listId);
2067        }
2068#endif
2069
2070#if SCALING_LIST_OUTPUT_RESULT
2071        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
2072#endif
2073
2074      }
2075    }
2076#if SCALING_LIST_OUTPUT_RESULT
2077  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
2078#endif
2079  return;
2080}
2081/** code DPCM
2082 * \param scalingList quantization matrix information
2083 * \param sizeIdc size index
2084 * \param listIdc list index
2085 */
2086Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
2087{
2088  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
2089  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
2090  Int nextCoef = SCALING_LIST_START_VALUE;
2091  Int data;
2092  Int *src = scalingList->getScalingListAddress(sizeId, listId);
2093
2094    if( sizeId > SCALING_LIST_8x8 )
2095    {
2096#if IL_SL_SIGNALLING_N0371
2097      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
2098      {
2099        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
2100        scalingList->setScalingListDC(sizeId,listId,ref_scalingListDC[scalingList->getScalingListRefLayerId()][sizeId][listId]);
2101      }
2102      else
2103      {
2104        WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
2105        nextCoef = scalingList->getScalingListDC(sizeId,listId);
2106        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
2107      }
2108#else
2109      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
2110      nextCoef = scalingList->getScalingListDC(sizeId,listId);
2111#endif
2112    }
2113    for(Int i=0;i<coefNum;i++)
2114    {
2115#if IL_SL_SIGNALLING_N0371
2116      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
2117      {
2118        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
2119        src[scan[i]] = ref_scalingListCoef[scalingList->getScalingListRefLayerId()][sizeId][listId][i];
2120      }
2121      else
2122      {
2123        data = src[scan[i]] - nextCoef;
2124        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
2125        nextCoef = src[scan[i]];
2126        if(data > 127)
2127        {
2128          data = data - 256;
2129        }
2130        if(data < -128)
2131        {
2132          data = data + 256;
2133        }
2134
2135        WRITE_SVLC( data,  "scaling_list_delta_coef");
2136      }
2137#else
2138      data = src[scan[i]] - nextCoef;
2139      nextCoef = src[scan[i]];
2140      if(data > 127)
2141      {
2142        data = data - 256;
2143      }
2144      if(data < -128)
2145      {
2146        data = data + 256;
2147      }
2148
2149      WRITE_SVLC( data,  "scaling_list_delta_coef");
2150#endif
2151    }
2152}
2153Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
2154{
2155  // Bool state = true, state2 = false;
2156  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
2157  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
2158  {
2159    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
2160    {
2161      *ltrpsIndex = k;
2162      return true;
2163    }
2164  }
2165  return false;
2166}
2167Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
2168{
2169  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
2170  {
2171    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
2172      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
2173     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
2174    {
2175      setRefMatrixId(sizeId, listId, predListIdx);
2176      return false;
2177    }
2178  }
2179  return true;
2180}
2181//! \}
Note: See TracBrowser for help on using the repository browser.