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

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

R0124, conformance check for vps_max_layers_minus1, provided by BYEONG-DOO CHOI <b.d.choi@…>

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