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

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

merge SHM-dev

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