source: SHVCSoftware/branches/SHM-upgrade/source/Lib/TLibEncoder/TEncCavlc.cpp @ 918

Last change on this file since 918 was 918, checked in by seregin, 10 years ago

update make file, add TAppDecoderAnalyser and TLibDecoderAnalyser

  • Property svn:eol-style set to native
File size: 121.9 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_UVLC( pcPPS->getScalingListRefLayerId(), "pps_scaling_list_ref_layer_id" );
315            }
316#endif
317
318#if REF_REGION_OFFSET
319            WRITE_UVLC( pcPPS->getNumScaledRefLayerOffsets(),      "num_ref_loc_offsets" );
320            for(Int k = 0; k < pcPPS->getNumScaledRefLayerOffsets(); k++)
321            {
322              WRITE_CODE( pcPPS->getScaledRefLayerId(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_UVLC( pcSPS->getScalingListRefLayerId(), "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#else
822  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
823#endif
824  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
825  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
826  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
827#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
828#if VPS_EXTN_OFFSET
829  WRITE_CODE( pcVPS->getExtensionOffset(),         16,        "vps_extension_offset" );
830#else
831  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
832#endif
833#else
834  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
835#endif
836  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
837  const Bool subLayerOrderingInfoPresentFlag = 1;
838  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
839  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
840  {
841    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
842    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
843    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
844    if (!subLayerOrderingInfoPresentFlag)
845    {
846      break;
847    }
848  }
849
850#if SVC_EXTENSION
851  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
852  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_ID_PLUS1 );
853#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
854  pcVPS->setNumLayerSets(1);
855#endif
856  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
857#if Q0078_ADD_LAYER_SETS
858  WRITE_UVLC(pcVPS->getVpsNumLayerSetsMinus1(),                "vps_num_layer_sets_minus1");
859  for (UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx++)
860#else
861  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
862  for (UInt opsIdx = 1; opsIdx <= (pcVPS->getNumLayerSets() - 1); opsIdx++)
863#endif
864  {
865    // Operation point set
866    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
867#else
868  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
869  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
870  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
871  pcVPS->setMaxOpSets(1);
872  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
873  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
874  {
875    // Operation point set
876    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
877#endif
878    {
879#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
880      // Only applicable for version 1
881      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
882#endif
883      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
884    }
885  }
886#if !FIX_LAYER_ID_INIT  // It was still called because NECESSARY_FLAG does not exist and is by default "false"
887#if !NECESSARY_FLAG   // Already called once in TAppEncTop.cpp
888#if DERIVE_LAYER_ID_LIST_VARIABLES
889  pcVPS->deriveLayerIdListVariables();
890#endif
891#endif
892#endif
893  TimingInfo *timingInfo = pcVPS->getTimingInfo();
894  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
895  if(timingInfo->getTimingInfoPresentFlag())
896  {
897    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
898    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
899    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
900    if(timingInfo->getPocProportionalToTimingFlag())
901    {
902      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
903    }
904    pcVPS->setNumHrdParameters( 0 );
905    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
906
907    if( pcVPS->getNumHrdParameters() > 0 )
908    {
909      pcVPS->createHrdParamBuffer();
910    }
911    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
912    {
913      // Only applicable for version 1
914      pcVPS->setHrdOpSetIdx( 0, i );
915      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
916      if( i > 0 )
917      {
918        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
919      }
920      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
921    }
922  }
923#if SVC_EXTENSION
924  // When MaxLayersMinus1 is greater than 0, vps_extension_flag shall be equal to 1.
925  if( pcVPS->getMaxLayers() > 1 )
926  {
927    assert( pcVPS->getVpsExtensionFlag() == true );
928  }
929
930  WRITE_FLAG( pcVPS->getVpsExtensionFlag() ? 1 : 0,                     "vps_extension_flag" );
931
932  if( pcVPS->getVpsExtensionFlag() )
933  {
934    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
935    {
936      WRITE_FLAG(1,                  "vps_extension_alignment_bit_equal_to_one");
937    }
938#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
939#if VPS_EXTN_OFFSET_CALC
940    Int vpsExntOffsetValueInBits = this->m_pcBitIf->getNumberOfWrittenBits() - numBytesInVps + 16; // 2 bytes for NUH
941    assert( vpsExntOffsetValueInBits % 8 == 0 );
942    pcVPS->setExtensionOffset( vpsExntOffsetValueInBits >> 3 );
943#endif
944#endif
945    codeVPSExtension(pcVPS);
946    WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
947  }
948#else
949  WRITE_FLAG( 0,                     "vps_extension_flag" );
950#endif 
951  //future extensions here..
952 
953  return;
954}
955
956Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
957{
958#if ENC_DEC_TRACE
959  xTraceSliceHeader (pcSlice);
960#endif
961
962  const ChromaFormat format                = pcSlice->getSPS()->getChromaFormatIdc();
963  const UInt         numberValidComponents = getNumberValidComponents(format);
964  const Bool         chromaEnabled         = isChromaEnabled(format);
965
966  //calculate number of bits required for slice address
967  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumberOfCtusInFrame();
968  Int bitsSliceSegmentAddress = 0;
969  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress))
970  {
971    bitsSliceSegmentAddress++;
972  }
973  const Int ctuTsAddress = pcSlice->getSliceSegmentCurStartCtuTsAddr();
974
975  //write slice address
976  const Int sliceSegmentRsAddress = pcSlice->getPic()->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddress);
977
978  WRITE_FLAG( sliceSegmentRsAddress==0, "first_slice_segment_in_pic_flag" );
979  if ( pcSlice->getRapPicFlag() )
980  {
981    WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
982  }
983  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
984  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentRsAddress!=0) )
985  {
986    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
987  }
988  if(sliceSegmentRsAddress>0)
989  {
990    WRITE_CODE( sliceSegmentRsAddress, bitsSliceSegmentAddress, "slice_segment_address" );
991  }
992  if ( !pcSlice->getDependentSliceSegmentFlag() )
993  {
994#if SVC_EXTENSION
995#if POC_RESET_FLAG
996    Int iBits = 0;
997    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
998    {
999      WRITE_FLAG( pcSlice->getPocResetFlag(), "poc_reset_flag" );
1000      iBits++;
1001    }
1002    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1003    {
1004      assert(!!"discardable_flag");
1005      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1006      iBits++;
1007    }
1008#if O0149_CROSS_LAYER_BLA_FLAG
1009    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1010    {
1011      assert(!!"cross_layer_bla_flag");
1012      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
1013      iBits++;
1014    }
1015#endif
1016    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1017    {
1018      assert(!!"slice_reserved_undetermined_flag[]");
1019      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1020    }
1021#else
1022#if CROSS_LAYER_BLA_FLAG_FIX
1023    Int iBits = 0;
1024    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
1025#else
1026    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
1027#endif
1028    {
1029      assert(!!"discardable_flag");
1030#if NON_REF_NAL_TYPE_DISCARDABLE
1031      if (pcSlice->getDiscardableFlag())
1032      {
1033        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
1034          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
1035          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
1036          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
1037          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
1038      }
1039#endif
1040      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1041#if CROSS_LAYER_BLA_FLAG_FIX
1042      iBits++;
1043#endif
1044    }
1045#if CROSS_LAYER_BLA_FLAG_FIX
1046    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1047    {
1048      assert(!!"cross_layer_bla_flag");
1049      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
1050      iBits++;
1051    }
1052    for (; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1053#else
1054    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1055#endif
1056    {
1057      assert(!!"slice_reserved_undetermined_flag[]");
1058      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1059    }
1060#endif
1061#else //SVC_EXTENSION
1062    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1063    {
1064      assert(!!"slice_reserved_undetermined_flag[]");
1065      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1066    }
1067#endif //SVC_EXTENSION
1068
1069    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1070
1071    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1072    {
1073      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1074    }
1075
1076#if N0065_LAYER_POC_ALIGNMENT
1077#if O0062_POC_LSB_NOT_PRESENT_FLAG
1078    if( (pcSlice->getLayerId() > 0 && !pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdInVps(pcSlice->getLayerId())) ) || !pcSlice->getIdrPicFlag())
1079#else
1080    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
1081#endif
1082#else
1083    if( !pcSlice->getIdrPicFlag() )
1084#endif
1085    {
1086#if POC_RESET_FLAG
1087      Int picOrderCntLSB;
1088      if( !pcSlice->getPocResetFlag() )
1089      {
1090        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1091      }
1092      else
1093      {
1094        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1095      }
1096#else
1097#if POC_RESET_IDC_ENCODER
1098      Int picOrderCntLSB;
1099      if( pcSlice->getPocResetIdc() == 2 )  // i.e. the LSB is reset
1100      {
1101        picOrderCntLSB = pcSlice->getPicOrderCntLsb();  // This will be the LSB value w.r.t to the previous POC reset period.
1102      }
1103      else
1104      {
1105        picOrderCntLSB = (pcSlice->getPOC() + (1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1106      }
1107#else
1108      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1109#endif
1110#endif
1111      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
1112
1113#if N0065_LAYER_POC_ALIGNMENT
1114#if SHM_FIX7
1115    }
1116#endif
1117      if( !pcSlice->getIdrPicFlag() )
1118      {
1119#endif
1120      TComReferencePictureSet* rps = pcSlice->getRPS();
1121
1122      // check for bitstream restriction stating that:
1123      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1124      // Ideally this process should not be repeated for each slice in a picture
1125#if SVC_EXTENSION
1126      if( pcSlice->getLayerId() == 0 )
1127#endif
1128      if (pcSlice->isIRAP())
1129      {
1130        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1131        {
1132          assert (!rps->getUsed(picIdx));
1133        }
1134      }
1135
1136      if(pcSlice->getRPSidx() < 0)
1137      {
1138        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1139        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1140      }
1141      else
1142      {
1143        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1144        Int numBits = 0;
1145        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1146        {
1147          numBits++;
1148        }
1149        if (numBits > 0)
1150        {
1151          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );
1152        }
1153      }
1154      if(pcSlice->getSPS()->getLongTermRefsPresent())
1155      {
1156        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1157        Int ltrpInSPS[MAX_NUM_REF_PICS];
1158        Int numLtrpInSPS = 0;
1159        UInt ltrpIndex;
1160        Int counter = 0;
1161        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--)
1162        {
1163          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k)))
1164          {
1165            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1166            numLtrpInSPS++;
1167          }
1168          else
1169          {
1170            counter++;
1171          }
1172        }
1173        numLtrpInSH -= numLtrpInSPS;
1174
1175        Int bitsForLtrpInSPS = 0;
1176        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1177        {
1178          bitsForLtrpInSPS++;
1179        }
1180        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
1181        {
1182          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1183        }
1184        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1185        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1186        // Not sorted here because LT ref indices will be used in setRefPicList()
1187        Int prevDeltaMSB = 0, prevLSB = 0;
1188        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1189        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
1190        {
1191          if (counter < numLtrpInSPS)
1192          {
1193            if (bitsForLtrpInSPS > 0)
1194            {
1195              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
1196            }
1197          }
1198          else
1199          {
1200            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1201            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag");
1202          }
1203          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1204
1205          if(rps->getDeltaPocMSBPresentFlag(i))
1206          {
1207            Bool deltaFlag = false;
1208            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1209            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1210            {
1211              deltaFlag = true;
1212            }
1213            if(deltaFlag)
1214            {
1215              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1216            }
1217            else
1218            {
1219              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1220              assert(differenceInDeltaMSB >= 0);
1221              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1222            }
1223            prevLSB = rps->getPocLSBLT(i);
1224            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1225          }
1226        }
1227      }
1228      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1229      {
1230#if R0226_SLICE_TMVP
1231        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
1232#else
1233        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
1234#endif
1235      }
1236#if N0065_LAYER_POC_ALIGNMENT && !SHM_FIX7
1237      }
1238#endif
1239    }
1240
1241#if SVC_EXTENSION
1242    if((pcSlice->getLayerId() > 0) && !(pcSlice->getVPS()->getIlpSshSignalingEnabledFlag()) && (pcSlice->getNumILRRefIdx() > 0) )
1243    {
1244      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
1245      if( pcSlice->getInterLayerPredEnabledFlag())
1246      {
1247        if(pcSlice->getNumILRRefIdx() > 1)
1248        {
1249          Int numBits = 1;
1250          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
1251          {
1252            numBits++;
1253          }
1254          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
1255          {
1256            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
1257          }       
1258
1259          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
1260          {
1261            for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1262            {
1263              WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
1264            }
1265          }
1266        }
1267      }
1268    }     
1269#if P0312_VERT_PHASE_ADJ
1270    for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1271    {
1272      UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
1273      if( pcSlice->getSPS()->getVertPhasePositionEnableFlag(refLayerIdc) )
1274      {
1275        WRITE_FLAG( pcSlice->getVertPhasePositionFlag(refLayerIdc), "vert_phase_position_flag" );
1276      }
1277    }
1278#endif
1279#endif //SVC_EXTENSION
1280
1281    if(pcSlice->getSPS()->getUseSAO())
1282    {
1283       WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA), "slice_sao_luma_flag" );
1284       if (chromaEnabled) WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA), "slice_sao_chroma_flag" );
1285    }
1286
1287    //check if numrefidxes match the defaults. If not, override
1288
1289    if (!pcSlice->isIntra())
1290    {
1291      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
1292      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
1293      if (overrideFlag)
1294      {
1295        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
1296        if (pcSlice->isInterB())
1297        {
1298          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
1299        }
1300        else
1301        {
1302          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1303        }
1304      }
1305    }
1306    else
1307    {
1308      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
1309      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1310    }
1311
1312    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
1313    {
1314      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1315      if(!pcSlice->isIntra())
1316      {
1317        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
1318        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
1319        {
1320          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
1321          if (numRpsCurrTempList0 > 1)
1322          {
1323            Int length = 1;
1324            numRpsCurrTempList0 --;
1325            while ( numRpsCurrTempList0 >>= 1)
1326            {
1327              length ++;
1328            }
1329            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
1330            {
1331              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
1332            }
1333          }
1334        }
1335      }
1336      if(pcSlice->isInterB())
1337      {
1338        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
1339        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
1340        {
1341          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
1342          if ( numRpsCurrTempList1 > 1 )
1343          {
1344            Int length = 1;
1345            numRpsCurrTempList1 --;
1346            while ( numRpsCurrTempList1 >>= 1)
1347            {
1348              length ++;
1349            }
1350            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
1351            {
1352              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
1353            }
1354          }
1355        }
1356      }
1357    }
1358
1359    if (pcSlice->isInterB())
1360    {
1361      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
1362    }
1363
1364    if(!pcSlice->isIntra())
1365    {
1366      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1367      {
1368        SliceType sliceType   = pcSlice->getSliceType();
1369        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
1370        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1371        pcSlice->setCabacInitFlag( encCabacInitFlag );
1372        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1373      }
1374    }
1375
1376    if ( pcSlice->getEnableTMVPFlag() )
1377    {
1378      if ( pcSlice->getSliceType() == B_SLICE )
1379      {
1380        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1381      }
1382
1383      if ( pcSlice->getSliceType() != I_SLICE &&
1384        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1385        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1386      {
1387        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1388      }
1389    }
1390    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1391    {
1392      xCodePredWeightTable( pcSlice );
1393    }
1394    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1395    if (!pcSlice->isIntra())
1396    {
1397      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1398    }
1399    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1400    WRITE_SVLC( iCode, "slice_qp_delta" );
1401    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1402    {
1403      if (numberValidComponents > COMPONENT_Cb) { WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb), "slice_qp_delta_cb" ); }
1404      if (numberValidComponents > COMPONENT_Cr) { WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr), "slice_qp_delta_cr" ); }
1405      assert(numberValidComponents <= COMPONENT_Cr+1);
1406    }
1407
1408    if (pcSlice->getPPS()->getChromaQpAdjTableSize() > 0)
1409    {
1410      WRITE_FLAG(pcSlice->getUseChromaQpAdj(), "slice_chroma_qp_adjustment_enabled_flag");
1411    }
1412
1413    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1414    {
1415      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1416      {
1417        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1418      }
1419      if (pcSlice->getDeblockingFilterOverrideFlag())
1420      {
1421        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1422        if(!pcSlice->getDeblockingFilterDisable())
1423        {
1424          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
1425          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
1426        }
1427      }
1428    }
1429
1430    Bool isSAOEnabled = pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (chromaEnabled && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
1431    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1432
1433    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1434    {
1435      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1436    }
1437  }
1438
1439#if !POC_RESET_IDC_SIGNALLING   // Wrong place to put slice header extension
1440  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1441  {
1442    WRITE_UVLC(0,"slice_header_extension_length");
1443  }
1444#endif
1445}
1446
1447Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1448{
1449  if(profilePresentFlag)
1450  {
1451    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1452  }
1453  WRITE_CODE( Int(pcPTL->getGeneralPTL()->getLevelIdc()), 8, "general_level_idc" );
1454
1455  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
1456  {
1457    if(profilePresentFlag)
1458    {
1459      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1460    }
1461
1462    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1463  }
1464
1465  if (maxNumSubLayersMinus1 > 0)
1466  {
1467    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
1468    {
1469      WRITE_CODE(0, 2, "reserved_zero_2bits");
1470    }
1471  }
1472
1473  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1474  {
1475    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1476    {
1477      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1478    }
1479    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1480    {
1481      WRITE_CODE( Int(pcPTL->getSubLayerPTL(i)->getLevelIdc()), 8, "sub_layer_level_idc[i]" );
1482    }
1483  }
1484}
1485Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1486{
1487  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1488  WRITE_FLAG( ptl->getTierFlag()==Level::HIGH, "XXX_tier_flag[]"    );
1489  WRITE_CODE( Int(ptl->getProfileIdc()), 5 ,  "XXX_profile_idc[]"  );
1490  for(Int j = 0; j < 32; j++)
1491  {
1492    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");
1493  }
1494
1495  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
1496  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
1497  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
1498  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
1499
1500  if (ptl->getProfileIdc() == Profile::MAINREXT || ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT )
1501  {
1502    const UInt         bitDepthConstraint=ptl->getBitDepthConstraint();
1503    WRITE_FLAG(bitDepthConstraint<=12, "general_max_12bit_constraint_flag");
1504    WRITE_FLAG(bitDepthConstraint<=10, "general_max_10bit_constraint_flag");
1505    WRITE_FLAG(bitDepthConstraint<= 8, "general_max_8bit_constraint_flag");
1506    const ChromaFormat chromaFmtConstraint=ptl->getChromaFormatConstraint();
1507    WRITE_FLAG(chromaFmtConstraint==CHROMA_422||chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400, "general_max_422chroma_constraint_flag");
1508    WRITE_FLAG(chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400,                                  "general_max_420chroma_constraint_flag");
1509    WRITE_FLAG(chromaFmtConstraint==CHROMA_400,                                                                   "general_max_monochrome_constraint_flag");
1510    WRITE_FLAG(ptl->getIntraConstraintFlag(),        "general_intra_constraint_flag");
1511    WRITE_FLAG(0,                                    "general_one_picture_only_constraint_flag");
1512    WRITE_FLAG(ptl->getLowerBitRateConstraintFlag(), "general_lower_bit_rate_constraint_flag");
1513    WRITE_CODE(0 , 16, "XXX_reserved_zero_35bits[0..15]");
1514    WRITE_CODE(0 , 16, "XXX_reserved_zero_35bits[16..31]");
1515    WRITE_CODE(0 ,  3, "XXX_reserved_zero_35bits[32..34]");
1516  }
1517  else
1518  {
1519    WRITE_CODE(0x0000 , 16, "XXX_reserved_zero_44bits[0..15]");
1520    WRITE_CODE(0x0000 , 16, "XXX_reserved_zero_44bits[16..31]");
1521    WRITE_CODE(0x000  , 12, "XXX_reserved_zero_44bits[32..43]");
1522  }
1523}
1524
1525/**
1526 - write tiles and wavefront substreams sizes for the slice header.
1527 .
1528 \param pcSlice Where we find the substream size information.
1529 */
1530Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1531{
1532  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1533  {
1534    return;
1535  }
1536  UInt maxOffset = 0;
1537  for(Int idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
1538  {
1539    UInt offset=pSlice->getSubstreamSize(idx);
1540    if ( offset > maxOffset )
1541    {
1542      maxOffset = offset;
1543    }
1544  }
1545
1546  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1547  UInt offsetLenMinus1 = 0;
1548  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1549  {
1550    offsetLenMinus1++;
1551    assert(offsetLenMinus1 + 1 < 32);
1552  }
1553
1554  WRITE_UVLC(pSlice->getNumberOfSubstreamSizes(), "num_entry_point_offsets");
1555  if (pSlice->getNumberOfSubstreamSizes()>0)
1556  {
1557    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1558
1559    for (UInt idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
1560    {
1561      WRITE_CODE(pSlice->getSubstreamSize(idx)-1, offsetLenMinus1+1, "entry_point_offset_minus1");
1562    }
1563  }
1564}
1565
1566Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1567{
1568}
1569
1570Void TEncCavlc::codeSliceFinish ()
1571{
1572}
1573
1574Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1575{
1576  assert(0);
1577}
1578
1579Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1580{
1581  assert(0);
1582}
1583
1584Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1585{
1586  assert(0);
1587}
1588
1589Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1590{
1591  assert(0);
1592}
1593
1594Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1595{
1596  assert(0);
1597}
1598
1599Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1600{
1601  assert(0);
1602}
1603
1604Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1605{
1606  assert(0);
1607}
1608
1609Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1610{
1611  assert(0);
1612}
1613
1614Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1615{
1616  assert(0);
1617}
1618
1619Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1620{
1621  assert(0);
1622}
1623
1624Void TEncCavlc::codeQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
1625{
1626  assert(0);
1627}
1628
1629Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1630{
1631  assert(0);
1632}
1633
1634Void TEncCavlc::codeQtCbfZero( TComTU &rTu, const ChannelType chType )
1635{
1636  assert(0);
1637}
1638Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
1639{
1640  assert(0);
1641}
1642
1643Void TEncCavlc::codeTransformSkipFlags (TComTU &rTu, ComponentID component )
1644{
1645  assert(0);
1646}
1647
1648/** Code I_PCM information.
1649 * \param pcCU pointer to CU
1650 * \param uiAbsPartIdx CU index
1651 * \returns Void
1652 */
1653Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
1654{
1655  assert(0);
1656}
1657
1658Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1659{
1660  assert(0);
1661}
1662
1663Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
1664{
1665  assert(0);
1666}
1667
1668Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
1669{
1670  assert(0);
1671}
1672
1673Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1674{
1675  assert(0);
1676}
1677
1678Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1679{
1680  assert(0);
1681}
1682
1683Void TEncCavlc::codeCrossComponentPrediction( TComTU& /*rTu*/, ComponentID /*compID*/ )
1684{
1685  assert(0);
1686}
1687
1688Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
1689{
1690  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
1691
1692#if REPN_FORMAT_IN_VPS
1693  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
1694#else
1695  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
1696#endif
1697  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
1698
1699  xWriteSvlc( iDQp );
1700
1701  return;
1702}
1703
1704Void TEncCavlc::codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx )
1705{
1706  assert(0);
1707}
1708
1709Void TEncCavlc::codeCoeffNxN    ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID )
1710{
1711  assert(0);
1712}
1713
1714Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, ChannelType chType )
1715{
1716  // printf("error : no VLC mode support in this version\n");
1717  return;
1718}
1719
1720// ====================================================================================================================
1721// Protected member functions
1722// ====================================================================================================================
1723
1724/** code explicit wp tables
1725 * \param TComSlice* pcSlice
1726 * \returns Void
1727 */
1728Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
1729{
1730  WPScalingParam  *wp;
1731  const ChromaFormat    format                = pcSlice->getPic()->getChromaFormat();
1732  const UInt            numberValidComponents = getNumberValidComponents(format);
1733  const Bool            bChroma               = isChromaEnabled(format);
1734  const Int             iNbRef                = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
1735        Bool            bDenomCoded           = false;
1736        UInt            uiMode                = 0;
1737        UInt            uiTotalSignalledWeightFlags = 0;
1738
1739  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
1740  {
1741    uiMode = 1; // explicit
1742  }
1743  if(uiMode == 1)
1744  {
1745    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ )
1746    {
1747      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1748
1749      // NOTE: wp[].uiLog2WeightDenom and wp[].bPresentFlag are actually per-channel-type settings.
1750
1751      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
1752      {
1753        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1754        if ( !bDenomCoded )
1755        {
1756          Int iDeltaDenom;
1757          WRITE_UVLC( wp[COMPONENT_Y].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
1758
1759          if( bChroma )
1760          {
1761            assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom); // check the channel-type settings are consistent across components.
1762            iDeltaDenom = (wp[COMPONENT_Cb].uiLog2WeightDenom - wp[COMPONENT_Y].uiLog2WeightDenom);
1763            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
1764          }
1765          bDenomCoded = true;
1766        }
1767        WRITE_FLAG( wp[COMPONENT_Y].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
1768        uiTotalSignalledWeightFlags += wp[COMPONENT_Y].bPresentFlag;
1769      }
1770      if (bChroma)
1771      {
1772        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
1773        {
1774          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1775          assert(wp[COMPONENT_Cb].bPresentFlag == wp[COMPONENT_Cr].bPresentFlag); // check the channel-type settings are consistent across components.
1776          WRITE_FLAG( wp[COMPONENT_Cb].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1777          uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
1778        }
1779      }
1780
1781      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
1782      {
1783        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1784        if ( wp[COMPONENT_Y].bPresentFlag )
1785        {
1786          Int iDeltaWeight = (wp[COMPONENT_Y].iWeight - (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
1787          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                            // se(v): delta_luma_weight_lX
1788          WRITE_SVLC( wp[COMPONENT_Y].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
1789        }
1790
1791        if ( bChroma )
1792        {
1793          if ( wp[COMPONENT_Cb].bPresentFlag )
1794          {
1795            for ( Int j = COMPONENT_Cb ; j < numberValidComponents ; j++ )
1796            {
1797              assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom);
1798              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[COMPONENT_Cb].uiLog2WeightDenom));
1799              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
1800
1801              Int range=pcSlice->getSPS()->getUseHighPrecisionPredictionWeighting() ? (1<<g_bitDepth[CHANNEL_TYPE_CHROMA])/2 : 128;
1802              Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
1803              Int iDeltaChroma = (wp[j].iOffset - pred);
1804              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
1805            }
1806          }
1807        }
1808      }
1809    }
1810    assert(uiTotalSignalledWeightFlags<=24);
1811  }
1812}
1813
1814/** code quantization matrix
1815 *  \param scalingList quantization matrix information
1816 */
1817Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
1818{
1819  UInt listId,sizeId;
1820  Bool scalingListPredModeFlag;
1821
1822  //for each size
1823  for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
1824  {
1825    Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
1826
1827    for(listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
1828    {
1829      scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
1830      WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
1831      if(!scalingListPredModeFlag)// Copy Mode
1832      {
1833        if (sizeId == SCALING_LIST_32x32)
1834        {
1835          // adjust the code, to cope with the missing chroma entries
1836          WRITE_UVLC( ((Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId)) / (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES), "scaling_list_pred_matrix_id_delta");
1837        }
1838        else
1839        {
1840          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
1841        }
1842      }
1843      else// DPCM Mode
1844      {
1845        xCodeScalingList(scalingList, sizeId, listId);
1846      }
1847    }
1848  }
1849  return;
1850}
1851/** code DPCM
1852 * \param scalingList quantization matrix information
1853 * \param sizeIdc size index
1854 * \param listIdc list index
1855 */
1856Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
1857{
1858  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
1859  UInt* scan  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
1860  Int nextCoef = SCALING_LIST_START_VALUE;
1861  Int data;
1862  Int *src = scalingList->getScalingListAddress(sizeId, listId);
1863    if( sizeId > SCALING_LIST_8x8 )
1864    {
1865      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
1866      nextCoef = scalingList->getScalingListDC(sizeId,listId);
1867    }
1868    for(Int i=0;i<coefNum;i++)
1869    {
1870      data = src[scan[i]] - nextCoef;
1871      nextCoef = src[scan[i]];
1872      if(data > 127)
1873      {
1874        data = data - 256;
1875      }
1876      if(data < -128)
1877      {
1878        data = data + 256;
1879      }
1880
1881      WRITE_SVLC( data,  "scaling_list_delta_coef");
1882    }
1883}
1884Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
1885{
1886  // Bool state = true, state2 = false;
1887  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1888  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
1889  {
1890    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
1891    {
1892      *ltrpsIndex = k;
1893      return true;
1894    }
1895  }
1896  return false;
1897}
1898Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
1899{
1900  Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
1901
1902  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx-=predListStep)
1903  {
1904    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
1905      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
1906     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
1907    {
1908      setRefMatrixId(sizeId, listId, predListIdx);
1909      return false;
1910    }
1911  }
1912  return true;
1913}
1914
1915Void TEncCavlc::codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID )
1916 {
1917   assert(0);
1918 }
1919
1920#if SVC_EXTENSION
1921
1922#if POC_RESET_IDC_SIGNALLING
1923Void  TEncCavlc::codeSliceHeaderExtn( TComSlice* slice, Int shBitsWrittenTillNow )
1924{
1925  Int tmpBitsBeforeWriting = getNumberOfWrittenBits();
1926  Int maxPocLsb = 1 << slice->getSPS()->getBitsForPOC();
1927  if(slice->getPPS()->getSliceHeaderExtensionPresentFlag())
1928  {
1929    // Derive the value of PocMsbValRequiredFlag
1930#if P0297_VPS_POC_LSB_ALIGNED_FLAG
1931    slice->setPocMsbValRequiredFlag( (slice->getCraPicFlag() || slice->getBlaPicFlag())
1932                                  && (!slice->getVPS()->getVpsPocLsbAlignedFlag() ||
1933                                      (slice->getVPS()->getVpsPocLsbAlignedFlag() && slice->getVPS()->getNumDirectRefLayers(slice->getLayerId()) == 0))
1934                                   );
1935#else
1936    slice->setPocMsbValRequiredFlag( slice->getCraPicFlag() || slice->getBlaPicFlag() );
1937#endif
1938
1939    // Determine value of SH extension length.
1940    Int shExtnLengthInBit = 0;
1941    if (slice->getPPS()->getPocResetInfoPresentFlag())
1942    {
1943      shExtnLengthInBit += 2;
1944    }
1945    if (slice->getPocResetIdc() > 0)
1946    {
1947      shExtnLengthInBit += 6;
1948    }
1949    if (slice->getPocResetIdc() == 3)
1950    {
1951      shExtnLengthInBit += (slice->getSPS()->getBitsForPOC() + 1);
1952    }
1953
1954
1955#if P0297_VPS_POC_LSB_ALIGNED_FLAG
1956    if (!slice->getPocMsbValRequiredFlag() && slice->getVPS()->getVpsPocLsbAlignedFlag())
1957#else
1958    if (!slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */)
1959#endif
1960    {
1961      shExtnLengthInBit++;
1962    }
1963    else
1964    {
1965      if( slice->getPocMsbValRequiredFlag() )
1966      {
1967        slice->setPocMsbValPresentFlag( true );
1968      }
1969      else
1970      {
1971        slice->setPocMsbValPresentFlag( false );
1972      }
1973    }
1974
1975#if P0297_VPS_POC_LSB_ALIGNED_FLAG
1976    if (slice->getPocMsbNeeded())
1977    {
1978      slice->setPocMsbValPresentFlag(true);
1979    }
1980#endif
1981
1982    if (slice->getPocMsbValPresentFlag())
1983    {
1984      UInt lengthVal = 1;
1985      UInt tempVal = (slice->getPocMsbVal() / maxPocLsb) + 1;
1986      assert ( tempVal );
1987      while( 1 != tempVal )
1988      {
1989        tempVal >>= 1;
1990        lengthVal += 2;
1991      }
1992      shExtnLengthInBit += lengthVal;
1993    }
1994    Int shExtnAdditionalBits = 0;
1995    if(shExtnLengthInBit % 8 != 0)
1996    {
1997      shExtnAdditionalBits = 8 - (shExtnLengthInBit % 8);
1998    }
1999    Int shExtnLength = (shExtnLengthInBit + shExtnAdditionalBits) / 8;
2000    WRITE_UVLC( shExtnLength, "slice_header_extension_length" );
2001
2002    if(slice->getPPS()->getPocResetInfoPresentFlag())
2003    {
2004      WRITE_CODE( slice->getPocResetIdc(), 2,                                 "poc_reset_idc");
2005    }
2006    if(slice->getPocResetIdc() > 0)
2007    {
2008      WRITE_CODE( slice->getPocResetPeriodId(), 6,                            "poc_reset_period_id");
2009    }
2010    if(slice->getPocResetIdc() == 3) 
2011    {
2012      WRITE_FLAG( slice->getFullPocResetFlag() ? 1 : 0,                       "full_poc_reset_flag");
2013      WRITE_CODE( slice->getPocLsbVal(), slice->getSPS()->getBitsForPOC(),  "poc_lsb_val");
2014    }
2015
2016#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2017    if (!slice->getPocMsbValRequiredFlag() && slice->getVPS()->getVpsPocLsbAlignedFlag())
2018#else
2019    if (!slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */)
2020#endif
2021    {
2022#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2023      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_cycle_val_present_flag" );
2024#else
2025      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_val_present_flag" );
2026#endif
2027    }
2028    if (slice->getPocMsbValPresentFlag())
2029    {
2030      assert(slice->getPocMsbVal() % maxPocLsb == 0);
2031#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2032      WRITE_UVLC(slice->getPocMsbVal() / maxPocLsb, "poc_msb_cycle_val");
2033#else
2034      WRITE_UVLC(slice->getPocMsbVal() / maxPocLsb, "poc_msb_val");
2035#endif
2036    }
2037    for (Int i = 0; i < shExtnAdditionalBits; i++)
2038    {
2039#if Q0146_SSH_EXT_DATA_BIT
2040      WRITE_FLAG( 1, "slice_segment_header_extension_data_bit");
2041#else
2042      WRITE_FLAG( 1, "slice_segment_header_extension_reserved_bit");
2043#endif
2044    }
2045  }
2046  shBitsWrittenTillNow += ( getNumberOfWrittenBits() - tmpBitsBeforeWriting );
2047 
2048  // Slice header byte_alignment() included in xAttachSliceDataToNalUnit
2049}
2050#endif
2051
2052Void TEncCavlc::codeVPSExtension (TComVPS *vps)
2053{
2054  // ... More syntax elements to be written here
2055#if P0300_ALT_OUTPUT_LAYER_FLAG
2056  Int NumOutputLayersInOutputLayerSet[MAX_VPS_LAYER_SETS_PLUS1];
2057  Int OlsHighestOutputLayerId[MAX_VPS_LAYER_SETS_PLUS1];
2058#endif
2059#if LIST_OF_PTL
2060  if( vps->getMaxLayers() > 1 && vps->getBaseLayerInternalFlag() )
2061  {
2062    codePTL( vps->getPTLForExtn(1), false, vps->getMaxTLayers() - 1 );
2063  }
2064#endif
2065#if VPS_EXTN_MASK_AND_DIM_INFO
2066  UInt i = 0, j = 0;
2067#if !VPS_AVC_BL_FLAG_REMOVAL
2068  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
2069#endif
2070#if !P0307_REMOVE_VPS_VUI_OFFSET
2071#if O0109_MOVE_VPS_VUI_FLAG
2072  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
2073  vps->setVpsVuiPresentFlag(true);
2074  if ( vps->getVpsVuiPresentFlag() ) 
2075  {
2076#if VPS_VUI_OFFSET
2077    WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" );
2078#endif
2079    WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
2080  }
2081#else
2082#if VPS_VUI_OFFSET
2083  WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" ); 
2084#endif
2085  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
2086#endif // O0109_MOVE_VPS_VUI_FLAG
2087#endif
2088  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
2089
2090  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
2091  {
2092    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
2093  }
2094
2095  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
2096  {
2097    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
2098  }
2099
2100  // The value of dimBitOffset[ NumScalabilityTypes ] is set equal to 6.
2101  if(vps->getSplittingFlag())
2102  {
2103    UInt splDimSum=0;
2104    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
2105    {
2106      splDimSum+=(vps->getDimensionIdLen(j));
2107    }
2108    assert(splDimSum<=6);
2109  }
2110
2111  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
2112  for(i = 1; i < vps->getMaxLayers(); i++)
2113  {
2114    if( vps->getNuhLayerIdPresentFlag() )
2115    {
2116      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
2117    }
2118
2119    if( !vps->getSplittingFlag() )
2120    {
2121    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
2122    {
2123      UInt bits = vps->getDimensionIdLen(j);
2124      WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
2125    }
2126  }
2127  }
2128#endif
2129#if VIEW_ID_RELATED_SIGNALING
2130  // if ( pcVPS->getNumViews() > 1 ) 
2131  //   However, this is a bug in the text since, view_id_len_minus1 is needed to parse view_id_val.
2132  {
2133#if O0109_VIEW_ID_LEN
2134    WRITE_CODE( vps->getViewIdLen( ), 4, "view_id_len" );
2135    assert ( vps->getNumViews() >= (1<<vps->getViewIdLen()) );
2136#else
2137    WRITE_CODE( vps->getViewIdLenMinus1( ), 4, "view_id_len_minus1" );
2138#endif
2139  }
2140
2141#if O0109_VIEW_ID_LEN
2142  if ( vps->getViewIdLen() > 0 )
2143  {
2144#endif
2145  for(  i = 0; i < vps->getNumViews(); i++ )
2146  {
2147#if O0109_VIEW_ID_LEN
2148    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLen( ), "view_id_val[i]" );
2149#else
2150    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLenMinus1( ) + 1, "view_id_val[i]" );
2151#endif
2152  }
2153#if O0109_VIEW_ID_LEN
2154  }
2155#endif
2156#endif // VIEW_ID_RELATED_SIGNALING
2157
2158#if VPS_EXTN_DIRECT_REF_LAYERS
2159  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
2160  {
2161    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
2162    {
2163      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
2164    }
2165  }
2166#endif
2167#if MOVE_ADDN_LS_SIGNALLING
2168#if Q0078_ADD_LAYER_SETS
2169  if (vps->getNumIndependentLayers() > 1)
2170  {
2171    WRITE_UVLC( vps->getNumAddLayerSets(), "num_add_layer_sets" );
2172    for (i = 0; i < vps->getNumAddLayerSets(); i++)
2173    {
2174      for (j = 1; j < vps->getNumIndependentLayers(); j++)
2175      {
2176        int len = 1;
2177        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
2178        {
2179          len++;
2180        }
2181        WRITE_CODE(vps->getHighestLayerIdxPlus1(i, j), len, "highest_layer_idx_plus1[i][j]");
2182      }
2183    }
2184  }
2185#endif
2186#endif
2187#if VPS_TSLAYERS
2188    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
2189    if (vps->getMaxTSLayersPresentFlag())
2190    {
2191        for( i = 0; i < vps->getMaxLayers(); i++)
2192        {
2193            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
2194        }
2195    }
2196#endif
2197   WRITE_FLAG( vps->getMaxTidRefPresentFlag(), "max_tid_ref_present_flag");
2198   if (vps->getMaxTidRefPresentFlag())
2199   {
2200     for( i = 0; i < vps->getMaxLayers() - 1; i++)
2201     {
2202#if O0225_MAX_TID_FOR_REF_LAYERS
2203       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
2204       {
2205         if(vps->getDirectDependencyFlag(j, i))
2206         {
2207           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
2208         }
2209       }
2210#else
2211       WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
2212#endif
2213     }
2214   }
2215   WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
2216#if VPS_EXTN_PROFILE_INFO
2217  // Profile-tier-level signalling
2218#if !VPS_EXTN_UEV_CODING
2219  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
2220  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
2221#else
2222  WRITE_UVLC( vps->getNumProfileTierLevel() - 1, "vps_num_profile_tier_level_minus1"); 
2223#if PER_LAYER_PTL
2224  Int const numBitsForPtlIdx = vps->calculateLenOfSyntaxElement( vps->getNumProfileTierLevel() );
2225#endif
2226#endif
2227#if LIST_OF_PTL
2228  assert( vps->getNumProfileTierLevel() == vps->getPTLForExtnPtr()->size());
2229  for(Int idx = vps->getBaseLayerInternalFlag() ? 2 : 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
2230#else
2231  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
2232#endif
2233  {
2234    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
2235#if !P0048_REMOVE_PROFILE_REF
2236    if( !vps->getProfilePresentFlag(idx) )
2237    {
2238      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
2239    }
2240#endif
2241    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
2242  }
2243#endif
2244
2245
2246#if !MOVE_ADDN_LS_SIGNALLING
2247#if Q0078_ADD_LAYER_SETS
2248  if (vps->getNumIndependentLayers() > 1)
2249  {
2250    WRITE_UVLC( vps->getNumAddLayerSets(), "num_add_layer_sets" );
2251    for (i = 0; i < vps->getNumAddLayerSets(); i++)
2252    {
2253      for (j = 1; j < vps->getNumIndependentLayers(); j++)
2254      {
2255        int len = 1;
2256        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
2257        {
2258          len++;
2259        }
2260        WRITE_CODE(vps->getHighestLayerIdxPlus1(i, j), len, "highest_layer_idx_plus1[i][j]");
2261      }
2262    }
2263  }
2264#endif
2265#endif
2266
2267#if !VPS_EXTN_UEV_CODING
2268  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
2269  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
2270  if(numOutputLayerSets > vps->getNumLayerSets())
2271  {
2272    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
2273  }
2274#else
2275  Int numOutputLayerSets = vps->getNumOutputLayerSets();
2276  Int numAddOutputLayerSets = numOutputLayerSets - (Int)vps->getNumLayerSets();
2277
2278  // The value of num_add_olss shall be in the range of 0 to 1023, inclusive.
2279  assert( numAddOutputLayerSets >= 0 && numAddOutputLayerSets < 1024 );
2280
2281#if Q0165_NUM_ADD_OUTPUT_LAYER_SETS
2282  if( vps->getNumLayerSets() > 1 )
2283  {
2284    WRITE_UVLC( numAddOutputLayerSets, "num_add_olss" );
2285    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_output_layer_idc" );
2286  }
2287#else
2288  WRITE_UVLC( numOutputLayerSets - vps->getNumLayerSets(), "num_add_output_layer_sets" );
2289#endif
2290#endif
2291
2292#if !Q0165_NUM_ADD_OUTPUT_LAYER_SETS
2293  if( numOutputLayerSets > 1 )
2294  {
2295#if P0295_DEFAULT_OUT_LAYER_IDC
2296    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_target_output_layer_idc" );   
2297#else
2298#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
2299    WRITE_CODE( vps->getDefaultOneTargetOutputLayerIdc(), 2, "default_one_target_output_layer_idc" );   
2300#else
2301    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
2302#endif
2303#endif
2304  }
2305#endif
2306
2307  for(i = 1; i < numOutputLayerSets; i++)
2308  {
2309    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx(i);
2310    if( i > (vps->getNumLayerSets() - 1) )
2311    {
2312      Int numBits = 1;
2313      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
2314      {
2315        numBits++;
2316      }
2317      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "layer_set_idx_for_ols_minus1"); 
2318#if P0295_DEFAULT_OUT_LAYER_IDC
2319    }
2320#if Q0078_ADD_LAYER_SETS
2321    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
2322#else
2323    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
2324#endif
2325    {
2326#endif
2327#if NUM_OL_FLAGS
2328      for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
2329#else
2330      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
2331#endif
2332      {
2333        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
2334      }
2335    }
2336#if PER_LAYER_PTL
2337    for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
2338    {
2339      if( vps->getNecessaryLayerFlag(i, j) )
2340      {
2341        WRITE_CODE( vps->getProfileLevelTierIdx(i, j), numBitsForPtlIdx, "profile_level_tier_idx[i]" );
2342      }
2343    }
2344#else
2345    Int numBits = 1;
2346    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
2347    {
2348      numBits++;
2349    }
2350    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
2351#endif
2352#if P0300_ALT_OUTPUT_LAYER_FLAG
2353    NumOutputLayersInOutputLayerSet[i] = 0;
2354    for (j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
2355    {
2356      NumOutputLayersInOutputLayerSet[i] += vps->getOutputLayerFlag(i, j);
2357      if (vps->getOutputLayerFlag(i, j))
2358      {
2359        OlsHighestOutputLayerId[i] = vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j);
2360      }
2361    }
2362    if (NumOutputLayersInOutputLayerSet[i] == 1 && vps->getNumDirectRefLayers(OlsHighestOutputLayerId[i]) > 0)
2363    {
2364      WRITE_FLAG(vps->getAltOuputLayerFlag(i), "alt_output_layer_flag[i]");
2365    }
2366
2367#if Q0165_OUTPUT_LAYER_SET
2368    assert( NumOutputLayersInOutputLayerSet[i]>0 );
2369#endif
2370
2371#endif
2372  }
2373
2374#if !P0300_ALT_OUTPUT_LAYER_FLAG
2375#if O0153_ALT_OUTPUT_LAYER_FLAG
2376  if( vps->getMaxLayers() > 1 )
2377  {
2378    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
2379  }
2380#endif
2381#endif
2382
2383#if REPN_FORMAT_IN_VPS
2384#if Q0195_REP_FORMAT_CLEANUP 
2385  // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
2386  assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
2387 
2388  WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
2389
2390  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
2391  {
2392    // Write rep_format_structures
2393    codeRepFormat( vps->getVpsRepFormat(i) );
2394  }
2395
2396  if( vps->getVpsNumRepFormats() > 1 )
2397  {
2398    WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
2399  }
2400  else
2401  {
2402    // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
2403    assert( !vps->getRepFormatIdxPresentFlag() );
2404  }
2405
2406  if( vps->getRepFormatIdxPresentFlag() )
2407  {
2408    for(i = 1; i < vps->getMaxLayers(); i++)
2409    {
2410      Int numBits = 1;
2411      while ((1 << numBits) < (vps->getVpsNumRepFormats()))
2412      {
2413        numBits++;
2414      }
2415      WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
2416    }
2417  }
2418#else
2419  WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
2420
2421  if( vps->getRepFormatIdxPresentFlag() )
2422  {
2423    // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
2424    assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
2425
2426#if O0096_REP_FORMAT_INDEX
2427#if !VPS_EXTN_UEV_CODING
2428    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
2429#else
2430    WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
2431#endif
2432#else
2433    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
2434#endif
2435  }
2436  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
2437  {
2438    // Read rep_format_structures
2439    codeRepFormat( vps->getVpsRepFormat(i) );
2440  }
2441 
2442  if( vps->getRepFormatIdxPresentFlag() )
2443  {
2444    for(i = 1; i < vps->getMaxLayers(); i++)
2445    {
2446      if( vps->getVpsNumRepFormats() > 1 )
2447      {
2448#if O0096_REP_FORMAT_INDEX
2449#if !VPS_EXTN_UEV_CODING
2450        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
2451#else
2452        Int numBits = 1;
2453        while ((1 << numBits) < (vps->getVpsNumRepFormats()))
2454        {
2455          numBits++;
2456        }
2457        WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
2458#endif
2459#else
2460        WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
2461#endif
2462      }
2463    }
2464  }
2465#endif
2466#endif
2467
2468  WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
2469#if P0297_VPS_POC_LSB_ALIGNED_FLAG
2470  WRITE_FLAG(vps->getVpsPocLsbAlignedFlag(), "vps_poc_lsb_aligned_flag");
2471#endif
2472#if O0062_POC_LSB_NOT_PRESENT_FLAG
2473  for(i = 1; i< vps->getMaxLayers(); i++)
2474  {
2475    if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
2476    {
2477      WRITE_FLAG(vps->getPocLsbNotPresentFlag(i), "poc_lsb_not_present_flag[i]");
2478    }
2479  }
2480#endif
2481#if O0215_PHASE_ALIGNMENT
2482  WRITE_FLAG(vps->getPhaseAlignFlag(), "cross_layer_phase_alignment_flag" );
2483#endif
2484#if !IRAP_ALIGN_FLAG_IN_VPS_VUI
2485  WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
2486#endif
2487#if VPS_DPB_SIZE_TABLE
2488  codeVpsDpbSizeTable(vps);
2489#endif
2490#if VPS_EXTN_DIRECT_REF_LAYERS
2491  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
2492#if O0096_DEFAULT_DEPENDENCY_TYPE
2493  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
2494  if (vps->getDefaultDirectDependencyTypeFlag())
2495  {
2496    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
2497  }
2498  else
2499  {
2500    for(i = 1; i < vps->getMaxLayers(); i++)
2501    {
2502      for(j = 0; j < i; j++)
2503      {
2504        if (vps->getDirectDependencyFlag(i, j))
2505        {
2506          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
2507        }
2508      }
2509    }
2510  }
2511#else
2512  for(i = 1; i < vps->getMaxLayers(); i++)
2513  {
2514    for(j = 0; j < i; j++)
2515    {
2516      if (vps->getDirectDependencyFlag(i, j))
2517      {
2518        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
2519      }
2520    }
2521  }
2522#endif
2523#endif
2524
2525#if !O0109_O0199_FLAGS_TO_VUI
2526#if M0040_ADAPTIVE_RESOLUTION_CHANGE
2527  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
2528#endif
2529#if HIGHER_LAYER_IRAP_SKIP_FLAG
2530  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
2531#endif
2532#endif
2533
2534#if P0307_VPS_NON_VUI_EXTENSION
2535  // The value of vps_non_vui_extension_length shall be in the range of 0 to 4096, inclusive.
2536  assert( vps->getVpsNonVuiExtLength() >= 0 && vps->getVpsNonVuiExtLength() <= 4096 );
2537
2538  WRITE_UVLC( vps->getVpsNonVuiExtLength(), "vps_non_vui_extension_length" );
2539#if P0307_VPS_NON_VUI_EXT_UPDATE
2540  for (i = 1; i <= vps->getVpsNonVuiExtLength(); i++)
2541  {
2542    WRITE_CODE(1, 8, "vps_non_vui_extension_data_byte");
2543  }
2544#else
2545  if ( vps->getVpsNonVuiExtLength() > 0 )
2546  {
2547    printf("\n\nUp to the current spec, the value of vps_non_vui_extension_length is supposed to be 0\n");
2548  }
2549#endif
2550#endif
2551
2552#if !O0109_MOVE_VPS_VUI_FLAG
2553  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
2554  if(1)   // Should be conditioned on the value of vps_vui_present_flag
2555  {
2556    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
2557    {
2558      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
2559    }
2560#if VPS_VUI_OFFSET
2561    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
2562    assert( vpsVuiOffsetValeInBits % 8 == 0 );
2563    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
2564#endif
2565    codeVPSVUI(vps); 
2566  }
2567#else
2568#if P0307_REMOVE_VPS_VUI_OFFSET
2569  vps->setVpsVuiPresentFlag(true);
2570  WRITE_FLAG( vps->getVpsVuiPresentFlag() ? 1 : 0,                     "vps_vui_present_flag" );
2571#endif
2572  if(vps->getVpsVuiPresentFlag())   // Should be conditioned on the value of vps_vui_present_flag
2573  {
2574    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
2575    {
2576      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
2577    }
2578#if !P0307_REMOVE_VPS_VUI_OFFSET
2579#if VPS_VUI_OFFSET
2580    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
2581    assert( vpsVuiOffsetValeInBits % 8 == 0 );
2582    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
2583#endif
2584#endif
2585    codeVPSVUI(vps); 
2586  }
2587#endif // 0109_MOVE_VPS_FLAG
2588}
2589
2590#if REPN_FORMAT_IN_VPS
2591Void  TEncCavlc::codeRepFormat( RepFormat *repFormat )
2592{
2593#if REPN_FORMAT_CONTROL_FLAG
2594  WRITE_CODE( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_vps_in_luma_samples" );   
2595  WRITE_CODE( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_vps_in_luma_samples" ); 
2596  WRITE_FLAG( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_present_flag" );
2597
2598  if( repFormat->getChromaAndBitDepthVpsPresentFlag() )
2599  {
2600    WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_vps_idc" );   
2601
2602    if( repFormat->getChromaFormatVpsIdc() == 3 )
2603    {
2604      WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_vps_flag" );     
2605    }
2606
2607    assert( repFormat->getBitDepthVpsLuma() >= 8 );
2608    assert( repFormat->getBitDepthVpsChroma() >= 8 );
2609    WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_vps_luma_minus8" );           
2610    WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_vps_chroma_minus8" );
2611  }
2612#else
2613  WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
2614 
2615  if( repFormat->getChromaFormatVpsIdc() == 3 )
2616  {
2617    WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");     
2618  }
2619
2620  WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );   
2621  WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );   
2622 
2623  assert( repFormat->getBitDepthVpsLuma() >= 8 );
2624  assert( repFormat->getBitDepthVpsChroma() >= 8 );
2625  WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
2626  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
2627#endif
2628
2629#if R0156_CONF_WINDOW_IN_REP_FORMAT
2630  Window conf = repFormat->getConformanceWindowVps();
2631
2632  WRITE_FLAG( conf.getWindowEnabledFlag(),    "conformance_window_vps_flag" );
2633  if (conf.getWindowEnabledFlag())
2634  {
2635    WRITE_UVLC( conf.getWindowLeftOffset(),   "conf_win_vps_left_offset"   );
2636    WRITE_UVLC( conf.getWindowRightOffset(),  "conf_win_vps_right_offset"  );
2637    WRITE_UVLC( conf.getWindowTopOffset(),    "conf_win_vps_top_offset"    );
2638    WRITE_UVLC( conf.getWindowBottomOffset(), "conf_win_vps_bottom_offset" );
2639  }
2640#endif
2641}
2642#endif
2643#if VPS_DPB_SIZE_TABLE
2644Void TEncCavlc::codeVpsDpbSizeTable(TComVPS *vps)
2645{
2646#if !SUB_LAYERS_IN_LAYER_SET  // MaxSLInLayerSets calculated earlier in the encoder
2647#if DPB_PARAMS_MAXTLAYERS
2648#if BITRATE_PICRATE_SIGNALLING
2649    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumLayerSets()];
2650    for(Int i = 0; i < vps->getNumLayerSets(); i++)
2651#else
2652    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumOutputLayerSets()];
2653    for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
2654#endif
2655    {
2656        UInt maxSLMinus1 = 0;
2657#if CHANGE_NUMSUBDPB_IDX
2658        Int optLsIdx = vps->getOutputLayerSetIdx( i );
2659#else
2660        Int optLsIdx = i;
2661#endif
2662#if BITRATE_PICRATE_SIGNALLING
2663        optLsIdx = i;
2664#endif
2665        for(Int k = 0; k < vps->getNumLayersInIdList(optLsIdx); k++ ) {
2666            Int  lId = vps->getLayerSetLayerIdList(optLsIdx, k);
2667            maxSLMinus1 = max(maxSLMinus1, vps->getMaxTSLayersMinus1(vps->getLayerIdInVps(lId)));
2668        }
2669        MaxSubLayersInLayerSetMinus1[ i ] = maxSLMinus1;
2670#if BITRATE_PICRATE_SIGNALLING
2671        vps->setMaxSLayersInLayerSetMinus1(i,MaxSubLayersInLayerSetMinus1[ i ]);
2672#endif
2673    }
2674#endif
2675#endif
2676   
2677   
2678  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
2679  {
2680#if CHANGE_NUMSUBDPB_IDX
2681    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
2682#endif
2683    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]");
2684#if SUB_LAYERS_IN_LAYER_SET
2685    for(Int j = 0; j <= vps->getMaxSLayersInLayerSetMinus1( layerSetIdxForOutputLayerSet ); j++)
2686#else
2687#if DPB_PARAMS_MAXTLAYERS
2688#if BITRATE_PICRATE_SIGNALLING
2689    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ vps->getOutputLayerSetIdx( i ) ]; j++)
2690#else
2691    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ i ]; j++)
2692#endif
2693#else
2694    for(Int j = 0; j < vps->getMaxTLayers(); j++)
2695#endif
2696#endif
2697    {
2698      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
2699      {
2700        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]"); 
2701      }
2702      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
2703      {
2704#if CHANGE_NUMSUBDPB_IDX
2705#if RESOLUTION_BASED_DPB
2706        for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
2707#else
2708        for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
2709#endif
2710#else
2711        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
2712#endif
2713        {
2714#if DPB_INTERNAL_BL_SIG
2715        if(vps->getBaseLayerInternalFlag()  || ( vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k)   !=  0 ) )
2716#endif
2717          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j), "max_vps_dec_pic_buffering_minus1[i][k][j]" );
2718        }
2719        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );             
2720#if RESOLUTION_BASED_DPB
2721        if( vps->getNumSubDpbs(layerSetIdxForOutputLayerSet) != vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ) )  // NumSubDpbs
2722        {
2723          for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
2724          {
2725            WRITE_UVLC( vps->getMaxVpsLayerDecPicBuffMinus1( i, k, j), "max_vps_layer_dec_pic_buff_minus1[i][k][j]" );
2726          }
2727        }
2728#endif
2729        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );       
2730      }
2731    }
2732  }
2733
2734#if !SUB_LAYERS_IN_LAYER_SET
2735#if BITRATE_PICRATE_SIGNALLING
2736  if( MaxSubLayersInLayerSetMinus1 )
2737  {
2738    delete [] MaxSubLayersInLayerSetMinus1;
2739  }
2740#endif
2741#endif
2742}
2743#endif
2744
2745Void TEncCavlc::codeVPSVUI (TComVPS *vps)
2746{
2747  Int i,j;
2748#if O0223_PICTURE_TYPES_ALIGN_FLAG
2749  WRITE_FLAG(vps->getCrossLayerPictureTypeAlignFlag(), "cross_layer_pic_type_aligned_flag");
2750  if (!vps->getCrossLayerPictureTypeAlignFlag())
2751  {
2752#endif
2753#if IRAP_ALIGN_FLAG_IN_VPS_VUI
2754    WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
2755#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
2756    if(vps->getCrossLayerIrapAlignFlag())
2757    {
2758       WRITE_FLAG(vps->getCrossLayerAlignedIdrOnlyFlag(), "all_layers_idr_aligned_flag");
2759    }
2760#endif
2761#endif
2762#if O0223_PICTURE_TYPES_ALIGN_FLAG
2763  }
2764#endif
2765  WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
2766  WRITE_FLAG( vps->getPicRatePresentVpsFlag(),        "pic_rate_present_vps_flag" );
2767
2768  if( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
2769  {
2770#if Q0078_ADD_LAYER_SETS
2771#if R0227_BR_PR_ADD_LAYER_SET
2772#if SIGNALLING_BITRATE_PICRATE_FIX
2773    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getNumLayerSets(); i++ )
2774#else
2775    for( i = 0; i < vps->getNumLayerSets(); i++ )
2776#endif
2777#else
2778    for( i = 0; i <= vps->getVpsNumLayerSetsMinus1(); i++ )
2779#endif
2780#else
2781    for( i = 0; i < vps->getNumLayerSets(); i++ )
2782#endif
2783    {
2784#if BITRATE_PICRATE_SIGNALLING
2785      for( j = 0; j <= vps->getMaxSLayersInLayerSetMinus1(i); j++ )
2786#else
2787      for( j = 0; j < vps->getMaxTLayers(); j++ )
2788#endif
2789      {
2790        if( vps->getBitRatePresentVpsFlag() )
2791        {
2792          WRITE_FLAG( vps->getBitRatePresentFlag( i, j),        "bit_rate_present_flag[i][j]" );
2793        }
2794        if( vps->getPicRatePresentVpsFlag() )
2795        {
2796          WRITE_FLAG( vps->getPicRatePresentFlag( i, j),        "pic_rate_present_flag[i][j]" );
2797        }
2798        if( vps->getBitRatePresentFlag(i, j) )
2799        {
2800          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "avg_bit_rate[i][j]" );
2801          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "max_bit_rate[i][j]" );
2802        }
2803        if( vps->getPicRatePresentFlag(i, j) )
2804        {
2805          WRITE_CODE( vps->getConstPicRateIdc( i, j), 2 , "constant_pic_rate_idc[i][j]" ); 
2806          WRITE_CODE( vps->getConstPicRateIdc( i, j), 16, "avg_pic_rate[i][j]"          ); 
2807        }
2808      }
2809    }
2810  }
2811#if VPS_VUI_VIDEO_SIGNAL_MOVE
2812  WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
2813  if (vps->getVideoSigPresentVpsFlag())
2814  {
2815    WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
2816  }
2817
2818  for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
2819  {
2820    WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
2821    WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
2822    WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
2823    WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
2824    WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
2825  }
2826
2827  if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
2828  {
2829#if VPS_VUI_VST_PARAMS
2830    for(i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
2831    {
2832      WRITE_CODE( vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
2833    }
2834#else
2835    for (i=1; i < vps->getMaxLayers(); i++)
2836      WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
2837#endif
2838  }
2839#endif
2840#if VPS_VUI_TILES_NOT_IN_USE__FLAG
2841  UInt layerIdx;
2842  WRITE_FLAG( vps->getTilesNotInUseFlag() ? 1 : 0 , "tiles_not_in_use_flag" );
2843  if (!vps->getTilesNotInUseFlag())
2844  {
2845    for(i = 0; i < vps->getMaxLayers(); i++)
2846    {
2847      WRITE_FLAG( vps->getTilesInUseFlag(i) ? 1 : 0 , "tiles_in_use_flag[ i ]" );
2848      if (vps->getTilesInUseFlag(i))
2849      {
2850        WRITE_FLAG( vps->getLoopFilterNotAcrossTilesFlag(i) ? 1 : 0 , "loop_filter_not_across_tiles_flag[ i ]" );
2851      }
2852    }
2853#endif
2854
2855    for(i = 1; i < vps->getMaxLayers(); i++)
2856    {
2857      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
2858      {
2859#if VPS_VUI_TILES_NOT_IN_USE__FLAG
2860        layerIdx = vps->getLayerIdInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
2861        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
2862          WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
2863        }
2864#else
2865        WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
2866#endif
2867      }
2868    } 
2869#if VPS_VUI_TILES_NOT_IN_USE__FLAG
2870  }
2871#endif
2872#if VPS_VUI_WPP_NOT_IN_USE__FLAG
2873  WRITE_FLAG( vps->getWppNotInUseFlag() ? 1 : 0 , "wpp_not_in_use_flag" );
2874  if (!vps->getWppNotInUseFlag())
2875  {
2876    for(i = 0; i < vps->getMaxLayers(); i++)
2877    {
2878      WRITE_FLAG( vps->getWppInUseFlag(i) ? 1 : 0 , "wpp_in_use_flag[ i ]" );
2879    }
2880  }
2881#endif
2882
2883#if O0109_O0199_FLAGS_TO_VUI
2884#if M0040_ADAPTIVE_RESOLUTION_CHANGE
2885  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
2886#endif
2887#if HIGHER_LAYER_IRAP_SKIP_FLAG
2888  // When single_layer_for_non_irap_flag is equal to 0, higher_layer_irap_skip_flag shall be equal to 0
2889  if( !vps->getSingleLayerForNonIrapFlag() )
2890  {
2891    assert( !vps->getHigherLayerIrapSkipFlag() );
2892  }
2893
2894  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
2895#endif
2896#endif
2897#if P0312_VERT_PHASE_ADJ
2898  WRITE_FLAG( vps->getVpsVuiVertPhaseInUseFlag(), "vps_vui_vert_phase_in_use_flag" );
2899#endif
2900#if N0160_VUI_EXT_ILP_REF
2901  WRITE_FLAG( vps->getIlpRestrictedRefLayersFlag() ? 1 : 0 , "ilp_restricted_ref_layers_flag" );   
2902  if( vps->getIlpRestrictedRefLayersFlag())
2903  {
2904    for(i = 1; i < vps->getMaxLayers(); i++)
2905    {
2906      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
2907      {       
2908        WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
2909       
2910        if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
2911        { 
2912          WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );   
2913         
2914          if(vps->getCtuBasedOffsetEnabledFlag(i,j)) 
2915          {
2916            WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");           
2917          }
2918        } 
2919      } 
2920    }
2921  }
2922#endif
2923#if VPS_VUI_VIDEO_SIGNAL
2924#if VPS_VUI_VIDEO_SIGNAL_MOVE
2925#else
2926    WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
2927    if (vps->getVideoSigPresentVpsFlag())
2928    {
2929        WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
2930    }
2931   
2932    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
2933    {
2934        WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
2935        WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
2936        WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
2937        WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
2938        WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
2939    }
2940   
2941    if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
2942    {
2943        for (i=1; i < vps->getMaxLayers(); i++)
2944            WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
2945    }
2946#endif
2947#endif
2948#if O0164_MULTI_LAYER_HRD
2949    WRITE_FLAG(vps->getVpsVuiBspHrdPresentFlag(), "vps_vui_bsp_hrd_present_flag" );
2950    if (vps->getVpsVuiBspHrdPresentFlag())
2951    {
2952#if VPS_VUI_BSP_HRD_PARAMS
2953      codeVpsVuiBspHrdParams(vps);
2954#else
2955      WRITE_UVLC( vps->getVpsNumBspHrdParametersMinus1(), "vps_num_bsp_hrd_parameters_minus1" );
2956      for( i = 0; i <= vps->getVpsNumBspHrdParametersMinus1(); i++ )
2957      {
2958        if( i > 0 )
2959        {
2960          WRITE_FLAG( vps->getBspCprmsPresentFlag(i), "bsp_cprms_present_flag[i]" );
2961        }
2962        codeHrdParameters(vps->getBspHrd(i), i==0 ? 1 : vps->getBspCprmsPresentFlag(i), vps->getMaxTLayers()-1);
2963      }
2964#if Q0078_ADD_LAYER_SETS
2965      for( UInt h = 1; h <= vps->getVpsNumLayerSetsMinus1(); h++ )
2966#else
2967      for( UInt h = 1; h <= (vps->getNumLayerSets()-1); h++ )
2968#endif
2969      {
2970        WRITE_UVLC( vps->getNumBitstreamPartitions(h), "num_bitstream_partitions[i]");
2971        for( i = 0; i < vps->getNumBitstreamPartitions(h); i++ )
2972        {
2973          for( j = 0; j <= (vps->getMaxLayers()-1); j++ )
2974          {
2975            if (vps->getLayerIdIncludedFlag(h, j))
2976            {
2977              WRITE_FLAG( vps->getLayerInBspFlag(h, i, j), "layer_in_bsp_flag[h][i][j]" );
2978            }
2979          }
2980        }
2981        if (vps->getNumBitstreamPartitions(h))
2982        {
2983#if Q0182_MULTI_LAYER_HRD_UPDATE
2984          WRITE_UVLC(vps->getNumBspSchedCombinations(h) - 1, "num_bsp_sched_combinations_minus1[h]");
2985#else
2986          WRITE_UVLC( vps->getNumBspSchedCombinations(h), "num_bsp_sched_combinations[h]");
2987#endif
2988          for( i = 0; i < vps->getNumBspSchedCombinations(h); i++ )
2989          {
2990            for( j = 0; j < vps->getNumBitstreamPartitions(h); j++ )
2991            {
2992              WRITE_UVLC( vps->getBspCombHrdIdx(h, i, j), "bsp_comb_hrd_idx[h][i][j]");
2993              WRITE_UVLC( vps->getBspCombSchedIdx(h, i, j), "bsp_comb_sched_idx[h][i][j]");
2994            }
2995          }
2996        }
2997      }
2998#endif
2999    }
3000#endif
3001#if P0182_VPS_VUI_PS_FLAG
3002    for(i = 1; i < vps->getMaxLayers(); i++)
3003    {
3004      if( vps->getNumRefLayers(vps->getLayerIdInNuh(i)) == 0 ) 
3005      {
3006        if( (vps->getSPSId(i) == 0) && (vps->getPPSId(i) == 0) )
3007        {
3008          vps->setBaseLayerPSCompatibilityFlag(i, 1);
3009        }
3010        else
3011        {
3012          vps->setBaseLayerPSCompatibilityFlag(i, 0);
3013        }
3014        WRITE_FLAG(vps->getBaseLayerPSCompatibilityFlag(i), "base_layer_parameter_set_compatibility_flag" );
3015      }
3016    }
3017#endif
3018}
3019
3020Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
3021{
3022  // more syntax elements to be written here
3023
3024  // Vertical MV component restriction is not used in SHVC CTC
3025  WRITE_FLAG( 0, "inter_view_mv_vert_constraint_flag" );
3026
3027#if !MOVE_SCALED_OFFSET_TO_PPS
3028  if( pcSPS->getLayerId() > 0 )
3029  {
3030    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
3031    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
3032    {
3033      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
3034#if O0098_SCALED_REF_LAYER_ID
3035      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
3036#endif
3037      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
3038      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
3039      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
3040      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
3041#if P0312_VERT_PHASE_ADJ
3042      WRITE_FLAG( scaledWindow.getVertPhasePositionEnableFlag(), "vert_phase_position_enable_flag" ); 
3043#endif
3044    }
3045  }
3046#endif
3047}
3048#endif //SVC_EXTENSION
3049
3050#if Q0048_CGS_3D_ASYMLUT
3051Void TEncCavlc::xCode3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT )
3052{
3053#if R0150_CGS_SIGNAL_CONSTRAINTS
3054  UInt uiNumRefLayers = ( UInt )pc3DAsymLUT->getRefLayerNum();
3055  WRITE_UVLC( uiNumRefLayers - 1 , "num_cm_ref_layers_minus1" );
3056  for( UInt i = 0 ; i < uiNumRefLayers ; i++ )
3057  {
3058    WRITE_CODE( pc3DAsymLUT->getRefLayerId( i ) , 6 , "cm_ref_layer_id" );
3059  }
3060#endif
3061  assert( pc3DAsymLUT->getCurOctantDepth() < 4 );
3062  WRITE_CODE( pc3DAsymLUT->getCurOctantDepth() , 2 , "cm_octant_depth" );
3063  assert( pc3DAsymLUT->getCurYPartNumLog2() < 4 );
3064  WRITE_CODE( pc3DAsymLUT->getCurYPartNumLog2() , 2 , "cm_y_part_num_log2" );
3065  assert( pc3DAsymLUT->getInputBitDepthY() < 16 );
3066#if R0150_CGS_SIGNAL_CONSTRAINTS
3067  WRITE_UVLC( pc3DAsymLUT->getInputBitDepthY() - 8 , "cm_input_luma_bit_depth_minus8" );
3068  WRITE_UVLC( pc3DAsymLUT->getInputBitDepthC() - 8 , "cm_input_chroma_bit_depth_minus8" );
3069  WRITE_UVLC( pc3DAsymLUT->getOutputBitDepthY() - 8 , "cm_output_luma_bit_depth_minus8" );
3070  WRITE_UVLC( pc3DAsymLUT->getOutputBitDepthC() - 8 , "cm_output_chroma_bit_depth_minus8" );
3071#else
3072  WRITE_CODE( pc3DAsymLUT->getInputBitDepthY() - 8 , 3 , "cm_input_bit_depth_minus8" );
3073  WRITE_SVLC(pc3DAsymLUT->getInputBitDepthC()-pc3DAsymLUT->getInputBitDepthY(), "cm_input_bit_depth_chroma delta");
3074  assert( pc3DAsymLUT->getOutputBitDepthY() < 16 );
3075  WRITE_CODE( pc3DAsymLUT->getOutputBitDepthY() - 8 , 3 , "cm_output_bit_depth_minus8" );
3076  WRITE_SVLC(pc3DAsymLUT->getOutputBitDepthC()-pc3DAsymLUT->getOutputBitDepthY(), "cm_output_bit_depth_chroma_delta");
3077#endif
3078  assert( pc3DAsymLUT->getResQuantBit() < 4 );
3079  WRITE_CODE( pc3DAsymLUT->getResQuantBit() , 2 , "cm_res_quant_bit" );
3080#if R0300_CGS_RES_COEFF_CODING
3081  xFindDeltaBits( pc3DAsymLUT );
3082  assert(pc3DAsymLUT->getDeltaBits() >=1 && pc3DAsymLUT->getDeltaBits() <= 4);
3083  WRITE_CODE( pc3DAsymLUT->getDeltaBits()-1 , 2 , "cm_delta_bit" );
3084#endif
3085#if R0151_CGS_3D_ASYMLUT_IMPROVE
3086  if( pc3DAsymLUT->getCurOctantDepth() == 1 )
3087  {
3088    WRITE_SVLC( pc3DAsymLUT->getAdaptChromaThresholdU() - ( 1 << ( pc3DAsymLUT->getInputBitDepthC() - 1 ) ) , "cm_adapt_threshold_u_delta" );
3089    WRITE_SVLC( pc3DAsymLUT->getAdaptChromaThresholdV() - ( 1 << ( pc3DAsymLUT->getInputBitDepthC() - 1 ) ) , "cm_adapt_threshold_v_delta" );
3090  }
3091#endif
3092
3093#if R0164_CGS_LUT_BUGFIX_CHECK
3094  pc3DAsymLUT->xInitCuboids();
3095#endif
3096  xCode3DAsymLUTOctant( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth() );
3097#if R0164_CGS_LUT_BUGFIX_CHECK
3098  xCuboidsFilledCheck( false );
3099  pc3DAsymLUT->display( false );
3100#endif
3101}
3102
3103Void TEncCavlc::xCode3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength )
3104{
3105  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
3106  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
3107    WRITE_FLAG( uiOctantSplit , "split_octant_flag" );
3108  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
3109  if( uiOctantSplit )
3110  {
3111    Int nHalfLength = nLength >> 1;
3112    for( Int l = 0 ; l < 2 ; l++ )
3113    {
3114      for( Int m = 0 ; m < 2 ; m++ )
3115      {
3116        for( Int n = 0 ; n < 2 ; n++ )
3117        {
3118          xCode3DAsymLUTOctant( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength );
3119        }
3120      }
3121    }
3122  }
3123  else
3124  {
3125#if R0300_CGS_RES_COEFF_CODING
3126    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-pc3DAsymLUT->getDeltaBits() ; 
3127    nFLCbits = nFLCbits >= 0 ? nFLCbits : 0;
3128#endif
3129    for( Int l = 0 ; l < nYPartNum ; l++ )
3130    {
3131#if R0164_CGS_LUT_BUGFIX     
3132      Int shift = pc3DAsymLUT->getCurOctantDepth() - nDepth ;
3133#endif
3134      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
3135      {
3136#if R0164_CGS_LUT_BUGFIX
3137        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + (l<<shift) , uIdx , vIdx , nVertexIdx );
3138#else
3139        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
3140#endif
3141        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
3142        WRITE_FLAG( uiCodeVertex , "coded_vertex_flag" );
3143        if( uiCodeVertex )
3144        {
3145#if R0151_CGS_3D_ASYMLUT_IMPROVE
3146#if R0300_CGS_RES_COEFF_CODING
3147          xWriteParam( sRes.Y, nFLCbits );
3148          xWriteParam( sRes.U, nFLCbits );
3149          xWriteParam( sRes.V, nFLCbits );
3150#else
3151          xWriteParam( sRes.Y );
3152          xWriteParam( sRes.U );
3153          xWriteParam( sRes.V );
3154#endif
3155#else
3156          WRITE_SVLC( sRes.Y , "resY" );
3157          WRITE_SVLC( sRes.U , "resU" );
3158          WRITE_SVLC( sRes.V , "resV" );
3159#endif
3160        }
3161      }
3162#if R0164_CGS_LUT_BUGFIX_CHECK
3163      pc3DAsymLUT->xSetExplicit( yIdx + (l<<shift) , uIdx , vIdx );
3164#endif
3165    }
3166  }
3167}
3168
3169#if R0151_CGS_3D_ASYMLUT_IMPROVE
3170#if R0300_CGS_RES_COEFF_CODING
3171Void TEncCavlc::xWriteParam( Int param, UInt rParam)
3172#else
3173Void TEncCavlc::xWriteParam( Int param)
3174#endif
3175{
3176#if !R0300_CGS_RES_COEFF_CODING
3177  const UInt rParam = 7;
3178#endif
3179  Int codeNumber = abs(param);
3180  WRITE_UVLC(codeNumber / (1 << rParam), "quotient");
3181  WRITE_CODE((codeNumber % (1 << rParam)), rParam, "remainder");
3182  if (abs(param))
3183    WRITE_FLAG( param <0, "sign");
3184}
3185#endif
3186
3187#if R0300_CGS_RES_COEFF_CODING
3188Void TEncCavlc::xFindDeltaBits( TCom3DAsymLUT * pc3DAsymLUT )
3189{
3190  Int nDeltaBits; 
3191  Int nBestDeltaBits = -1; 
3192  Int nBestBits = MAX_INT; 
3193  for( nDeltaBits = 1; nDeltaBits < 5; nDeltaBits++)
3194  {
3195    Int nCurBits = 0;
3196    xTally3DAsymLUTOctantBits( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth(), nDeltaBits, nCurBits );
3197    //printf("%d, %d, %d\n", nDeltaBits, nCurBits, nBestBits);
3198    if(nCurBits < nBestBits)
3199    {
3200      nBestDeltaBits = nDeltaBits; 
3201      nBestBits = nCurBits;
3202    }
3203  }
3204
3205  assert(nBestDeltaBits >=1 && nBestDeltaBits < 5);
3206  pc3DAsymLUT->setDeltaBits(nBestDeltaBits); 
3207}
3208
3209Void TEncCavlc::xTally3DAsymLUTOctantBits( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength, Int nDeltaBits, Int& nCurBits )
3210{
3211  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
3212  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
3213    nCurBits ++; 
3214  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
3215  if( uiOctantSplit )
3216  {
3217    Int nHalfLength = nLength >> 1;
3218    for( Int l = 0 ; l < 2 ; l++ )
3219    {
3220      for( Int m = 0 ; m < 2 ; m++ )
3221      {
3222        for( Int n = 0 ; n < 2 ; n++ )
3223        {
3224          xTally3DAsymLUTOctantBits( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength, nDeltaBits, nCurBits );
3225        }
3226      }
3227    }
3228  }
3229  else
3230  {
3231    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-nDeltaBits ; 
3232    nFLCbits = nFLCbits >= 0 ? nFLCbits:0;
3233    //printf("nFLCbits = %d\n", nFLCbits);
3234
3235    for( Int l = 0 ; l < nYPartNum ; l++ )
3236    {
3237      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
3238      {
3239        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
3240
3241        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
3242        nCurBits++;
3243        if( uiCodeVertex )
3244        {
3245          xCheckParamBits( sRes.Y, nFLCbits, nCurBits );
3246          xCheckParamBits( sRes.U, nFLCbits, nCurBits );
3247          xCheckParamBits( sRes.V, nFLCbits, nCurBits );
3248        }
3249      }
3250    }
3251  }
3252}
3253
3254Void TEncCavlc::xCheckParamBits( Int param, Int rParam, Int &nBits)
3255{
3256  Int codeNumber = abs(param);
3257  Int codeQuotient = codeNumber >> rParam;
3258  Int qLen; 
3259
3260  UInt uiLength = 1;
3261  UInt uiTemp = ++codeQuotient;
3262   
3263  while( 1 != uiTemp )
3264  {
3265    uiTemp >>= 1;
3266    uiLength += 2;
3267  }
3268
3269  qLen  = (uiLength >> 1);
3270  qLen += ((uiLength+1) >> 1);
3271
3272  nBits += qLen; 
3273  nBits += rParam; 
3274  if (abs(param))
3275    nBits++; 
3276}
3277#endif
3278#if VPS_VUI_BSP_HRD_PARAMS
3279Void TEncCavlc::codeVpsVuiBspHrdParams(TComVPS * const vps)
3280{
3281  WRITE_UVLC( vps->getVpsNumAddHrdParams(), "vps_num_add_hrd_params" );
3282  for( Int i = vps->getNumHrdParameters(), j = 0; i < vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams(); i++, j++ ) // j = i - vps->getNumHrdParameters()
3283  {
3284    if( i > 0 )
3285    {
3286      WRITE_FLAG( vps->getCprmsAddPresentFlag(j), "cprms_add_present_flag[i]" );
3287    }
3288    WRITE_UVLC( vps->getNumSubLayerHrdMinus1(j), "num_sub_layer_hrd_minus1[i]" );
3289    codeHrdParameters(vps->getBspHrd(j), i == 0 ? true : vps->getCprmsAddPresentFlag(j), vps->getNumSubLayerHrdMinus1(j));
3290  }
3291  for( Int h = 1; h < vps->getNumOutputLayerSets(); h++ )
3292  {
3293    Int lsIdx = vps->getOutputLayerSetIdx( h );
3294    WRITE_UVLC( vps->getNumSignalledPartitioningSchemes(h), "num_signalled_partitioning_schemes[h]");
3295    for( Int j = 0; j < vps->getNumSignalledPartitioningSchemes(h); j++ )
3296    {
3297      WRITE_UVLC( vps->getNumPartitionsInSchemeMinus1(h, j), "num_partitions_in_scheme_minus1[h][j]" );
3298      for( Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, j); k++ )
3299      {
3300        for( Int r = 0; r < vps->getNumLayersInIdList( lsIdx ); r++ )
3301        {
3302          WRITE_FLAG( vps->getLayerIncludedInPartitionFlag(h, j, k, r), "layer_included_in_partition_flag[h][j][k][r]" );
3303        }
3304      }
3305    }
3306    for( Int i = 0; i < vps->getNumSignalledPartitioningSchemes(h) + 1; i++ )
3307    {
3308      for( Int t = 0; t <= vps->getMaxSLayersInLayerSetMinus1(lsIdx); t++ )
3309      {
3310        WRITE_UVLC(vps->getNumBspSchedulesMinus1(h, i, t), "num_bsp_schedules_minus1[h][i][t]");
3311        for( Int j = 0; j <= vps->getNumBspSchedulesMinus1(h, i, t); j++ )
3312        {
3313          for( Int k = 0; k < vps->getNumPartitionsInSchemeMinus1(h, i); k++ )
3314          {
3315            WRITE_UVLC( vps->getBspHrdIdx(h, i, t, j, k),   "bsp_comb_hrd_idx[h][i][t][j][k]");
3316            WRITE_UVLC( vps->getBspSchedIdx(h, i, t, j, k), "bsp_comb_sched_idx[h][i][t][j][k]");
3317          }
3318        }
3319      }
3320    }
3321  }
3322}
3323#endif
3324#endif
3325//! \}
Note: See TracBrowser for help on using the repository browser.