source: 3DVCSoftware/branches/HTM-16.0-MV-draft-5/source/Lib/TLibEncoder/TEncCavlc.cpp

Last change on this file was 1390, checked in by tech, 9 years ago

Removed 3D.

  • Property svn:eol-style set to native
File size: 99.6 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-2015, 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#if NH_MV
43#include "TEncTop.h"
44#endif
45
46//! \ingroup TLibEncoder
47//! \{
48
49#if ENC_DEC_TRACE
50
51#if !NH_MV_ENC_DEC_TRAC
52Void  xTraceVPSHeader ()
53{
54  fprintf( g_hTrace, "=========== Video Parameter Set     ===========\n" );
55}
56
57Void  xTraceSPSHeader ()
58{
59  fprintf( g_hTrace, "=========== Sequence Parameter Set  ===========\n" );
60}
61
62Void  xTracePPSHeader ()
63{
64  fprintf( g_hTrace, "=========== Picture Parameter Set  ===========\n");
65}
66
67Void  xTraceSliceHeader ( )
68{
69  fprintf( g_hTrace, "=========== Slice ===========\n");
70}
71
72Void  xTraceAccessUnitDelimiter ()
73{
74  fprintf( g_hTrace, "=========== Access Unit Delimiter ===========\n");
75}
76
77#endif
78#endif
79
80Void AUDWriter::codeAUD(TComBitIf& bs, const Int pictureType)
81{
82#if ENC_DEC_TRACE
83  xTraceAccessUnitDelimiter();
84#endif
85
86  assert (pictureType < 3);
87  setBitstream(&bs);
88  WRITE_CODE(pictureType, 3, "pic_type");
89  xWriteRbspTrailingBits();
90}
91
92// ====================================================================================================================
93// Constructor / destructor / create / destroy
94// ====================================================================================================================
95
96TEncCavlc::TEncCavlc()
97{
98  m_pcBitIf           = NULL;
99}
100
101TEncCavlc::~TEncCavlc()
102{
103}
104
105
106// ====================================================================================================================
107// Public member functions
108// ====================================================================================================================
109
110Void TEncCavlc::resetEntropy(const TComSlice* /*pSlice*/)
111{
112}
113
114
115Void TEncCavlc::codeShortTermRefPicSet( const TComReferencePictureSet* rps, Bool calledFromSliceHeader, Int idx)
116{
117#if PRINT_RPS_INFO
118  Int lastBits = getNumberOfWrittenBits();
119#endif
120  if (idx > 0)
121  {
122  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
123  }
124  if (rps->getInterRPSPrediction())
125  {
126    Int deltaRPS = rps->getDeltaRPS();
127    if(calledFromSliceHeader)
128    {
129      WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
130    }
131
132    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
133    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
134
135    for(Int j=0; j < rps->getNumRefIdc(); j++)
136    {
137      Int refIdc = rps->getRefIdc(j);
138      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
139      if (refIdc != 1)
140      {
141        WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
142      }
143    }
144  }
145  else
146  {
147    WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
148    WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
149    Int prev = 0;
150    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
151    {
152      WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
153      prev = rps->getDeltaPOC(j);
154      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag");
155    }
156    prev = 0;
157    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
158    {
159      WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
160      prev = rps->getDeltaPOC(j);
161      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" );
162    }
163  }
164
165#if PRINT_RPS_INFO
166  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
167  rps->printDeltaPOC();
168#endif
169}
170
171
172Void TEncCavlc::codePPS( const TComPPS* pcPPS )
173{
174#if ENC_DEC_TRACE
175#if NH_MV_ENC_DEC_TRAC
176  tracePSHeader( "PPS", pcPPS->getLayerId() ); 
177#else
178  xTracePPSHeader ();
179#endif
180#endif
181  WRITE_UVLC( pcPPS->getPPSId(),                             "pps_pic_parameter_set_id" );
182  WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
183  WRITE_FLAG( pcPPS->getDependentSliceSegmentsEnabledFlag()    ? 1 : 0, "dependent_slice_segments_enabled_flag" );
184  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,     "output_flag_present_flag" );
185  WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3,        "num_extra_slice_header_bits");
186  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
187  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
188  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
189  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
190  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "init_qp_minus26");
191  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
192  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" );
193  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
194  if ( pcPPS->getUseDQP() )
195  {
196    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
197  }
198
199  WRITE_SVLC( pcPPS->getQpOffset(COMPONENT_Cb), "pps_cb_qp_offset" );
200  WRITE_SVLC( pcPPS->getQpOffset(COMPONENT_Cr), "pps_cr_qp_offset" );
201
202  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
203
204  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
205  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
206  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
207  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
208  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
209  if( pcPPS->getTilesEnabledFlag() )
210  {
211    WRITE_UVLC( pcPPS->getNumTileColumnsMinus1(),                                    "num_tile_columns_minus1" );
212    WRITE_UVLC( pcPPS->getNumTileRowsMinus1(),                                       "num_tile_rows_minus1" );
213    WRITE_FLAG( pcPPS->getTileUniformSpacingFlag(),                                  "uniform_spacing_flag" );
214    if( !pcPPS->getTileUniformSpacingFlag() )
215    {
216      for(UInt i=0; i<pcPPS->getNumTileColumnsMinus1(); i++)
217      {
218        WRITE_UVLC( pcPPS->getTileColumnWidth(i)-1,                                  "column_width_minus1" );
219      }
220      for(UInt i=0; i<pcPPS->getNumTileRowsMinus1(); i++)
221      {
222        WRITE_UVLC( pcPPS->getTileRowHeight(i)-1,                                    "row_height_minus1" );
223      }
224    }
225    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getNumTileRowsMinus1() !=0)
226    {
227      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
228    }
229  }
230  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "pps_loop_filter_across_slices_enabled_flag");
231  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
232  if(pcPPS->getDeblockingFilterControlPresentFlag())
233  {
234    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" );
235    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
236    if(!pcPPS->getPicDisableDeblockingFilterFlag())
237    {
238      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
239      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
240    }
241  }
242  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" );
243  if( pcPPS->getScalingListPresentFlag() )
244  {
245    codeScalingList( pcPPS->getScalingList() );
246  }
247  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
248  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
249  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
250#if !NH_MV
251  Bool pps_extension_present_flag=false;
252  Bool pps_extension_flags[NUM_PPS_EXTENSION_FLAGS]={false};
253
254  pps_extension_flags[PPS_EXT__REXT] = pcPPS->getPpsRangeExtension().settingsDifferFromDefaults(pcPPS->getUseTransformSkip());
255
256  // Other PPS extension flags checked here.
257
258  for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
259  {
260    pps_extension_present_flag|=pps_extension_flags[i];
261  }
262
263  WRITE_FLAG( (pps_extension_present_flag?1:0), "pps_extension_present_flag" );
264
265  if (pps_extension_present_flag)
266  {
267#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
268    static const TChar *syntaxStrings[]={ "pps_range_extension_flag",
269                                         "pps_multilayer_extension_flag",
270                                         "pps_extension_6bits[0]",
271                                         "pps_extension_6bits[1]",
272                                         "pps_extension_6bits[2]",
273                                         "pps_extension_6bits[3]",
274                                         "pps_extension_6bits[4]",
275                                         "pps_extension_6bits[5]" };
276#endif
277
278    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
279    {
280      WRITE_FLAG( pps_extension_flags[i]?1:0, syntaxStrings[i] );
281    }
282
283    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
284    {
285      if (pps_extension_flags[i])
286      {
287        switch (PPSExtensionFlagIndex(i))
288        {
289          case PPS_EXT__REXT:
290            {
291              const TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
292            if (pcPPS->getUseTransformSkip())
293            {
294                WRITE_UVLC( ppsRangeExtension.getLog2MaxTransformSkipBlockSize()-2,            "log2_max_transform_skip_block_size_minus2");
295            }
296
297              WRITE_FLAG((ppsRangeExtension.getCrossComponentPredictionEnabledFlag() ? 1 : 0), "cross_component_prediction_enabled_flag" );
298
299              WRITE_FLAG(UInt(ppsRangeExtension.getChromaQpOffsetListEnabledFlag()),           "chroma_qp_offset_list_enabled_flag" );
300              if (ppsRangeExtension.getChromaQpOffsetListEnabledFlag())
301            {
302                WRITE_UVLC(ppsRangeExtension.getDiffCuChromaQpOffsetDepth(),                   "diff_cu_chroma_qp_offset_depth");
303                WRITE_UVLC(ppsRangeExtension.getChromaQpOffsetListLen() - 1,                   "chroma_qp_offset_list_len_minus1");
304              /* skip zero index */
305                for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx < ppsRangeExtension.getChromaQpOffsetListLen(); cuChromaQpOffsetIdx++)
306              {
307                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CbOffset,     "cb_qp_offset_list[i]");
308                  WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CrOffset,     "cr_qp_offset_list[i]");
309              }
310            }
311
312              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA),           "log2_sao_offset_scale_luma"   );
313              WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA),         "log2_sao_offset_scale_chroma" );
314            }
315            break;
316          default:
317            assert(pps_extension_flags[i]==false); // Should never get here with an active PPS extension flag.
318            break;
319        } // switch
320      } // if flag present
321    } // loop over PPS flags
322  } // pps_extension_present_flag is non-zero
323#else
324    WRITE_FLAG( 1, "pps_extension_present_flag" );
325
326    WRITE_FLAG( pcPPS->getPpsRangeExtensionsFlag( ) ? 1 : 0 , "pps_range_extensions_flag" );
327    WRITE_FLAG( pcPPS->getPpsMultilayerExtensionFlag( ) ? 1 : 0 , "pps_multilayer_extension_flag" );
328    WRITE_FLAG( pcPPS->getPps3dExtensionFlag( ) ? 1 : 0 , "pps_3d_extension_flag" );
329    WRITE_CODE( pcPPS->getPpsExtension5bits( ), 5, "pps_extension_5bits" );
330    if ( pcPPS->getPpsRangeExtensionsFlag() )
331    { 
332      const TComPPSRExt &ppsRangeExtension = pcPPS->getPpsRangeExtension();
333      if (pcPPS->getUseTransformSkip())
334      {
335        WRITE_UVLC( ppsRangeExtension.getLog2MaxTransformSkipBlockSize()-2,            "log2_max_transform_skip_block_size_minus2");
336      }
337
338      WRITE_FLAG((ppsRangeExtension.getCrossComponentPredictionEnabledFlag() ? 1 : 0), "cross_component_prediction_enabled_flag" );
339
340      WRITE_FLAG(UInt(ppsRangeExtension.getChromaQpOffsetListEnabledFlag()),           "chroma_qp_offset_list_enabled_flag" );
341      if (ppsRangeExtension.getChromaQpOffsetListEnabledFlag())
342      {
343        WRITE_UVLC(ppsRangeExtension.getDiffCuChromaQpOffsetDepth(),                   "diff_cu_chroma_qp_offset_depth");
344        WRITE_UVLC(ppsRangeExtension.getChromaQpOffsetListLen() - 1,                   "chroma_qp_offset_list_len_minus1");
345        /* skip zero index */
346        for (Int cuChromaQpOffsetIdx = 0; cuChromaQpOffsetIdx < ppsRangeExtension.getChromaQpOffsetListLen(); cuChromaQpOffsetIdx++)
347        {
348          WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CbOffset,     "cb_qp_offset_list[i]");
349          WRITE_SVLC(ppsRangeExtension.getChromaQpOffsetListEntry(cuChromaQpOffsetIdx+1).u.comp.CrOffset,     "cr_qp_offset_list[i]");
350        }
351      }
352
353      WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA),           "log2_sao_offset_scale_luma"   );
354      WRITE_UVLC( ppsRangeExtension.getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA),         "log2_sao_offset_scale_chroma" );
355    }
356
357    if ( pcPPS->getPpsMultilayerExtensionFlag() )
358    { 
359      codePpsMultilayerExtension( pcPPS );
360    }
361
362#endif
363  xWriteRbspTrailingBits();
364}
365
366
367Void TEncCavlc::codeVUI( const TComVUI *pcVUI, const TComSPS* pcSPS )
368{
369#if ENC_DEC_TRACE
370  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
371#endif
372  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
373  if (pcVUI->getAspectRatioInfoPresentFlag())
374  {
375    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
376    if (pcVUI->getAspectRatioIdc() == 255)
377    {
378      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
379      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
380    }
381  }
382  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
383  if (pcVUI->getOverscanInfoPresentFlag())
384  {
385    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
386  }
387  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
388#if NH_MV
389  assert( pcSPS->getLayerId() == 0 || !pcVUI->getVideoSignalTypePresentFlag() ); 
390#endif
391  if (pcVUI->getVideoSignalTypePresentFlag())
392  {
393    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
394    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
395    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
396    if (pcVUI->getColourDescriptionPresentFlag())
397    {
398      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
399      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
400      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coeffs");
401    }
402  }
403
404  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
405  if (pcVUI->getChromaLocInfoPresentFlag())
406  {
407    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
408    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
409  }
410
411  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
412  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
413  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
414
415  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
416  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
417  if( defaultDisplayWindow.getWindowEnabledFlag() )
418  {
419    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_left_offset");
420    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset() / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_right_offset");
421    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset()   / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_top_offset");
422    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset()/ TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_bottom_offset");
423  }
424  const TimingInfo *timingInfo = pcVUI->getTimingInfo();
425  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
426  if(timingInfo->getTimingInfoPresentFlag())
427  {
428    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
429    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
430    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
431    if(timingInfo->getPocProportionalToTimingFlag())
432    {
433      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
434    }
435    WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "vui_hrd_parameters_present_flag");
436    if( pcVUI->getHrdParametersPresentFlag() )
437    {
438      codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
439    }
440  }
441
442  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
443  if (pcVUI->getBitstreamRestrictionFlag())
444  {
445    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
446    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
447    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
448    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
449    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
450    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_min_cu_denom");
451    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
452    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
453  }
454}
455
456Void TEncCavlc::codeHrdParameters( const TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
457{
458  if( commonInfPresentFlag )
459  {
460    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
461    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
462    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
463    {
464      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_hrd_params_present_flag" );
465      if( hrd->getSubPicCpbParamsPresentFlag() )
466      {
467        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
468        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_increment_length_minus1" );
469        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
470        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
471      }
472      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
473      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
474      if( hrd->getSubPicCpbParamsPresentFlag() )
475      {
476        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" );
477      }
478      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
479      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
480      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
481    }
482  }
483  Int i, j, nalOrVcl;
484  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
485  {
486    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
487    Bool fixedPixRateWithinCvsFlag = true;
488    if( !hrd->getFixedPicRateFlag( i ) )
489    {
490      fixedPixRateWithinCvsFlag = hrd->getFixedPicRateWithinCvsFlag( i );
491      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
492    }
493    if( fixedPixRateWithinCvsFlag )
494    {
495      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
496    }
497    else
498    {
499      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
500    }
501    if (!hrd->getLowDelayHrdFlag( i ))
502    {
503      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
504    }
505
506    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
507    {
508      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
509          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
510      {
511        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
512        {
513          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
514          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
515          if( hrd->getSubPicCpbParamsPresentFlag() )
516          {
517            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");
518            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
519          }
520          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
521        }
522      }
523    }
524  }
525}
526
527Void TEncCavlc::codeSPS( const TComSPS* pcSPS )
528{
529
530  const ChromaFormat format                = pcSPS->getChromaFormatIdc();
531  const Bool         chromaEnabled         = isChromaEnabled(format);
532
533#if ENC_DEC_TRACE
534#if NH_MV_ENC_DEC_TRAC
535  tracePSHeader( "SPS", pcSPS->getLayerId() ); 
536#else
537  xTraceSPSHeader ();
538#endif
539#endif
540  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
541#if NH_MV
542  if ( pcSPS->getLayerId() == 0 )
543  {
544#endif
545  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
546#if NH_MV
547  }
548  else
549  {
550    WRITE_CODE( pcSPS->getSpsExtOrMaxSubLayersMinus1( ), 3, "sps_ext_or_max_sub_layers_minus1" );
551  }
552  if ( !pcSPS->getMultiLayerExtSpsFlag() )
553  {
554#endif
555  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0, "sps_temporal_id_nesting_flag" );
556  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
557#if NH_MV
558}
559#endif
560  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
561#if NH_MV
562    if ( pcSPS->getMultiLayerExtSpsFlag() )
563  {
564    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag( ) ? 1 : 0 , "update_rep_format_flag" );
565    if ( pcSPS->getUpdateRepFormatFlag() )
566    { 
567      WRITE_CODE( pcSPS->getSpsRepFormatIdx( ), 8, "sps_rep_format_idx" );
568    }
569  }
570  else
571  {
572#endif
573  WRITE_UVLC( Int(pcSPS->getChromaFormatIdc ()),    "chroma_format_idc" );
574  if( format == CHROMA_444 )
575  {
576    WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
577  }
578
579  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
580  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
581  Window conf = pcSPS->getConformanceWindow();
582
583  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
584  if (conf.getWindowEnabledFlag())
585  {
586    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
587    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
588    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
589    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
590  }
591#if NH_MV
592}
593#endif
594#if NH_MV
595  if ( !pcSPS->getMultiLayerExtSpsFlag() )
596  { 
597#endif
598
599  WRITE_UVLC( pcSPS->getBitDepth(CHANNEL_TYPE_LUMA) - 8,                      "bit_depth_luma_minus8" );
600
601  WRITE_UVLC( chromaEnabled ? (pcSPS->getBitDepth(CHANNEL_TYPE_CHROMA) - 8):0,  "bit_depth_chroma_minus8" );
602#if NH_MV
603  }
604#endif
605  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
606#if NH_MV
607  if ( !pcSPS->getMultiLayerExtSpsFlag()) 
608  { 
609#endif
610
611  const Bool subLayerOrderingInfoPresentFlag = 1;
612  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
613  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
614  {
615    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
616    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_max_num_reorder_pics[i]" );
617#if NH_MV
618    WRITE_UVLC( pcSPS->getSpsMaxLatencyIncreasePlus1(i),   "sps_max_latency_increase_plus1[i]" );
619#else
620    WRITE_UVLC( pcSPS->getMaxLatencyIncreasePlus1(i),      "sps_max_latency_increase_plus1[i]" );
621#endif
622    if (!subLayerOrderingInfoPresentFlag)
623    {
624      break;
625    }
626  }
627#if NH_MV
628  }
629#endif
630
631  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
632  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_luma_coding_block_size_minus3" );
633  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_luma_coding_block_size" );
634  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_luma_transform_block_size_minus2" );
635  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_luma_transform_block_size" );
636  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
637  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
638  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" );
639  if(pcSPS->getScalingListFlag())
640  {
641#if NH_MV
642    if ( pcSPS->getMultiLayerExtSpsFlag() )
643    {   
644      WRITE_FLAG( pcSPS->getSpsInferScalingListFlag( ) ? 1 : 0 , "sps_infer_scaling_list_flag" );
645    }
646
647    if ( pcSPS->getSpsInferScalingListFlag() )
648    {
649      WRITE_CODE( pcSPS->getSpsScalingListRefLayerId( ), 6, "sps_scaling_list_ref_layer_id" );
650    }
651    else
652    {   
653#endif
654
655    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" );
656    if(pcSPS->getScalingListPresentFlag())
657    {
658      codeScalingList( pcSPS->getScalingList() );
659    }
660#if NH_MV
661    }
662#endif
663  }
664  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
665  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
666
667  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
668  if( pcSPS->getUsePCM() )
669  {
670    WRITE_CODE( pcSPS->getPCMBitDepth(CHANNEL_TYPE_LUMA) - 1, 4,                            "pcm_sample_bit_depth_luma_minus1" );
671    WRITE_CODE( chromaEnabled ? (pcSPS->getPCMBitDepth(CHANNEL_TYPE_CHROMA) - 1) : 0, 4,    "pcm_sample_bit_depth_chroma_minus1" );
672    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
673    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
674    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
675  }
676
677  assert( pcSPS->getMaxTLayers() > 0 );
678
679  const TComRPSList* rpsList = pcSPS->getRPSList();
680
681  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
682  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
683  {
684    const TComReferencePictureSet*rps = rpsList->getReferencePictureSet(i);
685    codeShortTermRefPicSet( rps,false, i);
686  }
687#if NH_MV
688  WRITE_FLAG( pcSPS->getLongTermRefPicsPresentFlag() ? 1 : 0,         "long_term_ref_pics_present_flag" );
689  if (pcSPS->getLongTermRefPicsPresentFlag())
690#else
691  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
692  if (pcSPS->getLongTermRefsPresent())
693#endif
694  {
695    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pics_sps" );
696    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
697    {
698      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
699      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag[i]");
700    }
701  }
702  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
703
704  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
705
706  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
707  if (pcSPS->getVuiParametersPresentFlag())
708  {
709      codeVUI(pcSPS->getVuiParameters(), pcSPS);
710  }
711
712#if !NH_MV
713  Bool sps_extension_present_flag=false;
714  Bool sps_extension_flags[NUM_SPS_EXTENSION_FLAGS]={false};
715
716  sps_extension_flags[SPS_EXT__REXT] = pcSPS->getSpsRangeExtension().settingsDifferFromDefaults();
717
718  // Other SPS extension flags checked here.
719
720  for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
721  {
722    sps_extension_present_flag|=sps_extension_flags[i];
723  }
724
725  WRITE_FLAG( (sps_extension_present_flag?1:0), "sps_extension_present_flag" );
726
727  if (sps_extension_present_flag)
728  {
729#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
730    static const TChar *syntaxStrings[]={ "sps_range_extension_flag",
731      "sps_multilayer_extension_flag",
732      "sps_extension_6bits[0]",
733      "sps_extension_6bits[1]",
734      "sps_extension_6bits[2]",
735      "sps_extension_6bits[3]",
736      "sps_extension_6bits[4]",
737      "sps_extension_6bits[5]" };
738#endif
739
740    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
741    {
742      WRITE_FLAG( sps_extension_flags[i]?1:0, syntaxStrings[i] );
743    }
744
745    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
746    {
747      if (sps_extension_flags[i])
748      {
749        switch (SPSExtensionFlagIndex(i))
750        {
751        case SPS_EXT__REXT:
752          {
753            const TComSPSRExt &spsRangeExtension=pcSPS->getSpsRangeExtension();
754
755            WRITE_FLAG( (spsRangeExtension.getTransformSkipRotationEnabledFlag() ? 1 : 0),      "transform_skip_rotation_enabled_flag");
756            WRITE_FLAG( (spsRangeExtension.getTransformSkipContextEnabledFlag() ? 1 : 0),       "transform_skip_context_enabled_flag");
757            WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT) ? 1 : 0), "implicit_rdpcm_enabled_flag" );
758            WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT) ? 1 : 0), "explicit_rdpcm_enabled_flag" );
759            WRITE_FLAG( (spsRangeExtension.getExtendedPrecisionProcessingFlag() ? 1 : 0),       "extended_precision_processing_flag" );
760            WRITE_FLAG( (spsRangeExtension.getIntraSmoothingDisabledFlag() ? 1 : 0),            "intra_smoothing_disabled_flag" );
761            WRITE_FLAG( (spsRangeExtension.getHighPrecisionOffsetsEnabledFlag() ? 1 : 0),       "high_precision_offsets_enabled_flag" );
762            WRITE_FLAG( (spsRangeExtension.getPersistentRiceAdaptationEnabledFlag() ? 1 : 0),   "persistent_rice_adaptation_enabled_flag" );
763            WRITE_FLAG( (spsRangeExtension.getCabacBypassAlignmentEnabledFlag() ? 1 : 0),       "cabac_bypass_alignment_enabled_flag" );
764          break;
765          }
766        default:
767          assert(sps_extension_flags[i]==false); // Should never get here with an active SPS extension flag.
768          break;
769        }
770      }
771    }
772  }
773#else
774  WRITE_FLAG( pcSPS->getSpsExtensionPresentFlag(), "sps_extension_present_flag" );
775
776  if ( pcSPS->getSpsExtensionPresentFlag() )
777  {
778    WRITE_FLAG( pcSPS->getSpsRangeExtensionsFlag( )     ? 1 : 0 , "sps_range_extensions_flag" );
779    WRITE_FLAG( pcSPS->getSpsMultilayerExtensionFlag( ) ? 1 : 0 , "sps_multilayer_extension_flag" );
780    WRITE_FLAG( pcSPS->getSps3dExtensionFlag( )         ? 1 : 0 , "sps_3d_extension_flag" );
781    WRITE_CODE( pcSPS->getSpsExtension5bits( )              , 5 , "sps_extension_5bits" );
782  }
783
784  if ( pcSPS->getSpsRangeExtensionsFlag() )
785  {
786    const TComSPSRExt &spsRangeExtension=pcSPS->getSpsRangeExtension();
787
788    WRITE_FLAG( (spsRangeExtension.getTransformSkipRotationEnabledFlag() ? 1 : 0),      "transform_skip_rotation_enabled_flag");
789    WRITE_FLAG( (spsRangeExtension.getTransformSkipContextEnabledFlag() ? 1 : 0),       "transform_skip_context_enabled_flag");
790    WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT) ? 1 : 0), "implicit_rdpcm_enabled_flag" );
791    WRITE_FLAG( (spsRangeExtension.getRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT) ? 1 : 0), "explicit_rdpcm_enabled_flag" );
792    WRITE_FLAG( (spsRangeExtension.getExtendedPrecisionProcessingFlag() ? 1 : 0),       "extended_precision_processing_flag" );
793    WRITE_FLAG( (spsRangeExtension.getIntraSmoothingDisabledFlag() ? 1 : 0),            "intra_smoothing_disabled_flag" );
794    WRITE_FLAG( (spsRangeExtension.getHighPrecisionOffsetsEnabledFlag() ? 1 : 0),       "high_precision_offsets_enabled_flag" );
795    WRITE_FLAG( (spsRangeExtension.getPersistentRiceAdaptationEnabledFlag() ? 1 : 0),   "persistent_rice_adaptation_enabled_flag" );
796    WRITE_FLAG( (spsRangeExtension.getCabacBypassAlignmentEnabledFlag() ? 1 : 0),       "cabac_bypass_alignment_enabled_flag" );
797  }
798
799  if ( pcSPS->getSpsMultilayerExtensionFlag() )
800  {
801    codeSPSExtension( pcSPS ); 
802  }
803
804#endif
805  xWriteRbspTrailingBits();
806}
807
808#if NH_MV
809Void TEncCavlc::codeSPSExtension( const TComSPS* pcSPS )
810{
811  WRITE_FLAG( pcSPS->getInterViewMvVertConstraintFlag() ? 1 : 0, "inter_view_mv_vert_constraint_flag" );
812}
813
814
815Void TEncCavlc::codePpsMultilayerExtension(const TComPPS* pcPPS)
816{
817  WRITE_FLAG( pcPPS->getPocResetInfoPresentFlag( ) ? 1 : 0 , "poc_reset_info_present_flag" );
818  WRITE_FLAG( pcPPS->getPpsInferScalingListFlag( ) ? 1 : 0 , "pps_infer_scaling_list_flag" );
819  if (pcPPS->getPpsInferScalingListFlag())
820  {
821    WRITE_CODE( pcPPS->getPpsScalingListRefLayerId( ), 6, "pps_scaling_list_ref_layer_id" );
822  }
823  WRITE_UVLC( 0, "num_ref_loc_offsets" );
824  WRITE_FLAG( 0 , "colour_mapping_enabled_flag" );
825
826}
827
828#endif
829
830
831
832Void TEncCavlc::codeVPS( const TComVPS* pcVPS )
833{
834#if ENC_DEC_TRACE
835#if NH_MV_ENC_DEC_TRAC
836  tracePSHeader( "VPS", getEncTop()->getLayerId() ); 
837#else
838  xTraceVPSHeader();
839#endif
840#endif
841  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
842#if NH_MV
843  WRITE_FLAG( pcVPS->getVpsBaseLayerInternalFlag( ) ? 1 : 0 , "vps_base_layer_internal_flag" );
844  WRITE_FLAG( pcVPS->getVpsBaseLayerAvailableFlag( ) ? 1 : 0 , "vps_base_layer_available_flag" );
845#else
846  WRITE_FLAG(                                       1,        "vps_base_layer_internal_flag" );
847  WRITE_FLAG(                                       1,        "vps_base_layer_available_flag" );
848#endif
849#if NH_MV
850  WRITE_CODE( pcVPS->getMaxLayersMinus1(),       6,        "vps_max_layers_minus1" );
851#else
852  WRITE_CODE( 0,                                    6,        "vps_max_layers_minus1" );
853#endif
854  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
855  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
856  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
857  WRITE_CODE( 0xffff,                              16,        "vps_reserved_0xffff_16bits" );
858  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
859  const Bool subLayerOrderingInfoPresentFlag = 1;
860  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
861  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
862  {
863    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
864    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_max_num_reorder_pics[i]" );
865    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
866    if (!subLayerOrderingInfoPresentFlag)
867    {
868      break;
869    }
870  }
871
872  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
873#if NH_MV
874  assert( pcVPS->getVpsMaxLayerId() < MAX_VPS_NUH_LAYER_ID_PLUS1 );
875  WRITE_CODE( pcVPS->getVpsMaxLayerId(), 6,                 "vps_max_layer_id" ); 
876  WRITE_UVLC( pcVPS->getVpsNumLayerSetsMinus1(),  "vps_num_layer_sets_minus1" );
877  for( UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx ++ )
878  {
879    // Operation point set
880    for( UInt i = 0; i <= pcVPS->getVpsMaxLayerId(); i ++ )
881    {
882#else
883  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
884  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_layer_id" );
885  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_num_layer_sets_minus1" );
886  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
887  {
888    // Operation point set
889    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
890    {
891      // Only applicable for version 1
892      // pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
893#endif
894      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
895    }
896  }
897  const TimingInfo *timingInfo = pcVPS->getTimingInfo();
898  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
899  if(timingInfo->getTimingInfoPresentFlag())
900  {
901    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
902    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
903    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
904    if(timingInfo->getPocProportionalToTimingFlag())
905    {
906      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
907    }
908    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
909
910    if( pcVPS->getNumHrdParameters() > 0 )
911    {
912      for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
913      {
914        // Only applicable for version 1
915        WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_layer_set_idx" );
916        if( i > 0 )
917        {
918          WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
919        }
920        codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
921      }
922    }
923  }
924#if NH_MV
925  WRITE_FLAG( pcVPS->getVpsExtensionFlag(),                     "vps_extension_flag" );
926  m_pcBitIf->writeAlignOne();
927  codeVPSExtension( pcVPS );                           
928  WRITE_FLAG( 0,                     "vps_extension2_flag" );
929#else
930  WRITE_FLAG( 0,                     "vps_extension_flag" );
931#endif
932
933  //future extensions here..
934  xWriteRbspTrailingBits();
935}
936
937#if NH_MV
938Void TEncCavlc::codeVPSExtension( const TComVPS *pcVPS ) 
939{ 
940  if( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() )
941  {
942    codePTL( pcVPS->getPTL( 1 ),0, pcVPS->getMaxSubLayersMinus1()  );
943  }
944
945  WRITE_FLAG( pcVPS->getSplittingFlag() ? 1 : 0,             "splitting_flag" );
946
947  for( Int type = 0; type < MAX_NUM_SCALABILITY_TYPES; type++ )
948  {
949    WRITE_FLAG( pcVPS->getScalabilityMaskFlag( type ) ? 1 : 0,   "scalability_mask_flag[i]" );
950  }
951
952  for( Int sIdx = 0; sIdx < pcVPS->getNumScalabilityTypes( ) - ( pcVPS->getSplittingFlag() ? 1 : 0 ); sIdx++ )
953  {
954    WRITE_CODE( pcVPS->getDimensionIdLen( sIdx ) - 1 , 3,    "dimension_id_len_minus1[j]");   
955  }
956
957  if ( pcVPS->getSplittingFlag() )
958  {   
959    assert( pcVPS->getDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1 ) == pcVPS->inferLastDimsionIdLenMinus1() + 1 );
960  }   
961
962  WRITE_FLAG( pcVPS->getVpsNuhLayerIdPresentFlag() ? 1 : 0,  "vps_nuh_layer_id_present_flag");
963
964  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
965  {
966    if ( pcVPS->getVpsNuhLayerIdPresentFlag() )
967    {     
968      WRITE_CODE( pcVPS->getLayerIdInNuh( i ), 6,          "layer_id_in_nuh[i]");
969    }
970    else
971    {
972      assert( pcVPS->getLayerIdInNuh( i ) == i ); 
973    }
974
975    assert(  pcVPS->getLayerIdInVps( pcVPS->getLayerIdInNuh( i ) ) == i ); 
976
977    for( Int j = 0; j < pcVPS->getNumScalabilityTypes() ; j++ )
978    {
979      if ( !pcVPS->getSplittingFlag() )
980      {
981        WRITE_CODE( pcVPS->getDimensionId( i, j ), pcVPS->getDimensionIdLen( j ), "dimension_id[i][j]");     
982      }
983      else
984      {
985        assert( pcVPS->getDimensionId( i, j ) ==  pcVPS->inferDimensionId( i, j )  );
986      }
987    }
988  }
989
990  WRITE_CODE( pcVPS->getViewIdLen( ), 4, "view_id_len" );
991
992  if ( pcVPS->getViewIdLen( ) > 0 )
993  {   
994    for( Int i = 0; i < pcVPS->getNumViews(); i++ )
995    {
996      WRITE_CODE( pcVPS->getViewIdVal( i ), pcVPS->getViewIdLen( ), "view_id_val[i]" );
997    }
998  }
999  else
1000  {
1001    for( Int i = 0; i < pcVPS->getNumViews(); i++ )
1002    {
1003      assert( pcVPS->getViewIdVal( i ) == 0 ); 
1004    }
1005  }
1006
1007
1008  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
1009  {
1010    for( Int j = 0; j < i; j++ )
1011    {
1012      WRITE_FLAG( pcVPS->getDirectDependencyFlag( i, j ),    "direct_dependency_flag[i][j]" );
1013    }
1014  }
1015
1016  if ( pcVPS->getNumIndependentLayers() > 1 ) 
1017  {
1018    WRITE_UVLC( pcVPS->getNumAddLayerSets( ), "num_add_layer_sets" );
1019  }
1020  for (Int i = 0; i < pcVPS->getNumAddLayerSets(); i++)
1021  {
1022    for (Int j = 1; j < pcVPS->getNumIndependentLayers(); j++)
1023    {
1024      WRITE_CODE( pcVPS->getHighestLayerIdxPlus1( i, j ), pcVPS->getHighestLayerIdxPlus1Len( j )  , "highest_layer_idx_plus1" );
1025    }
1026 
1027  }
1028
1029
1030  WRITE_FLAG( pcVPS->getVpsSubLayersMaxMinus1PresentFlag( ) ? 1 : 0 , "vps_sub_layers_max_minus1_present_flag" );
1031  if ( pcVPS->getVpsSubLayersMaxMinus1PresentFlag() )
1032  {
1033    for (Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
1034    {
1035      WRITE_CODE( pcVPS->getSubLayersVpsMaxMinus1( i ), 3, "sub_layers_vps_max_minus1" );
1036      pcVPS->checkSubLayersVpsMaxMinus1( i ); 
1037    }
1038  } 
1039  else
1040  {
1041    for (Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
1042    {
1043      assert( pcVPS->getSubLayersVpsMaxMinus1( i ) + 1 == pcVPS->getMaxTLayers( ) );   
1044    }
1045  }
1046  WRITE_FLAG( pcVPS->getMaxTidRefPresentFlag( ) ? 1 : 0 , "max_tid_ref_present_flag" );
1047
1048  if ( pcVPS->getMaxTidRefPresentFlag() )
1049  {   
1050    for( Int i = 0; i < pcVPS->getMaxLayersMinus1(); i++ )
1051    {
1052      for( Int j = i + 1; j <= pcVPS->getMaxLayersMinus1(); j++ )
1053      {
1054        if ( pcVPS->getDirectDependencyFlag(j,i) )
1055        {
1056          WRITE_CODE( pcVPS->getMaxTidIlRefPicsPlus1( i, j ), 3, "max_tid_il_ref_pics_plus1" );
1057        }
1058      }
1059    }
1060  }
1061
1062  WRITE_FLAG( pcVPS->getAllRefLayersActiveFlag( ) ? 1 : 0 , "all_ref_layers_active_flag" );
1063  WRITE_UVLC( pcVPS->getVpsNumProfileTierLevelMinus1( ), "vps_num_profile_tier_level_minus1" );
1064
1065  Int offsetVal =  ( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() ) ? 2 : 1;   
1066  for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 2 : 1; i <= pcVPS->getVpsNumProfileTierLevelMinus1(); i++ )
1067  {
1068    WRITE_FLAG( pcVPS->getVpsProfilePresentFlag( i ) ? 1 : 0, "vps_profile_present_flag[i]" );
1069    codePTL( pcVPS->getPTL( offsetVal ), pcVPS->getVpsProfilePresentFlag( i ), pcVPS->getMaxTLayers() - 1 );
1070    offsetVal++;
1071  }
1072
1073
1074  if (pcVPS->getNumLayerSets() > 1)
1075  {
1076    WRITE_UVLC( pcVPS->getNumAddOlss( ), "num_add_olss" );
1077    WRITE_CODE( pcVPS->getDefaultOutputLayerIdc( ), 2, "default_output_layer_idc" );
1078  }
1079
1080  assert( pcVPS->getOutputLayerFlag(0, 0) == pcVPS->inferOutputLayerFlag( 0, 0 )); 
1081  assert( pcVPS->getLayerSetIdxForOlsMinus1( 0 ) == -1 ); 
1082
1083
1084  if (pcVPS->getVpsBaseLayerInternalFlag() )
1085  { 
1086    assert( pcVPS->getProfileTierLevelIdx(0,0) == pcVPS->inferProfileTierLevelIdx(0,0) );
1087  }
1088
1089
1090  for( Int i = 1; i < pcVPS->getNumOutputLayerSets( ); i++ )
1091  {
1092    if( pcVPS->getNumLayerSets() > 2 && i >= pcVPS->getNumLayerSets( ) )   
1093    {     
1094      WRITE_CODE( pcVPS->getLayerSetIdxForOlsMinus1( i ), pcVPS->getLayerSetIdxForOlsMinus1Len( i ) ,      "layer_set_idx_for_ols_minus1[i]" );
1095    }
1096
1097    if ( i > pcVPS->getVpsNumLayerSetsMinus1() || pcVPS->getDefaultOutputLayerIdc() == 2 )
1098    {       
1099      for( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx( i ) ); j++ )
1100      {
1101        WRITE_FLAG( pcVPS->getOutputLayerFlag( i, j) ? 1 : 0, "output_layer_flag" );
1102      }             
1103    }
1104    else
1105    {
1106      for( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx( i ) ) - 1; j++ )
1107      {             
1108        assert( pcVPS->getOutputLayerFlag( i , j ) == pcVPS->inferOutputLayerFlag( i, j )); 
1109      }
1110    }       
1111       
1112    for ( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx(i)); j++ )
1113    {   
1114      if (pcVPS->getNecessaryLayerFlag( i, j ) && pcVPS->getVpsNumProfileTierLevelMinus1() > 0 )
1115      {
1116        WRITE_CODE( pcVPS->getProfileTierLevelIdx( i, j ), pcVPS->getProfileTierLevelIdxLen() ,"profile_tier_level_idx[ i ][ j ]" );   
1117      }
1118      if (pcVPS->getNecessaryLayerFlag( i, j ) && pcVPS->getVpsNumProfileTierLevelMinus1() == 0 )
1119      {
1120        assert( pcVPS->getProfileTierLevelIdx( i , j ) == pcVPS->inferProfileTierLevelIdx( i, j ) );
1121      }
1122
1123    }
1124    if( pcVPS->getNumOutputLayersInOutputLayerSet( i ) == 1 && pcVPS->getNumDirectRefLayers( pcVPS->getOlsHighestOutputLayerId( i ) ) > 0 )
1125    {
1126      WRITE_FLAG( pcVPS->getAltOutputLayerFlag( i ) ? 1 : 0 , "alt_output_layer_flag[ i ]" );
1127    }
1128  }
1129
1130  WRITE_UVLC( pcVPS->getVpsNumRepFormatsMinus1( ), "vps_num_rep_formats_minus1" );
1131
1132  for (Int i = 0; i <= pcVPS->getVpsNumRepFormatsMinus1(); i++ )
1133  {   
1134    const TComRepFormat* curRepFormat = pcVPS->getRepFormat(i);     
1135    const TComRepFormat* prevRepFormat = i > 0 ? pcVPS->getRepFormat( i - 1) : NULL; 
1136    codeRepFormat( i, curRepFormat ,  prevRepFormat); 
1137  }
1138
1139  if ( pcVPS->getVpsNumRepFormatsMinus1() > 0 )
1140  {
1141    WRITE_FLAG( pcVPS->getRepFormatIdxPresentFlag( ) ? 1 : 0 , "rep_format_idx_present_flag" );
1142  }
1143
1144  if( pcVPS->getRepFormatIdxPresentFlag() ) 
1145  {
1146    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 0; i <=  pcVPS->getMaxLayersMinus1(); i++ )
1147    {
1148        WRITE_CODE( pcVPS->getVpsRepFormatIdx(i), pcVPS->getVpsRepFormatIdxLen(), "vps_rep_format_idx[i]" );
1149    }
1150  }
1151  else
1152  {
1153    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 0; i <=  pcVPS->getMaxLayersMinus1(); i++ )
1154    {
1155      assert( pcVPS->getVpsRepFormatIdx( i ) ==  pcVPS->inferVpsRepFormatIdx( i ) );
1156    }
1157  }
1158
1159  WRITE_FLAG( pcVPS->getMaxOneActiveRefLayerFlag( ) ? 1 : 0, "max_one_active_ref_layer_flag" );
1160  WRITE_FLAG( pcVPS->getVpsPocLsbAlignedFlag( ) ? 1 : 0 , "vps_poc_lsb_aligned_flag" );
1161  for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
1162  {
1163    if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) )  ==  0 )
1164    {     
1165      WRITE_FLAG( pcVPS->getPocLsbNotPresentFlag( i ) ? 1 : 0 , "poc_lsb_not_present_flag" );
1166    }
1167  }
1168
1169  codeDpbSize( pcVPS ); 
1170
1171  WRITE_UVLC( pcVPS->getDirectDepTypeLenMinus2 ( ),         "direct_dep_type_len_minus2"); 
1172
1173  WRITE_FLAG( pcVPS->getDefaultDirectDependencyFlag( ) ? 1 : 0 , "default_direct_dependency_flag" );
1174  if ( pcVPS->getDefaultDirectDependencyFlag( ) )
1175  { 
1176    WRITE_CODE( pcVPS->getDefaultDirectDependencyType( ), pcVPS->getDirectDepTypeLenMinus2( ) + 2 , "default_direct_dependency_type" );   
1177  }
1178
1179  for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ?  1 : 2; i <= pcVPS->getMaxLayersMinus1(); i++ )
1180  {
1181    for( Int j = pcVPS->getVpsBaseLayerInternalFlag() ?  0 : 1; j < i; j++ )
1182    {
1183      if (pcVPS->getDirectDependencyFlag( i, j) )
1184      {       
1185        if ( pcVPS->getDefaultDirectDependencyFlag( ) )
1186        { 
1187          assert( pcVPS->getDirectDependencyType( i, j ) == pcVPS->getDefaultDirectDependencyType( ) );
1188        }
1189        else
1190        {
1191          assert ( pcVPS->getDirectDependencyType( i, j ) != -1 ); 
1192          WRITE_CODE( pcVPS->getDirectDependencyType( i, j ),pcVPS->getDirectDepTypeLenMinus2( ) + 2,  "direct_dependency_type[i][j]" );
1193        }
1194      }
1195    }
1196  } 
1197  WRITE_UVLC( 0, "vps_non_vui_extension_length" );
1198 
1199
1200
1201
1202  WRITE_FLAG( pcVPS->getVpsVuiPresentFlag() ? 1 : 0 , "vps_vui_present_flag" );
1203  if( pcVPS->getVpsVuiPresentFlag() )
1204  {
1205    m_pcBitIf->writeAlignOne();  // vps_vui_alignment_bit_equal_to_one
1206    codeVPSVUI( pcVPS ); 
1207  }     
1208  else
1209  {
1210    const TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
1211    assert( pcVPSVUI ); 
1212    assert( !pcVPSVUI->getCrossLayerIrapAlignedFlag() );     
1213  }
1214
1215}
1216
1217Void TEncCavlc::codeVideoSignalInfo( const TComVideoSignalInfo* pcVideoSignalInfo )
1218{
1219  assert( pcVideoSignalInfo ); 
1220  WRITE_CODE( pcVideoSignalInfo->getVideoVpsFormat( ), 3, "video_vps_format" );
1221  WRITE_FLAG( pcVideoSignalInfo->getVideoFullRangeVpsFlag( ) ? 1 : 0 , "video_full_range_vps_flag" );
1222  WRITE_CODE( pcVideoSignalInfo->getColourPrimariesVps( ), 8, "colour_primaries_vps" );
1223  WRITE_CODE( pcVideoSignalInfo->getTransferCharacteristicsVps( ), 8, "transfer_characteristics_vps" );
1224  WRITE_CODE( pcVideoSignalInfo->getMatrixCoeffsVps( ), 8, "matrix_coeffs_vps" );
1225}
1226
1227Void TEncCavlc::codeDpbSize( const TComVPS* vps )
1228{ 
1229  const TComDpbSize * dpbSize = vps->getDpbSize(); 
1230
1231  for( Int i = 1; i < vps->getNumOutputLayerSets(); i++ )
1232  { 
1233    Int currLsIdx = vps->olsIdxToLsIdx( i ); 
1234    WRITE_FLAG( dpbSize->getSubLayerFlagInfoPresentFlag( i ) ? 1 : 0 , "sub_layer_flag_info_present_flag" );
1235    for( Int j = 0; j  <=  vps->getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
1236    { 
1237      if( j > 0  &&  dpbSize->getSubLayerDpbInfoPresentFlag( i, j )  ) 
1238      {
1239        WRITE_FLAG( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) ? 1 : 0 , "sub_layer_dpb_info_present_flag" );
1240      }
1241      if( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) )
1242      { 
1243        for( Int k = 0; k < vps->getNumLayersInIdList( currLsIdx ); k++ )   
1244        {
1245          if ( vps->getNecessaryLayerFlag( i, k ) && ( vps->getVpsBaseLayerInternalFlag() || ( vps->getLayerSetLayerIdList(vps->olsIdxToLsIdx(i),k) != 0 ) ))
1246          {
1247            WRITE_UVLC( dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j ), "max_vps_dec_pic_buffering_minus1" );
1248          }
1249          else
1250          {
1251            if ( vps->getNecessaryLayerFlag( i, k ) && ( j == 0 ) && ( k == 0 ) ) 
1252            {
1253              assert( dpbSize->getMaxVpsDecPicBufferingMinus1(i ,k, j ) ==  0 );
1254            }
1255          }
1256        }
1257        WRITE_UVLC( dpbSize->getMaxVpsNumReorderPics( i, j ), "max_vps_num_reorder_pics" );
1258        WRITE_UVLC( dpbSize->getMaxVpsLatencyIncreasePlus1( i, j ), "max_vps_latency_increase_plus1" );
1259      }
1260      else
1261      {
1262        if ( j > 0 )
1263        {
1264          for( Int k = 0; k < vps->getNumLayersInIdList( vps->olsIdxToLsIdx( i ) ); k++ )   
1265          {
1266            if ( vps->getNecessaryLayerFlag(i, k ) )
1267            {           
1268              assert( dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j ) == dpbSize->getMaxVpsDecPicBufferingMinus1( i,k, j - 1 ) );
1269            }
1270          }
1271          assert( dpbSize->getMaxVpsNumReorderPics      ( i, j ) ==  dpbSize->getMaxVpsNumReorderPics      ( i, j - 1 ) );
1272          assert( dpbSize->getMaxVpsLatencyIncreasePlus1( i, j ) ==  dpbSize->getMaxVpsLatencyIncreasePlus1( i, j - 1 ) );
1273        }
1274      }
1275    }
1276  }
1277}
1278
1279Void TEncCavlc::codeRepFormat( Int i, const TComRepFormat* pcRepFormat, const TComRepFormat* pcPrevRepFormat )
1280{
1281  assert( pcRepFormat ); 
1282
1283  WRITE_CODE( pcRepFormat->getPicWidthVpsInLumaSamples( ),  16, "pic_width_vps_in_luma_samples" );
1284  WRITE_CODE( pcRepFormat->getPicHeightVpsInLumaSamples( ), 16, "pic_height_vps_in_luma_samples" );
1285  WRITE_FLAG( pcRepFormat->getChromaAndBitDepthVpsPresentFlag( ) ? 1 : 0 , "chroma_and_bit_depth_vps_present_flag" );
1286 
1287  pcRepFormat->checkChromaAndBitDepthVpsPresentFlag( i ); 
1288
1289  if ( pcRepFormat->getChromaAndBitDepthVpsPresentFlag() )
1290  { 
1291    WRITE_CODE( pcRepFormat->getChromaFormatVpsIdc( ), 2, "chroma_format_vps_idc" ); 
1292
1293    if ( pcRepFormat->getChromaFormatVpsIdc() == 3 )
1294    {
1295      WRITE_FLAG( pcRepFormat->getSeparateColourPlaneVpsFlag( ) ? 1 : 0 , "separate_colour_plane_vps_flag" );
1296    }
1297    WRITE_CODE( pcRepFormat->getBitDepthVpsLumaMinus8( ),      4, "bit_depth_vps_luma_minus8" );
1298    WRITE_CODE( pcRepFormat->getBitDepthVpsChromaMinus8( ),    4, "bit_depth_vps_chroma_minus8" );
1299  }
1300  else
1301  {
1302    pcRepFormat->checkInferChromaAndBitDepth(pcPrevRepFormat ); 
1303  }
1304  WRITE_FLAG( pcRepFormat->getConformanceWindowVpsFlag( ) ? 1 : 0 , "conformance_window_vps_flag" );
1305  if ( pcRepFormat->getConformanceWindowVpsFlag() )
1306  {   
1307    WRITE_UVLC( pcRepFormat->getConfWinVpsLeftOffset( ), "conf_win_vps_left_offset" );
1308    WRITE_UVLC( pcRepFormat->getConfWinVpsRightOffset( ), "conf_win_vps_right_offset" );
1309    WRITE_UVLC( pcRepFormat->getConfWinVpsTopOffset( ), "conf_win_vps_top_offset" );
1310    WRITE_UVLC( pcRepFormat->getConfWinVpsBottomOffset( ), "conf_win_vps_bottom_offset" );
1311  }
1312}
1313
1314Void TEncCavlc::codeVPSVUI( const TComVPS* pcVPS )
1315{
1316  assert( pcVPS ); 
1317
1318  const TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
1319
1320  assert( pcVPSVUI ); 
1321
1322
1323  WRITE_FLAG( pcVPSVUI->getCrossLayerPicTypeAlignedFlag( ) ? 1 : 0 , "cross_layer_pic_type_aligned_flag" );
1324  if ( !pcVPSVUI->getCrossLayerPicTypeAlignedFlag() )
1325  { 
1326    WRITE_FLAG( pcVPSVUI->getCrossLayerIrapAlignedFlag( ) ? 1 : 0 , "cross_layer_irap_aligned_flag" );
1327  }
1328  if( pcVPSVUI->getCrossLayerIrapAlignedFlag( ) )
1329  {
1330    WRITE_FLAG( pcVPSVUI->getAllLayersIdrAlignedFlag( ) ? 1 : 0 , "all_layers_idr_aligned_flag" );
1331  }
1332  WRITE_FLAG( pcVPSVUI->getBitRatePresentVpsFlag( ) ? 1 : 0 , "bit_rate_present_vps_flag" );
1333  WRITE_FLAG( pcVPSVUI->getPicRatePresentVpsFlag( ) ? 1 : 0 , "pic_rate_present_vps_flag" );
1334  if( pcVPSVUI->getBitRatePresentVpsFlag( )  ||  pcVPSVUI->getPicRatePresentVpsFlag( ) )
1335  {
1336    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i < pcVPS->getNumLayerSets(); i++ )
1337    {
1338      for( Int j = 0; j  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( i ); j++ ) 
1339      {
1340        if( pcVPSVUI->getBitRatePresentVpsFlag( ) )
1341        {
1342          WRITE_FLAG( pcVPSVUI->getBitRatePresentFlag( i, j ) ? 1 : 0 , "bit_rate_present_flag" );
1343        }
1344        if( pcVPSVUI->getBitRatePresentVpsFlag( )  )
1345        {
1346          WRITE_FLAG( pcVPSVUI->getPicRatePresentFlag( i, j ) ? 1 : 0 , "pic_rate_present_flag" );
1347        }
1348        if( pcVPSVUI->getBitRatePresentFlag( i, j ) )
1349        {
1350          WRITE_CODE( pcVPSVUI->getAvgBitRate( i, j ), 16, "avg_bit_rate" );
1351          WRITE_CODE( pcVPSVUI->getMaxBitRate( i, j ), 16, "max_bit_rate" );
1352        }
1353        if( pcVPSVUI->getPicRatePresentFlag( i, j ) )
1354        {
1355          WRITE_CODE( pcVPSVUI->getConstantPicRateIdc( i, j ), 2, "constant_pic_rate_idc" );
1356          WRITE_CODE( pcVPSVUI->getAvgPicRate( i, j ), 16, "avg_pic_rate" );
1357        }
1358      }
1359    }
1360  }
1361
1362  WRITE_FLAG( pcVPSVUI->getVideoSignalInfoIdxPresentFlag( ) ? 1 : 0 , "video_signal_info_idx_present_flag" );
1363  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() )
1364  {
1365    WRITE_CODE( pcVPSVUI->getVpsNumVideoSignalInfoMinus1( ), 4, "vps_num_video_signal_info_minus1" );
1366  }
1367  else
1368  {
1369    assert( pcVPSVUI->getVpsNumVideoSignalInfoMinus1() == pcVPS->getMaxLayersMinus1() - ( pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1)  ); 
1370  }
1371
1372  for( Int i = 0; i <= pcVPSVUI->getVpsNumVideoSignalInfoMinus1(); i++ )
1373  {
1374    assert( pcVPSVUI->getVideoSignalInfo( i ) != NULL ); 
1375    const TComVideoSignalInfo* curVideoSignalInfo = pcVPSVUI->getVideoSignalInfo( i ); 
1376    codeVideoSignalInfo( curVideoSignalInfo );     
1377
1378  }
1379
1380  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() && pcVPSVUI->getVpsNumVideoSignalInfoMinus1() > 0 )
1381  {
1382    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
1383    {
1384      WRITE_CODE( pcVPSVUI->getVpsVideoSignalInfoIdx( i ), 4, "vps_video_signal_info_idx" );
1385    }
1386  }
1387  WRITE_FLAG( pcVPSVUI->getTilesNotInUseFlag( ) ? 1 : 0 , "tiles_not_in_use_flag" );
1388  if( !pcVPSVUI->getTilesNotInUseFlag() ) 
1389  {     
1390    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
1391    {
1392      WRITE_FLAG( pcVPSVUI->getTilesInUseFlag( i ) ? 1 : 0 , "tiles_in_use_flag[i]" );
1393      if( pcVPSVUI->getTilesInUseFlag( i ) ) 
1394      {
1395        WRITE_FLAG( pcVPSVUI->getLoopFilterNotAcrossTilesFlag( i ) ? 1 : 0, "loop_filter_not_across_tiles_flag[i]" );
1396      }
1397    } 
1398    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 2; i  <=  pcVPS->getMaxLayersMinus1(); i++ ) 
1399    {
1400      for( Int j = 0; j < pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) ) ; j++ )
1401      { 
1402        Int layerIdx = pcVPS->getLayerIdInVps(pcVPS->getIdRefLayer(pcVPS->getLayerIdInNuh( i ) , j  )); 
1403        if( pcVPSVUI->getTilesInUseFlag( i )  &&  pcVPSVUI->getTilesInUseFlag( layerIdx ) ) 
1404        {
1405          WRITE_FLAG( pcVPSVUI->getTileBoundariesAlignedFlag( i, j ) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
1406        }
1407      } 
1408    }
1409  } 
1410
1411  WRITE_FLAG( pcVPSVUI->getWppNotInUseFlag( ) ? 1 : 0 , "wpp_not_in_use_flag" );
1412
1413  if( !pcVPSVUI->getWppNotInUseFlag( ) )
1414  {
1415    for( Int i = 0; i  <=  pcVPS->getMaxLayersMinus1(); i++ ) 
1416    {
1417      WRITE_FLAG( pcVPSVUI->getWppInUseFlag( i ) ? 1 : 0 , "wpp_in_use_flag[i]" );
1418    }
1419  }
1420  WRITE_FLAG( pcVPSVUI->getSingleLayerForNonIrapFlag( ) ? 1 : 0 , "single_layer_for_non_irap_flag" );
1421  WRITE_FLAG( pcVPSVUI->getHigherLayerIrapSkipFlag( ) ? 1 : 0 , "higher_layer_irap_skip_flag" );
1422  WRITE_FLAG( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) ? 1 : 0 , "ilp_restricted_ref_layers_flag" );
1423
1424  if( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) )
1425  {
1426    for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
1427    {
1428      for( Int j = 0; j < pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) ); j++ )
1429      {
1430        if( pcVPS->getVpsBaseLayerInternalFlag() || pcVPS->getIdRefLayer( pcVPS->getLayerIdInNuh( i ), j ) > 0 )
1431        {       
1432          WRITE_UVLC( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ), "min_spatial_segment_offset_plus1" );
1433          if( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
1434          {
1435            WRITE_FLAG( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) ? 1 : 0 , "ctu_based_offset_enabled_flag" );
1436            if( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) )
1437            {
1438              WRITE_UVLC( pcVPSVUI->getMinHorizontalCtuOffsetPlus1( i, j ), "min_horizontal_ctu_offset_plus1" );
1439            }
1440          }
1441        }
1442      }
1443    }
1444  }
1445
1446
1447  WRITE_FLAG( pcVPSVUI->getVpsVuiBspHrdPresentFlag( ) ? 1 : 0 , "vps_vui_bsp_hrd_present_flag" );
1448  if ( pcVPSVUI->getVpsVuiBspHrdPresentFlag( ) )
1449  {
1450    codeVpsVuiBspHrdParameters( pcVPS ); 
1451  }
1452  for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
1453  {
1454    if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i )) == 0 ) 
1455    {
1456      WRITE_FLAG( pcVPSVUI->getBaseLayerParameterSetCompatibilityFlag( i ) ? 1 : 0 , "base_layer_parameter_set_compatibility_flag" );
1457    }
1458  }
1459}
1460
1461Void TEncCavlc::codeVpsVuiBspHrdParameters( const TComVPS* pcVPS )
1462{
1463  assert( pcVPS ); 
1464
1465  const TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
1466
1467  assert( pcVPSVUI ); 
1468
1469  const TComVpsVuiBspHrdParameters*  vpsVuiBspHrdP = pcVPSVUI->getVpsVuiBspHrdParameters(); 
1470
1471  assert ( vpsVuiBspHrdP );
1472 
1473  WRITE_UVLC( vpsVuiBspHrdP->getVpsNumAddHrdParams( ), "vps_num_add_hrd_params" );
1474
1475  for( Int i = pcVPS->getNumHrdParameters(); i < pcVPS->getNumHrdParameters() + vpsVuiBspHrdP->getVpsNumAddHrdParams(); i++ )
1476  { 
1477    if( i > 0 ) 
1478    {
1479      WRITE_FLAG( vpsVuiBspHrdP->getCprmsAddPresentFlag( i ) ? 1 : 0 , "cprms_add_present_flag" );
1480    }
1481    WRITE_UVLC( vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ), "num_sub_layer_hrd_minus1" );
1482    const TComHRD* hrdParameters = vpsVuiBspHrdP->getHrdParametermeters( i ); 
1483    codeHrdParameters( hrdParameters, vpsVuiBspHrdP->getCprmsAddPresentFlag( i ), vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ) );     
1484  }
1485
1486  for( Int h = 1; h < pcVPS->getNumOutputLayerSets(); h++ )
1487  { 
1488    WRITE_UVLC( vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ), "num_signalled_partitioning_schemes" );
1489
1490    for( Int j = 1; j < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; j++ )
1491    { 
1492      WRITE_UVLC( vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ), "num_partitions_in_scheme_minus1" );
1493      for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ ) 
1494      {
1495        for( Int r = 0; r < pcVPS->getNumLayersInIdList(pcVPS->olsIdxToLsIdx( h ) )   ; r++ ) 
1496        {
1497          WRITE_FLAG( vpsVuiBspHrdP->getLayerIncludedInPartitionFlag( h, j, k, r ) ? 1 : 0 , "layer_included_in_partition_flag" );
1498        }
1499      }
1500    } 
1501    for( Int i = 0; i < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; i++ ) 
1502    {
1503      for( Int t = 0; t  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( pcVPS->olsIdxToLsIdx( h ) ); t++ )
1504      { 
1505        WRITE_UVLC( vpsVuiBspHrdP->getNumBspSchedulesMinus1( h, i, t ), "num_bsp_schedules_minus1" );
1506        for( Int j = 0; j  <=  vpsVuiBspHrdP->getNumBspSchedulesMinus1( h, i, t ); j++ ) 
1507        {
1508          for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )
1509          { 
1510            WRITE_CODE( vpsVuiBspHrdP->getBspHrdIdx( h, i, t, j, k ), vpsVuiBspHrdP->getBspHrdIdxLen( pcVPS ), "bsp_hrd_idx" );
1511            WRITE_UVLC( vpsVuiBspHrdP->getBspSchedIdx( h, i, t, j, k ), "bsp_sched_idx" );
1512          } 
1513        }
1514      } 
1515    }
1516  } 
1517} 
1518#endif
1519
1520
1521
1522Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
1523{
1524#if NH_MV
1525  const TComVPS* vps = pcSlice->getVPS(); 
1526#endif
1527
1528#if ENC_DEC_TRACE
1529#if NH_MV
1530  tracePSHeader( "Slice", pcSlice->getLayerId() ); 
1531#else
1532  xTraceSliceHeader ();
1533#endif
1534#endif
1535
1536  const ChromaFormat format                = pcSlice->getSPS()->getChromaFormatIdc();
1537  const UInt         numberValidComponents = getNumberValidComponents(format);
1538  const Bool         chromaEnabled         = isChromaEnabled(format);
1539
1540  //calculate number of bits required for slice address
1541  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumberOfCtusInFrame();
1542  Int bitsSliceSegmentAddress = 0;
1543  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress))
1544  {
1545    bitsSliceSegmentAddress++;
1546  }
1547  const Int ctuTsAddress = pcSlice->getSliceSegmentCurStartCtuTsAddr();
1548
1549  //write slice address
1550  const Int sliceSegmentRsAddress = pcSlice->getPic()->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddress);
1551#if NH_MV
1552  // This should actually be done somewhere else and not in writing process.
1553  pcSlice->setFirstSliceSegementInPicFlag( sliceSegmentRsAddress==0 ); 
1554  WRITE_FLAG( pcSlice->getFirstSliceSegementInPicFlag() , "first_slice_segment_in_pic_flag" );
1555#else
1556  WRITE_FLAG( sliceSegmentRsAddress==0, "first_slice_segment_in_pic_flag" );
1557#endif
1558  if ( pcSlice->getRapPicFlag() )
1559  {
1560    WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
1561  }
1562  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
1563  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentRsAddress!=0) )
1564  {
1565    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
1566  }
1567  if(sliceSegmentRsAddress>0)
1568  {
1569    WRITE_CODE( sliceSegmentRsAddress, bitsSliceSegmentAddress, "slice_segment_address" );
1570  }
1571  if ( !pcSlice->getDependentSliceSegmentFlag() )
1572  {
1573#if NH_MV   
1574    Int esb = 0;  //Don't use i, otherwise will shadow something below
1575
1576    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
1577    {
1578      esb++; 
1579      WRITE_FLAG( pcSlice->getDiscardableFlag( ) ? 1 : 0 , "discardable_flag" );
1580      if (pcSlice->getDiscardableFlag( ))
1581      {
1582        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
1583          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
1584          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
1585          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
1586          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
1587      }
1588    }
1589
1590    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
1591    {
1592      esb++; 
1593      WRITE_FLAG( pcSlice->getCrossLayerBlaFlag( ) ? 1 : 0 , "cross_layer_bla_flag" );
1594    }
1595    pcSlice->checkCrossLayerBlaFlag( ); 
1596
1597    for (; esb < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); esb++)   
1598#else
1599    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
1600#endif
1601    {
1602      WRITE_FLAG(0, "slice_reserved_flag[]");
1603    }
1604
1605
1606
1607    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
1608
1609    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
1610    {
1611      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
1612    }
1613
1614#if NH_MV
1615    if ( (pcSlice->getLayerId() > 0 && !vps->getPocLsbNotPresentFlag( pcSlice->getLayerIdInVps())) || !pcSlice->getIdrPicFlag() )
1616    {
1617      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1618      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "slice_pic_order_cnt_lsb");
1619      pcSlice->setSlicePicOrderCntLsb( picOrderCntLSB ); 
1620    }
1621
1622#endif
1623
1624    if( !pcSlice->getIdrPicFlag() )
1625    {
1626#if !NH_MV
1627      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
1628      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "slice_pic_order_cnt_lsb");
1629#endif
1630      const TComReferencePictureSet* rps = pcSlice->getRPS();
1631
1632      // check for bitstream restriction stating that:
1633      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
1634      // Ideally this process should not be repeated for each slice in a picture
1635      if (pcSlice->isIRAP())
1636      {
1637        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
1638        {
1639          assert (!rps->getUsed(picIdx));
1640        }
1641      }
1642
1643      if(pcSlice->getRPSidx() < 0)
1644      {
1645        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
1646        codeShortTermRefPicSet( rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
1647      }
1648      else
1649      {
1650        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
1651        Int numBits = 0;
1652        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
1653        {
1654          numBits++;
1655        }
1656        if (numBits > 0)
1657        {
1658          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );
1659        }
1660      }
1661#if NH_MV
1662      if(pcSlice->getSPS()->getLongTermRefPicsPresentFlag())
1663#else
1664      if(pcSlice->getSPS()->getLongTermRefsPresent())
1665#endif
1666      {
1667        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
1668        Int ltrpInSPS[MAX_NUM_REF_PICS];
1669        Int numLtrpInSPS = 0;
1670        UInt ltrpIndex;
1671        Int counter = 0;
1672        // WARNING: The following code only works only if a matching long-term RPS is
1673        //          found in the SPS for ALL long-term pictures
1674        //          The problem is that the SPS coded long-term pictures are moved to the
1675        //          beginning of the list which causes a mismatch when no reference picture
1676        //          list reordering is used
1677        //          NB: Long-term coding is currently not supported in general by the HM encoder
1678        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--)
1679        {
1680          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k)))
1681          {
1682            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
1683            numLtrpInSPS++;
1684          }
1685          else
1686          {
1687            counter++;
1688          }
1689        }
1690        numLtrpInSH -= numLtrpInSPS;
1691        // check that either all long-term pictures are coded in SPS or in slice header (no mixing)
1692        assert (numLtrpInSH==0 || numLtrpInSPS==0); 
1693
1694        Int bitsForLtrpInSPS = 0;
1695        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
1696        {
1697          bitsForLtrpInSPS++;
1698        }
1699        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
1700        {
1701          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
1702        }
1703        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
1704        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
1705        // Not sorted here because LT ref indices will be used in setRefPicList()
1706        Int prevDeltaMSB = 0, prevLSB = 0;
1707        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
1708        counter = 0;
1709        // Warning: If some pictures are moved to ltrpInSPS, i is referring to a wrong index
1710        //          (mapping would be required)
1711        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--, counter++)
1712        {
1713          if (counter < numLtrpInSPS)
1714          {
1715            if (bitsForLtrpInSPS > 0)
1716            {
1717              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
1718            }
1719          }
1720          else
1721          {
1722            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
1723            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag");
1724          }
1725          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
1726
1727          if(rps->getDeltaPocMSBPresentFlag(i))
1728          {
1729            Bool deltaFlag = false;
1730            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
1731            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
1732            {
1733              deltaFlag = true;
1734            }
1735            if(deltaFlag)
1736            {
1737              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
1738            }
1739            else
1740            {
1741              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
1742              assert(differenceInDeltaMSB >= 0);
1743              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
1744            }
1745            prevLSB = rps->getPocLSBLT(i);
1746            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
1747          }
1748        }
1749      }
1750      if (pcSlice->getSPS()->getTMVPFlagsPresent())
1751      {
1752#if NH_MV
1753        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
1754#else
1755        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
1756#endif
1757      }
1758    }
1759#if NH_MV
1760    Bool interLayerPredLayerIdcPresentFlag = false; 
1761    Int layerId = pcSlice->getLayerId(); 
1762    if( pcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumDirectRefLayers( layerId ) > 0 )
1763    {   
1764      WRITE_FLAG( pcSlice->getInterLayerPredEnabledFlag( ) ? 1 : 0 , "inter_layer_pred_enabled_flag" );
1765      if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerId ) > 1 )
1766      {           
1767        if( !vps->getMaxOneActiveRefLayerFlag()) 
1768        {
1769          WRITE_CODE( pcSlice->getNumInterLayerRefPicsMinus1( ), pcSlice->getNumInterLayerRefPicsMinus1Len( ), "num_inter_layer_ref_pics_minus1" );
1770        }
1771        if ( pcSlice->getNumActiveRefLayerPics() != vps->getNumDirectRefLayers( layerId ) )
1772        {       
1773          interLayerPredLayerIdcPresentFlag = true; 
1774          for( Int idx = 0; idx < pcSlice->getNumActiveRefLayerPics(); idx++ )   
1775          {
1776            WRITE_CODE( pcSlice->getInterLayerPredLayerIdc( idx ), pcSlice->getInterLayerPredLayerIdcLen( ), "inter_layer_pred_layer_idc" );
1777          }
1778        }
1779      } 
1780    }
1781    if ( !interLayerPredLayerIdcPresentFlag )
1782    {
1783      for( Int i = 0; i < pcSlice->getNumActiveRefLayerPics(); i++ )   
1784      {
1785        assert( pcSlice->getInterLayerPredLayerIdc( i ) == pcSlice->getRefLayerPicIdc( i ) );
1786      }
1787    }
1788#endif
1789
1790
1791    if(pcSlice->getSPS()->getUseSAO())
1792    {
1793       WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA), "slice_sao_luma_flag" );
1794       if (chromaEnabled)
1795       {
1796         WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA), "slice_sao_chroma_flag" );
1797       }
1798    }
1799
1800    //check if numrefidxes match the defaults. If not, override
1801
1802    if (!pcSlice->isIntra())
1803    {
1804      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
1805      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
1806      if (overrideFlag)
1807      {
1808        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
1809        if (pcSlice->isInterB())
1810        {
1811          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
1812        }
1813        else
1814        {
1815          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1816        }
1817      }
1818    }
1819    else
1820    {
1821      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
1822      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
1823    }
1824    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
1825    {
1826      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1827      if(!pcSlice->isIntra())
1828      {
1829        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
1830        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
1831        {
1832          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
1833          if (numRpsCurrTempList0 > 1)
1834          {
1835            Int length = 1;
1836            numRpsCurrTempList0 --;
1837            while ( numRpsCurrTempList0 >>= 1)
1838            {
1839              length ++;
1840            }
1841            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
1842            {
1843              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
1844            }
1845          }
1846        }
1847      }
1848      if(pcSlice->isInterB())
1849      {
1850        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
1851        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
1852        {
1853          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
1854          if ( numRpsCurrTempList1 > 1 )
1855          {
1856            Int length = 1;
1857            numRpsCurrTempList1 --;
1858            while ( numRpsCurrTempList1 >>= 1)
1859            {
1860              length ++;
1861            }
1862            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
1863            {
1864              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
1865            }
1866          }
1867        }
1868      }
1869    }
1870
1871    if (pcSlice->isInterB())
1872    {
1873      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
1874    }
1875
1876    if(!pcSlice->isIntra())
1877    {
1878      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1879      {
1880        SliceType sliceType   = pcSlice->getSliceType();
1881        SliceType  encCABACTableIdx = pcSlice->getEncCABACTableIdx();
1882        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1883        pcSlice->setCabacInitFlag( encCabacInitFlag );
1884        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1885      }
1886    }
1887
1888    if ( pcSlice->getEnableTMVPFlag() )
1889    {
1890      if ( pcSlice->getSliceType() == B_SLICE )
1891      {
1892        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1893      }
1894
1895      if ( pcSlice->getSliceType() != I_SLICE &&
1896        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1897        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1898      {
1899        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1900      }
1901    }
1902    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1903    {
1904      xCodePredWeightTable( pcSlice );
1905    }
1906    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1907    if (!pcSlice->isIntra())
1908    {
1909      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1910    }
1911    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1912    WRITE_SVLC( iCode, "slice_qp_delta" );
1913    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1914    {
1915      if (numberValidComponents > COMPONENT_Cb)
1916      {
1917        WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb), "slice_cb_qp_offset" );
1918      }
1919      if (numberValidComponents > COMPONENT_Cr)
1920      {
1921        WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr), "slice_cr_qp_offset" );
1922      }
1923      assert(numberValidComponents <= COMPONENT_Cr+1);
1924    }
1925
1926    if (pcSlice->getPPS()->getPpsRangeExtension().getChromaQpOffsetListEnabledFlag())
1927    {
1928      WRITE_FLAG(pcSlice->getUseChromaQpAdj(), "cu_chroma_qp_offset_enabled_flag");
1929    }
1930
1931    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1932    {
1933      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1934      {
1935        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1936      }
1937      if (pcSlice->getDeblockingFilterOverrideFlag())
1938      {
1939        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1940        if(!pcSlice->getDeblockingFilterDisable())
1941        {
1942          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
1943          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
1944        }
1945      }
1946    }
1947
1948    Bool isSAOEnabled = pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (chromaEnabled && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
1949    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1950
1951      if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1952    {
1953      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1954    }
1955
1956  }
1957#if !NH_MV
1958  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1959  {
1960    WRITE_UVLC(0,"slice_segment_header_extension_length");
1961  }
1962#else
1963  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1964  {
1965    // Derive the value of PocMsbValRequiredFlag
1966
1967    // Determine value of SH extension length.
1968    Int shExtnLengthInBit = 0;
1969    if (pcSlice->getPPS()->getPocResetInfoPresentFlag())
1970    {
1971      shExtnLengthInBit += 2;
1972    }
1973    if (pcSlice->getPocResetIdc() > 0)
1974    {
1975      shExtnLengthInBit += 6;
1976    }
1977    if (pcSlice->getPocResetIdc() == 3)
1978    {
1979      shExtnLengthInBit += (pcSlice->getSPS()->getBitsForPOC() + 1);
1980    }
1981
1982
1983    if( !pcSlice->getPocMsbValRequiredFlag() &&  pcSlice->getVPS()->getVpsPocLsbAlignedFlag() )
1984    {
1985      shExtnLengthInBit++;    // For poc_msb_val_present_flag
1986    }
1987    else
1988    {
1989      if( pcSlice->getPocMsbValRequiredFlag() )
1990      {
1991        pcSlice->setPocMsbCycleValPresentFlag( true );
1992      }
1993      else
1994      {
1995        pcSlice->setPocMsbCycleValPresentFlag( false );
1996      }
1997    }
1998
1999    if( pcSlice->getPocMsbCycleValPresentFlag() )
2000    {
2001//      Int iMaxPOClsb = 1<< pcSlice->getSPS()->getBitsForPOC(); currently unused
2002
2003      UInt lengthVal = 1;
2004      UInt tempVal = pcSlice->getPocMsbCycleVal() + 1;
2005      assert ( tempVal );
2006      while( 1 != tempVal )
2007      {
2008        tempVal >>= 1;
2009        lengthVal += 2;
2010      }
2011      shExtnLengthInBit += lengthVal;
2012    }
2013    Int shExtnAdditionalBits = 0;
2014    if(shExtnLengthInBit % 8 != 0)
2015    {
2016      shExtnAdditionalBits = 8 - (shExtnLengthInBit % 8);
2017    }
2018    pcSlice->setSliceSegmentHeaderExtensionLength((shExtnLengthInBit + shExtnAdditionalBits) / 8);
2019     
2020
2021    WRITE_UVLC( pcSlice->getSliceSegmentHeaderExtensionLength( ), "slice_segment_header_extension_length" );
2022    UInt posFollSliceSegHeaderExtLen = m_pcBitIf->getNumberOfWrittenBits();
2023    if( pcSlice->getPPS()->getPocResetInfoPresentFlag() )
2024    {
2025      WRITE_CODE( pcSlice->getPocResetIdc( ), 2, "poc_reset_idc" );
2026    }
2027    else
2028    {
2029      assert( pcSlice->getPocResetIdc( ) == 0 );
2030    }
2031
2032    pcSlice->checkPocResetIdc(); 
2033
2034    if( pcSlice->getPocResetIdc() !=  0 )
2035    {
2036      WRITE_CODE( pcSlice->getPocResetPeriodId( ), 6, "poc_reset_period_id" );
2037    }
2038   
2039    if( pcSlice->getPocResetIdc() ==  3 ) 
2040    {
2041      WRITE_FLAG( pcSlice->getFullPocResetFlag( ) ? 1 : 0 , "full_poc_reset_flag" );
2042      WRITE_CODE( pcSlice->getPocLsbVal( ), pcSlice->getPocLsbValLen() , "poc_lsb_val" );
2043    }             
2044    pcSlice->checkPocLsbVal(); 
2045
2046    if( !pcSlice->getPocMsbValRequiredFlag() &&  pcSlice->getVPS()->getVpsPocLsbAlignedFlag()  )
2047    {
2048      WRITE_FLAG( pcSlice->getPocMsbCycleValPresentFlag( ) ? 1 : 0 , "poc_msb_cycle_val_present_flag" );
2049    }
2050    else
2051    {
2052      assert( pcSlice->getPocMsbCycleValPresentFlag() ==  pcSlice->inferPocMsbCycleValPresentFlag( ) ); 
2053    }
2054   
2055    if( pcSlice->getPocMsbCycleValPresentFlag() )
2056    {
2057      WRITE_UVLC( pcSlice->getPocMsbCycleVal( ), "poc_msb_cycle_val" );
2058    }
2059   
2060    while( ( m_pcBitIf->getNumberOfWrittenBits() - posFollSliceSegHeaderExtLen ) < pcSlice->getSliceSegmentHeaderExtensionLength() * 8 )
2061    {
2062      WRITE_FLAG( 0, "slice_segment_header_extension_data_bit" );
2063    }
2064
2065    assert( ( m_pcBitIf->getNumberOfWrittenBits() - posFollSliceSegHeaderExtLen ) == pcSlice->getSliceSegmentHeaderExtensionLength() * 8  ); 
2066  }
2067#endif
2068
2069}
2070
2071Void TEncCavlc::codePTL( const TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
2072{
2073  if(profilePresentFlag)
2074  {
2075    codeProfileTier(pcPTL->getGeneralPTL(), false);    // general_...
2076  }
2077  WRITE_CODE( Int(pcPTL->getGeneralPTL()->getLevelIdc()), 8, "general_level_idc" );
2078
2079  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
2080  {
2081    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
2082    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
2083  }
2084
2085  if (maxNumSubLayersMinus1 > 0)
2086  {
2087    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
2088    {
2089      WRITE_CODE(0, 2, "reserved_zero_2bits");
2090    }
2091  }
2092
2093  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
2094  {
2095    if( pcPTL->getSubLayerProfilePresentFlag(i) )
2096    {
2097      codeProfileTier(pcPTL->getSubLayerPTL(i), true);  // sub_layer_...
2098    }
2099    if( pcPTL->getSubLayerLevelPresentFlag(i) )
2100    {
2101      WRITE_CODE( Int(pcPTL->getSubLayerPTL(i)->getLevelIdc()), 8, "sub_layer_level_idc[i]" );
2102    }
2103  }
2104}
2105
2106#if ENC_DEC_TRACE || RExt__DECODER_DEBUG_BIT_STATISTICS
2107Void TEncCavlc::codeProfileTier( const ProfileTierLevel* ptl, const Bool bIsSubLayer )
2108#define PTL_TRACE_TEXT(txt) bIsSubLayer?("sub_layer_" txt) : ("general_" txt)
2109#else
2110Void TEncCavlc::codeProfileTier( const ProfileTierLevel* ptl, const Bool /*bIsSubLayer*/ )
2111#define PTL_TRACE_TEXT(txt) txt
2112#endif
2113{
2114  WRITE_CODE( ptl->getProfileSpace(), 2 ,      PTL_TRACE_TEXT("profile_space"                   ));
2115  WRITE_FLAG( ptl->getTierFlag()==Level::HIGH, PTL_TRACE_TEXT("tier_flag"                       ));
2116  WRITE_CODE( Int(ptl->getProfileIdc()), 5 ,   PTL_TRACE_TEXT("profile_idc"                     ));
2117  for(Int j = 0; j < 32; j++)
2118  {
2119    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), PTL_TRACE_TEXT("profile_compatibility_flag[][j]" ));
2120  }
2121
2122  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   PTL_TRACE_TEXT("progressive_source_flag"         ));
2123  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    PTL_TRACE_TEXT("interlaced_source_flag"          ));
2124  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), PTL_TRACE_TEXT("non_packed_constraint_flag"      ));
2125  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), PTL_TRACE_TEXT("frame_only_constraint_flag"      ));
2126
2127#if NH_MV
2128  if( ptl->getV2ConstraintsPresentFlag() ) 
2129  {
2130    WRITE_FLAG( ptl->getMax12bitConstraintFlag( ) ? 1 : 0 , "max_12bit_constraint_flag" );
2131    WRITE_FLAG( ptl->getMax10bitConstraintFlag( ) ? 1 : 0 , "max_10bit_constraint_flag" );
2132    WRITE_FLAG( ptl->getMax8bitConstraintFlag( ) ? 1 : 0 , "max_8bit_constraint_flag" );
2133    WRITE_FLAG( ptl->getMax422chromaConstraintFlag( ) ? 1 : 0 , "max_422chroma_constraint_flag" );
2134    WRITE_FLAG( ptl->getMax420chromaConstraintFlag( ) ? 1 : 0 , "max_420chroma_constraint_flag" );
2135    WRITE_FLAG( ptl->getMaxMonochromeConstraintFlag( ) ? 1 : 0 , "max_monochrome_constraint_flag" );
2136    WRITE_FLAG( ptl->getIntraConstraintFlag( ) ? 1 : 0 , "intra_constraint_flag" );
2137    WRITE_FLAG( ptl->getOnePictureOnlyConstraintFlag( ) ? 1 : 0 , "one_picture_only_constraint_flag" );
2138    WRITE_FLAG( ptl->getLowerBitRateConstraintFlag( ) ? 1 : 0 , "lower_bit_rate_constraint_flag" );
2139    WRITE_CODE( 0, 16, "XXX_reserved_zero_34bits[0..15]");
2140    WRITE_CODE( 0, 16, "XXX_reserved_zero_34bits[16..31]");
2141    WRITE_CODE( 0, 2 , "XXX_reserved_zero_34bits[32..33]");
2142  }
2143  else
2144  {
2145    WRITE_CODE( 0, 16, "XXX_reserved_zero_43bits[0..15]");
2146    WRITE_CODE( 0, 16, "XXX_reserved_zero_43bits[16..31]");
2147    WRITE_CODE( 0, 11, "XXX_reserved_zero_43bits[32..42]");
2148  }
2149    if( ptl->getInbldPresentFlag() )
2150  {
2151    WRITE_FLAG( ptl->getInbldFlag( ) ? 1 : 0 , "inbld_flag" );
2152  }
2153  else
2154  {
2155    WRITE_FLAG(0, "reserved_zero_bit");
2156  }
2157#else
2158  if (ptl->getProfileIdc() == Profile::MAINREXT || ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT )
2159  {
2160    const UInt         bitDepthConstraint=ptl->getBitDepthConstraint();
2161    WRITE_FLAG(bitDepthConstraint<=12,          PTL_TRACE_TEXT("max_12bit_constraint_flag"       ));
2162    WRITE_FLAG(bitDepthConstraint<=10,          PTL_TRACE_TEXT("max_10bit_constraint_flag"       ));
2163    WRITE_FLAG(bitDepthConstraint<= 8,          PTL_TRACE_TEXT("max_8bit_constraint_flag"        ));
2164    const ChromaFormat chromaFmtConstraint=ptl->getChromaFormatConstraint();
2165    WRITE_FLAG(chromaFmtConstraint==CHROMA_422||chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400, PTL_TRACE_TEXT("max_422chroma_constraint_flag" ));
2166    WRITE_FLAG(chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400,                                  PTL_TRACE_TEXT("max_420chroma_constraint_flag" ));
2167    WRITE_FLAG(chromaFmtConstraint==CHROMA_400,                                                                   PTL_TRACE_TEXT("max_monochrome_constraint_flag"));
2168    WRITE_FLAG(ptl->getIntraConstraintFlag(),        PTL_TRACE_TEXT("intra_constraint_flag"           ));
2169    WRITE_FLAG(ptl->getOnePictureOnlyConstraintFlag(), PTL_TRACE_TEXT("one_picture_only_constraint_flag"));
2170    WRITE_FLAG(ptl->getLowerBitRateConstraintFlag(), PTL_TRACE_TEXT("lower_bit_rate_constraint_flag"  ));
2171    WRITE_CODE(0 , 16, PTL_TRACE_TEXT("reserved_zero_34bits[0..15]"     ));
2172    WRITE_CODE(0 , 16, PTL_TRACE_TEXT("reserved_zero_34bits[16..31]"    ));
2173    WRITE_CODE(0 ,  2, PTL_TRACE_TEXT("reserved_zero_34bits[32..33]"    ));
2174  }
2175  else
2176  {
2177    WRITE_CODE(0x0000 , 16, PTL_TRACE_TEXT("reserved_zero_43bits[0..15]"     ));
2178    WRITE_CODE(0x0000 , 16, PTL_TRACE_TEXT("reserved_zero_43bits[16..31]"    ));
2179    WRITE_CODE(0x000  , 11, PTL_TRACE_TEXT("reserved_zero_43bits[32..42]"    ));
2180  }
2181  WRITE_FLAG(false,   PTL_TRACE_TEXT("inbld_flag" ));
2182#undef PTL_TRACE_TEXT
2183#endif
2184}
2185
2186/**
2187 * Write tiles and wavefront substreams sizes for the slice header (entry points).
2188 *
2189 * \param pSlice TComSlice structure that contains the substream size information.
2190 */
2191Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
2192{
2193  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
2194  {
2195    return;
2196  }
2197  UInt maxOffset = 0;
2198  for(Int idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
2199  {
2200    UInt offset=pSlice->getSubstreamSize(idx);
2201    if ( offset > maxOffset )
2202    {
2203      maxOffset = offset;
2204    }
2205  }
2206
2207  // Determine number of bits "offsetLenMinus1+1" required for entry point information
2208  UInt offsetLenMinus1 = 0;
2209  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
2210  {
2211    offsetLenMinus1++;
2212    assert(offsetLenMinus1 + 1 < 32);
2213  }
2214
2215  WRITE_UVLC(pSlice->getNumberOfSubstreamSizes(), "num_entry_point_offsets");
2216  if (pSlice->getNumberOfSubstreamSizes()>0)
2217  {
2218    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
2219
2220    for (UInt idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
2221    {
2222      WRITE_CODE(pSlice->getSubstreamSize(idx)-1, offsetLenMinus1+1, "entry_point_offset_minus1");
2223    }
2224  }
2225}
2226
2227Void TEncCavlc::codeTerminatingBit      ( UInt /*uilsLast*/ )
2228{
2229}
2230
2231Void TEncCavlc::codeSliceFinish ()
2232{
2233}
2234
2235Void TEncCavlc::codeMVPIdx ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, RefPicList /*eRefList*/ )
2236{
2237  assert(0);
2238}
2239
2240Void TEncCavlc::codePartSize( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
2241{
2242  assert(0);
2243}
2244
2245Void TEncCavlc::codePredMode( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2246{
2247  assert(0);
2248}
2249
2250Void TEncCavlc::codeMergeFlag    ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2251{
2252  assert(0);
2253}
2254
2255Void TEncCavlc::codeMergeIndex    ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2256{
2257  assert(0);
2258}
2259
2260
2261
2262Void TEncCavlc::codeInterModeFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/, UInt /*uiEncMode*/ )
2263{
2264  assert(0);
2265}
2266
2267Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2268{
2269  assert(0);
2270}
2271
2272Void TEncCavlc::codeSkipFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2273{
2274  assert(0);
2275}
2276
2277Void TEncCavlc::codeSplitFlag   ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
2278{
2279  assert(0);
2280}
2281
2282Void TEncCavlc::codeTransformSubdivFlag( UInt /*uiSymbol*/, UInt /*uiCtx*/ )
2283{
2284  assert(0);
2285}
2286
2287Void TEncCavlc::codeQtCbf( TComTU& /*rTu*/, const ComponentID /*compID*/, const Bool /*lowestLevel*/ )
2288{
2289  assert(0);
2290}
2291
2292Void TEncCavlc::codeQtRootCbf( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2293{
2294  assert(0);
2295}
2296
2297Void TEncCavlc::codeQtCbfZero( TComTU& /*rTu*/, const ChannelType /*chType*/ )
2298{
2299  assert(0);
2300}
2301Void TEncCavlc::codeQtRootCbfZero( )
2302{
2303  assert(0);
2304}
2305
2306Void TEncCavlc::codeTransformSkipFlags (TComTU& /*rTu*/, ComponentID /*component*/ )
2307{
2308  assert(0);
2309}
2310
2311/** Code I_PCM information.
2312 * \param pcCU pointer to CU
2313 * \param uiAbsPartIdx CU index
2314 * \returns Void
2315 */
2316Void TEncCavlc::codeIPCMInfo( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2317{
2318  assert(0);
2319}
2320
2321Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, Bool /*isMultiple*/)
2322{
2323  assert(0);
2324}
2325
2326Void TEncCavlc::codeIntraDirChroma( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2327{
2328  assert(0);
2329}
2330
2331Void TEncCavlc::codeInterDir( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2332{
2333  assert(0);
2334}
2335
2336Void TEncCavlc::codeRefFrmIdx( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, RefPicList /*eRefList*/ )
2337{
2338  assert(0);
2339}
2340
2341Void TEncCavlc::codeMvd( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, RefPicList /*eRefList*/ )
2342{
2343  assert(0);
2344}
2345
2346Void TEncCavlc::codeCrossComponentPrediction( TComTU& /*rTu*/, ComponentID /*compID*/ )
2347{
2348  assert(0);
2349}
2350
2351Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
2352{
2353  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
2354
2355  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
2356  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
2357
2358  xWriteSvlc( iDQp );
2359
2360  return;
2361}
2362
2363Void TEncCavlc::codeChromaQpAdjustment( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/ )
2364{
2365  assert(0);
2366}
2367
2368Void TEncCavlc::codeCoeffNxN    ( TComTU& /*rTu*/, TCoeff* /*pcCoef*/, const ComponentID /*compID*/ )
2369{
2370  assert(0);
2371}
2372
2373Void TEncCavlc::estBit( estBitsSbacStruct* /*pcEstBitsCabac*/, Int /*width*/, Int /*height*/, ChannelType /*chType*/ )
2374{
2375  // printf("error : no VLC mode support in this version\n");
2376  return;
2377}
2378
2379// ====================================================================================================================
2380// Protected member functions
2381// ====================================================================================================================
2382
2383//! Code weighted prediction tables
2384Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
2385{
2386  WPScalingParam  *wp;
2387  const ChromaFormat    format                = pcSlice->getPic()->getChromaFormat();
2388  const UInt            numberValidComponents = getNumberValidComponents(format);
2389  const Bool            bChroma               = isChromaEnabled(format);
2390  const Int             iNbRef                = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
2391        Bool            bDenomCoded           = false;
2392        UInt            uiTotalSignalledWeightFlags = 0;
2393
2394  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
2395  {
2396    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) // loop over l0 and l1 syntax elements
2397    {
2398      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
2399
2400      // NOTE: wp[].uiLog2WeightDenom and wp[].bPresentFlag are actually per-channel-type settings.
2401
2402      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
2403      {
2404        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2405        if ( !bDenomCoded )
2406        {
2407          Int iDeltaDenom;
2408          WRITE_UVLC( wp[COMPONENT_Y].uiLog2WeightDenom, "luma_log2_weight_denom" );
2409
2410          if( bChroma )
2411          {
2412            assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom); // check the channel-type settings are consistent across components.
2413            iDeltaDenom = (wp[COMPONENT_Cb].uiLog2WeightDenom - wp[COMPONENT_Y].uiLog2WeightDenom);
2414            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );
2415          }
2416          bDenomCoded = true;
2417        }
2418        WRITE_FLAG( wp[COMPONENT_Y].bPresentFlag, iNumRef==0?"luma_weight_l0_flag[i]":"luma_weight_l1_flag[i]" );
2419        uiTotalSignalledWeightFlags += wp[COMPONENT_Y].bPresentFlag;
2420      }
2421      if (bChroma)
2422      {
2423        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
2424        {
2425          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2426          assert(wp[COMPONENT_Cb].bPresentFlag == wp[COMPONENT_Cr].bPresentFlag); // check the channel-type settings are consistent across components.
2427          WRITE_FLAG( wp[COMPONENT_Cb].bPresentFlag, iNumRef==0?"chroma_weight_l0_flag[i]":"chroma_weight_l1_flag[i]" );
2428          uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
2429        }
2430      }
2431
2432      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
2433      {
2434        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
2435        if ( wp[COMPONENT_Y].bPresentFlag )
2436        {
2437          Int iDeltaWeight = (wp[COMPONENT_Y].iWeight - (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
2438          WRITE_SVLC( iDeltaWeight, iNumRef==0?"delta_luma_weight_l0[i]":"delta_luma_weight_l1[i]" );
2439          WRITE_SVLC( wp[COMPONENT_Y].iOffset, iNumRef==0?"luma_offset_l0[i]":"luma_offset_l1[i]" );
2440        }
2441
2442        if ( bChroma )
2443        {
2444          if ( wp[COMPONENT_Cb].bPresentFlag )
2445          {
2446            for ( Int j = COMPONENT_Cb ; j < numberValidComponents ; j++ )
2447            {
2448              assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom);
2449              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[COMPONENT_Cb].uiLog2WeightDenom));
2450              WRITE_SVLC( iDeltaWeight, iNumRef==0?"delta_chroma_weight_l0[i]":"delta_chroma_weight_l1[i]" );
2451
2452              Int range=pcSlice->getSPS()->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag() ? (1<<pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_CHROMA))/2 : 128;
2453              Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
2454              Int iDeltaChroma = (wp[j].iOffset - pred);
2455              WRITE_SVLC( iDeltaChroma, iNumRef==0?"delta_chroma_offset_l0[i]":"delta_chroma_offset_l1[i]" );
2456            }
2457          }
2458        }
2459      }
2460    }
2461    assert(uiTotalSignalledWeightFlags<=24);
2462  }
2463}
2464
2465/** code quantization matrix
2466 *  \param scalingList quantization matrix information
2467 */
2468Void TEncCavlc::codeScalingList( const TComScalingList &scalingList )
2469{
2470  //for each size
2471  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2472  {
2473    const Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
2474
2475    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
2476    {
2477      Bool scalingListPredModeFlag = scalingList.getScalingListPredModeFlag(sizeId, listId);
2478      WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
2479      if(!scalingListPredModeFlag)// Copy Mode
2480      {
2481        if (sizeId == SCALING_LIST_32x32)
2482        {
2483          // adjust the code, to cope with the missing chroma entries
2484          WRITE_UVLC( ((Int)listId - (Int)scalingList.getRefMatrixId (sizeId,listId)) / (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES), "scaling_list_pred_matrix_id_delta");
2485        }
2486        else
2487        {
2488          WRITE_UVLC( (Int)listId - (Int)scalingList.getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
2489        }
2490      }
2491      else// DPCM Mode
2492      {
2493        xCodeScalingList(&scalingList, sizeId, listId);
2494      }
2495    }
2496  }
2497  return;
2498}
2499/** code DPCM
2500 * \param scalingList quantization matrix information
2501 * \param sizeId      size index
2502 * \param listId      list index
2503 */
2504Void TEncCavlc::xCodeScalingList(const TComScalingList* scalingList, UInt sizeId, UInt listId)
2505{
2506  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
2507  UInt* scan  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
2508  Int nextCoef = SCALING_LIST_START_VALUE;
2509  Int data;
2510  const Int *src = scalingList->getScalingListAddress(sizeId, listId);
2511    if( sizeId > SCALING_LIST_8x8 )
2512    {
2513      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
2514      nextCoef = scalingList->getScalingListDC(sizeId,listId);
2515    }
2516    for(Int i=0;i<coefNum;i++)
2517    {
2518      data = src[scan[i]] - nextCoef;
2519      nextCoef = src[scan[i]];
2520      if(data > 127)
2521      {
2522        data = data - 256;
2523      }
2524      if(data < -128)
2525      {
2526        data = data + 256;
2527      }
2528
2529      WRITE_SVLC( data,  "scaling_list_delta_coef");
2530    }
2531}
2532Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
2533{
2534  // Bool state = true, state2 = false;
2535  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
2536  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
2537  {
2538    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
2539    {
2540      *ltrpsIndex = k;
2541      return true;
2542    }
2543  }
2544  return false;
2545}
2546
2547Void TEncCavlc::codeExplicitRdpcmMode( TComTU& /*rTu*/, const ComponentID /*compID*/ )
2548 {
2549   assert(0);
2550 }
2551   
2552
2553
2554//! \}
Note: See TracBrowser for help on using the repository browser.