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

Last change on this file since 383 was 383, checked in by qualcomm, 11 years ago

Added byte alignment before parsing VPS VUI

From: Adarsh K. Ramasubramonian <aramasub@…>

  • Property svn:eol-style set to native
File size: 68.1 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  if( pcPPS->getScalingListPresentFlag() )
224  {
225#if SCALING_LIST_OUTPUT_RESULT
226    printf("PPS\n");
227#endif
228    codeScalingList( m_pcSlice->getScalingList() );
229  }
230  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
231  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
232  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
233  WRITE_FLAG( 0, "pps_extension_flag" );
234}
235
236Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
237{
238#if ENC_DEC_TRACE
239  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
240#endif
241  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
242  if (pcVUI->getAspectRatioInfoPresentFlag())
243  {
244    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
245    if (pcVUI->getAspectRatioIdc() == 255)
246    {
247      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
248      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
249    }
250  }
251  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
252  if (pcVUI->getOverscanInfoPresentFlag())
253  {
254    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
255  }
256  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
257  if (pcVUI->getVideoSignalTypePresentFlag())
258  {
259    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
260    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
261    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
262    if (pcVUI->getColourDescriptionPresentFlag())
263    {
264      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
265      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
266      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
267    }
268  }
269
270  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
271  if (pcVUI->getChromaLocInfoPresentFlag())
272  {
273    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
274    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
275  }
276
277  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
278  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
279  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
280
281  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
282  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
283  if( defaultDisplayWindow.getWindowEnabledFlag() )
284  {
285    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset(),      "def_disp_win_left_offset");
286    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset(),     "def_disp_win_right_offset");
287    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset(),       "def_disp_win_top_offset");
288    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset(),    "def_disp_win_bottom_offset");
289  }
290  TimingInfo *timingInfo = pcVUI->getTimingInfo();
291  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
292  if(timingInfo->getTimingInfoPresentFlag())
293  {
294    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
295    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
296    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
297    if(timingInfo->getPocProportionalToTimingFlag())
298    {
299      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
300    }
301  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
302  if( pcVUI->getHrdParametersPresentFlag() )
303  {
304    codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
305  }
306  }
307
308  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
309  if (pcVUI->getBitstreamRestrictionFlag())
310  {
311    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
312#if M0464_TILE_BOUNDARY_ALIGNED_FLAG
313    if ( pcSPS->getLayerId() > 0 )
314    {
315      WRITE_FLAG( pcVUI->getTileBoundariesAlignedFlag( ) ? 1 : 0 , "tile_boundaries_aligned_flag" );
316    }
317#endif
318    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
319    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
320    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
321    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
322    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
323    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
324    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
325  }
326}
327
328Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
329{
330  if( commonInfPresentFlag )
331  {
332    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
333    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
334    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
335    {
336      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
337      if( hrd->getSubPicCpbParamsPresentFlag() )
338      {
339        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
340        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
341        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
342        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
343      }
344      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
345      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
346      if( hrd->getSubPicCpbParamsPresentFlag() )
347      {
348        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" ); 
349      }
350      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
351      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
352      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
353    }
354  }
355  Int i, j, nalOrVcl;
356  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
357  {
358    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
359    if( !hrd->getFixedPicRateFlag( i ) )
360    {
361      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
362    }
363    else
364    {
365      hrd->setFixedPicRateWithinCvsFlag( i, true );
366    }
367    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
368    {
369      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
370    }
371    else
372    {
373      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
374    }
375    if (!hrd->getLowDelayHrdFlag( i ))
376    {
377      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
378    }
379   
380    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
381    {
382      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
383          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
384      {
385        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
386        {
387          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
388          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
389          if( hrd->getSubPicCpbParamsPresentFlag() )
390          {
391            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1"); 
392            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
393          }
394          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
395        }
396      }
397    }
398  }
399}
400
401Void TEncCavlc::codeSPS( TComSPS* pcSPS )
402{
403#if ENC_DEC_TRACE 
404  xTraceSPSHeader (pcSPS);
405#endif
406  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
407#if SPS_SUB_LAYER_INFO
408  if(pcSPS->getLayerId() == 0)
409  {
410#endif
411    WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
412    WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
413#if SPS_SUB_LAYER_INFO
414  }
415#endif
416#ifdef SPS_PTL_FIX
417  if (pcSPS->getLayerId() == 0)
418  {
419    codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
420  }
421#else
422  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
423#endif
424  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
425  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
426  assert(pcSPS->getChromaFormatIdc () == 1);
427  // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
428  if( pcSPS->getChromaFormatIdc () == 3 )
429  {
430    WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
431  }
432
433  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
434  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
435  Window conf = pcSPS->getConformanceWindow();
436
437  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
438  if (conf.getWindowEnabledFlag())
439  {
440    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
441    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
442    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
443    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
444  }
445
446  WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
447  WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
448
449  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
450
451  const Bool subLayerOrderingInfoPresentFlag = 1;
452  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
453  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
454  {
455    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
456    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
457    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
458    if (!subLayerOrderingInfoPresentFlag)
459    {
460      break;
461    }
462  }
463  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
464 
465  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
466  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
467  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
468  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
469  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
470  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
471  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
472  if(pcSPS->getScalingListFlag())
473  {
474    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
475    if(pcSPS->getScalingListPresentFlag())
476    {
477#if SCALING_LIST_OUTPUT_RESULT
478    printf("SPS\n");
479#endif
480      codeScalingList( m_pcSlice->getScalingList() );
481    }
482  }
483  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
484  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
485
486  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
487  if( pcSPS->getUsePCM() )
488  {
489    WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,                                  "pcm_sample_bit_depth_luma_minus1" );
490    WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4,                                "pcm_sample_bit_depth_chroma_minus1" );
491    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
492    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
493    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
494  }
495
496  assert( pcSPS->getMaxTLayers() > 0 );         
497
498  TComRPSList* rpsList = pcSPS->getRPSList();
499  TComReferencePictureSet*      rps;
500
501  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
502  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
503  {
504    rps = rpsList->getReferencePictureSet(i);
505    codeShortTermRefPicSet(pcSPS,rps,false, i);
506  }
507  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
508  if (pcSPS->getLongTermRefsPresent()) 
509  {
510    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
511    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
512    {
513      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
514      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
515    }
516  }
517  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
518#if REF_IDX_MFM
519#if !M0457_COL_PICTURE_SIGNALING
520  if( pcSPS->getLayerId() > 0 )
521  {
522    WRITE_FLAG( pcSPS->getMFMEnabledFlag() ? 1 : 0,          "sps_enh_mfm_enable_flag" );
523  }
524#endif
525#endif
526  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
527
528  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
529  if (pcSPS->getVuiParametersPresentFlag())
530  {
531      codeVUI(pcSPS->getVuiParameters(), pcSPS);
532  }
533
534#if SPS_EXTENSION
535  WRITE_FLAG( 1, "sps_extension_flag" );
536  if( 1 )   // if( sps_extension_flag )
537  {
538    codeSPSExtension( pcSPS );
539    WRITE_FLAG( 0, "sps_extension2_flag" );
540  }
541#else
542  WRITE_FLAG( 0, "sps_extension_flag" );
543#endif
544}
545#if SPS_EXTENSION
546Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
547{
548  // more syntax elements to be written here
549#if SCALED_REF_LAYER_OFFSETS
550#if SCALED_REF_LAYER_OFFSET_FLAG
551  WRITE_FLAG( pcSPS->getLayerId() > 0, "scaled_ref_layer_offset_present_flag" );
552  if( pcSPS->getLayerId() > 0 )
553#else
554  if( pcSPS->getLayerId() > 0 )
555#endif
556  {
557    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
558    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
559    {
560      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
561      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
562      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
563      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
564      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
565    }
566  }
567#endif
568#if M0463_VUI_EXT_ILP_REF
569  ////   sps_extension_vui_parameters( )
570  if( pcSPS->getVuiParameters()->getBitstreamRestrictionFlag() )
571  { 
572    WRITE_UVLC( pcSPS->getNumIlpRestrictedRefLayers( ),           "num_ilp_restricted_ref_layers" ); 
573    for( Int i = 0; i < pcSPS->getNumIlpRestrictedRefLayers( ); i++ ) 
574    { 
575      WRITE_UVLC( pcSPS->getMinSpatialSegmentOffsetPlus1( i ),    "min_spatial_segment_offset_plus1" ); 
576      if( pcSPS->getMinSpatialSegmentOffsetPlus1( i ) > 0 ) 
577      { 
578        WRITE_FLAG( pcSPS->getCtuBasedOffsetEnabledFlag( i ),      "ctu_based_offset_enabled_flag[ i ]"); 
579        if( pcSPS->getCtuBasedOffsetEnabledFlag( i ) ) 
580        {
581          WRITE_UVLC( pcSPS->getMinHorizontalCtuOffsetPlus1( i ), "min_horizontal_ctu_offset_plus1[ i ]"); 
582        }
583      } 
584    } 
585  } 
586  ////   sps_extension_vui_parameters( ) END
587#endif
588}
589#endif
590Void TEncCavlc::codeVPS( TComVPS* pcVPS )
591{
592  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
593  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
594#if VPS_RENAME
595  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );           
596#else
597  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
598#endif
599  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
600  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
601  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
602  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
603  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
604  const Bool subLayerOrderingInfoPresentFlag = 1;
605  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
606  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
607  {
608    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
609    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
610    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
611    if (!subLayerOrderingInfoPresentFlag)
612    {
613      break;
614    }
615  }
616
617#if VPS_RENAME
618  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
619  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_ID_PLUS1 );
620#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
621  pcVPS->setNumLayerSets(1);
622#endif
623  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
624  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
625  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getNumLayerSets() - 1 ); opsIdx ++ )
626  {
627    // Operation point set
628    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
629#else
630  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
631  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
632  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
633  pcVPS->setMaxOpSets(1);
634  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
635  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
636  {
637    // Operation point set
638    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
639#endif
640    {
641#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
642      // Only applicable for version 1
643      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
644#endif
645      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
646    }
647  }
648#if DERIVE_LAYER_ID_LIST_VARIABLES
649  pcVPS->deriveLayerIdListVariables();
650#endif
651  TimingInfo *timingInfo = pcVPS->getTimingInfo();
652  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
653  if(timingInfo->getTimingInfoPresentFlag())
654  {
655    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
656    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
657    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
658    if(timingInfo->getPocProportionalToTimingFlag())
659    {
660      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
661    }
662    pcVPS->setNumHrdParameters( 0 );
663    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
664
665    if( pcVPS->getNumHrdParameters() > 0 )
666    {
667      pcVPS->createHrdParamBuffer();
668    }
669    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
670    {
671      // Only applicable for version 1
672      pcVPS->setHrdOpSetIdx( 0, i );
673      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
674      if( i > 0 )
675      {
676        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
677      }
678      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
679    }
680  }
681#if !VPS_EXTNS
682  WRITE_FLAG( 0,                     "vps_extension_flag" );
683#else
684  WRITE_FLAG( 1,                     "vps_extension_flag" );
685  codeVPSExtension(pcVPS);
686  WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
687#endif 
688  //future extensions here..
689 
690  return;
691}
692
693#if VPS_EXTNS
694Void TEncCavlc::codeVPSExtension (TComVPS *vps)
695{
696  // ... More syntax elements to be written here
697#if VPS_EXTN_MASK_AND_DIM_INFO
698  UInt i = 0, j = 0;
699
700  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
701  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
702
703  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
704  {
705    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
706  }
707
708#if VPS_SPLIT_FLAG
709  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
710#else
711  for(j = 0; j < vps->getNumScalabilityTypes(); j++)
712#endif
713  {
714    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
715  }
716
717#if SPL_FLG_CHK
718  if(vps->getSplittingFlag())
719  {
720    UInt splDimSum=0;
721    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
722    {
723      splDimSum+=(vps->getDimensionIdLen(j));
724    }
725    assert(splDimSum<=6);
726  }
727#endif
728
729  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
730  for(i = 1; i < vps->getMaxLayers(); i++)
731  {
732    if( vps->getNuhLayerIdPresentFlag() )
733    {
734      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
735    }
736#if VPS_SPLIT_FLAG
737    if(!vps->getSplittingFlag())
738#endif
739    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
740    {
741      UInt bits = vps->getDimensionIdLen(j);
742      WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
743    }
744  }
745#endif
746#if VPS_MOVE_DIR_DEPENDENCY_FLAG
747#if VPS_EXTN_DIRECT_REF_LAYERS
748  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
749  {
750    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
751    {
752      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
753    }
754  }
755#endif
756#endif
757#if JCTVC_M0203_INTERLAYER_PRED_IDC
758#if N0120_MAX_TID_REF_PRESENT_FLAG
759   WRITE_FLAG( vps->getMaxTidIlRefPicsPlus1PresentFlag(), "max_tid_il_ref_pics_plus1_present_flag");
760   if (vps->getMaxTidIlRefPicsPlus1PresentFlag())
761   {
762     for( i = 0; i < vps->getMaxLayers() - 1; i++)
763     {
764       WRITE_CODE(vps->getMaxSublayerForIlpPlus1(i), 3, "max_sublayer_for_ilp_plus1[i]" );
765     }
766   }
767#else
768  for( i = 0; i < vps->getMaxLayers() - 1; i++)
769  {
770    WRITE_CODE(vps->getMaxSublayerForIlpPlus1(i), 3, "max_sublayer_for_ilp_plus1[i]" );
771  }
772#endif
773#endif
774#if ILP_SSH_SIG
775    WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
776#endif
777#if VPS_EXTN_PROFILE_INFO
778  // Profile-tier-level signalling
779#if VPS_PROFILE_OUTPUT_LAYERS
780  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
781  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
782  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
783#else
784  for(Int idx = 1; idx <= vps->getNumLayerSets() - 1; idx++)
785#endif
786  {
787    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
788    if( !vps->getProfilePresentFlag(idx) )
789    {
790#if VPS_PROFILE_OUTPUT_LAYERS
791      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
792#else
793      WRITE_UVLC( vps->getProfileLayerSetRef(idx) - 1, "vps_profile_layer_set_ref_minus1[i]" );
794#endif
795    }
796    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
797  }
798#endif
799
800#if VPS_PROFILE_OUTPUT_LAYERS
801  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
802  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
803  if(numOutputLayerSets > vps->getNumLayerSets())
804  {
805    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
806  }
807  if( numOutputLayerSets > 1 )
808  {
809    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
810  }
811
812  for(i = 1; i < numOutputLayerSets; i++)
813  {
814    if( i > (vps->getNumLayerSets() - 1) )
815    {
816      Int numBits = 1;
817      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
818      {
819        numBits++;
820      }
821      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "output_layer_set_idx_minus1"); 
822      Int lsIdx = vps->getOutputLayerSetIdx(i);
823      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
824      {
825        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
826      }
827    }
828    Int numBits = 1;
829    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
830    {
831      numBits++;
832    }
833    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
834  }
835#else
836#if VPS_EXTN_OP_LAYER_SETS
837  // Target output layer signalling
838  WRITE_UVLC( vps->getNumOutputLayerSets(),            "vps_num_output_layer_sets");
839  for(i = 0; i < vps->getNumOutputLayerSets(); i++)
840  {
841#if VPS_OUTPUT_LAYER_SET_IDX
842    assert(vps->getOutputLayerSetIdx(i) > 0);
843    WRITE_UVLC( vps->getOutputLayerSetIdx(i) - 1,           "vps_output_layer_set_idx_minus1[i]");
844#else
845    WRITE_UVLC( vps->getOutputLayerSetIdx(i),           "vps_output_layer_set_idx[i]");
846#endif
847    Int lsIdx = vps->getOutputLayerSetIdx(i);
848    for(j = 0; j <= vps->getMaxLayerId(); j++)
849    {
850      if(vps->getLayerIdIncludedFlag(lsIdx, j))
851      {
852        WRITE_FLAG( vps->getOutputLayerFlag(lsIdx, j), "vps_output_layer_flag[lsIdx][j]");
853      }
854    }
855  }
856#endif
857#endif
858#if JCTVC_M0458_INTERLAYER_RPS_SIG
859      WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
860#endif
861#if !VPS_MOVE_DIR_DEPENDENCY_FLAG
862#if VPS_EXTN_DIRECT_REF_LAYERS
863  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
864  {
865    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
866    {
867      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
868    }
869  }
870#endif
871#endif
872#if VPS_EXTN_DIRECT_REF_LAYERS && M0457_PREDICTION_INDICATIONS
873  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
874  for(i = 1; i < vps->getMaxLayers(); i++)
875  {
876    for(j = 0; j < i; j++)
877    {
878      if (vps->getDirectDependencyFlag(i, j))
879      {
880        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
881      }
882    }
883  }
884#endif
885#if M0040_ADAPTIVE_RESOLUTION_CHANGE
886  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
887#endif
888
889#if !VPS_VUI
890  WRITE_FLAG( 0,                     "vps_vui_present_flag" );
891#else
892  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
893  if(1)   // Should be conditioned on the value of vps_vui_present_flag
894  {
895    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
896    {
897      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
898    }
899    codeVPSVUI(vps); 
900  }
901#endif
902}
903#endif
904
905#if VPS_VUI
906Void TEncCavlc::codeVPSVUI (TComVPS *vps)
907{
908  Int i,j;
909#if N0160_TILE_BOUNDARY_ALIGNED_FLAG
910  for(i = 1; i < vps->getMaxLayers(); i++)
911  {
912    for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
913    {
914      WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
915    }
916  } 
917#endif
918#if N0160_VUI_EXT_ILP_REF
919  WRITE_FLAG( vps->getNumIlpRestrictedRefLayers() ? 1 : 0 , "num_ilp_restricted_ref_layers" );   
920  if( vps->getNumIlpRestrictedRefLayers())
921  {
922    for(i = 1; i < vps->getMaxLayers(); i++)
923    {
924      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
925      {       
926        WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
927       
928        if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
929        { 
930          WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );   
931         
932          if(vps->getCtuBasedOffsetEnabledFlag(i,j)) 
933          {
934            WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");           
935          }
936        } 
937      } 
938    }
939  }
940#endif
941}
942#endif
943
944Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
945{
946#if ENC_DEC_TRACE 
947  xTraceSliceHeader (pcSlice);
948#endif
949
950  //calculate number of bits required for slice address
951  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumCUsInFrame();
952  Int bitsSliceSegmentAddress = 0;
953  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress)) 
954  {
955    bitsSliceSegmentAddress++;
956  }
957  Int ctuAddress;
958  if (pcSlice->isNextSlice())
959  {
960    // Calculate slice address
961    ctuAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
962  }
963  else
964  {
965    // Calculate slice address
966    ctuAddress = (pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
967  }
968  //write slice address
969  Int sliceSegmentAddress = pcSlice->getPic()->getPicSym()->getCUOrderMap(ctuAddress);
970
971  WRITE_FLAG( sliceSegmentAddress==0, "first_slice_segment_in_pic_flag" );
972  if ( pcSlice->getRapPicFlag() )
973  {
974    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
975  }
976  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
977  pcSlice->setDependentSliceSegmentFlag(!pcSlice->isNextSlice());
978  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentAddress!=0) )
979  {
980    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
981  }
982  if(sliceSegmentAddress>0)
983  {
984    WRITE_CODE( sliceSegmentAddress, bitsSliceSegmentAddress, "slice_segment_address" );
985  }
986  if ( !pcSlice->getDependentSliceSegmentFlag() )
987  {
988
989#if SH_DISCARDABLE_FLAG
990    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
991    {
992      assert(!!"discardable_flag");
993      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
994    }
995    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
996    {
997      assert(!!"slice_reserved_undetermined_flag[]");
998      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
999    }
1000#else
1001    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1002    {
1003      assert(!!"slice_reserved_undetermined_flag[]");
1004      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
1005    }
1006#endif
1007
1008    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1009
1010    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1011    {
1012      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1013    }
1014
1015    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
1016    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
1017    // if( separate_colour_plane_flag  ==  1 )
1018    //   colour_plane_id                                      u(2)
1019
1020    if( !pcSlice->getIdrPicFlag() )
1021    {
1022      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
1023      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
1024      TComReferencePictureSet* rps = pcSlice->getRPS();
1025     
1026#if FIX1071
1027      // check for bitstream restriction stating that:
1028      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1029      // Ideally this process should not be repeated for each slice in a picture
1030#if SVC_EXTENSION
1031      if( pcSlice->getLayerId() == 0 )
1032#endif
1033      if (pcSlice->isIRAP())
1034      {
1035        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1036        {
1037          assert (!rps->getUsed(picIdx));
1038        }
1039      }
1040#endif
1041
1042      if(pcSlice->getRPSidx() < 0)
1043      {
1044        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1045        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1046      }
1047      else
1048      {
1049        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1050        Int numBits = 0;
1051        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1052        {
1053          numBits++;
1054        }
1055        if (numBits > 0)
1056        {
1057          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );         
1058        }
1059      }
1060      if(pcSlice->getSPS()->getLongTermRefsPresent())
1061      {
1062        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1063        Int ltrpInSPS[MAX_NUM_REF_PICS];
1064        Int numLtrpInSPS = 0;
1065        UInt ltrpIndex;
1066        Int counter = 0;
1067        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
1068        {
1069          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
1070          {
1071            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1072            numLtrpInSPS++;
1073          }
1074          else
1075          {
1076            counter++;
1077          }
1078        }
1079        numLtrpInSH -= numLtrpInSPS;
1080
1081        Int bitsForLtrpInSPS = 0;
1082        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1083        {
1084          bitsForLtrpInSPS++;
1085        }
1086        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
1087        {
1088          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1089        }
1090        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1091        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1092        // Not sorted here because LT ref indices will be used in setRefPicList()
1093        Int prevDeltaMSB = 0, prevLSB = 0;
1094        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1095        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
1096        {
1097          if (counter < numLtrpInSPS)
1098          {
1099            if (bitsForLtrpInSPS > 0)
1100            {
1101              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");             
1102            }
1103          }
1104          else 
1105          {
1106            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1107            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
1108          }
1109          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1110
1111          if(rps->getDeltaPocMSBPresentFlag(i))
1112          {
1113            Bool deltaFlag = false;
1114            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1115            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1116            {
1117              deltaFlag = true;
1118            }
1119            if(deltaFlag)
1120            {
1121              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1122            }
1123            else
1124            {             
1125              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1126              assert(differenceInDeltaMSB >= 0);
1127              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1128            }
1129            prevLSB = rps->getPocLSBLT(i);
1130            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1131          }
1132        }
1133      }
1134      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1135      {
1136        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
1137      }
1138    }
1139
1140#if JCTVC_M0458_INTERLAYER_RPS_SIG
1141#if ILP_SSH_SIG
1142    if((pcSlice->getSPS()->getLayerId() > 0) && pcSlice->getVPS()->getIlpSshSignalingEnabledFlag() && (pcSlice->getNumILRRefIdx() > 0) )
1143#else
1144    if((pcSlice->getSPS()->getLayerId() > 0)  &&  (pcSlice->getNumILRRefIdx() > 0) )
1145#endif
1146    {
1147      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
1148      if( pcSlice->getInterLayerPredEnabledFlag())
1149      {
1150        if(pcSlice->getNumILRRefIdx() > 1)
1151        {
1152          Int numBits = 1;
1153          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
1154          {
1155            numBits++;
1156          }
1157          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
1158          {
1159            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
1160          }       
1161#if ILP_NUM_REF_CHK
1162          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
1163          {
1164#endif
1165          for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
1166          {
1167            WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
1168          }
1169#if ILP_NUM_REF_CHK
1170          }
1171#endif
1172        }
1173      }
1174    }     
1175#if M0457_IL_SAMPLE_PRED_ONLY_FLAG
1176    if( pcSlice->getNumSamplePredRefLayers() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 )
1177    {
1178      WRITE_FLAG( pcSlice->getInterLayerSamplePredOnlyFlag(), "inter_layer_sample_pred_only_flag" );
1179    }
1180#endif
1181#endif
1182
1183    if(pcSlice->getSPS()->getUseSAO())
1184    {
1185      if (pcSlice->getSPS()->getUseSAO())
1186      {
1187         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
1188         {
1189           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
1190          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
1191         }
1192      }
1193    }
1194
1195    //check if numrefidxes match the defaults. If not, override
1196
1197    if (!pcSlice->isIntra())
1198    {
1199      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
1200      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
1201      if (overrideFlag) 
1202      {
1203        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
1204        if (pcSlice->isInterB())
1205        {
1206          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
1207        }
1208        else
1209        {
1210          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1211        }
1212      }
1213    }
1214    else
1215    {
1216      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
1217      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1218    }
1219
1220    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
1221    {
1222      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1223      if(!pcSlice->isIntra())
1224      {
1225        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
1226        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
1227        {
1228          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
1229          if (numRpsCurrTempList0 > 1)
1230          {
1231            Int length = 1;
1232            numRpsCurrTempList0 --;
1233            while ( numRpsCurrTempList0 >>= 1) 
1234            {
1235              length ++;
1236            }
1237            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
1238            {
1239              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
1240            }
1241          }
1242        }
1243      }
1244      if(pcSlice->isInterB())
1245      {   
1246        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
1247        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
1248        {
1249          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
1250          if ( numRpsCurrTempList1 > 1 )
1251          {
1252            Int length = 1;
1253            numRpsCurrTempList1 --;
1254            while ( numRpsCurrTempList1 >>= 1)
1255            {
1256              length ++;
1257            }
1258            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
1259            {
1260              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
1261            }
1262          }
1263        }
1264      }
1265    }
1266   
1267    if (pcSlice->isInterB())
1268    {
1269      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
1270    }
1271
1272    if(!pcSlice->isIntra())
1273    {
1274      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1275      {
1276        SliceType sliceType   = pcSlice->getSliceType();
1277        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
1278        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1279        pcSlice->setCabacInitFlag( encCabacInitFlag );
1280        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1281      }
1282    }
1283
1284    if ( pcSlice->getEnableTMVPFlag() )
1285    {
1286#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1287      if ( !pcSlice->getIdrPicFlag() && pcSlice->getLayerId() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 && pcSlice->getNumMotionPredRefLayers() > 0 )
1288      {
1289        WRITE_FLAG( pcSlice->getAltColIndicationFlag() ? 1 : 0, "alt_collocated_indication_flag" );
1290        if (pcSlice->getAltColIndicationFlag() && pcSlice->getNumMotionPredRefLayers() > 1)
1291        {
1292          WRITE_UVLC(0, "collocated_ref_layer_idx");
1293        }
1294      }
1295      else
1296      {
1297#endif
1298      if ( pcSlice->getSliceType() == B_SLICE )
1299      {
1300        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1301      }
1302
1303      if ( pcSlice->getSliceType() != I_SLICE &&
1304        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1305        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1306      {
1307        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1308      }
1309#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1310      }
1311#endif
1312    }
1313    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1314    {
1315      xCodePredWeightTable( pcSlice );
1316    }
1317    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1318    if (!pcSlice->isIntra())
1319    {
1320      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1321    }
1322    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1323    WRITE_SVLC( iCode, "slice_qp_delta" ); 
1324    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1325    {
1326      iCode = pcSlice->getSliceQpDeltaCb();
1327      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
1328      iCode = pcSlice->getSliceQpDeltaCr();
1329      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
1330    }
1331    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1332    {
1333      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1334      {
1335        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1336      }
1337      if (pcSlice->getDeblockingFilterOverrideFlag())
1338      {
1339        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1340        if(!pcSlice->getDeblockingFilterDisable())
1341        {
1342          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
1343          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
1344        }
1345      }
1346    }
1347
1348    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
1349    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1350
1351    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1352    {
1353      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1354    }
1355  }
1356  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1357  {
1358    WRITE_UVLC(0,"slice_header_extension_length");
1359  }
1360}
1361
1362Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1363{
1364  if(profilePresentFlag)
1365  {
1366    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1367  }
1368  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
1369
1370  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
1371  {
1372    if(profilePresentFlag)
1373    {
1374      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1375    }
1376   
1377    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1378  }
1379 
1380  if (maxNumSubLayersMinus1 > 0)
1381  {
1382    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
1383    {
1384      WRITE_CODE(0, 2, "reserved_zero_2bits");
1385    }
1386  }
1387 
1388  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1389  {
1390    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1391    {
1392      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1393    }
1394    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1395    {
1396      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
1397    }
1398  }
1399}
1400Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1401{
1402  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1403  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
1404  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
1405  for(Int j = 0; j < 32; j++)
1406  {
1407    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
1408  }
1409
1410  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
1411  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
1412  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
1413  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
1414 
1415  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[0..15]");
1416  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
1417  WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
1418}
1419
1420/**
1421 - write wavefront substreams sizes for the slice header.
1422 .
1423 \param pcSlice Where we find the substream size information.
1424 */
1425Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1426{
1427  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1428  {
1429    return;
1430  }
1431  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
1432  Int  numZeroSubstreamsAtStartOfSlice  = 0;
1433  UInt *entryPointOffset = NULL;
1434  if ( pSlice->getPPS()->getTilesEnabledFlag() )
1435  {
1436    numEntryPointOffsets = pSlice->getTileLocationCount();
1437    entryPointOffset     = new UInt[numEntryPointOffsets];
1438    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
1439    {
1440      if ( idx == 0 )
1441      {
1442        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
1443      }
1444      else
1445      {
1446        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
1447      }
1448
1449      if ( entryPointOffset[ idx ] > maxOffset )
1450      {
1451        maxOffset = entryPointOffset[ idx ];
1452      }
1453    }
1454  }
1455  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
1456  {
1457    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
1458    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
1459    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceSegmentCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1460    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceSegmentCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1461    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
1462    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
1463    entryPointOffset           = new UInt[numEntryPointOffsets];
1464    for (Int idx=0; idx<numEntryPointOffsets; idx++)
1465    {
1466      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
1467      if ( entryPointOffset[ idx ] > maxOffset )
1468      {
1469        maxOffset = entryPointOffset[ idx ];
1470      }
1471    }
1472  }
1473  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1474  offsetLenMinus1 = 0;
1475  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1476  {
1477    offsetLenMinus1++;
1478    assert(offsetLenMinus1 + 1 < 32);   
1479  }
1480
1481  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
1482  if (numEntryPointOffsets>0)
1483  {
1484    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1485  }
1486
1487  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
1488  {
1489    WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
1490  }
1491
1492  delete [] entryPointOffset;
1493}
1494
1495Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1496{
1497}
1498
1499Void TEncCavlc::codeSliceFinish ()
1500{
1501}
1502
1503Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1504{
1505  assert(0);
1506}
1507
1508Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1509{
1510  assert(0);
1511}
1512
1513Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1514{
1515  assert(0);
1516}
1517
1518Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1519{
1520  assert(0);
1521}
1522
1523Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1524{
1525  assert(0);
1526}
1527
1528Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1529{
1530  assert(0);
1531}
1532
1533Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1534{
1535  assert(0);
1536}
1537
1538Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1539{
1540  assert(0);
1541}
1542
1543Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1544{
1545  assert(0);
1546}
1547
1548Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1549{
1550  assert(0);
1551}
1552
1553Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1554{
1555  assert(0);
1556}
1557
1558Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1559{
1560  assert(0);
1561}
1562
1563Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
1564{
1565  assert(0);
1566}
1567Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
1568{
1569  assert(0);
1570}
1571
1572Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
1573{
1574  assert(0);
1575}
1576
1577/** Code I_PCM information.
1578 * \param pcCU pointer to CU
1579 * \param uiAbsPartIdx CU index
1580 * \returns Void
1581 */
1582Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
1583{
1584  assert(0);
1585}
1586
1587Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1588{
1589  assert(0);
1590}
1591
1592Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
1593{
1594  assert(0);
1595}
1596
1597Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
1598{
1599  assert(0);
1600}
1601
1602Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1603{
1604  assert(0);
1605}
1606
1607Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1608{
1609  assert(0);
1610}
1611
1612Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
1613{
1614  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
1615
1616  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
1617  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
1618
1619  xWriteSvlc( iDQp );
1620 
1621  return;
1622}
1623
1624Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
1625{
1626  assert(0);
1627}
1628
1629Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
1630{
1631  // printf("error : no VLC mode support in this version\n");
1632  return;
1633}
1634
1635// ====================================================================================================================
1636// Protected member functions
1637// ====================================================================================================================
1638
1639/** code explicit wp tables
1640 * \param TComSlice* pcSlice
1641 * \returns Void
1642 */
1643Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
1644{
1645  wpScalingParam  *wp;
1646  Bool            bChroma     = true; // color always present in HEVC ?
1647  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
1648  Bool            bDenomCoded  = false;
1649  UInt            uiMode = 0;
1650  UInt            uiTotalSignalledWeightFlags = 0;
1651  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
1652  {
1653    uiMode = 1; // explicit
1654  }
1655  if(uiMode == 1)
1656  {
1657
1658    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
1659    {
1660      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1661
1662      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1663      {
1664        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1665        if ( !bDenomCoded ) 
1666        {
1667          Int iDeltaDenom;
1668          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
1669
1670          if( bChroma )
1671          {
1672            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
1673            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
1674          }
1675          bDenomCoded = true;
1676        }
1677        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
1678        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
1679      }
1680      if (bChroma) 
1681      {
1682        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1683        {
1684          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1685          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1686          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
1687        }
1688      }
1689
1690      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1691      {
1692        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1693        if ( wp[0].bPresentFlag ) 
1694        {
1695          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
1696          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
1697          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
1698        }
1699
1700        if ( bChroma ) 
1701        {
1702          if ( wp[1].bPresentFlag )
1703          {
1704            for ( Int j=1 ; j<3 ; j++ ) 
1705            {
1706              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
1707              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
1708
1709              Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
1710              Int iDeltaChroma = (wp[j].iOffset - pred);
1711              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
1712            }
1713          }
1714        }
1715      }
1716    }
1717    assert(uiTotalSignalledWeightFlags<=24);
1718  }
1719}
1720
1721/** code quantization matrix
1722 *  \param scalingList quantization matrix information
1723 */
1724Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
1725{
1726  UInt listId,sizeId;
1727  Bool scalingListPredModeFlag;
1728
1729#if SCALING_LIST_OUTPUT_RESULT
1730  Int startBit;
1731  Int startTotalBit;
1732  startBit = m_pcBitIf->getNumberOfWrittenBits();
1733  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
1734#endif
1735
1736    //for each size
1737    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
1738    {
1739      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
1740      {
1741#if SCALING_LIST_OUTPUT_RESULT
1742        startBit = m_pcBitIf->getNumberOfWrittenBits();
1743#endif
1744        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
1745        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
1746        if(!scalingListPredModeFlag)// Copy Mode
1747        {
1748          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
1749        }
1750        else// DPCM Mode
1751        {
1752          xCodeScalingList(scalingList, sizeId, listId);
1753        }
1754#if SCALING_LIST_OUTPUT_RESULT
1755        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
1756#endif
1757      }
1758    }
1759#if SCALING_LIST_OUTPUT_RESULT
1760  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
1761#endif
1762  return;
1763}
1764/** code DPCM
1765 * \param scalingList quantization matrix information
1766 * \param sizeIdc size index
1767 * \param listIdc list index
1768 */
1769Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
1770{
1771  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
1772  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
1773  Int nextCoef = SCALING_LIST_START_VALUE;
1774  Int data;
1775  Int *src = scalingList->getScalingListAddress(sizeId, listId);
1776    if( sizeId > SCALING_LIST_8x8 )
1777    {
1778      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
1779      nextCoef = scalingList->getScalingListDC(sizeId,listId);
1780    }
1781    for(Int i=0;i<coefNum;i++)
1782    {
1783      data = src[scan[i]] - nextCoef;
1784      nextCoef = src[scan[i]];
1785      if(data > 127)
1786      {
1787        data = data - 256;
1788      }
1789      if(data < -128)
1790      {
1791        data = data + 256;
1792      }
1793
1794      WRITE_SVLC( data,  "scaling_list_delta_coef");
1795    }
1796}
1797Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
1798{
1799  // Bool state = true, state2 = false;
1800  Int lsb = ltrpPOC % (1<<pcSlice->getSPS()->getBitsForPOC());
1801  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
1802  {
1803    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
1804    {
1805      *ltrpsIndex = k;
1806      return true;
1807    }
1808  }
1809  return false;
1810}
1811Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
1812{
1813  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
1814  {
1815    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
1816      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
1817     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
1818    {
1819      setRefMatrixId(sizeId, listId, predListIdx);
1820      return false;
1821    }
1822  }
1823  return true;
1824}
1825//! \}
Note: See TracBrowser for help on using the repository browser.