source: 3DVCSoftware/trunk/source/Lib/TLibEncoder/TEncCavlc.cpp @ 1313

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

Merged 14.1-update-dev1@1312.

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