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

Last change on this file since 873 was 872, checked in by qualcomm, 10 years ago

Move calculation of MaxSubLayerInLayerSets to a separate function (Macro: SUB_LAYERS_IN_LAYER_SET)

From: Adarsh K. Ramasubramonian <aramasub@…>

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