source: 3DVCSoftware/branches/HTM-16.0-dev1/source/Lib/TLibEncoder/TEncCavlc.cpp @ 1392

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