source: SHVCSoftware/branches/SHM-dev/source/Lib/TLibEncoder/TEncCavlc.cpp @ 1048

Last change on this file since 1048 was 1048, checked in by interdigital, 10 years ago
  1. change MAX_VPS_LAYER_ID_PLUS1 to MAX_VPS_LAYER_IDX_PLUS1
  2. change layerId to layerIdx whenever layer index is used
  3. replace mistakenly used layer ID with layer index
  • Property svn:eol-style set to native
File size: 126.6 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-2014, 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}
74
75TEncCavlc::~TEncCavlc()
76{
77}
78
79
80// ====================================================================================================================
81// Public member functions
82// ====================================================================================================================
83
84Void TEncCavlc::resetEntropy()
85{
86}
87
88
89Void TEncCavlc::codeDFFlag(UInt uiCode, const Char *pSymbolName)
90{
91  WRITE_FLAG(uiCode, pSymbolName);
92}
93Void TEncCavlc::codeDFSvlc(Int iCode, const Char *pSymbolName)
94{
95  WRITE_SVLC(iCode, pSymbolName);
96}
97
98Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps, Bool calledFromSliceHeader, Int idx)
99{
100#if PRINT_RPS_INFO
101  Int lastBits = getNumberOfWrittenBits();
102#endif
103  if (idx > 0)
104  {
105  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
106  }
107  if (rps->getInterRPSPrediction())
108  {
109    Int deltaRPS = rps->getDeltaRPS();
110    if(calledFromSliceHeader)
111    {
112      WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
113    }
114
115    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
116    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
117
118    for(Int j=0; j < rps->getNumRefIdc(); j++)
119    {
120      Int refIdc = rps->getRefIdc(j);
121      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
122      if (refIdc != 1)
123      {
124        WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
125      }
126    }
127  }
128  else
129  {
130    WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
131    WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
132    Int prev = 0;
133    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
134    {
135      WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
136      prev = rps->getDeltaPOC(j);
137      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag");
138    }
139    prev = 0;
140    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
141    {
142      WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
143      prev = rps->getDeltaPOC(j);
144      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" );
145    }
146  }
147
148#if PRINT_RPS_INFO
149  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
150  rps->printDeltaPOC();
151#endif
152}
153
154
155Void TEncCavlc::codePPS( TComPPS* pcPPS
156#if Q0048_CGS_3D_ASYMLUT
157  , TEnc3DAsymLUT * pc3DAsymLUT
158#endif
159  )
160{
161#if ENC_DEC_TRACE
162  xTracePPSHeader (pcPPS);
163#endif
164
165  const UInt numberValidComponents = getNumberValidComponents(pcPPS->getSPS()->getChromaFormatIdc());
166
167  WRITE_UVLC( pcPPS->getPPSId(),                             "pps_pic_parameter_set_id" );
168  WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
169  WRITE_FLAG( pcPPS->getDependentSliceSegmentsEnabledFlag()    ? 1 : 0, "dependent_slice_segments_enabled_flag" );
170  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,     "output_flag_present_flag" );
171  WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3,        "num_extra_slice_header_bits");
172  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
173  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
174  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
175  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
176
177  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "init_qp_minus26");
178  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
179  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" );
180  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
181  if ( pcPPS->getUseDQP() )
182  {
183    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
184  }
185
186  WRITE_SVLC( COMPONENT_Cb<numberValidComponents ?  (pcPPS->getQpOffset(COMPONENT_Cb)) : 0, "pps_cb_qp_offset" );
187  WRITE_SVLC( COMPONENT_Cr<numberValidComponents ?  (pcPPS->getQpOffset(COMPONENT_Cr)) : 0, "pps_cr_qp_offset" );
188
189  assert(numberValidComponents <= 3); // if more than 3 components (eg 4:4:4:4), then additional offsets will have to go in extension area...
190
191  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
192
193  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
194  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
195  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
196  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
197  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
198  if( pcPPS->getTilesEnabledFlag() )
199  {
200    WRITE_UVLC( pcPPS->getNumTileColumnsMinus1(),                                    "num_tile_columns_minus1" );
201    WRITE_UVLC( pcPPS->getNumTileRowsMinus1(),                                       "num_tile_rows_minus1" );
202    WRITE_FLAG( pcPPS->getTileUniformSpacingFlag(),                                  "uniform_spacing_flag" );
203    if( !pcPPS->getTileUniformSpacingFlag() )
204    {
205      for(UInt i=0; i<pcPPS->getNumTileColumnsMinus1(); i++)
206      {
207        WRITE_UVLC( pcPPS->getTileColumnWidth(i)-1,                                  "column_width_minus1" );
208      }
209      for(UInt i=0; i<pcPPS->getNumTileRowsMinus1(); i++)
210      {
211        WRITE_UVLC( pcPPS->getTileRowHeight(i)-1,                                    "row_height_minus1" );
212      }
213    }
214    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getNumTileRowsMinus1() !=0)
215    {
216      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
217    }
218  }
219  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
220  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
221  if(pcPPS->getDeblockingFilterControlPresentFlag())
222  {
223    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" );
224    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
225    if(!pcPPS->getPicDisableDeblockingFilterFlag())
226    {
227      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
228      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
229    }
230  }
231  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" );
232  if( pcPPS->getScalingListPresentFlag() )
233  {
234    codeScalingList( m_pcSlice->getScalingList() );
235  }
236  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
237  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
238  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
239
240  Bool pps_extension_present_flag=false;
241  Bool pps_extension_flags[NUM_PPS_EXTENSION_FLAGS]={false};
242
243  pps_extension_flags[PPS_EXT__REXT] = (
244             ( pcPPS->getUseTransformSkip() && (pcPPS->getTransformSkipLog2MaxSize() != 2))
245          || pcPPS->getUseCrossComponentPrediction()
246          || ( pcPPS->getChromaQpAdjTableSize() > 0 )
247          || ( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_LUMA) !=0 ) || ( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_CHROMA) !=0 )
248     )
249    ;
250
251  // Other PPS extension flags checked here.
252
253#if SVC_EXTENSION
254  pps_extension_flags[PPS_EXT__MLAYER] = pcPPS->getExtensionFlag() ? 1 : 0;
255#if Q0048_CGS_3D_ASYMLUT
256  UInt bits = 0;
257#endif
258#endif
259
260  for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
261  {
262    pps_extension_present_flag|=pps_extension_flags[i];
263  }
264
265  WRITE_FLAG( (pps_extension_present_flag?1:0), "pps_extension_present_flag" );
266
267  if (pps_extension_present_flag)
268  {
269    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
270    {
271      WRITE_FLAG( pps_extension_flags[i]?1:0, "pps_extension_flag[]" );
272    }
273
274    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
275    {
276      if (pps_extension_flags[i])
277      {
278        switch (PPSExtensionFlagIndex(i))
279        {
280          case PPS_EXT__REXT:
281
282            if (pcPPS->getUseTransformSkip())
283            {
284              WRITE_UVLC( pcPPS->getTransformSkipLog2MaxSize()-2,                 "log2_transform_skip_max_size_minus2");
285            }
286
287            WRITE_FLAG((pcPPS->getUseCrossComponentPrediction() ? 1 : 0),         "cross_component_prediction_flag" );
288
289            WRITE_FLAG(UInt(pcPPS->getChromaQpAdjTableSize() > 0),                "chroma_qp_adjustment_enabled_flag" );
290            if (pcPPS->getChromaQpAdjTableSize() > 0)
291            {
292              WRITE_UVLC(pcPPS->getMaxCuChromaQpAdjDepth(),                       "diff_cu_chroma_qp_adjustment_depth");
293              WRITE_UVLC(pcPPS->getChromaQpAdjTableSize() - 1,                    "chroma_qp_adjustment_table_size_minus1");
294              /* skip zero index */
295              for (Int chromaQpAdjustmentIndex = 1; chromaQpAdjustmentIndex <= pcPPS->getChromaQpAdjTableSize(); chromaQpAdjustmentIndex++)
296              {
297                WRITE_SVLC(pcPPS->getChromaQpAdjTableAt(chromaQpAdjustmentIndex).u.comp.CbOffset,     "cb_qp_adjustnemt[i]");
298                WRITE_SVLC(pcPPS->getChromaQpAdjTableAt(chromaQpAdjustmentIndex).u.comp.CrOffset,     "cr_qp_adjustnemt[i]");
299              }
300            }
301
302            WRITE_UVLC( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_LUMA),           "sao_luma_bit_shift"   );
303            WRITE_UVLC( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_CHROMA),         "sao_chroma_bit_shift" );
304            break;
305#if SVC_EXTENSION
306          case PPS_EXT__MLAYER:
307            WRITE_FLAG( pcPPS->getPocResetInfoPresentFlag() ? 1 : 0, "poc_reset_info_present_flag" );
308#if SCALINGLIST_INFERRING
309            WRITE_FLAG( pcPPS->getInferScalingListFlag() ? 1 : 0, "pps_infer_scaling_list_flag" );
310            if( pcPPS->getInferScalingListFlag() )
311            {
312              // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
313              assert( pcPPS->getScalingListRefLayerId() <= 62 );
314              WRITE_CODE( pcPPS->getScalingListRefLayerId(), 6, "pps_scaling_list_ref_layer_id" );
315            }
316#endif
317
318#if REF_REGION_OFFSET
319            WRITE_UVLC( pcPPS->getNumRefLayerLocationOffsets(),      "num_ref_loc_offsets" );
320            for(Int k = 0; k < pcPPS->getNumRefLayerLocationOffsets(); k++)
321            {
322              WRITE_CODE( pcPPS->getRefLocationOffsetLayerId(k), 6, "ref_loc_offset_layer_id" );
323              WRITE_FLAG( pcPPS->getScaledRefLayerOffsetPresentFlag(k) ? 1 : 0, "scaled_ref_layer_offset_prsent_flag" );
324              if (pcPPS->getScaledRefLayerOffsetPresentFlag(k))
325              {
326                Window scaledWindow = pcPPS->getScaledRefLayerWindow(k);
327                WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
328                WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
329                WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
330                WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
331              }
332              WRITE_FLAG( pcPPS->getRefRegionOffsetPresentFlag(k) ? 1 : 0, "ref_region_offset_prsent_flag" );
333              if (pcPPS->getRefRegionOffsetPresentFlag(k))
334              {
335                Window refWindow = pcPPS->getRefLayerWindow(k);
336                WRITE_SVLC( refWindow.getWindowLeftOffset()   >> 1, "ref_region_left_offset" );
337                WRITE_SVLC( refWindow.getWindowTopOffset()    >> 1, "ref_region_top_offset" );
338                WRITE_SVLC( refWindow.getWindowRightOffset()  >> 1, "ref_region_right_offset" );
339                WRITE_SVLC( refWindow.getWindowBottomOffset() >> 1, "ref_region_bottom_offset" );
340              }
341#if R0209_GENERIC_PHASE
342              WRITE_FLAG( pcPPS->getResamplePhaseSetPresentFlag(k) ? 1 : 0, "resample_phase_set_present_flag" );
343              if (pcPPS->getResamplePhaseSetPresentFlag(k))
344              {
345                WRITE_UVLC( pcPPS->getPhaseHorLuma(k), "phase_hor_luma" );
346                WRITE_UVLC( pcPPS->getPhaseVerLuma(k), "phase_ver_luma" );
347                WRITE_UVLC( pcPPS->getPhaseHorChroma(k) + 8, "phase_hor_chroma_plus8" );
348                WRITE_UVLC( pcPPS->getPhaseVerChroma(k) + 8, "phase_ver_chroma_plus8" );
349              }
350#endif
351            }
352#else
353#if MOVE_SCALED_OFFSET_TO_PPS
354            WRITE_UVLC( pcPPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
355            for(Int k = 0; k < pcPPS->getNumScaledRefLayerOffsets(); k++)
356            {
357              Window scaledWindow = pcPPS->getScaledRefLayerWindow(k);
358#if O0098_SCALED_REF_LAYER_ID
359              WRITE_CODE( pcPPS->getScaledRefLayerId(k), 6,          "scaled_ref_layer_id" );
360#endif
361              WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
362              WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
363              WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
364              WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
365            }
366#endif
367#endif
368#if Q0048_CGS_3D_ASYMLUT
369            bits = getNumberOfWrittenBits();
370            WRITE_FLAG( pcPPS->getCGSFlag() , "colour_mapping_enabled_flag" );
371            if( pcPPS->getCGSFlag() )
372            {
373              assert( pc3DAsymLUT != NULL );
374              xCode3DAsymLUT( pc3DAsymLUT );
375            }
376            pc3DAsymLUT->setPPSBit( getNumberOfWrittenBits() - bits );
377#endif
378            break;
379#endif
380          default:
381            assert(pps_extension_flags[i]==false); // Should never get here with an active PPS extension flag.
382            break;
383        } // switch
384      } // if flag present
385    } // loop over PPS flags
386  } // pps_extension_present_flag is non-zero
387}
388
389Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
390{
391#if ENC_DEC_TRACE
392  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
393#endif
394  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
395  if (pcVUI->getAspectRatioInfoPresentFlag())
396  {
397    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
398    if (pcVUI->getAspectRatioIdc() == 255)
399    {
400      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
401      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
402    }
403  }
404  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
405  if (pcVUI->getOverscanInfoPresentFlag())
406  {
407    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
408  }
409  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
410  if (pcVUI->getVideoSignalTypePresentFlag())
411  {
412    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
413    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
414    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
415    if (pcVUI->getColourDescriptionPresentFlag())
416    {
417      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
418      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
419      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
420    }
421  }
422
423  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
424  if (pcVUI->getChromaLocInfoPresentFlag())
425  {
426    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
427    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
428  }
429
430  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
431  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
432  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
433
434  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
435  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
436  if( defaultDisplayWindow.getWindowEnabledFlag() )
437  {
438    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_left_offset");
439    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset() / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_right_offset");
440    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset()   / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_top_offset");
441    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset()/ TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_bottom_offset");
442  }
443  TimingInfo *timingInfo = pcVUI->getTimingInfo();
444  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
445  if(timingInfo->getTimingInfoPresentFlag())
446  {
447    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
448    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
449    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
450    if(timingInfo->getPocProportionalToTimingFlag())
451    {
452      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
453    }
454    WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
455    if( pcVUI->getHrdParametersPresentFlag() )
456    {
457      codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
458    }
459  }
460
461  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
462  if (pcVUI->getBitstreamRestrictionFlag())
463  {
464    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
465    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
466    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
467    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
468    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
469    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
470    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
471    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
472  }
473}
474
475Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
476{
477  if( commonInfPresentFlag )
478  {
479    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
480    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
481    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
482    {
483      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
484      if( hrd->getSubPicCpbParamsPresentFlag() )
485      {
486        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
487        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
488        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
489        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
490      }
491      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
492      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
493      if( hrd->getSubPicCpbParamsPresentFlag() )
494      {
495        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" );
496      }
497      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
498      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
499      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
500    }
501  }
502  Int i, j, nalOrVcl;
503  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
504  {
505    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
506    if( !hrd->getFixedPicRateFlag( i ) )
507    {
508      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
509    }
510    else
511    {
512      hrd->setFixedPicRateWithinCvsFlag( i, true );
513    }
514    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
515    {
516      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
517    }
518    else
519    {
520      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
521    }
522    if (!hrd->getLowDelayHrdFlag( i ))
523    {
524      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
525    }
526
527    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
528    {
529      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
530          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
531      {
532        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
533        {
534          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
535          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
536          if( hrd->getSubPicCpbParamsPresentFlag() )
537          {
538            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");
539            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
540          }
541          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
542        }
543      }
544    }
545  }
546}
547
548Void TEncCavlc::codeSPS( TComSPS* pcSPS )
549{
550#if SVC_EXTENSION
551  Bool V1CompatibleSPSFlag = !(pcSPS->getLayerId() != 0 && pcSPS->getNumDirectRefLayers() != 0);
552#endif
553
554  const ChromaFormat format                = pcSPS->getChromaFormatIdc();
555  const Bool         chromaEnabled         = isChromaEnabled(format);
556
557#if ENC_DEC_TRACE
558  xTraceSPSHeader (pcSPS);
559#endif
560  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
561#if SVC_EXTENSION
562  if(pcSPS->getLayerId() == 0)
563  {
564#endif
565  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
566#if SVC_EXTENSION
567  }
568  else
569  {
570    WRITE_CODE( V1CompatibleSPSFlag ? (pcSPS->getMaxTLayers() - 1) : 7,  3,       "sps_ext_or_max_sub_layers_minus1" );
571  }
572
573  if( V1CompatibleSPSFlag )
574  {
575#endif
576  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
577  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
578#if SVC_EXTENSION
579  }
580#endif
581  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
582#if SVC_EXTENSION
583  if( !V1CompatibleSPSFlag )
584  {
585    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
586 
587    if( pcSPS->getUpdateRepFormatFlag())
588    {
589      WRITE_CODE( pcSPS->getUpdateRepFormatIndex(), 8,   "sps_rep_format_idx");
590    }
591  }
592  else
593  {
594#endif
595  WRITE_UVLC( Int(pcSPS->getChromaFormatIdc ()),    "chroma_format_idc" );
596  if( format == CHROMA_444 )
597  {
598    WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
599  }
600
601  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
602  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
603  Window conf = pcSPS->getConformanceWindow();
604
605  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
606  if (conf.getWindowEnabledFlag())
607  {
608#if REPN_FORMAT_IN_VPS
609    WRITE_UVLC( conf.getWindowLeftOffset(),   "conf_win_left_offset"   );
610    WRITE_UVLC( conf.getWindowRightOffset(),  "conf_win_right_offset"  );
611    WRITE_UVLC( conf.getWindowTopOffset(),    "conf_win_top_offset"    );
612    WRITE_UVLC( conf.getWindowBottomOffset(), "conf_win_bottom_offset" );
613#else
614    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
615    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
616    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
617    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
618#endif
619  }
620#if SVC_EXTENSION
621  }
622
623  if( V1CompatibleSPSFlag )
624  {
625#endif
626  WRITE_UVLC( pcSPS->getBitDepth(CHANNEL_TYPE_LUMA) - 8,                      "bit_depth_luma_minus8" );
627
628  WRITE_UVLC( chromaEnabled ? (pcSPS->getBitDepth(CHANNEL_TYPE_CHROMA) - 8):0,  "bit_depth_chroma_minus8" );
629#if SVC_EXTENSION
630  }
631#endif
632
633  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
634
635#if SVC_EXTENSION
636  if( V1CompatibleSPSFlag )
637  {
638#endif
639  const Bool subLayerOrderingInfoPresentFlag = 1;
640  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
641  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
642  {
643    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
644    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
645    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
646    if (!subLayerOrderingInfoPresentFlag)
647    {
648      break;
649    }
650  }
651#if SVC_EXTENSION
652  }
653#endif
654  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
655
656  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
657  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
658  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
659  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
660  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
661  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
662  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" );
663  if(pcSPS->getScalingListFlag())
664  {
665#if SCALINGLIST_INFERRING
666    if( !V1CompatibleSPSFlag )
667    {
668      WRITE_FLAG( pcSPS->getInferScalingListFlag() ? 1 : 0, "sps_infer_scaling_list_flag" );
669    }
670
671    if( pcSPS->getInferScalingListFlag() )
672    {
673      // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
674      assert( pcSPS->getScalingListRefLayerId() <= 62 );
675
676      WRITE_CODE( pcSPS->getScalingListRefLayerId(), 6, "sps_scaling_list_ref_layer_id" );
677    }
678    else
679    {
680#endif
681    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" );
682    if(pcSPS->getScalingListPresentFlag())
683    {
684      codeScalingList( m_pcSlice->getScalingList() );
685    }
686#if SCALINGLIST_INFERRING
687    }
688#endif
689  }
690  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
691  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
692
693  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
694  if( pcSPS->getUsePCM() )
695  {
696    WRITE_CODE( pcSPS->getPCMBitDepth(CHANNEL_TYPE_LUMA) - 1, 4,                            "pcm_sample_bit_depth_luma_minus1" );
697    WRITE_CODE( chromaEnabled ? (pcSPS->getPCMBitDepth(CHANNEL_TYPE_CHROMA) - 1) : 0, 4,    "pcm_sample_bit_depth_chroma_minus1" );
698    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
699    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
700    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
701  }
702
703  assert( pcSPS->getMaxTLayers() > 0 );
704
705  TComRPSList* rpsList = pcSPS->getRPSList();
706  TComReferencePictureSet*      rps;
707
708  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
709  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
710  {
711    rps = rpsList->getReferencePictureSet(i);
712    codeShortTermRefPicSet(pcSPS,rps,false, i);
713  }
714  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
715  if (pcSPS->getLongTermRefsPresent())
716  {
717    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
718    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
719    {
720      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
721      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
722    }
723  }
724  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
725
726  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
727
728  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
729  if (pcSPS->getVuiParametersPresentFlag())
730  {
731      codeVUI(pcSPS->getVuiParameters(), pcSPS);
732  }
733
734  Bool sps_extension_present_flag=false;
735  Bool sps_extension_flags[NUM_SPS_EXTENSION_FLAGS]={false};
736
737  sps_extension_flags[SPS_EXT__REXT] = (
738          pcSPS->getUseResidualRotation()
739       || pcSPS->getUseSingleSignificanceMapContext()
740       || pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_IMPLICIT)
741       || pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_EXPLICIT)
742       || pcSPS->getUseExtendedPrecision()
743       || pcSPS->getDisableIntraReferenceSmoothing()
744       || pcSPS->getUseHighPrecisionPredictionWeighting()
745       || pcSPS->getUseGolombRiceParameterAdaptation()
746       || pcSPS->getAlignCABACBeforeBypass()
747    );
748
749  // Other SPS extension flags checked here.
750#if SVC_EXTENSION
751  sps_extension_flags[SPS_EXT__MLAYER] = pcSPS->getExtensionFlag() ? 1 : 0;
752#endif
753
754  for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
755  {
756    sps_extension_present_flag|=sps_extension_flags[i];
757  }
758
759  WRITE_FLAG( (sps_extension_present_flag?1:0), "sps_extension_present_flag" );
760
761  if (sps_extension_present_flag)
762  {
763    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
764    {
765      WRITE_FLAG( sps_extension_flags[i]?1:0, "sps_extension_flag[]" );
766    }
767
768    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
769    {
770      if (sps_extension_flags[i])
771      {
772        switch (SPSExtensionFlagIndex(i))
773        {
774          case SPS_EXT__REXT:
775
776            WRITE_FLAG( (pcSPS->getUseResidualRotation() ? 1 : 0),                  "transform_skip_rotation_enabled_flag");
777            WRITE_FLAG( (pcSPS->getUseSingleSignificanceMapContext() ? 1 : 0),      "transform_skip_context_enabled_flag");
778            WRITE_FLAG( (pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_IMPLICIT) ? 1 : 0), "residual_dpcm_implicit_enabled_flag" );
779            WRITE_FLAG( (pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_EXPLICIT) ? 1 : 0), "residual_dpcm_explicit_enabled_flag" );
780            WRITE_FLAG( (pcSPS->getUseExtendedPrecision() ? 1 : 0),                 "extended_precision_processing_flag" );
781            WRITE_FLAG( (pcSPS->getDisableIntraReferenceSmoothing() ? 1 : 0),       "intra_smoothing_disabled_flag" );
782            WRITE_FLAG( (pcSPS->getUseHighPrecisionPredictionWeighting() ? 1 : 0),  "high_precision_prediction_weighting_flag" );
783            WRITE_FLAG( (pcSPS->getUseGolombRiceParameterAdaptation() ? 1 : 0),     "golomb_rice_parameter_adaptation_flag" );
784            WRITE_FLAG( (pcSPS->getAlignCABACBeforeBypass() ? 1 : 0),               "cabac_bypass_alignment_enabled_flag" );
785            break;
786#if SVC_EXTENSION
787          case SPS_EXT__MLAYER:
788            codeSPSExtension( pcSPS ); //it is sps_multilayer_extension
789            break;
790#endif
791          default:
792            assert(sps_extension_flags[i]==false); // Should never get here with an active SPS extension flag.
793            break;
794        }
795      }
796    }
797  }
798}
799
800Void TEncCavlc::codeVPS( TComVPS* pcVPS )
801{
802#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
803#if VPS_EXTN_OFFSET_CALC
804  UInt numBytesInVps = this->m_pcBitIf->getNumberOfWrittenBits();
805#endif
806#endif
807#if !P0307_REMOVE_VPS_VUI_OFFSET
808#if VPS_VUI_OFFSET
809   m_vpsVuiCounter = this->m_pcBitIf->getNumberOfWrittenBits();
810#endif
811#endif
812  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
813#if VPS_RESERVED_FLAGS
814  WRITE_FLAG( pcVPS->getBaseLayerInternalFlag(),              "vps_base_layer_internal_flag");
815  WRITE_FLAG( pcVPS->getBaseLayerAvailableFlag(),             "vps_base_layer_available_flag");
816#else
817  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
818#endif
819#if SVC_EXTENSION
820  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );
821  assert( pcVPS->getBaseLayerInternalFlag() || pcVPS->getMaxLayers() > 1 );
822#else
823  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
824#endif
825  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
826  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
827  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
828#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
829#if VPS_EXTN_OFFSET
830  WRITE_CODE( pcVPS->getExtensionOffset(),         16,        "vps_extension_offset" );
831#else
832  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
833#endif
834#else
835  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
836#endif
837  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
838  const Bool subLayerOrderingInfoPresentFlag = 1;
839  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
840  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
841  {
842    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
843    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
844    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
845    if (!subLayerOrderingInfoPresentFlag)
846    {
847      break;
848    }
849  }
850
851#if SVC_EXTENSION
852  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
853  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_IDX_PLUS1 );
854#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
855  pcVPS->setNumLayerSets(1);
856#endif
857  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
858#if Q0078_ADD_LAYER_SETS
859  WRITE_UVLC(pcVPS->getVpsNumLayerSetsMinus1(),                "vps_num_layer_sets_minus1");
860  for (UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx++)
861#else
862  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
863  for (UInt opsIdx = 1; opsIdx <= (pcVPS->getNumLayerSets() - 1); opsIdx++)
864#endif
865  {
866    // Operation point set
867    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
868#else
869  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
870  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
871  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
872  pcVPS->setMaxOpSets(1);
873  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
874  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
875  {
876    // Operation point set
877    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
878#endif
879    {
880#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
881      // Only applicable for version 1
882      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
883#endif
884      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
885    }
886  }
887#if !FIX_LAYER_ID_INIT  // It was still called because NECESSARY_FLAG does not exist and is by default "false"
888#if !NECESSARY_FLAG   // Already called once in TAppEncTop.cpp
889#if DERIVE_LAYER_ID_LIST_VARIABLES
890  pcVPS->deriveLayerIdListVariables();
891#endif
892#endif
893#endif
894  TimingInfo *timingInfo = pcVPS->getTimingInfo();
895  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
896  if(timingInfo->getTimingInfoPresentFlag())
897  {
898    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
899    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
900    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
901    if(timingInfo->getPocProportionalToTimingFlag())
902    {
903      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
904    }
905    pcVPS->setNumHrdParameters( 0 );
906    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
907
908    if( pcVPS->getNumHrdParameters() > 0 )
909    {
910      pcVPS->createHrdParamBuffer();
911    }
912    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
913    {
914      // Only applicable for version 1
915      pcVPS->setHrdOpSetIdx( 0, i );
916      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
917      if( i > 0 )
918      {
919        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
920      }
921      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
922    }
923  }
924#if SVC_EXTENSION
925  // When MaxLayersMinus1 is greater than 0, vps_extension_flag shall be equal to 1.
926  if( pcVPS->getMaxLayers() > 1 )
927  {
928    assert( pcVPS->getVpsExtensionFlag() == true );
929  }
930
931  WRITE_FLAG( pcVPS->getVpsExtensionFlag() ? 1 : 0,                     "vps_extension_flag" );
932
933  if( pcVPS->getVpsExtensionFlag() )
934  {
935    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
936    {
937      WRITE_FLAG(1,                  "vps_extension_alignment_bit_equal_to_one");
938    }
939#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
940#if VPS_EXTN_OFFSET_CALC
941    Int vpsExntOffsetValueInBits = this->m_pcBitIf->getNumberOfWrittenBits() - numBytesInVps + 16; // 2 bytes for NUH
942    assert( vpsExntOffsetValueInBits % 8 == 0 );
943    pcVPS->setExtensionOffset( vpsExntOffsetValueInBits >> 3 );
944#endif
945#endif
946    codeVPSExtension(pcVPS);
947    WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
948  }
949#else
950  WRITE_FLAG( 0,                     "vps_extension_flag" );
951#endif 
952  //future extensions here..
953 
954  return;
955}
956
957Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
958{
959#if ENC_DEC_TRACE
960  xTraceSliceHeader (pcSlice);
961#endif
962
963  const ChromaFormat format                = pcSlice->getSPS()->getChromaFormatIdc();
964  const UInt         numberValidComponents = getNumberValidComponents(format);
965  const Bool         chromaEnabled         = isChromaEnabled(format);
966
967  //calculate number of bits required for slice address
968  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumberOfCtusInFrame();
969  Int bitsSliceSegmentAddress = 0;
970  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress))
971  {
972    bitsSliceSegmentAddress++;
973  }
974  const Int ctuTsAddress = pcSlice->getSliceSegmentCurStartCtuTsAddr();
975
976  //write slice address
977  const Int sliceSegmentRsAddress = pcSlice->getPic()->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddress);
978
979  WRITE_FLAG( sliceSegmentRsAddress==0, "first_slice_segment_in_pic_flag" );
980  if ( pcSlice->getRapPicFlag() )
981  {
982    WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
983  }
984  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
985  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentRsAddress!=0) )
986  {
987    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
988  }
989  if(sliceSegmentRsAddress>0)
990  {
991    WRITE_CODE( sliceSegmentRsAddress, bitsSliceSegmentAddress, "slice_segment_address" );
992  }
993  if ( !pcSlice->getDependentSliceSegmentFlag() )
994  {
995#if SVC_EXTENSION
996#if POC_RESET_FLAG
997    Int iBits = 0;
998    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
999    {
1000      WRITE_FLAG( pcSlice->getPocResetFlag(), "poc_reset_flag" );
1001      iBits++;
1002    }
1003    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1004    {
1005      assert(!!"discardable_flag");
1006      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1007      iBits++;
1008    }
1009#if O0149_CROSS_LAYER_BLA_FLAG
1010    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1011    {
1012      assert(!!"cross_layer_bla_flag");
1013      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
1014      iBits++;
1015    }
1016#endif
1017    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1018    {
1019      assert(!!"slice_reserved_undetermined_flag[]");
1020      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1021    }
1022#else
1023#if CROSS_LAYER_BLA_FLAG_FIX
1024    Int iBits = 0;
1025    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
1026#else
1027    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
1028#endif
1029    {
1030      assert(!!"discardable_flag");
1031#if NON_REF_NAL_TYPE_DISCARDABLE
1032      if (pcSlice->getDiscardableFlag())
1033      {
1034        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
1035          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
1036          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
1037          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
1038          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
1039      }
1040#endif
1041      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1042#if CROSS_LAYER_BLA_FLAG_FIX
1043      iBits++;
1044#endif
1045    }
1046#if CROSS_LAYER_BLA_FLAG_FIX
1047    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1048    {
1049      assert(!!"cross_layer_bla_flag");
1050      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
1051      iBits++;
1052    }
1053    for (; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1054#else
1055    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1056#endif
1057    {
1058      assert(!!"slice_reserved_undetermined_flag[]");
1059      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1060    }
1061#endif
1062#else //SVC_EXTENSION
1063    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1064    {
1065      assert(!!"slice_reserved_undetermined_flag[]");
1066      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1067    }
1068#endif //SVC_EXTENSION
1069
1070    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1071
1072    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1073    {
1074      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1075    }
1076
1077#if N0065_LAYER_POC_ALIGNMENT
1078#if O0062_POC_LSB_NOT_PRESENT_FLAG
1079    if( (pcSlice->getLayerId() > 0 && !pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdxInVps(pcSlice->getLayerId())) ) || !pcSlice->getIdrPicFlag())
1080#else
1081    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
1082#endif
1083#else
1084    if( !pcSlice->getIdrPicFlag() )
1085#endif
1086    {
1087#if POC_RESET_FLAG
1088      Int picOrderCntLSB;
1089      if( !pcSlice->getPocResetFlag() )
1090      {
1091        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1092      }
1093      else
1094      {
1095        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1096      }
1097#else
1098#if POC_RESET_IDC_ENCODER
1099      Int picOrderCntLSB;
1100      if( pcSlice->getPocResetIdc() == 2 )  // i.e. the LSB is reset
1101      {
1102        picOrderCntLSB = pcSlice->getPicOrderCntLsb();  // This will be the LSB value w.r.t to the previous POC reset period.
1103      }
1104      else
1105      {
1106        picOrderCntLSB = (pcSlice->getPOC() + (1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1107      }
1108#else
1109      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1110#endif
1111#endif
1112      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
1113
1114#if N0065_LAYER_POC_ALIGNMENT
1115#if SHM_FIX7
1116    }
1117#endif
1118      if( !pcSlice->getIdrPicFlag() )
1119      {
1120#endif
1121      TComReferencePictureSet* rps = pcSlice->getRPS();
1122
1123      // check for bitstream restriction stating that:
1124      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1125      // Ideally this process should not be repeated for each slice in a picture
1126#if SVC_EXTENSION
1127      if( pcSlice->getLayerId() == 0 )
1128#endif
1129      if (pcSlice->isIRAP())
1130      {
1131        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1132        {
1133          assert (!rps->getUsed(picIdx));
1134        }
1135      }
1136
1137      if(pcSlice->getRPSidx() < 0)
1138      {
1139        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1140        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1141      }
1142      else
1143      {
1144        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1145        Int numBits = 0;
1146        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1147        {
1148          numBits++;
1149        }
1150        if (numBits > 0)
1151        {
1152          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );
1153        }
1154      }
1155      if(pcSlice->getSPS()->getLongTermRefsPresent())
1156      {
1157        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1158        Int ltrpInSPS[MAX_NUM_REF_PICS];
1159        Int numLtrpInSPS = 0;
1160        UInt ltrpIndex;
1161        Int counter = 0;
1162        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--)
1163        {
1164          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k)))
1165          {
1166            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1167            numLtrpInSPS++;
1168          }
1169          else
1170          {
1171            counter++;
1172          }
1173        }
1174        numLtrpInSH -= numLtrpInSPS;
1175
1176        Int bitsForLtrpInSPS = 0;
1177        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1178        {
1179          bitsForLtrpInSPS++;
1180        }
1181        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
1182        {
1183          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1184        }
1185        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1186        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1187        // Not sorted here because LT ref indices will be used in setRefPicList()
1188        Int prevDeltaMSB = 0, prevLSB = 0;
1189        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1190        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
1191        {
1192          if (counter < numLtrpInSPS)
1193          {
1194            if (bitsForLtrpInSPS > 0)
1195            {
1196              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
1197            }
1198          }
1199          else
1200          {
1201            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1202            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag");
1203          }
1204          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1205
1206          if(rps->getDeltaPocMSBPresentFlag(i))
1207          {
1208            Bool deltaFlag = false;
1209            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1210            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1211            {
1212              deltaFlag = true;
1213            }
1214            if(deltaFlag)
1215            {
1216              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1217            }
1218            else
1219            {
1220              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1221              assert(differenceInDeltaMSB >= 0);
1222              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1223            }
1224            prevLSB = rps->getPocLSBLT(i);
1225            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1226          }
1227        }
1228      }
1229      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1230      {
1231#if R0226_SLICE_TMVP
1232        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
1233#else
1234        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
1235#endif
1236      }
1237#if N0065_LAYER_POC_ALIGNMENT && !SHM_FIX7
1238      }
1239#endif
1240    }
1241
1242#if SVC_EXTENSION
1243    if((pcSlice->getLayerId() > 0) && !(pcSlice->getVPS()->getIlpSshSignalingEnabledFlag()) && (pcSlice->getNumILRRefIdx() > 0) )
1244    {
1245      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
1246      if( pcSlice->getInterLayerPredEnabledFlag())
1247      {
1248        if(pcSlice->getNumILRRefIdx() > 1)
1249        {
1250          Int numBits = 1;
1251          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
1252          {
1253            numBits++;
1254          }
1255          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
1256          {
1257            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
1258          }       
1259
1260          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
1261          {
1262            for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1263            {
1264              WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
1265            }
1266          }
1267        }
1268      }
1269    }     
1270#if P0312_VERT_PHASE_ADJ
1271    for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1272    {
1273      UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
1274      if( pcSlice->getSPS()->getVertPhasePositionEnableFlag(refLayerIdc) )
1275      {
1276        WRITE_FLAG( pcSlice->getVertPhasePositionFlag(refLayerIdc), "vert_phase_position_flag" );
1277      }
1278    }
1279#endif
1280#endif //SVC_EXTENSION
1281
1282    if(pcSlice->getSPS()->getUseSAO())
1283    {
1284       WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA), "slice_sao_luma_flag" );
1285       if (chromaEnabled) WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA), "slice_sao_chroma_flag" );
1286    }
1287
1288    //check if numrefidxes match the defaults. If not, override
1289
1290    if (!pcSlice->isIntra())
1291    {
1292      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
1293      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
1294      if (overrideFlag)
1295      {
1296        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
1297        if (pcSlice->isInterB())
1298        {
1299          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
1300        }
1301        else
1302        {
1303          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1304        }
1305      }
1306    }
1307    else
1308    {
1309      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
1310      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1311    }
1312
1313    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
1314    {
1315      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1316      if(!pcSlice->isIntra())
1317      {
1318        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
1319        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
1320        {
1321          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
1322          if (numRpsCurrTempList0 > 1)
1323          {
1324            Int length = 1;
1325            numRpsCurrTempList0 --;
1326            while ( numRpsCurrTempList0 >>= 1)
1327            {
1328              length ++;
1329            }
1330            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
1331            {
1332              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
1333            }
1334          }
1335        }
1336      }
1337      if(pcSlice->isInterB())
1338      {
1339        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
1340        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
1341        {
1342          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
1343          if ( numRpsCurrTempList1 > 1 )
1344          {
1345            Int length = 1;
1346            numRpsCurrTempList1 --;
1347            while ( numRpsCurrTempList1 >>= 1)
1348            {
1349              length ++;
1350            }
1351            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
1352            {
1353              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
1354            }
1355          }
1356        }
1357      }
1358    }
1359
1360    if (pcSlice->isInterB())
1361    {
1362      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
1363    }
1364
1365    if(!pcSlice->isIntra())
1366    {
1367      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1368      {
1369        SliceType sliceType   = pcSlice->getSliceType();
1370        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
1371        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1372        pcSlice->setCabacInitFlag( encCabacInitFlag );
1373        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1374      }
1375    }
1376
1377    if ( pcSlice->getEnableTMVPFlag() )
1378    {
1379      if ( pcSlice->getSliceType() == B_SLICE )
1380      {
1381        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1382      }
1383
1384      if ( pcSlice->getSliceType() != I_SLICE &&
1385        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1386        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1387      {
1388        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1389      }
1390    }
1391    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1392    {
1393      xCodePredWeightTable( pcSlice );
1394    }
1395    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1396    if (!pcSlice->isIntra())
1397    {
1398      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1399    }
1400    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1401    WRITE_SVLC( iCode, "slice_qp_delta" );
1402    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1403    {
1404      if (numberValidComponents > COMPONENT_Cb) { WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb), "slice_qp_delta_cb" ); }
1405      if (numberValidComponents > COMPONENT_Cr) { WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr), "slice_qp_delta_cr" ); }
1406      assert(numberValidComponents <= COMPONENT_Cr+1);
1407    }
1408
1409    if (pcSlice->getPPS()->getChromaQpAdjTableSize() > 0)
1410    {
1411      WRITE_FLAG(pcSlice->getUseChromaQpAdj(), "slice_chroma_qp_adjustment_enabled_flag");
1412    }
1413
1414    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1415    {
1416      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1417      {
1418        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1419      }
1420      if (pcSlice->getDeblockingFilterOverrideFlag())
1421      {
1422        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1423        if(!pcSlice->getDeblockingFilterDisable())
1424        {
1425          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
1426          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
1427        }
1428      }
1429    }
1430
1431    Bool isSAOEnabled = pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (chromaEnabled && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
1432    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1433
1434    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1435    {
1436      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1437    }
1438  }
1439
1440#if !POC_RESET_IDC_SIGNALLING   // Wrong place to put slice header extension
1441  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1442  {
1443    WRITE_UVLC(0,"slice_header_extension_length");
1444  }
1445#endif
1446}
1447
1448Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1449{
1450  if(profilePresentFlag)
1451  {
1452    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1453  }
1454  WRITE_CODE( Int(pcPTL->getGeneralPTL()->getLevelIdc()), 8, "general_level_idc" );
1455
1456  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
1457  {
1458#if MULTIPLE_PTL_SUPPORT
1459    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1460#else
1461    if(profilePresentFlag)
1462    {
1463      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1464    }
1465#endif
1466
1467    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1468  }
1469
1470  if (maxNumSubLayersMinus1 > 0)
1471  {
1472    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
1473    {
1474      WRITE_CODE(0, 2, "reserved_zero_2bits");
1475    }
1476  }
1477
1478  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1479  {
1480#if MULTIPLE_PTL_SUPPORT
1481    if( pcPTL->getSubLayerProfilePresentFlag(i) )
1482#else
1483    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1484#endif
1485    {
1486      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1487    }
1488    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1489    {
1490      WRITE_CODE( Int(pcPTL->getSubLayerPTL(i)->getLevelIdc()), 8, "sub_layer_level_idc[i]" );
1491    }
1492  }
1493}
1494Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1495{
1496  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1497  WRITE_FLAG( ptl->getTierFlag()==Level::HIGH, "XXX_tier_flag[]"    );
1498#if MULTIPLE_PTL_SUPPORT
1499  WRITE_CODE( (ptl->getProfileIdc() == Profile::SCALABLEMAIN || ptl->getProfileIdc() == Profile::SCALABLEMAIN10) ? 7 : Int(ptl->getProfileIdc()), 5 ,  "XXX_profile_idc[]"  );
1500#else
1501  WRITE_CODE( Int(ptl->getProfileIdc()), 5 ,  "XXX_profile_idc[]"  );
1502#endif
1503  for(Int j = 0; j < 32; j++)
1504  {
1505    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");
1506  }
1507
1508  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
1509  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
1510  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
1511  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
1512
1513  if (ptl->getProfileIdc() == Profile::MAINREXT || ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT )
1514  {
1515    const UInt         bitDepthConstraint=ptl->getBitDepthConstraint();
1516    WRITE_FLAG(bitDepthConstraint<=12, "general_max_12bit_constraint_flag");
1517    WRITE_FLAG(bitDepthConstraint<=10, "general_max_10bit_constraint_flag");
1518    WRITE_FLAG(bitDepthConstraint<= 8, "general_max_8bit_constraint_flag");
1519    const ChromaFormat chromaFmtConstraint=ptl->getChromaFormatConstraint();
1520    WRITE_FLAG(chromaFmtConstraint==CHROMA_422||chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400, "general_max_422chroma_constraint_flag");
1521    WRITE_FLAG(chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400,                                  "general_max_420chroma_constraint_flag");
1522    WRITE_FLAG(chromaFmtConstraint==CHROMA_400,                                                                   "general_max_monochrome_constraint_flag");
1523    WRITE_FLAG(ptl->getIntraConstraintFlag(),        "general_intra_constraint_flag");
1524    WRITE_FLAG(0,                                    "general_one_picture_only_constraint_flag");
1525    WRITE_FLAG(ptl->getLowerBitRateConstraintFlag(), "general_lower_bit_rate_constraint_flag");
1526#if MULTIPLE_PTL_SUPPORT
1527    WRITE_CODE(0, 32,  "general_reserved_zero_34bits");  WRITE_CODE(0, 2,  "general_reserved_zero_34bits");
1528  }
1529  else if( ptl->getProfileIdc() == Profile::SCALABLEMAIN || ptl->getProfileIdc() == Profile::SCALABLEMAIN10 )      // at encoder side, scalable-main10 profile has a profile idc equal to 8, which is converted to 7 during signalling
1530  {
1531    WRITE_FLAG(true,   "general_max_12bit_constraint_flag");
1532    WRITE_FLAG(true,   "general_max_10bit_constraint_flag");
1533    WRITE_FLAG((ptl->getProfileIdc() == Profile::SCALABLEMAIN) ? true : false, "general_max_8bit_constraint_flag");
1534    WRITE_FLAG(true,   "general_max_422chroma_constraint_flag");
1535    WRITE_FLAG(true,   "general_max_420chroma_constraint_flag");
1536    WRITE_FLAG(false,  "general_max_monochrome_constraint_flag");
1537    WRITE_FLAG(false,  "general_intra_constraint_flag");
1538    WRITE_FLAG(false,  "general_one_picture_only_constraint_flag");
1539    WRITE_FLAG(true,   "general_lower_bit_rate_constraint_flag");
1540    WRITE_CODE(0, 32,  "general_reserved_zero_34bits");  WRITE_CODE(0, 2,  "general_reserved_zero_34bits");
1541  }
1542  else
1543  {
1544    WRITE_CODE(0, 32,  "general_reserved_zero_43bits");  WRITE_CODE(0, 11,  "general_reserved_zero_43bits");
1545  }
1546
1547  if( ( ptl->getProfileIdc() >= 1 && ptl->getProfileIdc() <= 5 ) || 
1548      ptl->getProfileCompatibilityFlag(1) || ptl->getProfileCompatibilityFlag(2) || 
1549      ptl->getProfileCompatibilityFlag(3) || ptl->getProfileCompatibilityFlag(4) || 
1550      ptl->getProfileCompatibilityFlag(5)                                           )
1551  {
1552    WRITE_FLAG(false, "general_inbld_flag");
1553  }
1554  else
1555  {
1556    WRITE_FLAG(false, "general_reserved_zero_bit");
1557  }
1558#else
1559    WRITE_CODE(0 , 16, "XXX_reserved_zero_35bits[0..15]");
1560    WRITE_CODE(0 , 16, "XXX_reserved_zero_35bits[16..31]");
1561    WRITE_CODE(0 ,  3, "XXX_reserved_zero_35bits[32..34]");
1562  }
1563  else
1564  {
1565    WRITE_CODE(0x0000 , 16, "XXX_reserved_zero_44bits[0..15]");
1566    WRITE_CODE(0x0000 , 16, "XXX_reserved_zero_44bits[16..31]");
1567    WRITE_CODE(0x000  , 12, "XXX_reserved_zero_44bits[32..43]");
1568  }
1569#endif
1570}
1571
1572/**
1573 - write tiles and wavefront substreams sizes for the slice header.
1574 .
1575 \param pcSlice Where we find the substream size information.
1576 */
1577Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1578{
1579  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1580  {
1581    return;
1582  }
1583  UInt maxOffset = 0;
1584  for(Int idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
1585  {
1586    UInt offset=pSlice->getSubstreamSize(idx);
1587    if ( offset > maxOffset )
1588    {
1589      maxOffset = offset;
1590    }
1591  }
1592
1593  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1594  UInt offsetLenMinus1 = 0;
1595  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1596  {
1597    offsetLenMinus1++;
1598    assert(offsetLenMinus1 + 1 < 32);
1599  }
1600
1601  WRITE_UVLC(pSlice->getNumberOfSubstreamSizes(), "num_entry_point_offsets");
1602  if (pSlice->getNumberOfSubstreamSizes()>0)
1603  {
1604    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1605
1606    for (UInt idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
1607    {
1608      WRITE_CODE(pSlice->getSubstreamSize(idx)-1, offsetLenMinus1+1, "entry_point_offset_minus1");
1609    }
1610  }
1611}
1612
1613Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1614{
1615}
1616
1617Void TEncCavlc::codeSliceFinish ()
1618{
1619}
1620
1621Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1622{
1623  assert(0);
1624}
1625
1626Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1627{
1628  assert(0);
1629}
1630
1631Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1632{
1633  assert(0);
1634}
1635
1636Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1637{
1638  assert(0);
1639}
1640
1641Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1642{
1643  assert(0);
1644}
1645
1646Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1647{
1648  assert(0);
1649}
1650
1651Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1652{
1653  assert(0);
1654}
1655
1656Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1657{
1658  assert(0);
1659}
1660
1661Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1662{
1663  assert(0);
1664}
1665
1666Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1667{
1668  assert(0);
1669}
1670
1671Void TEncCavlc::codeQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
1672{
1673  assert(0);
1674}
1675
1676Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1677{
1678  assert(0);
1679}
1680
1681Void TEncCavlc::codeQtCbfZero( TComTU &rTu, const ChannelType chType )
1682{
1683  assert(0);
1684}
1685Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
1686{
1687  assert(0);
1688}
1689
1690Void TEncCavlc::codeTransformSkipFlags (TComTU &rTu, ComponentID component )
1691{
1692  assert(0);
1693}
1694
1695/** Code I_PCM information.
1696 * \param pcCU pointer to CU
1697 * \param uiAbsPartIdx CU index
1698 * \returns Void
1699 */
1700Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
1701{
1702  assert(0);
1703}
1704
1705Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1706{
1707  assert(0);
1708}
1709
1710Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
1711{
1712  assert(0);
1713}
1714
1715Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
1716{
1717  assert(0);
1718}
1719
1720Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1721{
1722  assert(0);
1723}
1724
1725Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1726{
1727  assert(0);
1728}
1729
1730Void TEncCavlc::codeCrossComponentPrediction( TComTU& /*rTu*/, ComponentID /*compID*/ )
1731{
1732  assert(0);
1733}
1734
1735Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
1736{
1737  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
1738
1739#if REPN_FORMAT_IN_VPS
1740  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
1741#else
1742  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
1743#endif
1744  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
1745
1746  xWriteSvlc( iDQp );
1747
1748  return;
1749}
1750
1751Void TEncCavlc::codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx )
1752{
1753  assert(0);
1754}
1755
1756Void TEncCavlc::codeCoeffNxN    ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID )
1757{
1758  assert(0);
1759}
1760
1761Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, ChannelType chType )
1762{
1763  // printf("error : no VLC mode support in this version\n");
1764  return;
1765}
1766
1767// ====================================================================================================================
1768// Protected member functions
1769// ====================================================================================================================
1770
1771/** code explicit wp tables
1772 * \param TComSlice* pcSlice
1773 * \returns Void
1774 */
1775Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
1776{
1777  WPScalingParam  *wp;
1778  const ChromaFormat    format                = pcSlice->getPic()->getChromaFormat();
1779  const UInt            numberValidComponents = getNumberValidComponents(format);
1780  const Bool            bChroma               = isChromaEnabled(format);
1781  const Int             iNbRef                = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
1782        Bool            bDenomCoded           = false;
1783        UInt            uiMode                = 0;
1784        UInt            uiTotalSignalledWeightFlags = 0;
1785
1786  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
1787  {
1788    uiMode = 1; // explicit
1789  }
1790  if(uiMode == 1)
1791  {
1792    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ )
1793    {
1794      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1795
1796      // NOTE: wp[].uiLog2WeightDenom and wp[].bPresentFlag are actually per-channel-type settings.
1797
1798      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
1799      {
1800        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1801        if ( !bDenomCoded )
1802        {
1803          Int iDeltaDenom;
1804          WRITE_UVLC( wp[COMPONENT_Y].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
1805
1806          if( bChroma )
1807          {
1808            assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom); // check the channel-type settings are consistent across components.
1809            iDeltaDenom = (wp[COMPONENT_Cb].uiLog2WeightDenom - wp[COMPONENT_Y].uiLog2WeightDenom);
1810            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
1811          }
1812          bDenomCoded = true;
1813        }
1814        WRITE_FLAG( wp[COMPONENT_Y].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
1815        uiTotalSignalledWeightFlags += wp[COMPONENT_Y].bPresentFlag;
1816      }
1817      if (bChroma)
1818      {
1819        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
1820        {
1821          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1822          assert(wp[COMPONENT_Cb].bPresentFlag == wp[COMPONENT_Cr].bPresentFlag); // check the channel-type settings are consistent across components.
1823          WRITE_FLAG( wp[COMPONENT_Cb].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1824          uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
1825        }
1826      }
1827
1828      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
1829      {
1830        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1831        if ( wp[COMPONENT_Y].bPresentFlag )
1832        {
1833          Int iDeltaWeight = (wp[COMPONENT_Y].iWeight - (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
1834          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                            // se(v): delta_luma_weight_lX
1835          WRITE_SVLC( wp[COMPONENT_Y].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
1836        }
1837
1838        if ( bChroma )
1839        {
1840          if ( wp[COMPONENT_Cb].bPresentFlag )
1841          {
1842            for ( Int j = COMPONENT_Cb ; j < numberValidComponents ; j++ )
1843            {
1844              assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom);
1845              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[COMPONENT_Cb].uiLog2WeightDenom));
1846              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
1847
1848              Int range=pcSlice->getSPS()->getUseHighPrecisionPredictionWeighting() ? (1<<g_bitDepth[CHANNEL_TYPE_CHROMA])/2 : 128;
1849              Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
1850              Int iDeltaChroma = (wp[j].iOffset - pred);
1851              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
1852            }
1853          }
1854        }
1855      }
1856    }
1857    assert(uiTotalSignalledWeightFlags<=24);
1858  }
1859}
1860
1861/** code quantization matrix
1862 *  \param scalingList quantization matrix information
1863 */
1864Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
1865{
1866  UInt listId,sizeId;
1867  Bool scalingListPredModeFlag;
1868
1869  //for each size
1870  for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
1871  {
1872    Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
1873
1874    for(listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
1875    {
1876      scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
1877      WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
1878      if(!scalingListPredModeFlag)// Copy Mode
1879      {
1880        if (sizeId == SCALING_LIST_32x32)
1881        {
1882          // adjust the code, to cope with the missing chroma entries
1883          WRITE_UVLC( ((Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId)) / (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES), "scaling_list_pred_matrix_id_delta");
1884        }
1885        else
1886        {
1887          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
1888        }
1889      }
1890      else// DPCM Mode
1891      {
1892        xCodeScalingList(scalingList, sizeId, listId);
1893      }
1894    }
1895  }
1896  return;
1897}
1898/** code DPCM
1899 * \param scalingList quantization matrix information
1900 * \param sizeIdc size index
1901 * \param listIdc list index
1902 */
1903Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
1904{
1905  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
1906  UInt* scan  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
1907  Int nextCoef = SCALING_LIST_START_VALUE;
1908  Int data;
1909  Int *src = scalingList->getScalingListAddress(sizeId, listId);
1910    if( sizeId > SCALING_LIST_8x8 )
1911    {
1912      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
1913      nextCoef = scalingList->getScalingListDC(sizeId,listId);
1914    }
1915    for(Int i=0;i<coefNum;i++)
1916    {
1917      data = src[scan[i]] - nextCoef;
1918      nextCoef = src[scan[i]];
1919      if(data > 127)
1920      {
1921        data = data - 256;
1922      }
1923      if(data < -128)
1924      {
1925        data = data + 256;
1926      }
1927
1928      WRITE_SVLC( data,  "scaling_list_delta_coef");
1929    }
1930}
1931Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
1932{
1933  // Bool state = true, state2 = false;
1934  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1935  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
1936  {
1937    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
1938    {
1939      *ltrpsIndex = k;
1940      return true;
1941    }
1942  }
1943  return false;
1944}
1945Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
1946{
1947  Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
1948
1949  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx-=predListStep)
1950  {
1951    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
1952      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
1953     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
1954    {
1955      setRefMatrixId(sizeId, listId, predListIdx);
1956      return false;
1957    }
1958  }
1959  return true;
1960}
1961
1962Void TEncCavlc::codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID )
1963 {
1964   assert(0);
1965 }
1966
1967#if SVC_EXTENSION
1968
1969#if POC_RESET_IDC_SIGNALLING
1970Void  TEncCavlc::codeSliceHeaderExtn( TComSlice* slice, Int shBitsWrittenTillNow )
1971{
1972  Int tmpBitsBeforeWriting = getNumberOfWrittenBits();
1973  Int maxPocLsb = 1 << slice->getSPS()->getBitsForPOC();
1974  if(slice->getPPS()->getSliceHeaderExtensionPresentFlag())
1975  {
1976    // Derive the value of PocMsbValRequiredFlag
1977#if P0297_VPS_POC_LSB_ALIGNED_FLAG
1978    slice->setPocMsbValRequiredFlag( (slice->getCraPicFlag() || slice->getBlaPicFlag())
1979                                  && (!slice->getVPS()->getVpsPocLsbAlignedFlag() ||
1980                                      (slice->getVPS()->getVpsPocLsbAlignedFlag() && slice->getVPS()->getNumDirectRefLayers(slice->getLayerId()) == 0))
1981                                   );
1982#else
1983    slice->setPocMsbValRequiredFlag( slice->getCraPicFlag() || slice->getBlaPicFlag() );
1984#endif
1985
1986    // Determine value of SH extension length.
1987    Int shExtnLengthInBit = 0;
1988    if (slice->getPPS()->getPocResetInfoPresentFlag())
1989    {
1990      shExtnLengthInBit += 2;
1991    }
1992    if (slice->getPocResetIdc() > 0)
1993    {
1994      shExtnLengthInBit += 6;
1995    }
1996    if (slice->getPocResetIdc() == 3)
1997    {
1998      shExtnLengthInBit += (slice->getSPS()->getBitsForPOC() + 1);
1999    }
2000
2001
2002#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2003    if (!slice->getPocMsbValRequiredFlag() && slice->getVPS()->getVpsPocLsbAlignedFlag())
2004#else
2005    if (!slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */)
2006#endif
2007    {
2008      shExtnLengthInBit++;
2009    }
2010    else
2011    {
2012      if( slice->getPocMsbValRequiredFlag() )
2013      {
2014        slice->setPocMsbValPresentFlag( true );
2015      }
2016      else
2017      {
2018        slice->setPocMsbValPresentFlag( false );
2019      }
2020    }
2021
2022#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2023    if (slice->getPocMsbNeeded())
2024    {
2025      slice->setPocMsbValPresentFlag(true);
2026    }
2027#endif
2028
2029    if (slice->getPocMsbValPresentFlag())
2030    {
2031      UInt lengthVal = 1;
2032      UInt tempVal = (slice->getPocMsbVal() / maxPocLsb) + 1;
2033      assert ( tempVal );
2034      while( 1 != tempVal )
2035      {
2036        tempVal >>= 1;
2037        lengthVal += 2;
2038      }
2039      shExtnLengthInBit += lengthVal;
2040    }
2041    Int shExtnAdditionalBits = 0;
2042    if(shExtnLengthInBit % 8 != 0)
2043    {
2044      shExtnAdditionalBits = 8 - (shExtnLengthInBit % 8);
2045    }
2046    Int shExtnLength = (shExtnLengthInBit + shExtnAdditionalBits) / 8;
2047    WRITE_UVLC( shExtnLength, "slice_header_extension_length" );
2048
2049    if(slice->getPPS()->getPocResetInfoPresentFlag())
2050    {
2051      WRITE_CODE( slice->getPocResetIdc(), 2,                                 "poc_reset_idc");
2052    }
2053    if(slice->getPocResetIdc() > 0)
2054    {
2055      WRITE_CODE( slice->getPocResetPeriodId(), 6,                            "poc_reset_period_id");
2056    }
2057    if(slice->getPocResetIdc() == 3) 
2058    {
2059      WRITE_FLAG( slice->getFullPocResetFlag() ? 1 : 0,                       "full_poc_reset_flag");
2060      WRITE_CODE( slice->getPocLsbVal(), slice->getSPS()->getBitsForPOC(),  "poc_lsb_val");
2061    }
2062
2063#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2064    if (!slice->getPocMsbValRequiredFlag() && slice->getVPS()->getVpsPocLsbAlignedFlag())
2065#else
2066    if (!slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */)
2067#endif
2068    {
2069#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2070      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_cycle_val_present_flag" );
2071#else
2072      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_val_present_flag" );
2073#endif
2074    }
2075    if (slice->getPocMsbValPresentFlag())
2076    {
2077      assert(slice->getPocMsbVal() % maxPocLsb == 0);
2078#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2079      WRITE_UVLC(slice->getPocMsbVal() / maxPocLsb, "poc_msb_cycle_val");
2080#else
2081      WRITE_UVLC(slice->getPocMsbVal() / maxPocLsb, "poc_msb_val");
2082#endif
2083    }
2084    for (Int i = 0; i < shExtnAdditionalBits; i++)
2085    {
2086#if Q0146_SSH_EXT_DATA_BIT
2087      WRITE_FLAG( 1, "slice_segment_header_extension_data_bit");
2088#else
2089      WRITE_FLAG( 1, "slice_segment_header_extension_reserved_bit");
2090#endif
2091    }
2092  }
2093  shBitsWrittenTillNow += ( getNumberOfWrittenBits() - tmpBitsBeforeWriting );
2094 
2095  // Slice header byte_alignment() included in xAttachSliceDataToNalUnit
2096}
2097#endif
2098
2099Void TEncCavlc::codeVPSExtension (TComVPS *vps)
2100{
2101  // ... More syntax elements to be written here
2102#if P0300_ALT_OUTPUT_LAYER_FLAG
2103  Int NumOutputLayersInOutputLayerSet[MAX_VPS_LAYER_SETS_PLUS1];
2104  Int OlsHighestOutputLayerId[MAX_VPS_LAYER_SETS_PLUS1];
2105#endif
2106#if LIST_OF_PTL
2107  if( vps->getMaxLayers() > 1 && vps->getBaseLayerInternalFlag() )
2108  {
2109#if MULTIPLE_PTL_SUPPORT
2110    codePTL( vps->getPTL(1), false, vps->getMaxTLayers() - 1 );
2111#else
2112    codePTL( vps->getPTLForExtn(1), false, vps->getMaxTLayers() - 1 );
2113#endif
2114  }
2115#endif
2116#if VPS_EXTN_MASK_AND_DIM_INFO
2117  UInt i = 0, j = 0;
2118#if !VPS_AVC_BL_FLAG_REMOVAL
2119  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
2120#endif
2121#if !P0307_REMOVE_VPS_VUI_OFFSET
2122#if O0109_MOVE_VPS_VUI_FLAG
2123  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
2124  vps->setVpsVuiPresentFlag(true);
2125  if ( vps->getVpsVuiPresentFlag() ) 
2126  {
2127#if VPS_VUI_OFFSET
2128    WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" );
2129#endif
2130    WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
2131  }
2132#else
2133#if VPS_VUI_OFFSET
2134  WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" ); 
2135#endif
2136  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
2137#endif // O0109_MOVE_VPS_VUI_FLAG
2138#endif
2139  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
2140
2141  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
2142  {
2143    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
2144  }
2145
2146  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
2147  {
2148    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
2149  }
2150
2151  // The value of dimBitOffset[ NumScalabilityTypes ] is set equal to 6.
2152  if(vps->getSplittingFlag())
2153  {
2154    UInt splDimSum=0;
2155    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
2156    {
2157      splDimSum+=(vps->getDimensionIdLen(j));
2158    }
2159    assert(splDimSum<=6);
2160  }
2161
2162  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
2163  for(i = 1; i < vps->getMaxLayers(); i++)
2164  {
2165    if( vps->getNuhLayerIdPresentFlag() )
2166    {
2167      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
2168    }
2169
2170    if( !vps->getSplittingFlag() )
2171    {
2172    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
2173    {
2174      UInt bits = vps->getDimensionIdLen(j);
2175      WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
2176    }
2177  }
2178  }
2179#endif
2180#if VIEW_ID_RELATED_SIGNALING
2181  // if ( pcVPS->getNumViews() > 1 ) 
2182  //   However, this is a bug in the text since, view_id_len_minus1 is needed to parse view_id_val.
2183  {
2184#if O0109_VIEW_ID_LEN
2185    WRITE_CODE( vps->getViewIdLen( ), 4, "view_id_len" );
2186    assert ( vps->getNumViews() >= (1<<vps->getViewIdLen()) );
2187#else
2188    WRITE_CODE( vps->getViewIdLenMinus1( ), 4, "view_id_len_minus1" );
2189#endif
2190  }
2191
2192#if O0109_VIEW_ID_LEN
2193  if ( vps->getViewIdLen() > 0 )
2194  {
2195#endif
2196  for(  i = 0; i < vps->getNumViews(); i++ )
2197  {
2198#if O0109_VIEW_ID_LEN
2199    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLen( ), "view_id_val[i]" );
2200#else
2201    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLenMinus1( ) + 1, "view_id_val[i]" );
2202#endif
2203  }
2204#if O0109_VIEW_ID_LEN
2205  }
2206#endif
2207#endif // VIEW_ID_RELATED_SIGNALING
2208
2209#if VPS_EXTN_DIRECT_REF_LAYERS
2210  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
2211  {
2212    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
2213    {
2214      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
2215    }
2216  }
2217#endif
2218#if MOVE_ADDN_LS_SIGNALLING
2219#if Q0078_ADD_LAYER_SETS
2220  if (vps->getNumIndependentLayers() > 1)
2221  {
2222    WRITE_UVLC( vps->getNumAddLayerSets(), "num_add_layer_sets" );
2223    for (i = 0; i < vps->getNumAddLayerSets(); i++)
2224    {
2225      for (j = 1; j < vps->getNumIndependentLayers(); j++)
2226      {
2227        int len = 1;
2228        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
2229        {
2230          len++;
2231        }
2232        WRITE_CODE(vps->getHighestLayerIdxPlus1(i, j), len, "highest_layer_idx_plus1[i][j]");
2233      }
2234    }
2235  }
2236#endif
2237#endif
2238#if VPS_TSLAYERS
2239    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
2240    if (vps->getMaxTSLayersPresentFlag())
2241    {
2242        for( i = 0; i < vps->getMaxLayers(); i++)
2243        {
2244            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
2245        }
2246    }
2247#endif
2248   WRITE_FLAG( vps->getMaxTidRefPresentFlag(), "max_tid_ref_present_flag");
2249   if (vps->getMaxTidRefPresentFlag())
2250   {
2251     for( i = 0; i < vps->getMaxLayers() - 1; i++)
2252     {
2253#if O0225_MAX_TID_FOR_REF_LAYERS
2254       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
2255       {
2256         if(vps->getDirectDependencyFlag(j, i))
2257         {
2258           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
2259         }
2260       }
2261#else
2262       WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
2263#endif
2264     }
2265   }
2266   WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
2267#if VPS_EXTN_PROFILE_INFO
2268  // Profile-tier-level signalling
2269#if !VPS_EXTN_UEV_CODING
2270  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
2271  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
2272#else
2273  WRITE_UVLC( vps->getNumProfileTierLevel() - 1, "vps_num_profile_tier_level_minus1"); 
2274#if PER_LAYER_PTL
2275  Int const numBitsForPtlIdx = vps->calculateLenOfSyntaxElement( vps->getNumProfileTierLevel() );
2276#endif
2277#endif
2278#if LIST_OF_PTL
2279#if MULTIPLE_PTL_SUPPORT
2280  //Do something here to make sure the loop is correct to consider base layer internal stuff
2281#else
2282  assert( vps->getNumProfileTierLevel() == vps->getPTLForExtnPtr()->size());
2283#endif
2284  for(Int idx = vps->getBaseLayerInternalFlag() ? 2 : 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
2285#else
2286  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
2287#endif
2288  {
2289#if MULTIPLE_PTL_SUPPORT
2290    vps->setProfilePresentFlag(idx, true);
2291#endif
2292    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
2293#if !P0048_REMOVE_PROFILE_REF
2294    if( !vps->getProfilePresentFlag(idx) )
2295    {
2296      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
2297    }
2298#endif
2299#if MULTIPLE_PTL_SUPPORT
2300    codePTL( vps->getPTL(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
2301#else
2302    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
2303#endif
2304  }
2305#endif
2306
2307
2308#if !MOVE_ADDN_LS_SIGNALLING
2309#if Q0078_ADD_LAYER_SETS
2310  if (vps->getNumIndependentLayers() > 1)
2311  {
2312    WRITE_UVLC( vps->getNumAddLayerSets(), "num_add_layer_sets" );
2313    for (i = 0; i < vps->getNumAddLayerSets(); i++)
2314    {
2315      for (j = 1; j < vps->getNumIndependentLayers(); j++)
2316      {
2317        int len = 1;
2318        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
2319        {
2320          len++;
2321        }
2322        WRITE_CODE(vps->getHighestLayerIdxPlus1(i, j), len, "highest_layer_idx_plus1[i][j]");
2323      }
2324    }
2325  }
2326#endif
2327#endif
2328
2329#if !VPS_EXTN_UEV_CODING
2330  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
2331  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
2332  if(numOutputLayerSets > vps->getNumLayerSets())
2333  {
2334    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
2335  }
2336#else
2337  Int numOutputLayerSets = vps->getNumOutputLayerSets();
2338  Int numAddOutputLayerSets = numOutputLayerSets - (Int)vps->getNumLayerSets();
2339
2340  // The value of num_add_olss shall be in the range of 0 to 1023, inclusive.
2341  assert( numAddOutputLayerSets >= 0 && numAddOutputLayerSets < 1024 );
2342
2343#if Q0165_NUM_ADD_OUTPUT_LAYER_SETS
2344  if( vps->getNumLayerSets() > 1 )
2345  {
2346    WRITE_UVLC( numAddOutputLayerSets, "num_add_olss" );
2347    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_output_layer_idc" );
2348  }
2349#else
2350  WRITE_UVLC( numOutputLayerSets - vps->getNumLayerSets(), "num_add_output_layer_sets" );
2351#endif
2352#endif
2353
2354#if !Q0165_NUM_ADD_OUTPUT_LAYER_SETS
2355  if( numOutputLayerSets > 1 )
2356  {
2357#if P0295_DEFAULT_OUT_LAYER_IDC
2358    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_target_output_layer_idc" );   
2359#else
2360#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
2361    WRITE_CODE( vps->getDefaultOneTargetOutputLayerIdc(), 2, "default_one_target_output_layer_idc" );   
2362#else
2363    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
2364#endif
2365#endif
2366  }
2367#endif
2368
2369  for(i = 1; i < numOutputLayerSets; i++)
2370  {
2371    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx(i);
2372#if VPS_FIX_TO_MATCH_SPEC
2373    if( vps->getNumLayerSets() > 2 && i >= vps->getNumLayerSets() )
2374#else
2375    if( i > (vps->getNumLayerSets() - 1) )
2376#endif
2377    {
2378      Int numBits = 1;
2379      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
2380      {
2381        numBits++;
2382      }
2383      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "layer_set_idx_for_ols_minus1"); 
2384#if P0295_DEFAULT_OUT_LAYER_IDC
2385    }
2386#if Q0078_ADD_LAYER_SETS
2387    if ( i > vps->getVpsNumLayerSetsMinus1() || vps->getDefaultTargetOutputLayerIdc() >= 2 ) //Instead of == 2, >= 2 is used to follow the agreement that value 3 should be interpreted as 2
2388#else
2389    if ( i > (vps->getNumLayerSets() - 1) || vps->getDefaultTargetOutputLayerIdc() >= 2 ) //Instead of == 2, >= 2 is used to follow the agreement that value 3 should be interpreted as 2
2390#endif
2391    {
2392#endif
2393#if NUM_OL_FLAGS
2394      for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
2395#else
2396      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
2397#endif
2398      {
2399        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
2400      }
2401    }
2402#if PER_LAYER_PTL
2403    for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
2404    {
2405#if VPS_FIX_TO_MATCH_SPEC
2406      if( vps->getNecessaryLayerFlag(i, j) && (vps->getNumProfileTierLevel() - 1) > 0 )
2407#else
2408      if( vps->getNecessaryLayerFlag(i, j) )
2409#endif
2410      {
2411        WRITE_CODE( vps->getProfileLevelTierIdx(i, j), numBitsForPtlIdx, "profile_level_tier_idx[i]" );
2412      }
2413    }
2414#else
2415    Int numBits = 1;
2416    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
2417    {
2418      numBits++;
2419    }
2420    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
2421#endif
2422#if P0300_ALT_OUTPUT_LAYER_FLAG
2423    NumOutputLayersInOutputLayerSet[i] = 0;
2424    for (j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
2425    {
2426      NumOutputLayersInOutputLayerSet[i] += vps->getOutputLayerFlag(i, j);
2427      if (vps->getOutputLayerFlag(i, j))
2428      {
2429        OlsHighestOutputLayerId[i] = vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j);
2430      }
2431    }
2432    if (NumOutputLayersInOutputLayerSet[i] == 1 && vps->getNumDirectRefLayers(OlsHighestOutputLayerId[i]) > 0)
2433    {
2434      WRITE_FLAG(vps->getAltOuputLayerFlag(i), "alt_output_layer_flag[i]");
2435    }
2436
2437#if Q0165_OUTPUT_LAYER_SET
2438    assert( NumOutputLayersInOutputLayerSet[i]>0 );
2439#endif
2440
2441#endif
2442  }
2443
2444#if !P0300_ALT_OUTPUT_LAYER_FLAG
2445#if O0153_ALT_OUTPUT_LAYER_FLAG
2446  if( vps->getMaxLayers() > 1 )
2447  {
2448    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
2449  }
2450#endif
2451#endif
2452
2453#if REPN_FORMAT_IN_VPS
2454#if Q0195_REP_FORMAT_CLEANUP 
2455  // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
2456  assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
2457 
2458  WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
2459
2460  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
2461  {
2462    // Write rep_format_structures
2463    codeRepFormat( vps->getVpsRepFormat(i) );
2464  }
2465
2466  if( vps->getVpsNumRepFormats() > 1 )
2467  {
2468    WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
2469  }
2470  else
2471  {
2472    // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
2473    assert( !vps->getRepFormatIdxPresentFlag() );
2474  }
2475
2476  if( vps->getRepFormatIdxPresentFlag() )
2477  {
2478#if VPS_FIX_TO_MATCH_SPEC
2479    for( i = vps->getBaseLayerInternalFlag() ? 1 : 0; i < vps->getMaxLayers(); i++ )
2480#else
2481    for(i = 1; i < vps->getMaxLayers(); i++)
2482#endif
2483    {
2484      Int numBits = 1;
2485      while ((1 << numBits) < (vps->getVpsNumRepFormats()))
2486      {
2487        numBits++;
2488      }
2489      WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
2490    }
2491  }
2492#else
2493  WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
2494
2495  if( vps->getRepFormatIdxPresentFlag() )
2496  {
2497    // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
2498    assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
2499
2500#if O0096_REP_FORMAT_INDEX
2501#if !VPS_EXTN_UEV_CODING
2502    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
2503#else
2504    WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
2505#endif
2506#else
2507    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
2508#endif
2509  }
2510  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
2511  {
2512    // Read rep_format_structures
2513    codeRepFormat( vps->getVpsRepFormat(i) );
2514  }
2515 
2516  if( vps->getRepFormatIdxPresentFlag() )
2517  {
2518    for(i = 1; i < vps->getMaxLayers(); i++)
2519    {
2520      if( vps->getVpsNumRepFormats() > 1 )
2521      {
2522#if O0096_REP_FORMAT_INDEX
2523#if !VPS_EXTN_UEV_CODING
2524        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
2525#else
2526        Int numBits = 1;
2527        while ((1 << numBits) < (vps->getVpsNumRepFormats()))
2528        {
2529          numBits++;
2530        }
2531        WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
2532#endif
2533#else
2534        WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
2535#endif
2536      }
2537    }
2538  }
2539#endif
2540#endif
2541
2542  WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
2543#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2544  WRITE_FLAG(vps->getVpsPocLsbAlignedFlag(), "vps_poc_lsb_aligned_flag");
2545#endif
2546#if O0062_POC_LSB_NOT_PRESENT_FLAG
2547  for(i = 1; i< vps->getMaxLayers(); i++)
2548  {
2549    if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
2550    {
2551      WRITE_FLAG(vps->getPocLsbNotPresentFlag(i), "poc_lsb_not_present_flag[i]");
2552    }
2553  }
2554#endif
2555#if O0215_PHASE_ALIGNMENT
2556  WRITE_FLAG(vps->getPhaseAlignFlag(), "cross_layer_phase_alignment_flag" );
2557#endif
2558#if !IRAP_ALIGN_FLAG_IN_VPS_VUI
2559  WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
2560#endif
2561#if VPS_DPB_SIZE_TABLE
2562  codeVpsDpbSizeTable(vps);
2563#endif
2564#if VPS_EXTN_DIRECT_REF_LAYERS
2565  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
2566#if O0096_DEFAULT_DEPENDENCY_TYPE
2567  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
2568  if (vps->getDefaultDirectDependencyTypeFlag())
2569  {
2570    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
2571  }
2572  else
2573  {
2574#if VPS_FIX_TO_MATCH_SPEC
2575    for( i = vps->getBaseLayerInternalFlag() ? 1 : 2; i < vps->getMaxLayers(); i++ )
2576#else
2577    for(i = 1; i < vps->getMaxLayers(); i++)
2578#endif
2579    {
2580#if VPS_FIX_TO_MATCH_SPEC
2581      for( j = vps->getBaseLayerInternalFlag() ? 0 : 1; j < i; j++ )
2582#else
2583      for(j = 0; j < i; j++)
2584#endif
2585      {
2586        if (vps->getDirectDependencyFlag(i, j))
2587        {
2588          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
2589        }
2590      }
2591    }
2592  }
2593#else
2594  for(i = 1; i < vps->getMaxLayers(); i++)
2595  {
2596    for(j = 0; j < i; j++)
2597    {
2598      if (vps->getDirectDependencyFlag(i, j))
2599      {
2600        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
2601      }
2602    }
2603  }
2604#endif
2605#endif
2606
2607#if !O0109_O0199_FLAGS_TO_VUI
2608#if M0040_ADAPTIVE_RESOLUTION_CHANGE
2609  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
2610#endif
2611#if HIGHER_LAYER_IRAP_SKIP_FLAG
2612  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
2613#endif
2614#endif
2615
2616#if P0307_VPS_NON_VUI_EXTENSION
2617  // The value of vps_non_vui_extension_length shall be in the range of 0 to 4096, inclusive.
2618  assert( vps->getVpsNonVuiExtLength() >= 0 && vps->getVpsNonVuiExtLength() <= 4096 );
2619
2620  WRITE_UVLC( vps->getVpsNonVuiExtLength(), "vps_non_vui_extension_length" );
2621#if P0307_VPS_NON_VUI_EXT_UPDATE
2622  for (i = 1; i <= vps->getVpsNonVuiExtLength(); i++)
2623  {
2624    WRITE_CODE(1, 8, "vps_non_vui_extension_data_byte");
2625  }
2626#else
2627  if ( vps->getVpsNonVuiExtLength() > 0 )
2628  {
2629    printf("\n\nUp to the current spec, the value of vps_non_vui_extension_length is supposed to be 0\n");
2630  }
2631#endif
2632#endif
2633
2634#if !O0109_MOVE_VPS_VUI_FLAG
2635  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
2636  if(1)   // Should be conditioned on the value of vps_vui_present_flag
2637  {
2638    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
2639    {
2640      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
2641    }
2642#if VPS_VUI_OFFSET
2643    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
2644    assert( vpsVuiOffsetValeInBits % 8 == 0 );
2645    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
2646#endif
2647    codeVPSVUI(vps); 
2648  }
2649#else
2650#if P0307_REMOVE_VPS_VUI_OFFSET
2651  vps->setVpsVuiPresentFlag(true);
2652  WRITE_FLAG( vps->getVpsVuiPresentFlag() ? 1 : 0,                     "vps_vui_present_flag" );
2653#endif
2654  if(vps->getVpsVuiPresentFlag())   // Should be conditioned on the value of vps_vui_present_flag
2655  {
2656    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
2657    {
2658      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
2659    }
2660#if !P0307_REMOVE_VPS_VUI_OFFSET
2661#if VPS_VUI_OFFSET
2662    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
2663    assert( vpsVuiOffsetValeInBits % 8 == 0 );
2664    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
2665#endif
2666#endif
2667    codeVPSVUI(vps); 
2668  }
2669#endif // 0109_MOVE_VPS_FLAG
2670}
2671
2672#if REPN_FORMAT_IN_VPS
2673Void  TEncCavlc::codeRepFormat( RepFormat *repFormat )
2674{
2675#if REPN_FORMAT_CONTROL_FLAG
2676  WRITE_CODE( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_vps_in_luma_samples" );   
2677  WRITE_CODE( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_vps_in_luma_samples" ); 
2678  WRITE_FLAG( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_present_flag" );
2679
2680  if( repFormat->getChromaAndBitDepthVpsPresentFlag() )
2681  {
2682    WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_vps_idc" );   
2683
2684    if( repFormat->getChromaFormatVpsIdc() == 3 )
2685    {
2686      WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_vps_flag" );     
2687    }
2688
2689    assert( repFormat->getBitDepthVpsLuma() >= 8 );
2690    assert( repFormat->getBitDepthVpsChroma() >= 8 );
2691    WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_vps_luma_minus8" );           
2692    WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_vps_chroma_minus8" );
2693  }
2694#else
2695  WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
2696 
2697  if( repFormat->getChromaFormatVpsIdc() == 3 )
2698  {
2699    WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");     
2700  }
2701
2702  WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );   
2703  WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );   
2704 
2705  assert( repFormat->getBitDepthVpsLuma() >= 8 );
2706  assert( repFormat->getBitDepthVpsChroma() >= 8 );
2707  WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
2708  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
2709#endif
2710
2711#if R0156_CONF_WINDOW_IN_REP_FORMAT
2712  Window conf = repFormat->getConformanceWindowVps();
2713
2714  WRITE_FLAG( conf.getWindowEnabledFlag(),    "conformance_window_vps_flag" );
2715  if (conf.getWindowEnabledFlag())
2716  {
2717    WRITE_UVLC( conf.getWindowLeftOffset(),   "conf_win_vps_left_offset"   );
2718    WRITE_UVLC( conf.getWindowRightOffset(),  "conf_win_vps_right_offset"  );
2719    WRITE_UVLC( conf.getWindowTopOffset(),    "conf_win_vps_top_offset"    );
2720    WRITE_UVLC( conf.getWindowBottomOffset(), "conf_win_vps_bottom_offset" );
2721  }
2722#endif
2723}
2724#endif
2725#if VPS_DPB_SIZE_TABLE
2726Void TEncCavlc::codeVpsDpbSizeTable(TComVPS *vps)
2727{
2728#if !SUB_LAYERS_IN_LAYER_SET  // MaxSLInLayerSets calculated earlier in the encoder
2729#if DPB_PARAMS_MAXTLAYERS
2730#if BITRATE_PICRATE_SIGNALLING
2731    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumLayerSets()];
2732    for(Int i = 0; i < vps->getNumLayerSets(); i++)
2733#else
2734    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumOutputLayerSets()];
2735    for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
2736#endif
2737    {
2738        UInt maxSLMinus1 = 0;
2739#if CHANGE_NUMSUBDPB_IDX
2740        Int optLsIdx = vps->getOutputLayerSetIdx( i );
2741#else
2742        Int optLsIdx = i;
2743#endif
2744#if BITRATE_PICRATE_SIGNALLING
2745        optLsIdx = i;
2746#endif
2747        for(Int k = 0; k < vps->getNumLayersInIdList(optLsIdx); k++ ) {
2748            Int  lId = vps->getLayerSetLayerIdList(optLsIdx, k);
2749            maxSLMinus1 = max(maxSLMinus1, vps->getMaxTSLayersMinus1(vps->getLayerIdxInVps(lId)));
2750        }
2751        MaxSubLayersInLayerSetMinus1[ i ] = maxSLMinus1;
2752#if BITRATE_PICRATE_SIGNALLING
2753        vps->setMaxSLayersInLayerSetMinus1(i,MaxSubLayersInLayerSetMinus1[ i ]);
2754#endif
2755    }
2756#endif
2757#endif
2758   
2759   
2760  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
2761  {
2762#if CHANGE_NUMSUBDPB_IDX
2763    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
2764#endif
2765    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]");
2766#if SUB_LAYERS_IN_LAYER_SET
2767    for(Int j = 0; j <= vps->getMaxSLayersInLayerSetMinus1( layerSetIdxForOutputLayerSet ); j++)
2768#else
2769#if DPB_PARAMS_MAXTLAYERS
2770#if BITRATE_PICRATE_SIGNALLING
2771    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ vps->getOutputLayerSetIdx( i ) ]; j++)
2772#else
2773    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ i ]; j++)
2774#endif
2775#else
2776    for(Int j = 0; j < vps->getMaxTLayers(); j++)
2777#endif
2778#endif
2779    {
2780      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
2781      {
2782        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]"); 
2783      }
2784      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
2785      {
2786#if CHANGE_NUMSUBDPB_IDX
2787#if RESOLUTION_BASED_DPB
2788        for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
2789#else
2790        for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
2791#endif
2792#else
2793        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
2794#endif
2795        {
2796#if DPB_INTERNAL_BL_SIG
2797#if VPS_FIX_TO_MATCH_SPEC
2798        if( vps->getNecessaryLayerFlag(i, k) && (vps->getBaseLayerInternalFlag() || (vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k) != 0)) )
2799#else
2800        if(vps->getBaseLayerInternalFlag()  || ( vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k)   !=  0 ) )
2801#endif
2802#endif
2803          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j), "max_vps_dec_pic_buffering_minus1[i][k][j]" );
2804        }
2805        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );             
2806#if RESOLUTION_BASED_DPB
2807        if( vps->getNumSubDpbs(layerSetIdxForOutputLayerSet) != vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ) )  // NumSubDpbs
2808        {
2809          for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
2810          {
2811            WRITE_UVLC( vps->getMaxVpsLayerDecPicBuffMinus1( i, k, j), "max_vps_layer_dec_pic_buff_minus1[i][k][j]" );
2812          }
2813        }
2814#endif
2815        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );       
2816      }
2817    }
2818  }
2819
2820#if !SUB_LAYERS_IN_LAYER_SET
2821#if BITRATE_PICRATE_SIGNALLING
2822  if( MaxSubLayersInLayerSetMinus1 )
2823  {
2824    delete [] MaxSubLayersInLayerSetMinus1;
2825  }
2826#endif
2827#endif
2828}
2829#endif
2830
2831Void TEncCavlc::codeVPSVUI (TComVPS *vps)
2832{
2833  Int i,j;
2834#if O0223_PICTURE_TYPES_ALIGN_FLAG
2835  WRITE_FLAG(vps->getCrossLayerPictureTypeAlignFlag(), "cross_layer_pic_type_aligned_flag");
2836  if (!vps->getCrossLayerPictureTypeAlignFlag())
2837  {
2838#endif
2839#if IRAP_ALIGN_FLAG_IN_VPS_VUI
2840    WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
2841#endif
2842#if O0223_PICTURE_TYPES_ALIGN_FLAG
2843  }
2844  else
2845  {
2846    vps->setCrossLayerIrapAlignFlag(vps->getVpsVuiPresentFlag()); // When not present, the value of cross_layer_irap_aligned_flag is inferred to be equal to vps_vui_present_flag
2847  }
2848#endif
2849#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
2850  if(vps->getCrossLayerIrapAlignFlag())
2851  {
2852    WRITE_FLAG(vps->getCrossLayerAlignedIdrOnlyFlag(), "all_layers_idr_aligned_flag");
2853  }
2854#endif
2855
2856  WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
2857  WRITE_FLAG( vps->getPicRatePresentVpsFlag(),        "pic_rate_present_vps_flag" );
2858
2859  if( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
2860  {
2861#if Q0078_ADD_LAYER_SETS
2862#if R0227_BR_PR_ADD_LAYER_SET
2863#if SIGNALLING_BITRATE_PICRATE_FIX
2864    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getNumLayerSets(); i++ )
2865#else
2866    for( i = 0; i < vps->getNumLayerSets(); i++ )
2867#endif
2868#else
2869    for( i = 0; i <= vps->getVpsNumLayerSetsMinus1(); i++ )
2870#endif
2871#else
2872    for( i = 0; i < vps->getNumLayerSets(); i++ )
2873#endif
2874    {
2875#if BITRATE_PICRATE_SIGNALLING
2876      for( j = 0; j <= vps->getMaxSLayersInLayerSetMinus1(i); j++ )
2877#else
2878      for( j = 0; j < vps->getMaxTLayers(); j++ )
2879#endif
2880      {
2881        if( vps->getBitRatePresentVpsFlag() )
2882        {
2883          WRITE_FLAG( vps->getBitRatePresentFlag( i, j),        "bit_rate_present_flag[i][j]" );
2884        }
2885        if( vps->getPicRatePresentVpsFlag() )
2886        {
2887          WRITE_FLAG( vps->getPicRatePresentFlag( i, j),        "pic_rate_present_flag[i][j]" );
2888        }
2889        if( vps->getBitRatePresentFlag(i, j) )
2890        {
2891          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "avg_bit_rate[i][j]" );
2892          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "max_bit_rate[i][j]" );
2893        }
2894        if( vps->getPicRatePresentFlag(i, j) )
2895        {
2896          WRITE_CODE( vps->getConstPicRateIdc( i, j), 2 , "constant_pic_rate_idc[i][j]" ); 
2897          WRITE_CODE( vps->getConstPicRateIdc( i, j), 16, "avg_pic_rate[i][j]"          ); 
2898        }
2899      }
2900    }
2901  }
2902#if VPS_VUI_VIDEO_SIGNAL_MOVE
2903  WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
2904  if (vps->getVideoSigPresentVpsFlag())
2905  {
2906    WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
2907  }
2908
2909  for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
2910  {
2911    WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
2912    WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
2913    WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
2914    WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
2915    WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
2916  }
2917
2918  if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
2919  {
2920#if VPS_VUI_VST_PARAMS
2921    for(i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
2922    {
2923      WRITE_CODE( vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
2924    }
2925#else
2926    for (i=1; i < vps->getMaxLayers(); i++)
2927      WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
2928#endif
2929  }
2930#endif
2931#if VPS_VUI_TILES_NOT_IN_USE__FLAG
2932  UInt layerIdx;
2933  WRITE_FLAG( vps->getTilesNotInUseFlag() ? 1 : 0 , "tiles_not_in_use_flag" );
2934  if (!vps->getTilesNotInUseFlag())
2935  {
2936#if VPS_FIX_TO_MATCH_SPEC
2937    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++ )
2938#else
2939    for(i = 0; i < vps->getMaxLayers(); i++)
2940#endif
2941    {
2942      WRITE_FLAG( vps->getTilesInUseFlag(i) ? 1 : 0 , "tiles_in_use_flag[ i ]" );
2943      if (vps->getTilesInUseFlag(i))
2944      {
2945        WRITE_FLAG( vps->getLoopFilterNotAcrossTilesFlag(i) ? 1 : 0 , "loop_filter_not_across_tiles_flag[ i ]" );
2946      }
2947    }
2948#endif
2949
2950#if VPS_FIX_TO_MATCH_SPEC
2951    for( i = vps->getBaseLayerInternalFlag() ? 1 : 2; i < vps->getMaxLayers(); i++ )
2952#else
2953    for(i = 1; i < vps->getMaxLayers(); i++)
2954#endif
2955    {
2956      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
2957      {
2958#if VPS_VUI_TILES_NOT_IN_USE__FLAG
2959        layerIdx = vps->getLayerIdxInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
2960        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
2961          WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
2962        }
2963#else
2964        WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
2965#endif
2966      }
2967    } 
2968#if VPS_VUI_TILES_NOT_IN_USE__FLAG
2969  }
2970#endif
2971#if VPS_VUI_WPP_NOT_IN_USE__FLAG
2972  WRITE_FLAG( vps->getWppNotInUseFlag() ? 1 : 0 , "wpp_not_in_use_flag" );
2973  if (!vps->getWppNotInUseFlag())
2974  {
2975#if VPS_FIX_TO_MATCH_SPEC
2976    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++ )
2977#else
2978    for(i = 0; i < vps->getMaxLayers(); i++)
2979#endif
2980    {
2981      WRITE_FLAG( vps->getWppInUseFlag(i) ? 1 : 0 , "wpp_in_use_flag[ i ]" );
2982    }
2983  }
2984#endif
2985
2986#if O0109_O0199_FLAGS_TO_VUI
2987#if M0040_ADAPTIVE_RESOLUTION_CHANGE
2988  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
2989#endif
2990#if HIGHER_LAYER_IRAP_SKIP_FLAG
2991  // When single_layer_for_non_irap_flag is equal to 0, higher_layer_irap_skip_flag shall be equal to 0
2992  if( !vps->getSingleLayerForNonIrapFlag() )
2993  {
2994    assert( !vps->getHigherLayerIrapSkipFlag() );
2995  }
2996
2997  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
2998#endif
2999#endif
3000#if P0312_VERT_PHASE_ADJ
3001  WRITE_FLAG( vps->getVpsVuiVertPhaseInUseFlag(), "vps_vui_vert_phase_in_use_flag" );
3002#endif
3003#if N0160_VUI_EXT_ILP_REF
3004  WRITE_FLAG( vps->getIlpRestrictedRefLayersFlag() ? 1 : 0 , "ilp_restricted_ref_layers_flag" );   
3005  if( vps->getIlpRestrictedRefLayersFlag())
3006  {
3007    for(i = 1; i < vps->getMaxLayers(); i++)
3008    {
3009      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
3010      {
3011#if VPS_FIX_TO_MATCH_SPEC
3012        if (vps->getBaseLayerInternalFlag() || vps->getRefLayerId(vps->getLayerIdInNuh(i), j))
3013        {
3014#endif
3015          WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
3016
3017          if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
3018          { 
3019            WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );   
3020
3021            if(vps->getCtuBasedOffsetEnabledFlag(i,j)) 
3022            {
3023              WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");           
3024            }
3025          }
3026#if VPS_FIX_TO_MATCH_SPEC
3027        }
3028#endif
3029      } 
3030    }
3031  }
3032#endif
3033#if VPS_VUI_VIDEO_SIGNAL
3034#if VPS_VUI_VIDEO_SIGNAL_MOVE
3035#else
3036    WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
3037    if (vps->getVideoSigPresentVpsFlag())
3038    {
3039        WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
3040    }
3041   
3042    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
3043    {
3044        WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
3045        WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
3046        WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
3047        WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
3048        WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
3049    }
3050   
3051    if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
3052    {
3053        for (i=1; i < vps->getMaxLayers(); i++)
3054            WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
3055    }
3056#endif
3057#endif
3058#if O0164_MULTI_LAYER_HRD
3059    WRITE_FLAG(vps->getVpsVuiBspHrdPresentFlag(), "vps_vui_bsp_hrd_present_flag" );
3060    if (vps->getVpsVuiBspHrdPresentFlag())
3061    {
3062#if VPS_VUI_BSP_HRD_PARAMS
3063      codeVpsVuiBspHrdParams(vps);
3064#else
3065      WRITE_UVLC( vps->getVpsNumBspHrdParametersMinus1(), "vps_num_bsp_hrd_parameters_minus1" );
3066      for( i = 0; i <= vps->getVpsNumBspHrdParametersMinus1(); i++ )
3067      {
3068        if( i > 0 )
3069        {
3070          WRITE_FLAG( vps->getBspCprmsPresentFlag(i), "bsp_cprms_present_flag[i]" );
3071        }
3072        codeHrdParameters(vps->getBspHrd(i), i==0 ? 1 : vps->getBspCprmsPresentFlag(i), vps->getMaxTLayers()-1);
3073      }
3074#if Q0078_ADD_LAYER_SETS
3075      for( UInt h = 1; h <= vps->getVpsNumLayerSetsMinus1(); h++ )
3076#else
3077      for( UInt h = 1; h <= (vps->getNumLayerSets()-1); h++ )
3078#endif
3079      {
3080        WRITE_UVLC( vps->getNumBitstreamPartitions(h), "num_bitstream_partitions[i]");
3081        for( i = 0; i < vps->getNumBitstreamPartitions(h); i++ )
3082        {
3083          for( j = 0; j <= (vps->getMaxLayers()-1); j++ )
3084          {
3085            if (vps->getLayerIdIncludedFlag(h, j))
3086            {
3087              WRITE_FLAG( vps->getLayerInBspFlag(h, i, j), "layer_in_bsp_flag[h][i][j]" );
3088            }
3089          }
3090        }
3091        if (vps->getNumBitstreamPartitions(h))
3092        {
3093#if Q0182_MULTI_LAYER_HRD_UPDATE
3094          WRITE_UVLC(vps->getNumBspSchedCombinations(h) - 1, "num_bsp_sched_combinations_minus1[h]");
3095#else
3096          WRITE_UVLC( vps->getNumBspSchedCombinations(h), "num_bsp_sched_combinations[h]");
3097#endif
3098          for( i = 0; i < vps->getNumBspSchedCombinations(h); i++ )
3099          {
3100            for( j = 0; j < vps->getNumBitstreamPartitions(h); j++ )
3101            {
3102              WRITE_UVLC( vps->getBspCombHrdIdx(h, i, j), "bsp_comb_hrd_idx[h][i][j]");
3103              WRITE_UVLC( vps->getBspCombSchedIdx(h, i, j), "bsp_comb_sched_idx[h][i][j]");
3104            }
3105          }
3106        }
3107      }
3108#endif
3109    }
3110#endif
3111#if P0182_VPS_VUI_PS_FLAG
3112    for(i = 1; i < vps->getMaxLayers(); i++)
3113    {
3114      if( vps->getNumRefLayers(vps->getLayerIdInNuh(i)) == 0 ) 
3115      {
3116        WRITE_FLAG(vps->getBaseLayerPSCompatibilityFlag(i), "base_layer_parameter_set_compatibility_flag" );
3117      }
3118    }
3119#endif
3120}
3121
3122Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
3123{
3124  // more syntax elements to be written here
3125
3126  // Vertical MV component restriction is not used in SHVC CTC
3127  WRITE_FLAG( 0, "inter_view_mv_vert_constraint_flag" );
3128
3129#if !MOVE_SCALED_OFFSET_TO_PPS
3130  if( pcSPS->getLayerId() > 0 )
3131  {
3132    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
3133    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
3134    {
3135      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
3136#if O0098_SCALED_REF_LAYER_ID
3137      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
3138#endif
3139      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
3140      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
3141      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
3142      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
3143#if P0312_VERT_PHASE_ADJ
3144      WRITE_FLAG( scaledWindow.getVertPhasePositionEnableFlag(), "vert_phase_position_enable_flag" ); 
3145#endif
3146    }
3147  }
3148#endif
3149}
3150#endif //SVC_EXTENSION
3151
3152#if Q0048_CGS_3D_ASYMLUT
3153Void TEncCavlc::xCode3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT )
3154{
3155#if R0150_CGS_SIGNAL_CONSTRAINTS
3156  UInt uiNumRefLayers = ( UInt )pc3DAsymLUT->getRefLayerNum();
3157  WRITE_UVLC( uiNumRefLayers - 1 , "num_cm_ref_layers_minus1" );
3158  for( UInt i = 0 ; i < uiNumRefLayers ; i++ )
3159  {
3160    WRITE_CODE( pc3DAsymLUT->getRefLayerId( i ) , 6 , "cm_ref_layer_id" );
3161  }
3162#endif
3163  assert( pc3DAsymLUT->getCurOctantDepth() < 4 );
3164  WRITE_CODE( pc3DAsymLUT->getCurOctantDepth() , 2 , "cm_octant_depth" );
3165  assert( pc3DAsymLUT->getCurYPartNumLog2() < 4 );
3166  WRITE_CODE( pc3DAsymLUT->getCurYPartNumLog2() , 2 , "cm_y_part_num_log2" );
3167  assert( pc3DAsymLUT->getInputBitDepthY() < 16 );
3168#if R0150_CGS_SIGNAL_CONSTRAINTS
3169  WRITE_UVLC( pc3DAsymLUT->getInputBitDepthY() - 8 , "cm_input_luma_bit_depth_minus8" );
3170  WRITE_UVLC( pc3DAsymLUT->getInputBitDepthC() - 8 , "cm_input_chroma_bit_depth_minus8" );
3171  WRITE_UVLC( pc3DAsymLUT->getOutputBitDepthY() - 8 , "cm_output_luma_bit_depth_minus8" );
3172  WRITE_UVLC( pc3DAsymLUT->getOutputBitDepthC() - 8 , "cm_output_chroma_bit_depth_minus8" );
3173#else
3174  WRITE_CODE( pc3DAsymLUT->getInputBitDepthY() - 8 , 3 , "cm_input_bit_depth_minus8" );
3175  WRITE_SVLC(pc3DAsymLUT->getInputBitDepthC()-pc3DAsymLUT->getInputBitDepthY(), "cm_input_bit_depth_chroma delta");
3176  assert( pc3DAsymLUT->getOutputBitDepthY() < 16 );
3177  WRITE_CODE( pc3DAsymLUT->getOutputBitDepthY() - 8 , 3 , "cm_output_bit_depth_minus8" );
3178  WRITE_SVLC(pc3DAsymLUT->getOutputBitDepthC()-pc3DAsymLUT->getOutputBitDepthY(), "cm_output_bit_depth_chroma_delta");
3179#endif
3180  assert( pc3DAsymLUT->getResQuantBit() < 4 );
3181  WRITE_CODE( pc3DAsymLUT->getResQuantBit() , 2 , "cm_res_quant_bit" );
3182#if R0300_CGS_RES_COEFF_CODING
3183  xFindDeltaBits( pc3DAsymLUT );
3184  assert(pc3DAsymLUT->getDeltaBits() >=1 && pc3DAsymLUT->getDeltaBits() <= 4);
3185  WRITE_CODE( pc3DAsymLUT->getDeltaBits()-1 , 2 , "cm_delta_bit" );
3186#endif
3187#if R0151_CGS_3D_ASYMLUT_IMPROVE
3188  if( pc3DAsymLUT->getCurOctantDepth() == 1 )
3189  {
3190    WRITE_SVLC( pc3DAsymLUT->getAdaptChromaThresholdU() - ( 1 << ( pc3DAsymLUT->getInputBitDepthC() - 1 ) ) , "cm_adapt_threshold_u_delta" );
3191    WRITE_SVLC( pc3DAsymLUT->getAdaptChromaThresholdV() - ( 1 << ( pc3DAsymLUT->getInputBitDepthC() - 1 ) ) , "cm_adapt_threshold_v_delta" );
3192  }
3193#endif
3194
3195#if R0164_CGS_LUT_BUGFIX_CHECK
3196  pc3DAsymLUT->xInitCuboids();
3197#endif
3198  xCode3DAsymLUTOctant( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth() );
3199#if R0164_CGS_LUT_BUGFIX_CHECK
3200  xCuboidsFilledCheck( false );
3201  pc3DAsymLUT->display( false );
3202#endif
3203}
3204
3205Void TEncCavlc::xCode3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength )
3206{
3207  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
3208  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
3209    WRITE_FLAG( uiOctantSplit , "split_octant_flag" );
3210  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
3211  if( uiOctantSplit )
3212  {
3213    Int nHalfLength = nLength >> 1;
3214    for( Int l = 0 ; l < 2 ; l++ )
3215    {
3216      for( Int m = 0 ; m < 2 ; m++ )
3217      {
3218        for( Int n = 0 ; n < 2 ; n++ )
3219        {
3220          xCode3DAsymLUTOctant( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength );
3221        }
3222      }
3223    }
3224  }
3225  else
3226  {
3227#if R0300_CGS_RES_COEFF_CODING
3228    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-pc3DAsymLUT->getDeltaBits() ; 
3229    nFLCbits = nFLCbits >= 0 ? nFLCbits : 0;
3230#endif
3231    for( Int l = 0 ; l < nYPartNum ; l++ )
3232    {
3233#if R0164_CGS_LUT_BUGFIX     
3234      Int shift = pc3DAsymLUT->getCurOctantDepth() - nDepth ;
3235#endif
3236      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
3237      {
3238#if R0164_CGS_LUT_BUGFIX
3239        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + (l<<shift) , uIdx , vIdx , nVertexIdx );
3240#else
3241        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
3242#endif
3243        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
3244        WRITE_FLAG( uiCodeVertex , "coded_vertex_flag" );
3245        if( uiCodeVertex )
3246        {
3247#if R0151_CGS_3D_ASYMLUT_IMPROVE
3248#if R0300_CGS_RES_COEFF_CODING
3249          xWriteParam( sRes.Y, nFLCbits );
3250          xWriteParam( sRes.U, nFLCbits );
3251          xWriteParam( sRes.V, nFLCbits );
3252#else
3253          xWriteParam( sRes.Y );
3254          xWriteParam( sRes.U );
3255          xWriteParam( sRes.V );
3256#endif
3257#else
3258          WRITE_SVLC( sRes.Y , "resY" );
3259          WRITE_SVLC( sRes.U , "resU" );
3260          WRITE_SVLC( sRes.V , "resV" );
3261#endif
3262        }
3263      }
3264#if R0164_CGS_LUT_BUGFIX_CHECK
3265      pc3DAsymLUT->xSetExplicit( yIdx + (l<<shift) , uIdx , vIdx );
3266#endif
3267    }
3268  }
3269}
3270
3271#if R0151_CGS_3D_ASYMLUT_IMPROVE
3272#if R0300_CGS_RES_COEFF_CODING
3273Void TEncCavlc::xWriteParam( Int param, UInt rParam)
3274#else
3275Void TEncCavlc::xWriteParam( Int param)
3276#endif
3277{
3278#if !R0300_CGS_RES_COEFF_CODING
3279  const UInt rParam = 7;
3280#endif
3281  Int codeNumber = abs(param);
3282  WRITE_UVLC(codeNumber / (1 << rParam), "quotient");
3283  WRITE_CODE((codeNumber % (1 << rParam)), rParam, "remainder");
3284  if (abs(param))
3285    WRITE_FLAG( param <0, "sign");
3286}
3287#endif
3288
3289#if R0300_CGS_RES_COEFF_CODING
3290Void TEncCavlc::xFindDeltaBits( TCom3DAsymLUT * pc3DAsymLUT )
3291{
3292  Int nDeltaBits; 
3293  Int nBestDeltaBits = -1; 
3294  Int nBestBits = MAX_INT; 
3295  for( nDeltaBits = 1; nDeltaBits < 5; nDeltaBits++)
3296  {
3297    Int nCurBits = 0;
3298    xTally3DAsymLUTOctantBits( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth(), nDeltaBits, nCurBits );
3299    //printf("%d, %d, %d\n", nDeltaBits, nCurBits, nBestBits);
3300    if(nCurBits < nBestBits)
3301    {
3302      nBestDeltaBits = nDeltaBits; 
3303      nBestBits = nCurBits;
3304    }
3305  }
3306
3307  assert(nBestDeltaBits >=1 && nBestDeltaBits < 5);
3308  pc3DAsymLUT->setDeltaBits(nBestDeltaBits); 
3309}
3310
3311Void TEncCavlc::xTally3DAsymLUTOctantBits( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength, Int nDeltaBits, Int& nCurBits )
3312{
3313  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
3314  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
3315    nCurBits ++; 
3316  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
3317  if( uiOctantSplit )
3318  {
3319    Int nHalfLength = nLength >> 1;
3320    for( Int l = 0 ; l < 2 ; l++ )
3321    {
3322      for( Int m = 0 ; m < 2 ; m++ )
3323      {
3324        for( Int n = 0 ; n < 2 ; n++ )
3325        {
3326          xTally3DAsymLUTOctantBits( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength, nDeltaBits, nCurBits );
3327        }
3328      }
3329    }
3330  }
3331  else
3332  {
3333    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-nDeltaBits ; 
3334    nFLCbits = nFLCbits >= 0 ? nFLCbits:0;
3335    //printf("nFLCbits = %d\n", nFLCbits);
3336
3337    for( Int l = 0 ; l < nYPartNum ; l++ )
3338    {
3339      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
3340      {
3341        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
3342
3343        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
3344        nCurBits++;
3345        if( uiCodeVertex )
3346        {
3347          xCheckParamBits( sRes.Y, nFLCbits, nCurBits );
3348          xCheckParamBits( sRes.U, nFLCbits, nCurBits );
3349          xCheckParamBits( sRes.V, nFLCbits, nCurBits );
3350        }
3351      }
3352    }
3353  }
3354}
3355
3356Void TEncCavlc::xCheckParamBits( Int param, Int rParam, Int &nBits)
3357{
3358  Int codeNumber = abs(param);
3359  Int codeQuotient = codeNumber >> rParam;
3360  Int qLen; 
3361
3362  UInt uiLength = 1;
3363  UInt uiTemp = ++codeQuotient;
3364   
3365  while( 1 != uiTemp )
3366  {
3367    uiTemp >>= 1;
3368    uiLength += 2;
3369  }
3370
3371  qLen  = (uiLength >> 1);
3372  qLen += ((uiLength+1) >> 1);
3373
3374  nBits += qLen; 
3375  nBits += rParam; 
3376  if (abs(param))
3377    nBits++; 
3378}
3379#endif
3380#if VPS_VUI_BSP_HRD_PARAMS
3381Void TEncCavlc::codeVpsVuiBspHrdParams(TComVPS * const vps)
3382{
3383  WRITE_UVLC( vps->getVpsNumAddHrdParams(), "vps_num_add_hrd_params" );
3384  for( Int i = vps->getNumHrdParameters(), j = 0; i < vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams(); i++, j++ ) // j = i - vps->getNumHrdParameters()
3385  {
3386    if( i > 0 )
3387    {
3388      WRITE_FLAG( vps->getCprmsAddPresentFlag(j), "cprms_add_present_flag[i]" );
3389    }
3390    WRITE_UVLC( vps->getNumSubLayerHrdMinus1(j), "num_sub_layer_hrd_minus1[i]" );
3391    codeHrdParameters(vps->getBspHrd(j), i == 0 ? true : vps->getCprmsAddPresentFlag(j), vps->getNumSubLayerHrdMinus1(j));
3392  }
3393
3394#if VPS_FIX_TO_MATCH_SPEC
3395  if( vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams() > 0 )
3396  {
3397#endif
3398  for( Int h = 1; h < vps->getNumOutputLayerSets(); h++ )
3399  {
3400    Int lsIdx = vps->getOutputLayerSetIdx( h );
3401    WRITE_UVLC( vps->getNumSignalledPartitioningSchemes(h), "num_signalled_partitioning_schemes[h]");
3402
3403#if VPS_FIX_TO_MATCH_SPEC
3404    for( Int j = 1; j < vps->getNumSignalledPartitioningSchemes(h) + 1; j++ )
3405#else
3406    for( Int j = 0; j < vps->getNumSignalledPartitioningSchemes(h); j++ )
3407#endif
3408    {
3409      WRITE_UVLC( vps->getNumPartitionsInSchemeMinus1(h, j), "num_partitions_in_scheme_minus1[h][j]" );
3410      for( Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, j); k++ )
3411      {
3412        for( Int r = 0; r < vps->getNumLayersInIdList( lsIdx ); r++ )
3413        {
3414          WRITE_FLAG( vps->getLayerIncludedInPartitionFlag(h, j, k, r), "layer_included_in_partition_flag[h][j][k][r]" );
3415        }
3416      }
3417    }
3418
3419    for( Int i = 0; i < vps->getNumSignalledPartitioningSchemes(h) + 1; i++ )
3420    {
3421      for( Int t = 0; t <= vps->getMaxSLayersInLayerSetMinus1(lsIdx); t++ )
3422      {
3423        WRITE_UVLC(vps->getNumBspSchedulesMinus1(h, i, t), "num_bsp_schedules_minus1[h][i][t]");
3424
3425        for( Int j = 0; j <= vps->getNumBspSchedulesMinus1(h, i, t); j++ )
3426        {
3427#if VPS_FIX_TO_MATCH_SPEC
3428          for (Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, i); k++)
3429#else
3430          for( Int k = 0; k < vps->getNumPartitionsInSchemeMinus1(h, i); k++ )
3431#endif
3432          {
3433#if VPS_FIX_TO_MATCH_SPEC
3434            if (vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams() > 1)
3435            {
3436              Int numBits = 1;
3437              while ((1 << numBits) < (vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams()))
3438              {
3439                numBits++;
3440              }
3441              WRITE_CODE(vps->getBspHrdIdx(h, i, t, j, k), numBits, "bsp_comb_hrd_idx[h][i][t][j][k]");
3442            }
3443#else
3444            WRITE_UVLC( vps->getBspHrdIdx(h, i, t, j, k),   "bsp_comb_hrd_idx[h][i][t][j][k]");
3445#endif
3446            WRITE_UVLC( vps->getBspSchedIdx(h, i, t, j, k), "bsp_comb_sched_idx[h][i][t][j][k]");
3447          }
3448        }
3449      }
3450    }
3451  }
3452#if VPS_FIX_TO_MATCH_SPEC
3453  }
3454#endif
3455}
3456#endif
3457#endif
3458//! \}
Note: See TracBrowser for help on using the repository browser.