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

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

DPB-information for output layer sets in the VPS extension. (MACRO: VPS_DPB_SIZE_TABLE)

Includes DPB-table signaling for output layer sets in the VPS extension.

From: Adarsh K. Ramasubramonian <aramasub@…>

  • Property svn:eol-style set to native
File size: 85.3 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-2013, 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{
158#if ENC_DEC_TRACE 
159  xTracePPSHeader (pcPPS);
160#endif
161 
162  WRITE_UVLC( pcPPS->getPPSId(),                             "pps_pic_parameter_set_id" );
163  WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
164  WRITE_FLAG( pcPPS->getDependentSliceSegmentsEnabledFlag()    ? 1 : 0, "dependent_slice_segments_enabled_flag" );
165  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,     "output_flag_present_flag" );
166  WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3,        "num_extra_slice_header_bits");
167  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
168  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
169  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
170  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
171
172  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "init_qp_minus26");
173  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
174  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" ); 
175  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
176  if ( pcPPS->getUseDQP() )
177  {
178    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
179  }
180  WRITE_SVLC( pcPPS->getChromaCbQpOffset(),                   "pps_cb_qp_offset" );
181  WRITE_SVLC( pcPPS->getChromaCrQpOffset(),                   "pps_cr_qp_offset" );
182  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
183
184  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
185  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
186  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
187  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
188  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
189  if( pcPPS->getTilesEnabledFlag() )
190  {
191    WRITE_UVLC( pcPPS->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
192    WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
193    WRITE_FLAG( pcPPS->getUniformSpacingFlag(),                                  "uniform_spacing_flag" );
194    if( pcPPS->getUniformSpacingFlag() == 0 )
195    {
196      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
197      {
198        WRITE_UVLC( pcPPS->getColumnWidth(i)-1,                                  "column_width_minus1" );
199      }
200      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
201      {
202        WRITE_UVLC( pcPPS->getRowHeight(i)-1,                                    "row_height_minus1" );
203      }
204    }
205    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=0)
206    {
207      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
208    }
209  }
210  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
211  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
212  if(pcPPS->getDeblockingFilterControlPresentFlag())
213  {
214    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" ); 
215    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
216    if(!pcPPS->getPicDisableDeblockingFilterFlag())
217    {
218      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
219      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
220    }
221  }
222  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
223
224#if IL_SL_SIGNALLING_N0371
225  pcPPS->setPPS( pcPPS->getLayerId(), pcPPS ); 
226#endif
227
228  if( pcPPS->getScalingListPresentFlag() )
229  {
230#if SCALING_LIST_OUTPUT_RESULT
231    printf("PPS\n");
232#endif
233
234#if IL_SL_SIGNALLING_N0371
235    m_pcSlice->getScalingList()->setLayerId( pcPPS->getLayerId() );
236
237    if( pcPPS->getLayerId() > 0 )
238    {
239      WRITE_FLAG( pcPPS->getPredScalingListFlag() ? 1 : 0,                          "pps_pred_scaling_list_flag" );
240      m_pcSlice->getScalingList()->setPredScalingListFlag( pcPPS->getPredScalingListFlag() );
241
242      if( pcPPS->getPredScalingListFlag() )
243      {
244        // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
245        assert( /*pcPPS->getScalingListRefLayerId() >= 0 &&*/ pcPPS->getScalingListRefLayerId() <= 62 );
246
247        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of pps_scaling_list_ref_layer_id shall be greater than 0
248        if( pcPPS->getSPS()->getVPS()->getAvcBaseLayerFlag() )
249        {
250          assert( pcPPS->getScalingListRefLayerId() > 0 );
251        }
252
253        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
254        // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
255        assert( pcPPS->getPPS( pcPPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
256
257        // It is a requirement of bitstream conformance that, when a PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
258        // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
259        assert( pcPPS->getSPS()->getVPS()->getScalingListLayerDependency( pcPPS->getLayerId(), pcPPS->getScalingListRefLayerId() ) == true );
260       
261        WRITE_UVLC( pcPPS->getScalingListRefLayerId(),                            "scaling_list_pps_ref_layer_id" );
262        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcPPS->getScalingListRefLayerId() );
263        codeScalingList( m_pcSlice->getScalingList() );
264      }
265      else
266      {
267        codeScalingList( m_pcSlice->getScalingList() );
268      }
269    }
270    else
271    {
272      codeScalingList( m_pcSlice->getScalingList() );
273    }
274#else
275    codeScalingList( m_pcSlice->getScalingList() );
276#endif
277
278  }
279  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
280  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
281  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
282  WRITE_FLAG( 0, "pps_extension_flag" );
283}
284
285Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
286{
287#if ENC_DEC_TRACE
288  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
289#endif
290  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
291  if (pcVUI->getAspectRatioInfoPresentFlag())
292  {
293    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
294    if (pcVUI->getAspectRatioIdc() == 255)
295    {
296      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
297      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
298    }
299  }
300  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
301  if (pcVUI->getOverscanInfoPresentFlag())
302  {
303    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
304  }
305  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
306  if (pcVUI->getVideoSignalTypePresentFlag())
307  {
308    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
309    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
310    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
311    if (pcVUI->getColourDescriptionPresentFlag())
312    {
313      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
314      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
315      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
316    }
317  }
318
319  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
320  if (pcVUI->getChromaLocInfoPresentFlag())
321  {
322    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
323    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
324  }
325
326  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
327  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
328  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
329
330  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
331  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
332  if( defaultDisplayWindow.getWindowEnabledFlag() )
333  {
334    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset(),      "def_disp_win_left_offset");
335    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset(),     "def_disp_win_right_offset");
336    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset(),       "def_disp_win_top_offset");
337    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset(),    "def_disp_win_bottom_offset");
338  }
339  TimingInfo *timingInfo = pcVUI->getTimingInfo();
340  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
341  if(timingInfo->getTimingInfoPresentFlag())
342  {
343    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
344    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
345    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
346    if(timingInfo->getPocProportionalToTimingFlag())
347    {
348      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
349    }
350  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
351  if( pcVUI->getHrdParametersPresentFlag() )
352  {
353    codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
354  }
355  }
356
357  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
358  if (pcVUI->getBitstreamRestrictionFlag())
359  {
360    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
361    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
362    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
363    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
364    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
365    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
366    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
367    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
368  }
369}
370
371Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
372{
373  if( commonInfPresentFlag )
374  {
375    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
376    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
377    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
378    {
379      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
380      if( hrd->getSubPicCpbParamsPresentFlag() )
381      {
382        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
383        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
384        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
385        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
386      }
387      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
388      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
389      if( hrd->getSubPicCpbParamsPresentFlag() )
390      {
391        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" ); 
392      }
393      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
394      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
395      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
396    }
397  }
398  Int i, j, nalOrVcl;
399  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
400  {
401    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
402    if( !hrd->getFixedPicRateFlag( i ) )
403    {
404      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
405    }
406    else
407    {
408      hrd->setFixedPicRateWithinCvsFlag( i, true );
409    }
410    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
411    {
412      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
413    }
414    else
415    {
416      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
417    }
418    if (!hrd->getLowDelayHrdFlag( i ))
419    {
420      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
421    }
422   
423    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
424    {
425      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
426          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
427      {
428        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
429        {
430          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
431          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
432          if( hrd->getSubPicCpbParamsPresentFlag() )
433          {
434            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1"); 
435            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
436          }
437          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
438        }
439      }
440    }
441  }
442}
443
444Void TEncCavlc::codeSPS( TComSPS* pcSPS )
445{
446#if ENC_DEC_TRACE 
447  xTraceSPSHeader (pcSPS);
448#endif
449  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
450#if SVC_EXTENSION
451  if(pcSPS->getLayerId() == 0)
452  {
453#endif
454    WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
455    WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
456#if SVC_EXTENSION
457  }
458#endif
459#ifdef SPS_PTL_FIX
460  if (pcSPS->getLayerId() == 0)
461  {
462    codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
463  }
464#else
465  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
466#endif
467  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
468#if REPN_FORMAT_IN_VPS
469  if( pcSPS->getLayerId() > 0 )
470  {
471    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
472  }
473#if O0096_REP_FORMAT_INDEX
474  if( pcSPS->getLayerId() == 0 ) 
475#else
476  if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
477#endif
478  {
479#endif
480    WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
481    assert(pcSPS->getChromaFormatIdc () == 1);
482    // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
483    if( pcSPS->getChromaFormatIdc () == 3 )
484    {
485      WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
486    }
487
488    WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
489    WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
490#if REPN_FORMAT_IN_VPS
491  }
492#if O0096_REP_FORMAT_INDEX
493  else if (pcSPS->getUpdateRepFormatFlag())
494  {
495    WRITE_CODE( pcSPS->getUpdateRepFormatIndex(), 8,   "update_rep_format_index");
496  }
497#endif
498#endif
499  Window conf = pcSPS->getConformanceWindow();
500
501  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
502  if (conf.getWindowEnabledFlag())
503  {
504    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
505    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
506    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
507    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
508  }
509
510#if REPN_FORMAT_IN_VPS
511#if O0096_REP_FORMAT_INDEX
512  if( pcSPS->getLayerId() == 0 ) 
513#else
514  if( pcSPS->getLayerId() == 0 || pcSPS->getUpdateRepFormatFlag() ) 
515#endif 
516  {
517    assert( pcSPS->getBitDepthY() >= 8 );
518    assert( pcSPS->getBitDepthC() >= 8 );
519#endif
520    WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
521    WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
522#if REPN_FORMAT_IN_VPS
523  }
524#endif
525  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
526
527  const Bool subLayerOrderingInfoPresentFlag = 1;
528  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
529  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
530  {
531    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
532    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
533    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
534    if (!subLayerOrderingInfoPresentFlag)
535    {
536      break;
537    }
538  }
539  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
540 
541  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
542  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
543  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
544  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
545  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
546  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
547  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
548
549#if IL_SL_SIGNALLING_N0371
550  pcSPS->setSPS( pcSPS->getLayerId(), pcSPS );
551#endif
552
553  if(pcSPS->getScalingListFlag())
554  {
555    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
556    if(pcSPS->getScalingListPresentFlag())
557    {
558#if SCALING_LIST_OUTPUT_RESULT
559    printf("SPS\n");
560#endif
561
562#if IL_SL_SIGNALLING_N0371
563    m_pcSlice->getScalingList()->setLayerId( pcSPS->getLayerId() );
564
565    if( pcSPS->getLayerId() > 0 )
566    {
567      WRITE_FLAG( pcSPS->getPredScalingListFlag() ? 1 : 0,                          "sps_pred_scaling_list_flag" );
568      m_pcSlice->getScalingList()->setPredScalingListFlag( pcSPS->getPredScalingListFlag() );
569
570      if( pcSPS->getPredScalingListFlag() )
571      {
572
573        // The value of sps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
574        assert( /*pcSPS->getScalingListRefLayerId() >= 0 &&*/ pcSPS->getScalingListRefLayerId() <= 62 );
575       
576        // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
577        if( pcSPS->getVPS()->getAvcBaseLayerFlag() )
578        {
579          assert( pcSPS->getScalingListRefLayerId() > 0 );
580        }
581
582        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
583        // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
584        assert( pcSPS->getSPS( pcSPS->getScalingListRefLayerId() )->getPredScalingListFlag() == false );
585
586        // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
587        // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
588        assert( pcSPS->getVPS()->getScalingListLayerDependency( pcSPS->getLayerId(), pcSPS->getScalingListRefLayerId() ) == true );
589
590        WRITE_UVLC( pcSPS->getScalingListRefLayerId(),                            "scaling_list_sps_ref_layer_id" );
591        m_pcSlice->getScalingList()->setScalingListRefLayerId( pcSPS->getScalingListRefLayerId() );
592        codeScalingList( m_pcSlice->getScalingList() );
593      }
594      else
595      {
596        codeScalingList( m_pcSlice->getScalingList() );
597      }
598    }
599    else
600    {
601      codeScalingList( m_pcSlice->getScalingList() );
602    }
603#else
604      codeScalingList( m_pcSlice->getScalingList() );
605#endif
606
607    }
608  }
609  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
610  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
611
612  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
613  if( pcSPS->getUsePCM() )
614  {
615    WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,                                  "pcm_sample_bit_depth_luma_minus1" );
616    WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4,                                "pcm_sample_bit_depth_chroma_minus1" );
617    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
618    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
619    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
620  }
621
622  assert( pcSPS->getMaxTLayers() > 0 );         
623
624  TComRPSList* rpsList = pcSPS->getRPSList();
625  TComReferencePictureSet*      rps;
626 
627  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
628  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
629  {
630    rps = rpsList->getReferencePictureSet(i);
631    codeShortTermRefPicSet(pcSPS,rps,false, i);
632  }
633  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
634  if (pcSPS->getLongTermRefsPresent()) 
635  {
636    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
637    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
638    {
639      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
640      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
641    }
642  }
643  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
644#if REF_IDX_MFM
645#if !M0457_COL_PICTURE_SIGNALING
646  if( pcSPS->getLayerId() > 0 )
647  {
648    WRITE_FLAG( pcSPS->getMFMEnabledFlag() ? 1 : 0,          "sps_enh_mfm_enable_flag" );
649  }
650#endif
651#endif
652  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
653
654  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
655  if (pcSPS->getVuiParametersPresentFlag())
656  {
657      codeVUI(pcSPS->getVuiParameters(), pcSPS);
658  }
659
660#if SPS_EXTENSION
661  WRITE_FLAG( 1, "sps_extension_flag" );
662  if( 1 )   // if( sps_extension_flag )
663  {
664#if O0142_CONDITIONAL_SPS_EXTENSION
665    UInt spsExtensionTypeFlag[8] = { 0, 1, 0, 0, 0, 0, 0, 0 };
666    for (UInt i = 0; i < 8; i++)
667    {
668      WRITE_FLAG( spsExtensionTypeFlag[i], "sps_extension_type_flag" );
669    }
670    if (spsExtensionTypeFlag[1])
671    {
672      codeSPSExtension( pcSPS );
673    }
674#else
675    codeSPSExtension( pcSPS );
676    WRITE_FLAG( 0, "sps_extension2_flag" );
677#endif
678  }
679#else
680  WRITE_FLAG( 0, "sps_extension_flag" );
681#endif
682}
683#if SPS_EXTENSION
684Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
685{
686  // more syntax elements to be written here
687
688#if VERT_MV_CONSTRAINT
689  // Vertical MV component restriction is not used in SHVC CTC
690  WRITE_FLAG( 0, "inter_view_mv_vert_constraint_flag" );
691#endif
692  if( pcSPS->getLayerId() > 0 )
693  {
694    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
695    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
696    {
697      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
698#if O0098_SCALED_REF_LAYER_ID
699      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
700#endif
701      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
702      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
703      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
704      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
705    }
706  }
707#if M0463_VUI_EXT_ILP_REF
708  ////   sps_extension_vui_parameters( )
709  if( pcSPS->getVuiParameters()->getBitstreamRestrictionFlag() )
710  { 
711    WRITE_UVLC( pcSPS->getNumIlpRestrictedRefLayers( ),           "num_ilp_restricted_ref_layers" ); 
712    for( Int i = 0; i < pcSPS->getNumIlpRestrictedRefLayers( ); i++ ) 
713    { 
714      WRITE_UVLC( pcSPS->getMinSpatialSegmentOffsetPlus1( i ),    "min_spatial_segment_offset_plus1" ); 
715      if( pcSPS->getMinSpatialSegmentOffsetPlus1( i ) > 0 ) 
716      { 
717        WRITE_FLAG( pcSPS->getCtuBasedOffsetEnabledFlag( i ),      "ctu_based_offset_enabled_flag[ i ]"); 
718        if( pcSPS->getCtuBasedOffsetEnabledFlag( i ) ) 
719        {
720          WRITE_UVLC( pcSPS->getMinHorizontalCtuOffsetPlus1( i ), "min_horizontal_ctu_offset_plus1[ i ]"); 
721        }
722      } 
723    } 
724  } 
725  ////   sps_extension_vui_parameters( ) END
726#endif
727}
728#endif
729Void TEncCavlc::codeVPS( TComVPS* pcVPS )
730{
731#if VPS_EXTN_OFFSET_CALC
732  UInt numBytesInVps = this->m_pcBitIf->getNumberOfWrittenBits();
733#endif
734  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
735  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
736#if VPS_RENAME
737  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );           
738#else
739  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
740#endif
741  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
742  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
743  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
744#if VPS_EXTN_OFFSET
745  WRITE_CODE( pcVPS->getExtensionOffset(),         16,        "vps_extension_offset" );
746#else
747  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
748#endif
749  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
750  const Bool subLayerOrderingInfoPresentFlag = 1;
751  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
752  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
753  {
754    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
755    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
756    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
757    if (!subLayerOrderingInfoPresentFlag)
758    {
759      break;
760    }
761  }
762
763#if VPS_RENAME
764  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
765  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_ID_PLUS1 );
766#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
767  pcVPS->setNumLayerSets(1);
768#endif
769  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
770  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
771  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getNumLayerSets() - 1 ); opsIdx ++ )
772  {
773    // Operation point set
774    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
775#else
776  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
777  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
778  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
779  pcVPS->setMaxOpSets(1);
780  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
781  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
782  {
783    // Operation point set
784    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
785#endif
786    {
787#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
788      // Only applicable for version 1
789      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
790#endif
791      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
792    }
793  }
794#if DERIVE_LAYER_ID_LIST_VARIABLES
795  pcVPS->deriveLayerIdListVariables();
796#endif
797  TimingInfo *timingInfo = pcVPS->getTimingInfo();
798  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
799  if(timingInfo->getTimingInfoPresentFlag())
800  {
801    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
802    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
803    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
804    if(timingInfo->getPocProportionalToTimingFlag())
805    {
806      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
807    }
808    pcVPS->setNumHrdParameters( 0 );
809    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
810
811    if( pcVPS->getNumHrdParameters() > 0 )
812    {
813      pcVPS->createHrdParamBuffer();
814    }
815    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
816    {
817      // Only applicable for version 1
818      pcVPS->setHrdOpSetIdx( 0, i );
819      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
820      if( i > 0 )
821      {
822        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
823      }
824      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
825    }
826  }
827#if !VPS_EXTNS
828  WRITE_FLAG( 0,                     "vps_extension_flag" );
829#else
830  WRITE_FLAG( 1,                     "vps_extension_flag" );
831  if(1) // Should be conditioned on the value of vps_extension_flag
832  {
833    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
834    {
835      WRITE_FLAG(1,                  "vps_extension_alignment_bit_equal_to_one");
836    }
837#if VPS_EXTN_OFFSET_CALC
838    Int vpsExntOffsetValueInBits = this->m_pcBitIf->getNumberOfWrittenBits() - numBytesInVps + 16; // 2 bytes for NUH
839    assert( vpsExntOffsetValueInBits % 8 == 0 );
840    pcVPS->setExtensionOffset( vpsExntOffsetValueInBits >> 3 );
841#endif
842    codeVPSExtension(pcVPS);
843    WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
844  }
845#endif 
846  //future extensions here..
847 
848  return;
849}
850
851#if SVC_EXTENSION
852#if VPS_EXTNS
853Void TEncCavlc::codeVPSExtension (TComVPS *vps)
854{
855  // ... More syntax elements to be written here
856#if VPS_EXTN_MASK_AND_DIM_INFO
857  UInt i = 0, j = 0;
858
859  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
860  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
861
862  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
863  {
864    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
865  }
866
867  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
868  {
869    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
870  }
871
872#if SPL_FLG_CHK
873  if(vps->getSplittingFlag())
874  {
875    UInt splDimSum=0;
876    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
877    {
878      splDimSum+=(vps->getDimensionIdLen(j));
879    }
880    assert(splDimSum<=6);
881  }
882#endif
883
884  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
885  for(i = 1; i < vps->getMaxLayers(); i++)
886  {
887    if( vps->getNuhLayerIdPresentFlag() )
888    {
889      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
890    }
891
892    if( !vps->getSplittingFlag() )
893    {
894    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
895    {
896      UInt bits = vps->getDimensionIdLen(j);
897      WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
898    }
899  }
900  }
901#endif
902#if VIEW_ID_RELATED_SIGNALING
903  // if ( pcVPS->getNumViews() > 1 ) 
904  //   However, this is a bug in the text since, view_id_len_minus1 is needed to parse view_id_val.
905  {
906    WRITE_CODE( vps->getViewIdLenMinus1( ), 4, "view_id_len_minus1" );
907  }
908
909  for(  i = 0; i < vps->getNumViews(); i++ )
910  {
911    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLenMinus1( ) + 1, "view_id_val[i]" );
912  }
913#endif
914#if VPS_EXTN_DIRECT_REF_LAYERS
915  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
916  {
917    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
918    {
919      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
920    }
921  }
922#endif
923#if VPS_TSLAYERS
924    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
925    if (vps->getMaxTSLayersPresentFlag())
926    {
927        for( i = 0; i < vps->getMaxLayers() - 1; i++)
928        {
929            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
930        }
931    }
932#endif
933#if JCTVC_M0203_INTERLAYER_PRED_IDC
934#if N0120_MAX_TID_REF_PRESENT_FLAG
935   WRITE_FLAG( vps->getMaxTidRefPresentFlag(), "max_tid_ref_present_flag");
936   if (vps->getMaxTidRefPresentFlag())
937   {
938     for( i = 0; i < vps->getMaxLayers() - 1; i++)
939     {
940#if O0225_MAX_TID_FOR_REF_LAYERS
941       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
942       {
943         if(vps->getDirectDependencyFlag(j, i))
944         {
945           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
946         }
947       }
948#else
949       WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
950#endif
951     }
952   }
953#else
954  for( i = 0; i < vps->getMaxLayers() - 1; i++)
955  {
956#if O0225_MAX_TID_FOR_REF_LAYERS
957       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
958       {
959         if(vps->getDirectDependencyFlag(j, i))
960         {
961           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
962         }
963       }
964#else
965    WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i), 3, "max_tid_il_ref_pics_plus1[i]" );
966#endif
967  }
968#endif
969#endif
970#if ILP_SSH_SIG
971    WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
972#endif
973#if VPS_EXTN_PROFILE_INFO
974  // Profile-tier-level signalling
975  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
976  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
977  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
978  {
979    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
980    if( !vps->getProfilePresentFlag(idx) )
981    {
982      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
983    }
984    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
985  }
986#endif
987
988  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
989  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
990  if(numOutputLayerSets > vps->getNumLayerSets())
991  {
992    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
993  }
994  if( numOutputLayerSets > 1 )
995  {
996    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
997  }
998
999  for(i = 1; i < numOutputLayerSets; i++)
1000  {
1001    if( i > (vps->getNumLayerSets() - 1) )
1002    {
1003      Int numBits = 1;
1004      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
1005      {
1006        numBits++;
1007      }
1008      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "output_layer_set_idx_minus1"); 
1009      Int lsIdx = vps->getOutputLayerSetIdx(i);
1010      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
1011      {
1012        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
1013      }
1014    }
1015    Int numBits = 1;
1016    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
1017    {
1018      numBits++;
1019    }
1020    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
1021  }
1022
1023#if O0153_ALT_OUTPUT_LAYER_FLAG
1024  if( vps->getMaxLayers() > 1 )
1025  {
1026    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
1027  }
1028#endif
1029
1030#if REPN_FORMAT_IN_VPS
1031  WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
1032
1033  if( vps->getRepFormatIdxPresentFlag() )
1034  {
1035#if O0096_REP_FORMAT_INDEX
1036    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
1037#else
1038    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
1039#endif
1040  }
1041  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
1042  {
1043    // Read rep_format_structures
1044    codeRepFormat( vps->getVpsRepFormat(i) );
1045  }
1046 
1047  if( vps->getRepFormatIdxPresentFlag() )
1048  {
1049    for(i = 1; i < vps->getMaxLayers(); i++)
1050    {
1051      if( vps->getVpsNumRepFormats() > 1 )
1052      {
1053#if O0096_REP_FORMAT_INDEX
1054        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
1055#else
1056        WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
1057#endif
1058      }
1059    }
1060  }
1061#endif
1062
1063#if JCTVC_M0458_INTERLAYER_RPS_SIG
1064      WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
1065#endif
1066#if O0062_POC_LSB_NOT_PRESENT_FLAG
1067  for(i = 1; i< vps->getMaxLayers(); i++)
1068  {
1069    if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
1070    {
1071      WRITE_FLAG(vps->getPocLsbNotPresentFlag(i), "poc_lsb_not_present_flag[i]");
1072    }
1073  }
1074#endif
1075#if O0215_PHASE_ALIGNMENT
1076  WRITE_FLAG(vps->getPhaseAlignFlag(), "cross_layer_phase_alignment_flag" );
1077#endif
1078#if N0147_IRAP_ALIGN_FLAG && !IRAP_ALIGN_FLAG_IN_VPS_VUI
1079  WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
1080#endif
1081#if VPS_DPB_SIZE_TABLE
1082  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
1083  {
1084    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]"); 
1085    for(j = 0; j < vps->getMaxTLayers(); j++)
1086    {
1087      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
1088      {
1089        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]"); 
1090      }
1091      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
1092      {
1093        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
1094        {
1095          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j), "max_vps_dec_pic_buffering_minus1[i][k][j]" ); 
1096        }
1097        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );             
1098        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );       
1099      }
1100    }
1101  }
1102#endif
1103#if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
1104  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
1105#if O0096_DEFAULT_DEPENDENCY_TYPE
1106  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
1107  if (vps->getDefaultDirectDependencyTypeFlag())
1108  {
1109    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
1110  }
1111  else
1112  {
1113    for(i = 1; i < vps->getMaxLayers(); i++)
1114    {
1115      for(j = 0; j < i; j++)
1116      {
1117        if (vps->getDirectDependencyFlag(i, j))
1118        {
1119          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
1120        }
1121      }
1122    }
1123  }
1124#else
1125  for(i = 1; i < vps->getMaxLayers(); i++)
1126  {
1127    for(j = 0; j < i; j++)
1128    {
1129      if (vps->getDirectDependencyFlag(i, j))
1130      {
1131        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
1132      }
1133    }
1134  }
1135#endif
1136
1137#if IL_SL_SIGNALLING_N0371
1138  for(i = 1; i < vps->getMaxLayers(); i++)
1139  {
1140    for(j = 0; j < i; j++)
1141    {
1142      vps->setScalingListLayerDependency( i, j, vps->checkLayerDependency( i,j ) );
1143    }
1144  }
1145#endif
1146
1147#endif
1148#if M0040_ADAPTIVE_RESOLUTION_CHANGE
1149  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
1150#endif
1151
1152#if !VPS_VUI
1153  WRITE_FLAG( 0,                     "vps_vui_present_flag" );
1154#else
1155  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
1156  if(1)   // Should be conditioned on the value of vps_vui_present_flag
1157  {
1158    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
1159    {
1160      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
1161    }
1162    codeVPSVUI(vps); 
1163  }
1164#endif
1165}
1166#endif
1167#if REPN_FORMAT_IN_VPS
1168Void  TEncCavlc::codeRepFormat      ( RepFormat *repFormat )
1169{
1170#if REPN_FORMAT_CONTROL_FLAG
1171   WRITE_FLAG ( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_presenet_flag"); 
1172
1173   WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );   
1174   WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" ); 
1175
1176   if ( repFormat->getChromaAndBitDepthVpsPresentFlag() )
1177   {
1178     WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
1179
1180     if( repFormat->getChromaFormatVpsIdc() == 3 )
1181     {
1182       WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");     
1183     }
1184
1185     assert( repFormat->getBitDepthVpsLuma() >= 8 );
1186     assert( repFormat->getBitDepthVpsChroma() >= 8 );
1187     WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
1188     WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
1189   }
1190#else
1191  WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );   
1192 
1193  if( repFormat->getChromaFormatVpsIdc() == 3 )
1194  {
1195    WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");     
1196  }
1197
1198  WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );   
1199  WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );   
1200 
1201  assert( repFormat->getBitDepthVpsLuma() >= 8 );
1202  assert( repFormat->getBitDepthVpsChroma() >= 8 );
1203  WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
1204  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
1205#endif
1206
1207}
1208#endif
1209#if VPS_VUI
1210Void TEncCavlc::codeVPSVUI (TComVPS *vps)
1211{
1212  Int i,j;
1213#if IRAP_ALIGN_FLAG_IN_VPS_VUI
1214      WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
1215#endif
1216#if VPS_VUI_BITRATE_PICRATE
1217  WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
1218  WRITE_FLAG( vps->getPicRatePresentVpsFlag(),        "pic_rate_present_vps_flag" );
1219
1220  if( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
1221  {
1222    for( i = 0; i < vps->getNumLayerSets(); i++ )
1223    {
1224      for( j = 0; j < vps->getMaxTLayers(); j++ )
1225      {
1226        if( vps->getBitRatePresentVpsFlag() )
1227        {
1228          WRITE_FLAG( vps->getBitRatePresentFlag( i, j),        "bit_rate_present_vps_flag[i][j]" );
1229        }
1230        if( vps->getPicRatePresentVpsFlag() )
1231        {
1232          WRITE_FLAG( vps->getPicRatePresentFlag( i, j),        "pic_rate_present_vps_flag[i][j]" );
1233        }
1234        if( vps->getBitRatePresentFlag(i, j) )
1235        {
1236          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "avg_bit_rate[i][j]" );
1237          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "max_bit_rate[i][j]" );
1238        }
1239        if( vps->getPicRatePresentFlag(i, j) )
1240        {
1241          WRITE_CODE( vps->getConstPicRateIdc( i, j), 2 , "constant_pic_rate_idc[i][j]" ); 
1242          WRITE_CODE( vps->getConstPicRateIdc( i, j), 16, "avg_pic_rate[i][j]"          ); 
1243        }
1244      }
1245    }
1246  }
1247#endif
1248#if TILE_BOUNDARY_ALIGNED_FLAG
1249  for(i = 1; i < vps->getMaxLayers(); i++)
1250  {
1251    for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
1252    {
1253      WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
1254    }
1255  } 
1256#endif
1257#if N0160_VUI_EXT_ILP_REF
1258  WRITE_FLAG( vps->getNumIlpRestrictedRefLayers() ? 1 : 0 , "num_ilp_restricted_ref_layers" );   
1259  if( vps->getNumIlpRestrictedRefLayers())
1260  {
1261    for(i = 1; i < vps->getMaxLayers(); i++)
1262    {
1263      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
1264      {       
1265        WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
1266       
1267        if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
1268        { 
1269          WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );   
1270         
1271          if(vps->getCtuBasedOffsetEnabledFlag(i,j)) 
1272          {
1273            WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");           
1274          }
1275        } 
1276      } 
1277    }
1278  }
1279#endif
1280}
1281#endif
1282#endif //SVC_EXTENSION
1283
1284Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
1285{
1286#if ENC_DEC_TRACE 
1287  xTraceSliceHeader (pcSlice);
1288#endif
1289
1290  //calculate number of bits required for slice address
1291  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumCUsInFrame();
1292  Int bitsSliceSegmentAddress = 0;
1293  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress)) 
1294  {
1295    bitsSliceSegmentAddress++;
1296  }
1297  Int ctuAddress;
1298  if (pcSlice->isNextSlice())
1299  {
1300    // Calculate slice address
1301    ctuAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
1302  }
1303  else
1304  {
1305    // Calculate slice address
1306    ctuAddress = (pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
1307  }
1308  //write slice address
1309  Int sliceSegmentAddress = pcSlice->getPic()->getPicSym()->getCUOrderMap(ctuAddress);
1310
1311  WRITE_FLAG( sliceSegmentAddress==0, "first_slice_segment_in_pic_flag" );
1312  if ( pcSlice->getRapPicFlag() )
1313  {
1314    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
1315  }
1316  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
1317  pcSlice->setDependentSliceSegmentFlag(!pcSlice->isNextSlice());
1318  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentAddress!=0) )
1319  {
1320    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
1321  }
1322  if(sliceSegmentAddress>0)
1323  {
1324    WRITE_CODE( sliceSegmentAddress, bitsSliceSegmentAddress, "slice_segment_address" );
1325  }
1326  if ( !pcSlice->getDependentSliceSegmentFlag() )
1327  {
1328#if SVC_EXTENSION
1329#if POC_RESET_FLAG
1330    Int iBits = 0;
1331    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1332    {
1333      WRITE_FLAG( pcSlice->getPocResetFlag(), "poc_reset_flag" );
1334      iBits++;
1335    }
1336    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
1337    {
1338      assert(!!"discardable_flag");
1339      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1340      iBits++;
1341    }
1342    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
1343    {
1344      assert(!!"slice_reserved_undetermined_flag[]");
1345      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1346    }
1347#else
1348    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
1349    {
1350      assert(!!"discardable_flag");
1351      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
1352    }
1353    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1354    {
1355      assert(!!"slice_reserved_undetermined_flag[]");
1356      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1357    }
1358#endif
1359#else //SVC_EXTENSION
1360    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1361    {
1362      assert(!!"slice_reserved_undetermined_flag[]");
1363      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1364    }
1365#endif //SVC_EXTENSION
1366
1367    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1368
1369    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1370    {
1371      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1372    }
1373
1374#if !AUXILIARY_PICTURES
1375#if REPN_FORMAT_IN_VPS
1376    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1377    assert( pcSlice->getChromaFormatIdc() == 1 );
1378#else
1379    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1380    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
1381#endif
1382#endif
1383    // if( separate_colour_plane_flag  ==  1 )
1384    //   colour_plane_id                                      u(2)
1385
1386#if N0065_LAYER_POC_ALIGNMENT
1387#if O0062_POC_LSB_NOT_PRESENT_FLAG
1388    if( (pcSlice->getLayerId() > 0 && !pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdInVps(pcSlice->getLayerId())) ) || !pcSlice->getIdrPicFlag())
1389#else
1390    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
1391#endif
1392#else
1393    if( !pcSlice->getIdrPicFlag() )
1394#endif
1395    {
1396#if POC_RESET_FLAG
1397      Int picOrderCntLSB;
1398      if( !pcSlice->getPocResetFlag() )
1399      {
1400        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1401      }
1402      else
1403      {
1404        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1405      }
1406#else
1407      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1408#endif
1409      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
1410
1411#if N0065_LAYER_POC_ALIGNMENT
1412#if SHM_FIX7
1413    }
1414#endif
1415      if( !pcSlice->getIdrPicFlag() )
1416      {
1417#endif
1418      TComReferencePictureSet* rps = pcSlice->getRPS();
1419     
1420#if FIX1071
1421      // check for bitstream restriction stating that:
1422      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1423      // Ideally this process should not be repeated for each slice in a picture
1424#if SVC_EXTENSION
1425      if( pcSlice->getLayerId() == 0 )
1426#endif
1427      if (pcSlice->isIRAP())
1428      {
1429        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1430        {
1431          assert (!rps->getUsed(picIdx));
1432        }
1433      }
1434#endif
1435
1436      if(pcSlice->getRPSidx() < 0)
1437      {
1438        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1439        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1440      }
1441      else
1442      {
1443        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1444        Int numBits = 0;
1445        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1446        {
1447          numBits++;
1448        }
1449        if (numBits > 0)
1450        {
1451          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );         
1452        }
1453      }
1454      if(pcSlice->getSPS()->getLongTermRefsPresent())
1455      {
1456        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1457        Int ltrpInSPS[MAX_NUM_REF_PICS];
1458        Int numLtrpInSPS = 0;
1459        UInt ltrpIndex;
1460        Int counter = 0;
1461        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
1462        {
1463          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
1464          {
1465            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1466            numLtrpInSPS++;
1467          }
1468          else
1469          {
1470            counter++;
1471          }
1472        }
1473        numLtrpInSH -= numLtrpInSPS;
1474
1475        Int bitsForLtrpInSPS = 0;
1476        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1477        {
1478          bitsForLtrpInSPS++;
1479        }
1480        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
1481        {
1482          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1483        }
1484        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1485        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1486        // Not sorted here because LT ref indices will be used in setRefPicList()
1487        Int prevDeltaMSB = 0, prevLSB = 0;
1488        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1489        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
1490        {
1491          if (counter < numLtrpInSPS)
1492          {
1493            if (bitsForLtrpInSPS > 0)
1494            {
1495              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");             
1496            }
1497          }
1498          else 
1499          {
1500            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1501            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
1502          }
1503          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1504
1505          if(rps->getDeltaPocMSBPresentFlag(i))
1506          {
1507            Bool deltaFlag = false;
1508            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1509            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1510            {
1511              deltaFlag = true;
1512            }
1513            if(deltaFlag)
1514            {
1515              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1516            }
1517            else
1518            {             
1519              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1520              assert(differenceInDeltaMSB >= 0);
1521              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1522            }
1523            prevLSB = rps->getPocLSBLT(i);
1524            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1525          }
1526        }
1527      }
1528      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1529      {
1530        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
1531      }
1532#if N0065_LAYER_POC_ALIGNMENT && !SHM_FIX7
1533      }
1534#endif
1535    }
1536
1537#if JCTVC_M0458_INTERLAYER_RPS_SIG
1538#if ILP_SSH_SIG
1539#if ILP_SSH_SIG_FIX
1540    if((pcSlice->getSPS()->getLayerId() > 0) && !(pcSlice->getVPS()->getIlpSshSignalingEnabledFlag()) && (pcSlice->getNumILRRefIdx() > 0) )
1541#else
1542    if((pcSlice->getSPS()->getLayerId() > 0) && pcSlice->getVPS()->getIlpSshSignalingEnabledFlag() && (pcSlice->getNumILRRefIdx() > 0) )
1543#endif
1544#else
1545    if((pcSlice->getSPS()->getLayerId() > 0)  &&  (pcSlice->getNumILRRefIdx() > 0) )
1546#endif
1547    {
1548      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
1549      if( pcSlice->getInterLayerPredEnabledFlag())
1550      {
1551        if(pcSlice->getNumILRRefIdx() > 1)
1552        {
1553          Int numBits = 1;
1554          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
1555          {
1556            numBits++;
1557          }
1558          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
1559          {
1560            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
1561          }       
1562#if ILP_NUM_REF_CHK
1563          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
1564          {
1565#endif
1566          for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1567          {
1568            WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
1569          }
1570#if ILP_NUM_REF_CHK
1571          }
1572#endif
1573        }
1574      }
1575    }     
1576#if M0457_IL_SAMPLE_PRED_ONLY_FLAG
1577    if( pcSlice->getNumSamplePredRefLayers() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 )
1578    {
1579      WRITE_FLAG( pcSlice->getInterLayerSamplePredOnlyFlag(), "inter_layer_sample_pred_only_flag" );
1580    }
1581#endif
1582#endif
1583
1584    if(pcSlice->getSPS()->getUseSAO())
1585    {
1586      if (pcSlice->getSPS()->getUseSAO())
1587      {
1588         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
1589         {
1590#if AUXILIARY_PICTURES
1591           if (pcSlice->getChromaFormatIdc() != CHROMA_400)
1592           {
1593#endif
1594           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
1595          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
1596#if AUXILIARY_PICTURES
1597           }
1598#endif
1599         }
1600      }
1601    }
1602
1603    //check if numrefidxes match the defaults. If not, override
1604
1605    if (!pcSlice->isIntra())
1606    {
1607      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
1608      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
1609      if (overrideFlag) 
1610      {
1611        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
1612        if (pcSlice->isInterB())
1613        {
1614          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
1615        }
1616        else
1617        {
1618          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1619        }
1620      }
1621    }
1622    else
1623    {
1624      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
1625      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1626    }
1627
1628    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
1629    {
1630      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1631      if(!pcSlice->isIntra())
1632      {
1633        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
1634        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
1635        {
1636          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
1637          if (numRpsCurrTempList0 > 1)
1638          {
1639            Int length = 1;
1640            numRpsCurrTempList0 --;
1641            while ( numRpsCurrTempList0 >>= 1) 
1642            {
1643              length ++;
1644            }
1645            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
1646            {
1647              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
1648            }
1649          }
1650        }
1651      }
1652      if(pcSlice->isInterB())
1653      {   
1654        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
1655        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
1656        {
1657          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
1658          if ( numRpsCurrTempList1 > 1 )
1659          {
1660            Int length = 1;
1661            numRpsCurrTempList1 --;
1662            while ( numRpsCurrTempList1 >>= 1)
1663            {
1664              length ++;
1665            }
1666            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
1667            {
1668              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
1669            }
1670          }
1671        }
1672      }
1673    }
1674   
1675    if (pcSlice->isInterB())
1676    {
1677      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
1678    }
1679
1680    if(!pcSlice->isIntra())
1681    {
1682      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1683      {
1684        SliceType sliceType   = pcSlice->getSliceType();
1685        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
1686        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1687        pcSlice->setCabacInitFlag( encCabacInitFlag );
1688        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1689      }
1690    }
1691
1692    if ( pcSlice->getEnableTMVPFlag() )
1693    {
1694#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1695      if ( !pcSlice->getIdrPicFlag() && pcSlice->getLayerId() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 && pcSlice->getNumMotionPredRefLayers() > 0 )
1696      {
1697        WRITE_FLAG( pcSlice->getAltColIndicationFlag() ? 1 : 0, "alt_collocated_indication_flag" );
1698        if (pcSlice->getAltColIndicationFlag() && pcSlice->getNumMotionPredRefLayers() > 1)
1699        {
1700          WRITE_UVLC(0, "collocated_ref_layer_idx");
1701        }
1702      }
1703      else
1704      {
1705#endif
1706      if ( pcSlice->getSliceType() == B_SLICE )
1707      {
1708        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1709      }
1710
1711      if ( pcSlice->getSliceType() != I_SLICE &&
1712        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1713        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1714      {
1715        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1716      }
1717#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1718      }
1719#endif
1720    }
1721    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1722    {
1723      xCodePredWeightTable( pcSlice );
1724    }
1725    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1726    if (!pcSlice->isIntra())
1727    {
1728      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1729    }
1730    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1731    WRITE_SVLC( iCode, "slice_qp_delta" ); 
1732    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1733    {
1734      iCode = pcSlice->getSliceQpDeltaCb();
1735      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
1736      iCode = pcSlice->getSliceQpDeltaCr();
1737      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
1738    }
1739    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1740    {
1741      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1742      {
1743        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1744      }
1745      if (pcSlice->getDeblockingFilterOverrideFlag())
1746      {
1747        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1748        if(!pcSlice->getDeblockingFilterDisable())
1749        {
1750          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
1751          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
1752        }
1753      }
1754    }
1755
1756    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
1757    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1758
1759    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1760    {
1761      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1762    }
1763  }
1764  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1765  {
1766    WRITE_UVLC(0,"slice_header_extension_length");
1767  }
1768}
1769
1770Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1771{
1772  if(profilePresentFlag)
1773  {
1774    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1775  }
1776  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
1777
1778  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
1779  {
1780    if(profilePresentFlag)
1781    {
1782      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1783    }
1784   
1785    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1786  }
1787 
1788  if (maxNumSubLayersMinus1 > 0)
1789  {
1790    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
1791    {
1792      WRITE_CODE(0, 2, "reserved_zero_2bits");
1793    }
1794  }
1795 
1796  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1797  {
1798    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1799    {
1800      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1801    }
1802    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1803    {
1804      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
1805    }
1806  }
1807}
1808Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1809{
1810  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1811  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
1812  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
1813  for(Int j = 0; j < 32; j++)
1814  {
1815    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
1816  }
1817
1818  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
1819  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
1820  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
1821  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
1822 
1823  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[0..15]");
1824  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
1825  WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
1826}
1827
1828/**
1829 - write wavefront substreams sizes for the slice header.
1830 .
1831 \param pcSlice Where we find the substream size information.
1832 */
1833Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1834{
1835  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1836  {
1837    return;
1838  }
1839  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
1840  Int  numZeroSubstreamsAtStartOfSlice  = 0;
1841  UInt *entryPointOffset = NULL;
1842  if ( pSlice->getPPS()->getTilesEnabledFlag() )
1843  {
1844    numEntryPointOffsets = pSlice->getTileLocationCount();
1845    entryPointOffset     = new UInt[numEntryPointOffsets];
1846    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
1847    {
1848      if ( idx == 0 )
1849      {
1850        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
1851      }
1852      else
1853      {
1854        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
1855      }
1856
1857      if ( entryPointOffset[ idx ] > maxOffset )
1858      {
1859        maxOffset = entryPointOffset[ idx ];
1860      }
1861    }
1862  }
1863  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
1864  {
1865    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
1866    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
1867    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceSegmentCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1868    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceSegmentCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1869    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
1870    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
1871    entryPointOffset           = new UInt[numEntryPointOffsets];
1872    for (Int idx=0; idx<numEntryPointOffsets; idx++)
1873    {
1874      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
1875      if ( entryPointOffset[ idx ] > maxOffset )
1876      {
1877        maxOffset = entryPointOffset[ idx ];
1878      }
1879    }
1880  }
1881  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1882  offsetLenMinus1 = 0;
1883  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1884  {
1885    offsetLenMinus1++;
1886    assert(offsetLenMinus1 + 1 < 32);   
1887  }
1888
1889  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
1890  if (numEntryPointOffsets>0)
1891  {
1892    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1893  }
1894
1895  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
1896  {
1897    WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
1898  }
1899
1900  delete [] entryPointOffset;
1901}
1902
1903Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1904{
1905}
1906
1907Void TEncCavlc::codeSliceFinish ()
1908{
1909}
1910
1911Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1912{
1913  assert(0);
1914}
1915
1916Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1917{
1918  assert(0);
1919}
1920
1921Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1922{
1923  assert(0);
1924}
1925
1926Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1927{
1928  assert(0);
1929}
1930
1931Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1932{
1933  assert(0);
1934}
1935
1936Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1937{
1938  assert(0);
1939}
1940
1941Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1942{
1943  assert(0);
1944}
1945
1946Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1947{
1948  assert(0);
1949}
1950
1951Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1952{
1953  assert(0);
1954}
1955
1956Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1957{
1958  assert(0);
1959}
1960
1961Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1962{
1963  assert(0);
1964}
1965
1966Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1967{
1968  assert(0);
1969}
1970
1971Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
1972{
1973  assert(0);
1974}
1975Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
1976{
1977  assert(0);
1978}
1979
1980Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
1981{
1982  assert(0);
1983}
1984
1985/** Code I_PCM information.
1986 * \param pcCU pointer to CU
1987 * \param uiAbsPartIdx CU index
1988 * \returns Void
1989 */
1990Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
1991{
1992  assert(0);
1993}
1994
1995Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1996{
1997  assert(0);
1998}
1999
2000Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
2001{
2002  assert(0);
2003}
2004
2005Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
2006{
2007  assert(0);
2008}
2009
2010Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
2011{
2012  assert(0);
2013}
2014
2015Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
2016{
2017  assert(0);
2018}
2019
2020Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
2021{
2022  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
2023
2024#if REPN_FORMAT_IN_VPS
2025  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
2026#else
2027  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
2028#endif
2029  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
2030
2031  xWriteSvlc( iDQp );
2032 
2033  return;
2034}
2035
2036Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
2037{
2038  assert(0);
2039}
2040
2041Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
2042{
2043  // printf("error : no VLC mode support in this version\n");
2044  return;
2045}
2046
2047// ====================================================================================================================
2048// Protected member functions
2049// ====================================================================================================================
2050
2051/** code explicit wp tables
2052 * \param TComSlice* pcSlice
2053 * \returns Void
2054 */
2055Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
2056{
2057  wpScalingParam  *wp;
2058  Bool            bChroma     = true; // color always present in HEVC ?
2059  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
2060  Bool            bDenomCoded  = false;
2061  UInt            uiMode = 0;
2062  UInt            uiTotalSignalledWeightFlags = 0;
2063#if AUXILIARY_PICTURES
2064  if (pcSlice->getChromaFormatIdc() == CHROMA_400)
2065  {
2066    bChroma = false;
2067  }
2068#endif
2069  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
2070  {
2071    uiMode = 1; // explicit
2072  }
2073  if(uiMode == 1)
2074  {
2075
2076    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
2077    {
2078      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
2079
2080      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
2081      {
2082        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2083        if ( !bDenomCoded ) 
2084        {
2085          Int iDeltaDenom;
2086          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
2087
2088          if( bChroma )
2089          {
2090            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
2091            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
2092          }
2093          bDenomCoded = true;
2094        }
2095        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
2096        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
2097      }
2098      if (bChroma) 
2099      {
2100        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
2101        {
2102          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2103          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
2104          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
2105        }
2106      }
2107
2108      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
2109      {
2110        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2111        if ( wp[0].bPresentFlag ) 
2112        {
2113          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
2114          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
2115          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
2116        }
2117
2118        if ( bChroma ) 
2119        {
2120          if ( wp[1].bPresentFlag )
2121          {
2122            for ( Int j=1 ; j<3 ; j++ ) 
2123            {
2124              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
2125              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
2126
2127              Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
2128              Int iDeltaChroma = (wp[j].iOffset - pred);
2129              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
2130            }
2131          }
2132        }
2133      }
2134    }
2135    assert(uiTotalSignalledWeightFlags<=24);
2136  }
2137}
2138
2139/** code quantization matrix
2140 *  \param scalingList quantization matrix information
2141 */
2142Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
2143{
2144  UInt listId,sizeId;
2145  Bool scalingListPredModeFlag;
2146
2147#if SCALING_LIST_OUTPUT_RESULT
2148  Int startBit;
2149  Int startTotalBit;
2150  startBit = m_pcBitIf->getNumberOfWrittenBits();
2151  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
2152#endif
2153
2154    //for each size
2155    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2156    {
2157      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
2158      {
2159#if SCALING_LIST_OUTPUT_RESULT
2160        startBit = m_pcBitIf->getNumberOfWrittenBits();
2161#endif
2162
2163#if IL_SL_SIGNALLING_N0371
2164        if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
2165        {
2166          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2167          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2168          if(!scalingListPredModeFlag)// Copy Mode
2169          {
2170            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2171          }
2172          else// DPCM Mode
2173          {
2174            xCodeScalingList(scalingList, sizeId, listId);
2175          }
2176        }
2177        else
2178        {
2179          scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2180          WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2181          if(!scalingListPredModeFlag)// Copy Mode
2182          {
2183            WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2184          }
2185          else// DPCM Mode
2186          {
2187            xCodeScalingList(scalingList, sizeId, listId);
2188          }
2189        }
2190#else
2191        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
2192        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2193        if(!scalingListPredModeFlag)// Copy Mode
2194        {
2195          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2196        }
2197        else// DPCM Mode
2198        {
2199          xCodeScalingList(scalingList, sizeId, listId);
2200        }
2201#endif
2202
2203#if SCALING_LIST_OUTPUT_RESULT
2204        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
2205#endif
2206
2207      }
2208    }
2209#if SCALING_LIST_OUTPUT_RESULT
2210  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
2211#endif
2212  return;
2213}
2214/** code DPCM
2215 * \param scalingList quantization matrix information
2216 * \param sizeIdc size index
2217 * \param listIdc list index
2218 */
2219Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
2220{
2221  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
2222  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
2223  Int nextCoef = SCALING_LIST_START_VALUE;
2224  Int data;
2225  Int *src = scalingList->getScalingListAddress(sizeId, listId);
2226
2227    if( sizeId > SCALING_LIST_8x8 )
2228    {
2229#if IL_SL_SIGNALLING_N0371
2230      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
2231      {
2232        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
2233        scalingList->setScalingListDC(sizeId,listId,ref_scalingListDC[scalingList->getScalingListRefLayerId()][sizeId][listId]);
2234      }
2235      else
2236      {
2237        WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
2238        nextCoef = scalingList->getScalingListDC(sizeId,listId);
2239        ref_scalingListDC[scalingList->getLayerId()][sizeId][listId] = scalingList->getScalingListDC(sizeId,listId);
2240      }
2241#else
2242      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
2243      nextCoef = scalingList->getScalingListDC(sizeId,listId);
2244#endif
2245    }
2246    for(Int i=0;i<coefNum;i++)
2247    {
2248#if IL_SL_SIGNALLING_N0371
2249      if( scalingList->getLayerId() > 0 && scalingList->getPredScalingListFlag() )
2250      {
2251        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
2252        src[scan[i]] = ref_scalingListCoef[scalingList->getScalingListRefLayerId()][sizeId][listId][i];
2253      }
2254      else
2255      {
2256        data = src[scan[i]] - nextCoef;
2257        ref_scalingListCoef[scalingList->getLayerId()][sizeId][listId][i] = src[scan[i]];
2258        nextCoef = src[scan[i]];
2259        if(data > 127)
2260        {
2261          data = data - 256;
2262        }
2263        if(data < -128)
2264        {
2265          data = data + 256;
2266        }
2267
2268        WRITE_SVLC( data,  "scaling_list_delta_coef");
2269      }
2270#else
2271      data = src[scan[i]] - nextCoef;
2272      nextCoef = src[scan[i]];
2273      if(data > 127)
2274      {
2275        data = data - 256;
2276      }
2277      if(data < -128)
2278      {
2279        data = data + 256;
2280      }
2281
2282      WRITE_SVLC( data,  "scaling_list_delta_coef");
2283#endif
2284    }
2285}
2286Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
2287{
2288  // Bool state = true, state2 = false;
2289  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
2290  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
2291  {
2292    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
2293    {
2294      *ltrpsIndex = k;
2295      return true;
2296    }
2297  }
2298  return false;
2299}
2300Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
2301{
2302  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
2303  {
2304    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
2305      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
2306     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
2307    {
2308      setRefMatrixId(sizeId, listId, predListIdx);
2309      return false;
2310    }
2311  }
2312  return true;
2313}
2314//! \}
Note: See TracBrowser for help on using the repository browser.