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

Last change on this file since 915 was 908, checked in by nokia, 10 years ago

Fix layer sets layer id list initialization.

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