source: 3DVCSoftware/branches/HTM-15.0-dev0/source/Lib/TLibEncoder/TEncCavlc.cpp @ 1317

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

Clean-ups. HLS.

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