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

Last change on this file since 677 was 677, checked in by qualcomm, 12 years ago

Integration of JCTVC-Q0048 Asymmetric 3D LUT based CGS

  • Property svn:eol-style set to native
File size: 98.2 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->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
196    WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
197    WRITE_FLAG( pcPPS->getUniformSpacingFlag(),                                  "uniform_spacing_flag" );
198    if( pcPPS->getUniformSpacingFlag() == 0 )
199    {
200      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
201      {
202        WRITE_UVLC( pcPPS->getColumnWidth(i)-1,                                  "column_width_minus1" );
203      }
204      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
205      {
206        WRITE_UVLC( pcPPS->getRowHeight(i)-1,                                    "row_height_minus1" );
207      }
208    }
209    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=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 SCALINGLIST_INFERRING
228  if( pcPPS->getLayerId() > 0 )
229  {
230    WRITE_FLAG( pcPPS->getInferScalingListFlag() ? 1 : 0, "pps_infer_scaling_list_flag" );
231  }
232
233  if( pcPPS->getInferScalingListFlag() )
234  {
235    // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
236    assert( pcPPS->getScalingListRefLayerId() <= 62 );
237
238    WRITE_UVLC( pcPPS->getScalingListRefLayerId(), "pps_scaling_list_ref_layer_id" );
239  }
240  else
241  {
242#endif
243
244  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
245  if( pcPPS->getScalingListPresentFlag() )
246  {
247    codeScalingList( m_pcSlice->getScalingList() );
248  }
249
250#if SCALINGLIST_INFERRING
251  }
252#endif
253
254  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
255  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
256  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
257#if P0166_MODIFIED_PPS_EXTENSION
258  WRITE_FLAG( 1, "pps_extension_flag" );
259  if( 1 ) //pps_extension_flag
260  {
261#if !POC_RESET_IDC
262    UInt ppsExtensionTypeFlag[8] = { 0, 1, 0, 0, 0, 0, 0, 0 };
263#else
264    UInt ppsExtensionTypeFlag[8] = { 1, 0, 0, 0, 0, 0, 0, 0 };
265#endif
266    for (UInt i = 0; i < 8; i++)
267    {
268      WRITE_FLAG( ppsExtensionTypeFlag[i], "pps_extension_type_flag" );
269    }
270#if POC_RESET_IDC
271    if( ppsExtensionTypeFlag[0] )
272    {
273      WRITE_FLAG( pcPPS->getPocResetInfoPresentFlag() ? 1 : 0, "poc_reset_info_present_flag" );
274#if Q0048_CGS_3D_ASYMLUT
275      UInt uiPos = getNumberOfWrittenBits();
276      WRITE_FLAG( pcPPS->getCGSFlag() , "colour_mapping_enabled_flag" );
277      if( pcPPS->getCGSFlag() == Q0048_CGS_3D_ASYMLUT_PPSUPDATE )
278      {
279        assert( pc3DAsymLUT != NULL );
280        xCode3DAsymLUT( pc3DAsymLUT );
281      }
282      pc3DAsymLUT->setPPSBit( getNumberOfWrittenBits() - uiPos );
283#endif
284#endif
285    }
286  }
287#else
288  WRITE_FLAG( 0, "pps_extension_flag" );
289#endif
290}
291
292Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
293{
294#if ENC_DEC_TRACE
295  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
296#endif
297  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
298  if (pcVUI->getAspectRatioInfoPresentFlag())
299  {
300    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
301    if (pcVUI->getAspectRatioIdc() == 255)
302    {
303      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
304      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
305    }
306  }
307  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
308  if (pcVUI->getOverscanInfoPresentFlag())
309  {
310    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
311  }
312  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
313  if (pcVUI->getVideoSignalTypePresentFlag())
314  {
315    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
316    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
317    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
318    if (pcVUI->getColourDescriptionPresentFlag())
319    {
320      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
321      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
322      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
323    }
324  }
325
326  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
327  if (pcVUI->getChromaLocInfoPresentFlag())
328  {
329    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
330    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
331  }
332
333  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
334  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
335  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
336
337  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
338  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
339  if( defaultDisplayWindow.getWindowEnabledFlag() )
340  {
341    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset(),      "def_disp_win_left_offset");
342    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset(),     "def_disp_win_right_offset");
343    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset(),       "def_disp_win_top_offset");
344    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset(),    "def_disp_win_bottom_offset");
345  }
346  TimingInfo *timingInfo = pcVUI->getTimingInfo();
347  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
348  if(timingInfo->getTimingInfoPresentFlag())
349  {
350    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
351    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
352    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
353    if(timingInfo->getPocProportionalToTimingFlag())
354    {
355      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
356    }
357  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
358  if( pcVUI->getHrdParametersPresentFlag() )
359  {
360    codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
361  }
362  }
363
364  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
365  if (pcVUI->getBitstreamRestrictionFlag())
366  {
367    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
368    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
369    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
370    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
371    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
372    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
373    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
374    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
375  }
376}
377
378Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
379{
380  if( commonInfPresentFlag )
381  {
382    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
383    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
384    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
385    {
386      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
387      if( hrd->getSubPicCpbParamsPresentFlag() )
388      {
389        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
390        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
391        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
392        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
393      }
394      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
395      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
396      if( hrd->getSubPicCpbParamsPresentFlag() )
397      {
398        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" ); 
399      }
400      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
401      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
402      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
403    }
404  }
405  Int i, j, nalOrVcl;
406  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
407  {
408    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
409    if( !hrd->getFixedPicRateFlag( i ) )
410    {
411      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
412    }
413    else
414    {
415      hrd->setFixedPicRateWithinCvsFlag( i, true );
416    }
417    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
418    {
419      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
420    }
421    else
422    {
423      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
424    }
425    if (!hrd->getLowDelayHrdFlag( i ))
426    {
427      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
428    }
429   
430    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
431    {
432      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
433          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
434      {
435        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
436        {
437          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
438          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
439          if( hrd->getSubPicCpbParamsPresentFlag() )
440          {
441            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1"); 
442            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
443          }
444          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
445        }
446      }
447    }
448  }
449}
450
451Void TEncCavlc::codeSPS( TComSPS* pcSPS )
452{
453#if ENC_DEC_TRACE 
454  xTraceSPSHeader (pcSPS);
455#endif
456  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
457#if SVC_EXTENSION
458  if(pcSPS->getLayerId() == 0)
459  {
460#endif
461    WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
462    WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
463#if SVC_EXTENSION
464  }
465#endif
466#ifdef SPS_PTL_FIX
467  if (pcSPS->getLayerId() == 0)
468  {
469    codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
470  }
471#else
472  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
473#endif
474  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
475#if REPN_FORMAT_IN_VPS
476  if( pcSPS->getLayerId() > 0 )
477  {
478    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
479  }
480#if O0096_REP_FORMAT_INDEX
481  if( pcSPS->getLayerId() == 0 ) 
482#else
483  if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
484#endif
485  {
486#endif
487    WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
488    assert(pcSPS->getChromaFormatIdc () == 1);
489    // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
490    if( pcSPS->getChromaFormatIdc () == 3 )
491    {
492      WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
493    }
494
495    WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
496    WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
497#if REPN_FORMAT_IN_VPS
498  }
499#if O0096_REP_FORMAT_INDEX
500  else if (pcSPS->getUpdateRepFormatFlag())
501  {
502    WRITE_CODE( pcSPS->getUpdateRepFormatIndex(), 8,   "update_rep_format_index");
503  }
504#endif
505#endif
506  Window conf = pcSPS->getConformanceWindow();
507
508  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
509  if (conf.getWindowEnabledFlag())
510  {
511    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
512    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
513    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
514    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
515  }
516
517#if REPN_FORMAT_IN_VPS
518#if O0096_REP_FORMAT_INDEX
519  if( pcSPS->getLayerId() == 0 ) 
520#else
521  if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
522#endif 
523  {
524    assert( pcSPS->getBitDepthY() >= 8 );
525    assert( pcSPS->getBitDepthC() >= 8 );
526#endif
527    WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
528    WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
529#if REPN_FORMAT_IN_VPS
530  }
531#endif
532  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
533
534#if SPS_DPB_PARAMS
535  if( pcSPS->getLayerId() == 0 )
536  {
537#endif
538  const Bool subLayerOrderingInfoPresentFlag = 1;
539  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
540  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
541  {
542    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
543    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
544    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
545    if (!subLayerOrderingInfoPresentFlag)
546    {
547      break;
548    }
549  }
550#if SPS_DPB_PARAMS
551  }
552#endif
553  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
554 
555  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
556  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
557  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
558  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
559  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
560  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
561  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
562  if(pcSPS->getScalingListFlag())
563  {
564#if SCALINGLIST_INFERRING
565    if( pcSPS->getLayerId() > 0 )
566    {
567      WRITE_FLAG( pcSPS->getInferScalingListFlag() ? 1 : 0, "sps_infer_scaling_list_flag" );
568    }
569
570    if( pcSPS->getInferScalingListFlag() )
571    {
572      // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
573      assert( pcSPS->getScalingListRefLayerId() <= 62 );
574
575      WRITE_UVLC( pcSPS->getScalingListRefLayerId(), "sps_scaling_list_ref_layer_id" );
576    }
577    else
578    {
579#endif
580    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
581    if(pcSPS->getScalingListPresentFlag())
582    {
583      codeScalingList( m_pcSlice->getScalingList() );
584    }
585#if SCALINGLIST_INFERRING
586    }
587#endif
588  }
589  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
590  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
591
592  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
593  if( pcSPS->getUsePCM() )
594  {
595    WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,                                  "pcm_sample_bit_depth_luma_minus1" );
596    WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4,                                "pcm_sample_bit_depth_chroma_minus1" );
597    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
598    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
599    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
600  }
601
602  assert( pcSPS->getMaxTLayers() > 0 );         
603
604  TComRPSList* rpsList = pcSPS->getRPSList();
605  TComReferencePictureSet*      rps;
606 
607  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
608  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
609  {
610    rps = rpsList->getReferencePictureSet(i);
611    codeShortTermRefPicSet(pcSPS,rps,false, i);
612  }
613  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
614  if (pcSPS->getLongTermRefsPresent()) 
615  {
616    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
617    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
618    {
619      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
620      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
621    }
622  }
623  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
624
625  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
626
627  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
628  if (pcSPS->getVuiParametersPresentFlag())
629  {
630      codeVUI(pcSPS->getVuiParameters(), pcSPS);
631  }
632
633#if SPS_EXTENSION
634  WRITE_FLAG( 1, "sps_extension_flag" );
635  if( 1 )   // if( sps_extension_flag )
636  {
637#if O0142_CONDITIONAL_SPS_EXTENSION
638    UInt spsExtensionTypeFlag[8] = { 0, 1, 0, 0, 0, 0, 0, 0 };
639    for (UInt i = 0; i < 8; i++)
640    {
641      WRITE_FLAG( spsExtensionTypeFlag[i], "sps_extension_type_flag" );
642    }
643    if (spsExtensionTypeFlag[1])
644    {
645      codeSPSExtension( pcSPS );
646    }
647#else
648    codeSPSExtension( pcSPS );
649    WRITE_FLAG( 0, "sps_extension2_flag" );
650#endif
651  }
652#else
653  WRITE_FLAG( 0, "sps_extension_flag" );
654#endif
655}
656#if SPS_EXTENSION
657Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
658{
659  // more syntax elements to be written here
660
661  // Vertical MV component restriction is not used in SHVC CTC
662  WRITE_FLAG( 0, "inter_view_mv_vert_constraint_flag" );
663
664  if( pcSPS->getLayerId() > 0 )
665  {
666    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
667    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
668    {
669      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
670#if O0098_SCALED_REF_LAYER_ID
671      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
672#endif
673      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
674      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
675      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
676      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
677#if P0312_VERT_PHASE_ADJ
678      WRITE_FLAG( scaledWindow.getVertPhasePositionEnableFlag(), "vert_phase_position_enable_flag" ); 
679#endif
680    }
681  }
682}
683#endif
684Void TEncCavlc::codeVPS( TComVPS* pcVPS )
685{
686#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
687#if VPS_EXTN_OFFSET_CALC
688  UInt numBytesInVps = this->m_pcBitIf->getNumberOfWrittenBits();
689#endif
690#endif
691#if !P0307_REMOVE_VPS_VUI_OFFSET
692#if VPS_VUI_OFFSET
693   m_vpsVuiCounter = this->m_pcBitIf->getNumberOfWrittenBits();
694#endif
695#endif
696  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
697  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
698#if VPS_RENAME
699  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );           
700#else
701  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
702#endif
703  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
704  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
705  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
706#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
707#if VPS_EXTN_OFFSET
708  WRITE_CODE( pcVPS->getExtensionOffset(),         16,        "vps_extension_offset" );
709#else
710  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
711#endif
712#else
713  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
714#endif
715  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
716  const Bool subLayerOrderingInfoPresentFlag = 1;
717  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
718  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
719  {
720    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
721    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
722    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
723    if (!subLayerOrderingInfoPresentFlag)
724    {
725      break;
726    }
727  }
728
729#if VPS_RENAME
730  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
731  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_ID_PLUS1 );
732#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
733  pcVPS->setNumLayerSets(1);
734#endif
735  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
736  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
737  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getNumLayerSets() - 1 ); opsIdx ++ )
738  {
739    // Operation point set
740    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
741#else
742  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
743  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
744  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
745  pcVPS->setMaxOpSets(1);
746  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
747  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
748  {
749    // Operation point set
750    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
751#endif
752    {
753#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
754      // Only applicable for version 1
755      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
756#endif
757      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
758    }
759  }
760#if DERIVE_LAYER_ID_LIST_VARIABLES
761  pcVPS->deriveLayerIdListVariables();
762#endif
763  TimingInfo *timingInfo = pcVPS->getTimingInfo();
764  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
765  if(timingInfo->getTimingInfoPresentFlag())
766  {
767    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
768    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
769    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
770    if(timingInfo->getPocProportionalToTimingFlag())
771    {
772      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
773    }
774    pcVPS->setNumHrdParameters( 0 );
775    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
776
777    if( pcVPS->getNumHrdParameters() > 0 )
778    {
779      pcVPS->createHrdParamBuffer();
780    }
781    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
782    {
783      // Only applicable for version 1
784      pcVPS->setHrdOpSetIdx( 0, i );
785      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
786      if( i > 0 )
787      {
788        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
789      }
790      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
791    }
792  }
793#if VPS_EXTNS
794  // When MaxLayersMinus1 is greater than 0, vps_extension_flag shall be equal to 1.
795  if( pcVPS->getMaxLayers() > 1 )
796  {
797    assert( pcVPS->getVpsExtensionFlag() == true );
798  }
799
800  WRITE_FLAG( pcVPS->getVpsExtensionFlag() ? 1 : 0,                     "vps_extension_flag" );
801
802  if( pcVPS->getVpsExtensionFlag() )
803  {
804    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
805    {
806      WRITE_FLAG(1,                  "vps_extension_alignment_bit_equal_to_one");
807    }
808#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
809#if VPS_EXTN_OFFSET_CALC
810    Int vpsExntOffsetValueInBits = this->m_pcBitIf->getNumberOfWrittenBits() - numBytesInVps + 16; // 2 bytes for NUH
811    assert( vpsExntOffsetValueInBits % 8 == 0 );
812    pcVPS->setExtensionOffset( vpsExntOffsetValueInBits >> 3 );
813#endif
814#endif
815    codeVPSExtension(pcVPS);
816    WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
817  }
818#else
819  WRITE_FLAG( 0,                     "vps_extension_flag" );
820#endif 
821  //future extensions here..
822 
823  return;
824}
825
826#if SVC_EXTENSION
827#if VPS_EXTNS
828Void TEncCavlc::codeVPSExtension (TComVPS *vps)
829{
830  // ... More syntax elements to be written here
831#if P0300_ALT_OUTPUT_LAYER_FLAG
832  Int NumOutputLayersInOutputLayerSet[MAX_VPS_LAYER_SETS_PLUS1];
833  Int OlsHighestOutputLayerId[MAX_VPS_LAYER_SETS_PLUS1];
834#endif
835#if VPS_EXTN_MASK_AND_DIM_INFO
836  UInt i = 0, j = 0;
837
838  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
839#if !P0307_REMOVE_VPS_VUI_OFFSET
840#if O0109_MOVE_VPS_VUI_FLAG
841#if !VPS_VUI
842  WRITE_FLAG( 0,                     "vps_vui_present_flag" );
843  vps->setVpsVuiPresentFlag(false);
844#else
845  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
846  vps->setVpsVuiPresentFlag(true);
847#endif
848  if ( vps->getVpsVuiPresentFlag() ) 
849  {
850#if VPS_VUI_OFFSET
851    WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" );
852#endif
853    WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
854  }
855#else
856#if VPS_VUI_OFFSET
857  WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" ); 
858#endif
859  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
860#endif // O0109_MOVE_VPS_VUI_FLAG
861#endif
862  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
863
864  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
865  {
866    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
867  }
868
869  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
870  {
871    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
872  }
873
874#if SPL_FLG_CHK
875  if(vps->getSplittingFlag())
876  {
877    UInt splDimSum=0;
878    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
879    {
880      splDimSum+=(vps->getDimensionIdLen(j));
881    }
882    assert(splDimSum<=6);
883  }
884#endif
885
886  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
887  for(i = 1; i < vps->getMaxLayers(); i++)
888  {
889    if( vps->getNuhLayerIdPresentFlag() )
890    {
891      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
892    }
893
894    if( !vps->getSplittingFlag() )
895    {
896    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
897    {
898      UInt bits = vps->getDimensionIdLen(j);
899      WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
900    }
901  }
902  }
903#endif
904#if VIEW_ID_RELATED_SIGNALING
905  // if ( pcVPS->getNumViews() > 1 ) 
906  //   However, this is a bug in the text since, view_id_len_minus1 is needed to parse view_id_val.
907  {
908#if O0109_VIEW_ID_LEN
909    WRITE_CODE( vps->getViewIdLen( ), 4, "view_id_len" );
910    assert ( vps->getNumViews() >= (1<<vps->getViewIdLen()) );
911#else
912    WRITE_CODE( vps->getViewIdLenMinus1( ), 4, "view_id_len_minus1" );
913#endif
914  }
915
916#if O0109_VIEW_ID_LEN
917  if ( vps->getViewIdLen() > 0 )
918  {
919#endif
920  for(  i = 0; i < vps->getNumViews(); i++ )
921  {
922#if O0109_VIEW_ID_LEN
923    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLen( ), "view_id_val[i]" );
924#else
925    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLenMinus1( ) + 1, "view_id_val[i]" );
926#endif
927  }
928#if O0109_VIEW_ID_LEN
929  }
930#endif
931#endif // VIEW_ID_RELATED_SIGNALING
932
933#if VPS_EXTN_DIRECT_REF_LAYERS
934  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
935  {
936    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
937    {
938      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
939    }
940  }
941#endif
942#if VPS_TSLAYERS
943    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
944    if (vps->getMaxTSLayersPresentFlag())
945    {
946        for( i = 0; i < vps->getMaxLayers(); i++)
947        {
948            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
949        }
950    }
951#endif
952#if N0120_MAX_TID_REF_PRESENT_FLAG
953   WRITE_FLAG( vps->getMaxTidRefPresentFlag(), "max_tid_ref_present_flag");
954   if (vps->getMaxTidRefPresentFlag())
955   {
956     for( i = 0; i < vps->getMaxLayers() - 1; i++)
957     {
958#if O0225_MAX_TID_FOR_REF_LAYERS
959       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
960       {
961         if(vps->getDirectDependencyFlag(j, i))
962         {
963           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
964         }
965       }
966#else
967       WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
968#endif
969     }
970   }
971#else
972  for( i = 0; i < vps->getMaxLayers() - 1; i++)
973  {
974#if O0225_MAX_TID_FOR_REF_LAYERS
975       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
976       {
977         if(vps->getDirectDependencyFlag(j, i))
978         {
979           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
980         }
981       }
982#else
983    WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
984#endif
985  }
986#endif
987#if ILP_SSH_SIG
988    WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
989#endif
990#if VPS_EXTN_PROFILE_INFO
991  // Profile-tier-level signalling
992#if !VPS_EXTN_UEV_CODING
993  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
994  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
995#else
996  WRITE_UVLC( vps->getNumProfileTierLevel() - 1, "vps_num_profile_tier_level_minus1"); 
997#endif
998  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
999  {
1000    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
1001#if !P0048_REMOVE_PROFILE_REF
1002    if( !vps->getProfilePresentFlag(idx) )
1003    {
1004      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
1005    }
1006#endif
1007    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
1008  }
1009#endif
1010
1011#if !VPS_EXTN_UEV_CODING
1012  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
1013  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
1014  if(numOutputLayerSets > vps->getNumLayerSets())
1015  {
1016    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
1017  }
1018#else
1019  Int numOutputLayerSets = vps->getNumOutputLayerSets();
1020  Int numAddOutputLayerSets = numOutputLayerSets - (Int)vps->getNumLayerSets();
1021
1022  // The value of num_add_output_layer_sets shall be in the range of 0 to 1023, inclusive.
1023  assert( numAddOutputLayerSets >= 0 && numAddOutputLayerSets < 1024 );
1024
1025#if Q0165_NUM_ADD_OUTPUT_LAYER_SETS
1026  if( vps->getNumLayerSets() > 1 )
1027  {
1028    WRITE_UVLC( numAddOutputLayerSets, "num_add_output_layer_sets" );
1029    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_target_output_layer_idc" );
1030  }
1031#else
1032  WRITE_UVLC( numOutputLayerSets - vps->getNumLayerSets(), "num_add_output_layer_sets" );
1033#endif
1034#endif
1035
1036#if !Q0165_NUM_ADD_OUTPUT_LAYER_SETS
1037  if( numOutputLayerSets > 1 )
1038  {
1039#if P0295_DEFAULT_OUT_LAYER_IDC
1040    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_target_output_layer_idc" );   
1041#else
1042#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
1043    WRITE_CODE( vps->getDefaultOneTargetOutputLayerIdc(), 2, "default_one_target_output_layer_idc" );   
1044#else
1045    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
1046#endif
1047#endif
1048  }
1049#endif
1050
1051  for(i = 1; i < numOutputLayerSets; i++)
1052  {
1053    if( i > (vps->getNumLayerSets() - 1) )
1054    {
1055      Int numBits = 1;
1056      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
1057      {
1058        numBits++;
1059      }
1060      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "output_layer_set_idx_minus1"); 
1061#if P0295_DEFAULT_OUT_LAYER_IDC
1062    }
1063    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
1064    {
1065#endif
1066      Int lsIdx = vps->getOutputLayerSetIdx(i);
1067#if NUM_OL_FLAGS
1068      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) ; j++)
1069#else
1070      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
1071#endif
1072      {
1073        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
1074      }
1075    }
1076    Int numBits = 1;
1077    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
1078    {
1079      numBits++;
1080    }
1081    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
1082#if P0300_ALT_OUTPUT_LAYER_FLAG
1083    NumOutputLayersInOutputLayerSet[i] = 0;
1084    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx(i);
1085    for (j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
1086    {
1087      NumOutputLayersInOutputLayerSet[i] += vps->getOutputLayerFlag(i, j);
1088      if (vps->getOutputLayerFlag(i, j))
1089      {
1090        OlsHighestOutputLayerId[i] = vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j);
1091      }
1092    }
1093    if (NumOutputLayersInOutputLayerSet[i] == 1 && vps->getNumDirectRefLayers(OlsHighestOutputLayerId[i]) > 0)
1094    {
1095      WRITE_FLAG(vps->getAltOuputLayerFlag(i), "alt_output_layer_flag[i]");
1096    }
1097
1098#if Q0165_OUTPUT_LAYER_SET
1099    assert( NumOutputLayersInOutputLayerSet[i]>0 );
1100#endif
1101
1102#endif
1103  }
1104
1105#if !P0300_ALT_OUTPUT_LAYER_FLAG
1106#if O0153_ALT_OUTPUT_LAYER_FLAG
1107  if( vps->getMaxLayers() > 1 )
1108  {
1109    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
1110  }
1111#endif
1112#endif
1113
1114#if REPN_FORMAT_IN_VPS
1115#if Q0195_REP_FORMAT_CLEANUP 
1116  // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
1117  assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
1118 
1119  WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
1120
1121  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
1122  {
1123    // Write rep_format_structures
1124    codeRepFormat( vps->getVpsRepFormat(i) );
1125  }
1126
1127  if( vps->getVpsNumRepFormats() > 1 )
1128  {
1129    WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
1130  }
1131  else
1132  {
1133    // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
1134    assert( !vps->getRepFormatIdxPresentFlag() );
1135  }
1136
1137  if( vps->getRepFormatIdxPresentFlag() )
1138  {
1139    for(i = 1; i < vps->getMaxLayers(); i++)
1140    {
1141      Int numBits = 1;
1142      while ((1 << numBits) < (vps->getVpsNumRepFormats()))
1143      {
1144        numBits++;
1145      }
1146      WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
1147    }
1148  }
1149#else
1150  WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
1151
1152  if( vps->getRepFormatIdxPresentFlag() )
1153  {
1154    // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
1155    assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
1156
1157#if O0096_REP_FORMAT_INDEX
1158#if !VPS_EXTN_UEV_CODING
1159    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
1160#else
1161    WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
1162#endif
1163#else
1164    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
1165#endif
1166  }
1167  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
1168  {
1169    // Read rep_format_structures
1170    codeRepFormat( vps->getVpsRepFormat(i) );
1171  }
1172 
1173  if( vps->getRepFormatIdxPresentFlag() )
1174  {
1175    for(i = 1; i < vps->getMaxLayers(); i++)
1176    {
1177      if( vps->getVpsNumRepFormats() > 1 )
1178      {
1179#if O0096_REP_FORMAT_INDEX
1180#if !VPS_EXTN_UEV_CODING
1181        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
1182#else
1183        Int numBits = 1;
1184        while ((1 << numBits) < (vps->getVpsNumRepFormats()))
1185        {
1186          numBits++;
1187        }
1188        WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
1189#endif
1190#else
1191        WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
1192#endif
1193      }
1194    }
1195  }
1196#endif
1197#endif
1198
1199  WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
1200#if O0062_POC_LSB_NOT_PRESENT_FLAG
1201  for(i = 1; i< vps->getMaxLayers(); i++)
1202  {
1203    if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
1204    {
1205      WRITE_FLAG(vps->getPocLsbNotPresentFlag(i), "poc_lsb_not_present_flag[i]");
1206    }
1207  }
1208#endif
1209#if O0215_PHASE_ALIGNMENT
1210  WRITE_FLAG(vps->getPhaseAlignFlag(), "cross_layer_phase_alignment_flag" );
1211#endif
1212#if N0147_IRAP_ALIGN_FLAG && !IRAP_ALIGN_FLAG_IN_VPS_VUI
1213  WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
1214#endif
1215#if VPS_DPB_SIZE_TABLE
1216  codeVpsDpbSizeTable(vps);
1217#endif
1218#if VPS_EXTN_DIRECT_REF_LAYERS
1219  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
1220#if O0096_DEFAULT_DEPENDENCY_TYPE
1221  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
1222  if (vps->getDefaultDirectDependencyTypeFlag())
1223  {
1224    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
1225  }
1226  else
1227  {
1228    for(i = 1; i < vps->getMaxLayers(); i++)
1229    {
1230      for(j = 0; j < i; j++)
1231      {
1232        if (vps->getDirectDependencyFlag(i, j))
1233        {
1234          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
1235        }
1236      }
1237    }
1238  }
1239#else
1240  for(i = 1; i < vps->getMaxLayers(); i++)
1241  {
1242    for(j = 0; j < i; j++)
1243    {
1244      if (vps->getDirectDependencyFlag(i, j))
1245      {
1246        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
1247      }
1248    }
1249  }
1250#endif
1251#endif
1252
1253#if !O0109_O0199_FLAGS_TO_VUI
1254#if M0040_ADAPTIVE_RESOLUTION_CHANGE
1255  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
1256#endif
1257#if HIGHER_LAYER_IRAP_SKIP_FLAG
1258  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
1259#endif
1260#endif
1261
1262#if P0307_VPS_NON_VUI_EXTENSION
1263  // The value of vps_non_vui_extension_length shall be in the range of 0 to 4096, inclusive.
1264  assert( vps->getVpsNonVuiExtLength() >= 0 && vps->getVpsNonVuiExtLength() <= 4096 );
1265
1266  WRITE_UVLC( vps->getVpsNonVuiExtLength(), "vps_non_vui_extension_length" );
1267#if P0307_VPS_NON_VUI_EXT_UPDATE
1268  for (i = 1; i <= vps->getVpsNonVuiExtLength(); i++)
1269  {
1270    WRITE_CODE(1, 8, "vps_non_vui_extension_data_byte");
1271  }
1272#else
1273  if ( vps->getVpsNonVuiExtLength() > 0 )
1274  {
1275    printf("\n\nUp to the current spec, the value of vps_non_vui_extension_length is supposed to be 0\n");
1276  }
1277#endif
1278#endif
1279
1280#if !O0109_MOVE_VPS_VUI_FLAG
1281#if !VPS_VUI
1282  WRITE_FLAG( 0,                     "vps_vui_present_flag" );
1283#else
1284  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
1285  if(1)   // Should be conditioned on the value of vps_vui_present_flag
1286  {
1287    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
1288    {
1289      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
1290    }
1291#if VPS_VUI_OFFSET
1292    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
1293    assert( vpsVuiOffsetValeInBits % 8 == 0 );
1294    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
1295#endif
1296    codeVPSVUI(vps); 
1297  }
1298#endif
1299#else
1300#if P0307_REMOVE_VPS_VUI_OFFSET
1301  vps->setVpsVuiPresentFlag(true);
1302  WRITE_FLAG( vps->getVpsVuiPresentFlag() ? 1 : 0,                     "vps_vui_present_flag" );
1303#endif
1304  if(vps->getVpsVuiPresentFlag())   // Should be conditioned on the value of vps_vui_present_flag
1305  {
1306    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
1307    {
1308      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
1309    }
1310#if !P0307_REMOVE_VPS_VUI_OFFSET
1311#if VPS_VUI_OFFSET
1312    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
1313    assert( vpsVuiOffsetValeInBits % 8 == 0 );
1314    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
1315#endif
1316#endif
1317    codeVPSVUI(vps); 
1318  }
1319#endif // 0109_MOVE_VPS_FLAG
1320}
1321#endif
1322#if REPN_FORMAT_IN_VPS
1323Void  TEncCavlc::codeRepFormat( RepFormat *repFormat )
1324{
1325#if REPN_FORMAT_CONTROL_FLAG
1326  WRITE_CODE( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_vps_in_luma_samples" );   
1327  WRITE_CODE( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_vps_in_luma_samples" ); 
1328  WRITE_FLAG( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_present_flag" );
1329
1330  if( repFormat->getChromaAndBitDepthVpsPresentFlag() )
1331  {
1332    WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_vps_idc" );   
1333
1334    if( repFormat->getChromaFormatVpsIdc() == 3 )
1335    {
1336      WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_vps_flag" );     
1337    }
1338
1339    assert( repFormat->getBitDepthVpsLuma() >= 8 );
1340    assert( repFormat->getBitDepthVpsChroma() >= 8 );
1341    WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_vps_luma_minus8" );           
1342    WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_vps_chroma_minus8" );
1343  }
1344#else
1345  WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
1346 
1347  if( repFormat->getChromaFormatVpsIdc() == 3 )
1348  {
1349    WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");     
1350  }
1351
1352  WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );   
1353  WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );   
1354 
1355  assert( repFormat->getBitDepthVpsLuma() >= 8 );
1356  assert( repFormat->getBitDepthVpsChroma() >= 8 );
1357  WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
1358  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
1359#endif
1360}
1361#endif
1362#if VPS_DPB_SIZE_TABLE
1363Void TEncCavlc::codeVpsDpbSizeTable(TComVPS *vps)
1364{
1365#if DPB_PARAMS_MAXTLAYERS
1366    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumOutputLayerSets()];
1367    for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
1368    {
1369        UInt maxSLMinus1 = 0;
1370#if CHANGE_NUMSUBDPB_IDX
1371        Int optLsIdx = vps->getOutputLayerSetIdx( i );
1372#else
1373        Int optLsIdx = i;
1374#endif
1375        for(Int k = 0; k < vps->getNumLayersInIdList(optLsIdx); k++ ) {
1376            Int  lId = vps->getLayerSetLayerIdList(optLsIdx, k);
1377            maxSLMinus1 = max(maxSLMinus1, vps->getMaxTSLayersMinus1(vps->getLayerIdInVps(lId)));
1378        }
1379        MaxSubLayersInLayerSetMinus1[ i ] = maxSLMinus1;
1380    }
1381#endif
1382   
1383  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
1384  {
1385#if CHANGE_NUMSUBDPB_IDX
1386    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
1387#endif
1388    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]");
1389#if DPB_PARAMS_MAXTLAYERS
1390    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ i ]; j++)
1391#else
1392    for(Int j = 0; j < vps->getMaxTLayers(); j++)
1393#endif
1394    {
1395      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
1396      {
1397        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]"); 
1398      }
1399      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
1400      {
1401#if CHANGE_NUMSUBDPB_IDX
1402        for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
1403#else
1404        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
1405#endif
1406        {
1407          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j), "max_vps_dec_pic_buffering_minus1[i][k][j]" ); 
1408        }
1409        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );             
1410#if RESOLUTION_BASED_DPB
1411        if( vps->getNumSubDpbs(layerSetIdxForOutputLayerSet) != vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ) )  // NumSubDpbs
1412        {
1413          for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
1414          {
1415            WRITE_UVLC( vps->getMaxVpsLayerDecPicBuffMinus1( i, k, j), "max_vps_layer_dec_pic_buff_minus1[i][k][j]" );
1416          }
1417        }
1418#endif
1419        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );       
1420      }
1421    }
1422  }
1423}
1424#endif
1425#if VPS_VUI
1426Void TEncCavlc::codeVPSVUI (TComVPS *vps)
1427{
1428  Int i,j;
1429#if O0223_PICTURE_TYPES_ALIGN_FLAG
1430  WRITE_FLAG(vps->getCrossLayerPictureTypeAlignFlag(), "cross_layer_pic_type_aligned_flag");
1431  if (!vps->getCrossLayerPictureTypeAlignFlag())
1432  {
1433#endif
1434#if IRAP_ALIGN_FLAG_IN_VPS_VUI
1435    WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
1436#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
1437    if(vps->getCrossLayerIrapAlignFlag())
1438    {
1439       WRITE_FLAG(vps->getCrossLayerAlignedIdrOnlyFlag(), "all_layers_idr_aligned_flag");
1440    }
1441#endif
1442#endif
1443#if O0223_PICTURE_TYPES_ALIGN_FLAG
1444  }
1445#endif
1446#if VPS_VUI_BITRATE_PICRATE
1447  WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
1448  WRITE_FLAG( vps->getPicRatePresentVpsFlag(),        "pic_rate_present_vps_flag" );
1449
1450  if( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
1451  {
1452    for( i = 0; i < vps->getNumLayerSets(); i++ )
1453    {
1454      for( j = 0; j < vps->getMaxTLayers(); j++ )
1455      {
1456        if( vps->getBitRatePresentVpsFlag() )
1457        {
1458          WRITE_FLAG( vps->getBitRatePresentFlag( i, j),        "bit_rate_present_flag[i][j]" );
1459        }
1460        if( vps->getPicRatePresentVpsFlag() )
1461        {
1462          WRITE_FLAG( vps->getPicRatePresentFlag( i, j),        "pic_rate_present_flag[i][j]" );
1463        }
1464        if( vps->getBitRatePresentFlag(i, j) )
1465        {
1466          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "avg_bit_rate[i][j]" );
1467          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "max_bit_rate[i][j]" );
1468        }
1469        if( vps->getPicRatePresentFlag(i, j) )
1470        {
1471          WRITE_CODE( vps->getConstPicRateIdc( i, j), 2 , "constant_pic_rate_idc[i][j]" ); 
1472          WRITE_CODE( vps->getConstPicRateIdc( i, j), 16, "avg_pic_rate[i][j]"          ); 
1473        }
1474      }
1475    }
1476  }
1477#endif
1478#if VPS_VUI_VIDEO_SIGNAL_MOVE
1479  WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
1480  if (vps->getVideoSigPresentVpsFlag())
1481  {
1482    WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
1483  }
1484
1485  for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
1486  {
1487    WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
1488    WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
1489    WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
1490    WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
1491    WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
1492  }
1493
1494  if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
1495  {
1496    for (i=1; i < vps->getMaxLayers(); i++)
1497      WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
1498  }
1499#endif
1500#if VPS_VUI_TILES_NOT_IN_USE__FLAG
1501  UInt layerIdx;
1502  WRITE_FLAG( vps->getTilesNotInUseFlag() ? 1 : 0 , "tiles_not_in_use_flag" );
1503  if (!vps->getTilesNotInUseFlag())
1504  {
1505    for(i = 0; i < vps->getMaxLayers(); i++)
1506    {
1507      WRITE_FLAG( vps->getTilesInUseFlag(i) ? 1 : 0 , "tiles_in_use_flag[ i ]" );
1508      if (vps->getTilesInUseFlag(i))
1509      {
1510        WRITE_FLAG( vps->getLoopFilterNotAcrossTilesFlag(i) ? 1 : 0 , "loop_filter_not_across_tiles_flag[ i ]" );
1511      }
1512    }
1513#endif
1514#if TILE_BOUNDARY_ALIGNED_FLAG
1515    for(i = 1; i < vps->getMaxLayers(); i++)
1516    {
1517      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
1518      {
1519#if VPS_VUI_TILES_NOT_IN_USE__FLAG
1520        layerIdx = vps->getLayerIdInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
1521        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
1522          WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
1523        }
1524#else
1525        WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
1526#endif
1527      }
1528    } 
1529#endif
1530#if VPS_VUI_TILES_NOT_IN_USE__FLAG
1531  }
1532#endif
1533#if VPS_VUI_WPP_NOT_IN_USE__FLAG
1534  WRITE_FLAG( vps->getWppNotInUseFlag() ? 1 : 0 , "wpp_not_in_use_flag" );
1535  if (!vps->getWppNotInUseFlag())
1536  {
1537    for(i = 0; i < vps->getMaxLayers(); i++)
1538    {
1539      WRITE_FLAG( vps->getWppInUseFlag(i) ? 1 : 0 , "wpp_in_use_flag[ i ]" );
1540    }
1541  }
1542#endif
1543
1544#if O0109_O0199_FLAGS_TO_VUI
1545#if M0040_ADAPTIVE_RESOLUTION_CHANGE
1546  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
1547#endif
1548#if HIGHER_LAYER_IRAP_SKIP_FLAG
1549  // When single_layer_for_non_irap_flag is equal to 0, higher_layer_irap_skip_flag shall be equal to 0
1550  if( !vps->getSingleLayerForNonIrapFlag() )
1551  {
1552    assert( !vps->getHigherLayerIrapSkipFlag() );
1553  }
1554
1555  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
1556#endif
1557#endif
1558#if P0312_VERT_PHASE_ADJ
1559  WRITE_FLAG( vps->getVpsVuiVertPhaseInUseFlag(), "vps_vui_vert_phase_in_use_flag" );
1560#endif
1561#if N0160_VUI_EXT_ILP_REF
1562  WRITE_FLAG( vps->getIlpRestrictedRefLayersFlag() ? 1 : 0 , "ilp_restricted_ref_layers_flag" );   
1563  if( vps->getIlpRestrictedRefLayersFlag())
1564  {
1565    for(i = 1; i < vps->getMaxLayers(); i++)
1566    {
1567      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
1568      {       
1569        WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
1570       
1571        if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
1572        { 
1573          WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );   
1574         
1575          if(vps->getCtuBasedOffsetEnabledFlag(i,j)) 
1576          {
1577            WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");           
1578          }
1579        } 
1580      } 
1581    }
1582  }
1583#endif
1584#if VPS_VUI_VIDEO_SIGNAL
1585#if VPS_VUI_VIDEO_SIGNAL_MOVE
1586#else
1587    WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
1588    if (vps->getVideoSigPresentVpsFlag())
1589    {
1590        WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
1591    }
1592   
1593    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
1594    {
1595        WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
1596        WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
1597        WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
1598        WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
1599        WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
1600    }
1601   
1602    if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
1603    {
1604        for (i=1; i < vps->getMaxLayers(); i++)
1605            WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
1606    }
1607#endif
1608#endif
1609#if O0164_MULTI_LAYER_HRD
1610    WRITE_FLAG(vps->getVpsVuiBspHrdPresentFlag(), "vps_vui_bsp_hrd_present_flag" );
1611    if (vps->getVpsVuiBspHrdPresentFlag())
1612    {
1613      WRITE_UVLC( vps->getVpsNumBspHrdParametersMinus1(), "vps_num_bsp_hrd_parameters_minus1" );
1614      for( i = 0; i <= vps->getVpsNumBspHrdParametersMinus1(); i++ )
1615      {
1616        if( i > 0 )
1617        {
1618          WRITE_FLAG( vps->getBspCprmsPresentFlag(i), "bsp_cprms_present_flag[i]" );
1619        }
1620        codeHrdParameters(vps->getBspHrd(i), i==0 ? 1 : vps->getBspCprmsPresentFlag(i), vps->getMaxTLayers()-1);
1621      }
1622      for( UInt h = 1; h <= (vps->getNumLayerSets()-1); h++ )
1623      {
1624        WRITE_UVLC( vps->getNumBitstreamPartitions(h), "num_bitstream_partitions[i]");
1625        for( i = 0; i < vps->getNumBitstreamPartitions(h); i++ )
1626        {
1627          for( j = 0; j <= (vps->getMaxLayers()-1); j++ )
1628          {
1629            if (vps->getLayerIdIncludedFlag(h, j))
1630            {
1631              WRITE_FLAG( vps->getLayerInBspFlag(h, i, j), "layer_in_bsp_flag[h][i][j]" );
1632            }
1633          }
1634        }
1635        if (vps->getNumBitstreamPartitions(h))
1636        {
1637          WRITE_UVLC( vps->getNumBspSchedCombinations(h), "num_bsp_sched_combinations[h]");
1638          for( i = 0; i < vps->getNumBspSchedCombinations(h); i++ )
1639          {
1640            for( j = 0; j < vps->getNumBitstreamPartitions(h); j++ )
1641            {
1642              WRITE_UVLC( vps->getBspCombHrdIdx(h, i, j), "bsp_comb_hrd_idx[h][i][j]");
1643              WRITE_UVLC( vps->getBspCombSchedIdx(h, i, j), "bsp_comb_sched_idx[h][i][j]");
1644            }
1645          }
1646        }
1647      }
1648    }
1649#endif
1650#if P0182_VPS_VUI_PS_FLAG
1651    for(i = 1; i < vps->getMaxLayers(); i++)
1652    {
1653      if( vps->getNumRefLayers(vps->getLayerIdInNuh(i)) == 0 ) 
1654      {
1655        if( (vps->getSPSId(i) == 0) && (vps->getPPSId(i) == 0) )
1656        {
1657          vps->setBaseLayerPSCompatibilityFlag(i, 1);
1658        }
1659        else
1660        {
1661          vps->setBaseLayerPSCompatibilityFlag(i, 0);
1662        }
1663        WRITE_FLAG(vps->getBaseLayerPSCompatibilityFlag(i), "base_layer_parameter_set_compatibility_flag" );
1664      }
1665    }
1666#endif
1667}
1668#endif
1669#endif //SVC_EXTENSION
1670
1671Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
1672{
1673#if ENC_DEC_TRACE 
1674  xTraceSliceHeader (pcSlice);
1675#endif
1676
1677  //calculate number of bits required for slice address
1678  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumCUsInFrame();
1679  Int bitsSliceSegmentAddress = 0;
1680  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress)) 
1681  {
1682    bitsSliceSegmentAddress++;
1683  }
1684  Int ctuAddress;
1685  if (pcSlice->isNextSlice())
1686  {
1687    // Calculate slice address
1688    ctuAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
1689  }
1690  else
1691  {
1692    // Calculate slice address
1693    ctuAddress = (pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
1694  }
1695  //write slice address
1696  Int sliceSegmentAddress = pcSlice->getPic()->getPicSym()->getCUOrderMap(ctuAddress);
1697
1698  WRITE_FLAG( sliceSegmentAddress==0, "first_slice_segment_in_pic_flag" );
1699  if ( pcSlice->getRapPicFlag() )
1700  {
1701#if SETTING_NO_OUT_PIC_PRIOR
1702    WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
1703#else
1704    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
1705#endif
1706  }
1707  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
1708  pcSlice->setDependentSliceSegmentFlag(!pcSlice->isNextSlice());
1709  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentAddress!=0) )
1710  {
1711    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
1712  }
1713  if(sliceSegmentAddress>0)
1714  {
1715    WRITE_CODE( sliceSegmentAddress, bitsSliceSegmentAddress, "slice_segment_address" );
1716  }
1717  if ( !pcSlice->getDependentSliceSegmentFlag() )
1718  {
1719#if SVC_EXTENSION
1720#if POC_RESET_FLAG
1721    Int iBits = 0;
1722    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1723    {
1724      WRITE_FLAG( pcSlice->getPocResetFlag(), "poc_reset_flag" );
1725      iBits++;
1726    }
1727    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1728    {
1729      assert(!!"discardable_flag");
1730      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1731      iBits++;
1732    }
1733#if O0149_CROSS_LAYER_BLA_FLAG
1734    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1735    {
1736      assert(!!"cross_layer_bla_flag");
1737      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
1738      iBits++;
1739    }
1740#endif
1741    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1742    {
1743      assert(!!"slice_reserved_undetermined_flag[]");
1744      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1745    }
1746#else
1747    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
1748    {
1749      assert(!!"discardable_flag");
1750      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1751    }
1752    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1753    {
1754      assert(!!"slice_reserved_undetermined_flag[]");
1755      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1756    }
1757#endif
1758#else //SVC_EXTENSION
1759    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1760    {
1761      assert(!!"slice_reserved_undetermined_flag[]");
1762      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1763    }
1764#endif //SVC_EXTENSION
1765
1766    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1767
1768    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1769    {
1770      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1771    }
1772
1773#if !AUXILIARY_PICTURES
1774#if REPN_FORMAT_IN_VPS
1775    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1776    assert( pcSlice->getChromaFormatIdc() == 1 );
1777#else
1778    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1779    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
1780#endif
1781#endif
1782    // if( separate_colour_plane_flag  ==  1 )
1783    //   colour_plane_id                                      u(2)
1784
1785#if N0065_LAYER_POC_ALIGNMENT
1786#if O0062_POC_LSB_NOT_PRESENT_FLAG
1787    if( (pcSlice->getLayerId() > 0 && !pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdInVps(pcSlice->getLayerId())) ) || !pcSlice->getIdrPicFlag())
1788#else
1789    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
1790#endif
1791#else
1792    if( !pcSlice->getIdrPicFlag() )
1793#endif
1794    {
1795#if POC_RESET_FLAG
1796      Int picOrderCntLSB;
1797      if( !pcSlice->getPocResetFlag() )
1798      {
1799        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1800      }
1801      else
1802      {
1803        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1804      }
1805#else
1806      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1807#endif
1808      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
1809
1810#if N0065_LAYER_POC_ALIGNMENT
1811#if SHM_FIX7
1812    }
1813#endif
1814      if( !pcSlice->getIdrPicFlag() )
1815      {
1816#endif
1817      TComReferencePictureSet* rps = pcSlice->getRPS();
1818     
1819      // check for bitstream restriction stating that:
1820      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1821      // Ideally this process should not be repeated for each slice in a picture
1822#if SVC_EXTENSION
1823      if( pcSlice->getLayerId() == 0 )
1824#endif
1825      if (pcSlice->isIRAP())
1826      {
1827        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1828        {
1829          assert (!rps->getUsed(picIdx));
1830        }
1831      }
1832
1833      if(pcSlice->getRPSidx() < 0)
1834      {
1835        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1836        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1837      }
1838      else
1839      {
1840        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1841        Int numBits = 0;
1842        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1843        {
1844          numBits++;
1845        }
1846        if (numBits > 0)
1847        {
1848          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );         
1849        }
1850      }
1851      if(pcSlice->getSPS()->getLongTermRefsPresent())
1852      {
1853        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1854        Int ltrpInSPS[MAX_NUM_REF_PICS];
1855        Int numLtrpInSPS = 0;
1856        UInt ltrpIndex;
1857        Int counter = 0;
1858        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
1859        {
1860          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
1861          {
1862            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1863            numLtrpInSPS++;
1864          }
1865          else
1866          {
1867            counter++;
1868          }
1869        }
1870        numLtrpInSH -= numLtrpInSPS;
1871
1872        Int bitsForLtrpInSPS = 0;
1873        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1874        {
1875          bitsForLtrpInSPS++;
1876        }
1877        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
1878        {
1879          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1880        }
1881        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1882        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1883        // Not sorted here because LT ref indices will be used in setRefPicList()
1884        Int prevDeltaMSB = 0, prevLSB = 0;
1885        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1886        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
1887        {
1888          if (counter < numLtrpInSPS)
1889          {
1890            if (bitsForLtrpInSPS > 0)
1891            {
1892              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");             
1893            }
1894          }
1895          else 
1896          {
1897            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1898            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
1899          }
1900          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1901
1902          if(rps->getDeltaPocMSBPresentFlag(i))
1903          {
1904            Bool deltaFlag = false;
1905            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1906            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1907            {
1908              deltaFlag = true;
1909            }
1910            if(deltaFlag)
1911            {
1912              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1913            }
1914            else
1915            {             
1916              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1917              assert(differenceInDeltaMSB >= 0);
1918              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1919            }
1920            prevLSB = rps->getPocLSBLT(i);
1921            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1922          }
1923        }
1924      }
1925      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1926      {
1927        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
1928      }
1929#if N0065_LAYER_POC_ALIGNMENT && !SHM_FIX7
1930      }
1931#endif
1932    }
1933
1934#if SVC_EXTENSION
1935#if ILP_SSH_SIG
1936#if ILP_SSH_SIG_FIX
1937    if((pcSlice->getLayerId() > 0) && !(pcSlice->getVPS()->getIlpSshSignalingEnabledFlag()) && (pcSlice->getNumILRRefIdx() > 0) )
1938#else
1939    if((pcSlice->getLayerId() > 0) && pcSlice->getVPS()->getIlpSshSignalingEnabledFlag() && (pcSlice->getNumILRRefIdx() > 0) )
1940#endif
1941#else
1942    if((pcSlice->getLayerId() > 0)  &&  (pcSlice->getNumILRRefIdx() > 0) )
1943#endif
1944    {
1945      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
1946      if( pcSlice->getInterLayerPredEnabledFlag())
1947      {
1948        if(pcSlice->getNumILRRefIdx() > 1)
1949        {
1950          Int numBits = 1;
1951          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
1952          {
1953            numBits++;
1954          }
1955          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
1956          {
1957            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
1958          }       
1959#if ILP_NUM_REF_CHK
1960          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
1961          {
1962#endif
1963          for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1964          {
1965            WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
1966          }
1967#if ILP_NUM_REF_CHK
1968          }
1969#endif
1970        }
1971      }
1972    }     
1973#if P0312_VERT_PHASE_ADJ
1974    for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1975    {
1976      UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
1977      if( pcSlice->getSPS()->getVertPhasePositionEnableFlag(refLayerIdc) )
1978      {
1979        WRITE_FLAG( pcSlice->getVertPhasePositionFlag(refLayerIdc), "vert_phase_position_flag" );
1980      }
1981    }
1982#endif
1983#endif //SVC_EXTENSION
1984
1985    if(pcSlice->getSPS()->getUseSAO())
1986    {
1987      if (pcSlice->getSPS()->getUseSAO())
1988      {
1989         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );         
1990#if AUXILIARY_PICTURES
1991         if (pcSlice->getChromaFormatIdc() != CHROMA_400)         
1992#endif
1993         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
1994      }
1995    }   
1996
1997    //check if numrefidxes match the defaults. If not, override
1998
1999    if (!pcSlice->isIntra())
2000    {
2001      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
2002      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
2003      if (overrideFlag) 
2004      {
2005        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
2006        if (pcSlice->isInterB())
2007        {
2008          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
2009        }
2010        else
2011        {
2012          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
2013        }
2014      }
2015    }
2016    else
2017    {
2018      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
2019      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
2020    }
2021
2022    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
2023    {
2024      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
2025      if(!pcSlice->isIntra())
2026      {
2027        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
2028        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
2029        {
2030          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
2031          if (numRpsCurrTempList0 > 1)
2032          {
2033            Int length = 1;
2034            numRpsCurrTempList0 --;
2035            while ( numRpsCurrTempList0 >>= 1) 
2036            {
2037              length ++;
2038            }
2039            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
2040            {
2041              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
2042            }
2043          }
2044        }
2045      }
2046      if(pcSlice->isInterB())
2047      {   
2048        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
2049        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
2050        {
2051          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
2052          if ( numRpsCurrTempList1 > 1 )
2053          {
2054            Int length = 1;
2055            numRpsCurrTempList1 --;
2056            while ( numRpsCurrTempList1 >>= 1)
2057            {
2058              length ++;
2059            }
2060            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
2061            {
2062              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
2063            }
2064          }
2065        }
2066      }
2067    }
2068   
2069    if (pcSlice->isInterB())
2070    {
2071      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
2072    }
2073
2074    if(!pcSlice->isIntra())
2075    {
2076      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
2077      {
2078        SliceType sliceType   = pcSlice->getSliceType();
2079        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
2080        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
2081        pcSlice->setCabacInitFlag( encCabacInitFlag );
2082        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
2083      }
2084    }
2085
2086    if ( pcSlice->getEnableTMVPFlag() )
2087    {
2088      if ( pcSlice->getSliceType() == B_SLICE )
2089      {
2090        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
2091      }
2092
2093      if ( pcSlice->getSliceType() != I_SLICE &&
2094        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
2095        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
2096      {
2097        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
2098      }
2099    }
2100    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
2101    {
2102      xCodePredWeightTable( pcSlice );
2103    }
2104    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
2105    if (!pcSlice->isIntra())
2106    {
2107      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
2108    }
2109    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
2110    WRITE_SVLC( iCode, "slice_qp_delta" ); 
2111    if (pcSlice->getPPS()->getSliceChromaQpFlag())
2112    {
2113      iCode = pcSlice->getSliceQpDeltaCb();
2114      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
2115      iCode = pcSlice->getSliceQpDeltaCr();
2116      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
2117    }
2118    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
2119    {
2120      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
2121      {
2122        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
2123      }
2124      if (pcSlice->getDeblockingFilterOverrideFlag())
2125      {
2126        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
2127        if(!pcSlice->getDeblockingFilterDisable())
2128        {
2129          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
2130          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
2131        }
2132      }
2133    }
2134
2135    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
2136    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
2137
2138    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
2139    {
2140      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
2141    }
2142  }
2143
2144#if !POC_RESET_IDC_SIGNALLING   // Wrong place to put slice header extension
2145  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
2146  {
2147    WRITE_UVLC(0,"slice_header_extension_length");
2148  }
2149#endif
2150}
2151
2152Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
2153{
2154  if(profilePresentFlag)
2155  {
2156    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
2157  }
2158  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
2159
2160  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
2161  {
2162    if(profilePresentFlag)
2163    {
2164      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
2165    }
2166   
2167    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
2168  }
2169 
2170  if (maxNumSubLayersMinus1 > 0)
2171  {
2172    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
2173    {
2174      WRITE_CODE(0, 2, "reserved_zero_2bits");
2175    }
2176  }
2177 
2178  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
2179  {
2180    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
2181    {
2182      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
2183    }
2184    if( pcPTL->getSubLayerLevelPresentFlag(i) )
2185    {
2186      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
2187    }
2188  }
2189}
2190Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
2191{
2192  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
2193  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
2194  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
2195  for(Int j = 0; j < 32; j++)
2196  {
2197    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
2198  }
2199
2200  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
2201  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
2202  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
2203  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
2204 
2205  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[0..15]");
2206  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
2207  WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
2208}
2209
2210/**
2211 - write wavefront substreams sizes for the slice header.
2212 .
2213 \param pcSlice Where we find the substream size information.
2214 */
2215Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
2216{
2217  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
2218  {
2219    return;
2220  }
2221  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
2222  Int  numZeroSubstreamsAtStartOfSlice  = 0;
2223  UInt *entryPointOffset = NULL;
2224  if ( pSlice->getPPS()->getTilesEnabledFlag() )
2225  {
2226    numEntryPointOffsets = pSlice->getTileLocationCount();
2227    entryPointOffset     = new UInt[numEntryPointOffsets];
2228    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
2229    {
2230      if ( idx == 0 )
2231      {
2232        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
2233      }
2234      else
2235      {
2236        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
2237      }
2238
2239      if ( entryPointOffset[ idx ] > maxOffset )
2240      {
2241        maxOffset = entryPointOffset[ idx ];
2242      }
2243    }
2244  }
2245  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
2246  {
2247    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
2248    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
2249    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceSegmentCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
2250    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceSegmentCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
2251    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
2252    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
2253    entryPointOffset           = new UInt[numEntryPointOffsets];
2254    for (Int idx=0; idx<numEntryPointOffsets; idx++)
2255    {
2256      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
2257      if ( entryPointOffset[ idx ] > maxOffset )
2258      {
2259        maxOffset = entryPointOffset[ idx ];
2260      }
2261    }
2262  }
2263  // Determine number of bits "offsetLenMinus1+1" required for entry point information
2264  offsetLenMinus1 = 0;
2265  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
2266  {
2267    offsetLenMinus1++;
2268    assert(offsetLenMinus1 + 1 < 32);   
2269  }
2270
2271  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
2272  if (numEntryPointOffsets>0)
2273  {
2274    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
2275  }
2276
2277  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
2278  {
2279    WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
2280  }
2281
2282  delete [] entryPointOffset;
2283}
2284
2285#if POC_RESET_IDC_SIGNALLING
2286Void  TEncCavlc::codeSliceHeaderExtn( TComSlice* slice, Int shBitsWrittenTillNow )
2287{
2288  Int tmpBitsBeforeWriting = getNumberOfWrittenBits();
2289  if(slice->getPPS()->getSliceHeaderExtensionPresentFlag())
2290  {
2291    // Derive the value of PocMsbValRequiredFlag
2292    slice->setPocMsbValRequiredFlag( slice->getCraPicFlag() || slice->getBlaPicFlag()
2293                                          /* || related to vps_poc_lsb_aligned_flag */
2294                                          );
2295
2296    // Determine value of SH extension length.
2297    Int shExtnLengthInBit = 0;
2298    if (slice->getPPS()->getPocResetInfoPresentFlag())
2299    {
2300      shExtnLengthInBit += 2;
2301    }
2302    if (slice->getPocResetIdc() > 0)
2303    {
2304      shExtnLengthInBit += 6;
2305    }
2306    if (slice->getPocResetIdc() == 3)
2307    {
2308      shExtnLengthInBit += (slice->getSPS()->getBitsForPOC() + 1);
2309    }
2310
2311
2312    if( !slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */ )
2313    {
2314      shExtnLengthInBit++;
2315    }
2316    else
2317    {
2318      if( slice->getPocMsbValRequiredFlag() )
2319      {
2320        slice->setPocMsbValPresentFlag( true );
2321      }
2322      else
2323      {
2324        slice->setPocMsbValPresentFlag( false );
2325      }
2326    }
2327
2328    if( slice->getPocMsbValPresentFlag() )
2329    {
2330      UInt lengthVal = 1;
2331      UInt tempVal = slice->getPocMsbVal() + 1;
2332      assert ( tempVal );
2333      while( 1 != tempVal )
2334      {
2335        tempVal >>= 1;
2336        lengthVal += 2;
2337      }
2338      shExtnLengthInBit += lengthVal;
2339    }
2340    Int shExtnAdditionalBits = 0;
2341    if(shExtnLengthInBit % 8 != 0)
2342    {
2343      shExtnAdditionalBits = 8 - (shExtnLengthInBit % 8);
2344    }
2345    Int shExtnLength = (shExtnLengthInBit + shExtnAdditionalBits) / 8;
2346    WRITE_UVLC( shExtnLength, "slice_header_extension_length" );
2347
2348    if(slice->getPPS()->getPocResetInfoPresentFlag())
2349    {
2350      WRITE_CODE( slice->getPocResetIdc(), 2,                                 "poc_reset_idc");
2351    }
2352    if(slice->getPocResetIdc() > 0)
2353    {
2354      WRITE_CODE( slice->getPocResetPeriodId(), 6,                            "poc_reset_period_id");
2355    }
2356    if(slice->getPocResetIdc() == 3) 
2357    {
2358      WRITE_FLAG( slice->getFullPocResetFlag() ? 1 : 0,                       "full_poc_reset_flag");
2359      WRITE_CODE( slice->getPocLsbVal(), slice->getSPS()->getBitsForPOC(),  "poc_lsb_val");
2360    }
2361
2362    if( !slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */ )
2363    {
2364      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_val_present_flag" );
2365    }
2366    if( slice->getPocMsbValPresentFlag() )
2367    {
2368      WRITE_UVLC( slice->getPocMsbVal(),                                      "poc_msb_val" );
2369    }
2370    for (Int i = 0; i < shExtnAdditionalBits; i++)
2371    {
2372      WRITE_FLAG( 1, "slice_segment_header_extension_reserved_bit");
2373    }
2374  }
2375  shBitsWrittenTillNow += ( getNumberOfWrittenBits() - tmpBitsBeforeWriting );
2376 
2377  // Slice header byte_alignment() included in xAttachSliceDataToNalUnit
2378}
2379#endif
2380
2381Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
2382{
2383}
2384
2385Void TEncCavlc::codeSliceFinish ()
2386{
2387}
2388
2389Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
2390{
2391  assert(0);
2392}
2393
2394Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
2395{
2396  assert(0);
2397}
2398
2399Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
2400{
2401  assert(0);
2402}
2403
2404Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
2405{
2406  assert(0);
2407}
2408
2409Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
2410{
2411  assert(0);
2412}
2413
2414Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
2415{
2416  assert(0);
2417}
2418
2419Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
2420{
2421  assert(0);
2422}
2423
2424Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
2425{
2426  assert(0);
2427}
2428
2429Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
2430{
2431  assert(0);
2432}
2433
2434Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
2435{
2436  assert(0);
2437}
2438
2439Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
2440{
2441  assert(0);
2442}
2443
2444Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
2445{
2446  assert(0);
2447}
2448
2449Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
2450{
2451  assert(0);
2452}
2453Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
2454{
2455  assert(0);
2456}
2457
2458Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
2459{
2460  assert(0);
2461}
2462
2463/** Code I_PCM information.
2464 * \param pcCU pointer to CU
2465 * \param uiAbsPartIdx CU index
2466 * \returns Void
2467 */
2468Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
2469{
2470  assert(0);
2471}
2472
2473Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
2474{
2475  assert(0);
2476}
2477
2478Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
2479{
2480  assert(0);
2481}
2482
2483Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
2484{
2485  assert(0);
2486}
2487
2488Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
2489{
2490  assert(0);
2491}
2492
2493Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
2494{
2495  assert(0);
2496}
2497
2498Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
2499{
2500  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
2501
2502#if REPN_FORMAT_IN_VPS
2503  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
2504#else
2505  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
2506#endif
2507  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
2508
2509  xWriteSvlc( iDQp );
2510 
2511  return;
2512}
2513
2514Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
2515{
2516  assert(0);
2517}
2518
2519Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
2520{
2521  // printf("error : no VLC mode support in this version\n");
2522  return;
2523}
2524
2525// ====================================================================================================================
2526// Protected member functions
2527// ====================================================================================================================
2528
2529/** code explicit wp tables
2530 * \param TComSlice* pcSlice
2531 * \returns Void
2532 */
2533Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
2534{
2535  wpScalingParam  *wp;
2536  Bool            bChroma     = true; // color always present in HEVC ?
2537  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
2538  Bool            bDenomCoded  = false;
2539  UInt            uiMode = 0;
2540  UInt            uiTotalSignalledWeightFlags = 0;
2541#if AUXILIARY_PICTURES
2542  if (pcSlice->getChromaFormatIdc() == CHROMA_400)
2543  {
2544    bChroma = false;
2545  }
2546#endif
2547  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
2548  {
2549    uiMode = 1; // explicit
2550  }
2551  if(uiMode == 1)
2552  {
2553
2554    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
2555    {
2556      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
2557
2558      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
2559      {
2560        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2561        if ( !bDenomCoded ) 
2562        {
2563          Int iDeltaDenom;
2564          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
2565
2566          if( bChroma )
2567          {
2568            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
2569            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
2570          }
2571          bDenomCoded = true;
2572        }
2573        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
2574        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
2575      }
2576      if (bChroma) 
2577      {
2578        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
2579        {
2580          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2581          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
2582          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
2583        }
2584      }
2585
2586      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
2587      {
2588        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2589        if ( wp[0].bPresentFlag ) 
2590        {
2591          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
2592          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
2593          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
2594        }
2595
2596        if ( bChroma ) 
2597        {
2598          if ( wp[1].bPresentFlag )
2599          {
2600            for ( Int j=1 ; j<3 ; j++ ) 
2601            {
2602              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
2603              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
2604
2605              Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
2606              Int iDeltaChroma = (wp[j].iOffset - pred);
2607              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
2608            }
2609          }
2610        }
2611      }
2612    }
2613    assert(uiTotalSignalledWeightFlags<=24);
2614  }
2615}
2616
2617/** code quantization matrix
2618 *  \param scalingList quantization matrix information
2619 */
2620Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
2621{
2622  UInt listId,sizeId;
2623  Bool scalingListPredModeFlag;
2624
2625    //for each size
2626    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2627    {
2628      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
2629      {
2630        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2631        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2632        if(!scalingListPredModeFlag)// Copy Mode
2633        {
2634          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2635        }
2636        else// DPCM Mode
2637        {
2638          xCodeScalingList(scalingList, sizeId, listId);
2639        }
2640      }
2641    }
2642  return;
2643}
2644/** code DPCM
2645 * \param scalingList quantization matrix information
2646 * \param sizeIdc size index
2647 * \param listIdc list index
2648 */
2649Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
2650{
2651  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
2652  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
2653  Int nextCoef = SCALING_LIST_START_VALUE;
2654  Int data;
2655  Int *src = scalingList->getScalingListAddress(sizeId, listId);
2656  if( sizeId > SCALING_LIST_8x8 )
2657  {
2658    WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
2659    nextCoef = scalingList->getScalingListDC(sizeId,listId);
2660  }
2661  for(Int i=0;i<coefNum;i++)
2662  {
2663    data = src[scan[i]] - nextCoef;
2664    nextCoef = src[scan[i]];
2665    if(data > 127)
2666    {
2667      data = data - 256;
2668    }
2669    if(data < -128)
2670    {
2671      data = data + 256;
2672    }
2673
2674    WRITE_SVLC( data,  "scaling_list_delta_coef");
2675  }
2676}
2677Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
2678{
2679  // Bool state = true, state2 = false;
2680  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
2681  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
2682  {
2683    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
2684    {
2685      *ltrpsIndex = k;
2686      return true;
2687    }
2688  }
2689  return false;
2690}
2691Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
2692{
2693  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
2694  {
2695    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
2696      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
2697     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
2698    {
2699      setRefMatrixId(sizeId, listId, predListIdx);
2700      return false;
2701    }
2702  }
2703  return true;
2704}
2705
2706#if Q0048_CGS_3D_ASYMLUT
2707Void TEncCavlc::xCode3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT )
2708{
2709  assert( pc3DAsymLUT->getCurOctantDepth() < 4 );
2710  WRITE_CODE( pc3DAsymLUT->getCurOctantDepth() , 2 , "cm_octant_depth" );
2711  assert( pc3DAsymLUT->getCurYPartNumLog2() < 4 );
2712  WRITE_CODE( pc3DAsymLUT->getCurYPartNumLog2() , 2 , "cm_y_part_num_log2" );
2713  assert( pc3DAsymLUT->getInputBitDepthY() < 16 );
2714  WRITE_CODE( pc3DAsymLUT->getInputBitDepthY() - 8 , 3 , "cm_input_bit_depth_minus8" );
2715  WRITE_SVLC(pc3DAsymLUT->getInputBitDepthC()-pc3DAsymLUT->getInputBitDepthY(), "cm_input_bit_depth_chroma delta");
2716  assert( pc3DAsymLUT->getOutputBitDepthY() < 16 );
2717  WRITE_CODE( pc3DAsymLUT->getOutputBitDepthY() - 8 , 3 , "cm_output_bit_depth_minus8" );
2718  WRITE_SVLC(pc3DAsymLUT->getOutputBitDepthC()-pc3DAsymLUT->getOutputBitDepthY(), "cm_output_bit_depth_chroma_delta");
2719  assert( pc3DAsymLUT->getResQuantBit() < 4 );
2720  WRITE_CODE( pc3DAsymLUT->getResQuantBit() , 2 , "cm_res_quant_bit" );
2721
2722  xCode3DAsymLUTOctant( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth() );
2723}
2724
2725Void TEncCavlc::xCode3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength )
2726{
2727  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
2728  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
2729    WRITE_FLAG( uiOctantSplit , "split_octant_flag" );
2730  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
2731  if( uiOctantSplit )
2732  {
2733    Int nHalfLength = nLength >> 1;
2734    for( Int l = 0 ; l < 2 ; l++ )
2735    {
2736      for( Int m = 0 ; m < 2 ; m++ )
2737      {
2738        for( Int n = 0 ; n < 2 ; n++ )
2739        {
2740          xCode3DAsymLUTOctant( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength );
2741        }
2742      }
2743    }
2744  }
2745  else
2746  {
2747    for( Int l = 0 ; l < nYPartNum ; l++ )
2748    {
2749      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
2750      {
2751        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
2752        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
2753        WRITE_FLAG( uiCodeVertex , "coded_vertex_flag" );
2754        if( uiCodeVertex )
2755        {
2756          WRITE_SVLC( sRes.Y , "resY" );
2757          WRITE_SVLC( sRes.U , "resU" );
2758          WRITE_SVLC( sRes.V , "resV" );
2759        }
2760      }
2761    }
2762  }
2763}
2764#endif
2765//! \}
Note: See TracBrowser for help on using the repository browser.