source: SHVCSoftware/branches/SHM-1.1-dev/source/Lib/TLibEncoder/TEncCavlc.cpp @ 1183

Last change on this file since 1183 was 33, checked in by seregin, 12 years ago

Reintegrate SHM-1.0-dev

File size: 63.8 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-2012, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncCavlc.cpp
35    \brief    CAVLC encoder class
36*/
37
38#include "../TLibCommon/CommonDef.h"
39#include "TEncCavlc.h"
40#include "SEIwrite.h"
41
42//! \ingroup TLibEncoder
43//! \{
44
45#if ENC_DEC_TRACE
46
47Void  xTraceSPSHeader (TComSPS *pSPS)
48{
49  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
50}
51
52Void  xTracePPSHeader (TComPPS *pPPS)
53{
54  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
55}
56
57#if !REMOVE_APS
58Void  xTraceAPSHeader (TComAPS *pAPS)
59{
60  fprintf( g_hTrace, "=========== Adaptation Parameter Set ===========\n");
61}
62#endif
63
64Void  xTraceSliceHeader (TComSlice *pSlice)
65{
66  fprintf( g_hTrace, "=========== Slice ===========\n");
67}
68
69#endif
70
71
72
73// ====================================================================================================================
74// Constructor / destructor / create / destroy
75// ====================================================================================================================
76
77TEncCavlc::TEncCavlc()
78{
79  m_pcBitIf           = NULL;
80  m_uiCoeffCost       = 0;
81#if !REMOVE_FGS
82  m_iSliceGranularity = 0;
83#endif
84}
85
86TEncCavlc::~TEncCavlc()
87{
88}
89
90
91// ====================================================================================================================
92// Public member functions
93// ====================================================================================================================
94
95Void TEncCavlc::resetEntropy()
96{
97}
98
99
100#if !REMOVE_APS
101Void  TEncCavlc::codeAPSInitInfo(TComAPS* pcAPS)
102{
103
104#if ENC_DEC_TRACE 
105  xTraceAPSHeader(pcAPS);
106#endif
107  //APS ID
108  WRITE_UVLC( pcAPS->getAPSID(), "aps_id" );
109}
110#endif
111
112Void TEncCavlc::codeDFFlag(UInt uiCode, const Char *pSymbolName)
113{
114  WRITE_FLAG(uiCode, pSymbolName);
115}
116Void TEncCavlc::codeDFSvlc(Int iCode, const Char *pSymbolName)
117{
118  WRITE_SVLC(iCode, pSymbolName);
119}
120
121#if J0234_INTER_RPS_SIMPL
122Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps, Bool calledFromSliceHeader)
123#else
124Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps )
125#endif
126{
127#if PRINT_RPS_INFO
128  int lastBits = getNumberOfWrittenBits();
129#endif
130  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
131  if (rps->getInterRPSPrediction()) 
132  {
133    Int deltaRPS = rps->getDeltaRPS();
134#if J0234_INTER_RPS_SIMPL
135    if(calledFromSliceHeader)
136    {
137      WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
138    }
139#else
140    WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
141#endif
142
143    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
144    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
145
146    for(Int j=0; j < rps->getNumRefIdc(); j++)
147    {
148      Int refIdc = rps->getRefIdc(j);
149      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
150      if (refIdc != 1) 
151      {
152        WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
153      }
154    }
155  }
156  else
157  {
158    WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
159    WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
160    Int prev = 0;
161    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
162    {
163      WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
164      prev = rps->getDeltaPOC(j);
165      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag"); 
166    }
167    prev = 0;
168    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
169    {
170      WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
171      prev = rps->getDeltaPOC(j);
172      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" ); 
173    }
174  }
175
176#if PRINT_RPS_INFO
177  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
178  rps->printDeltaPOC();
179#endif
180}
181
182
183Void TEncCavlc::codePPS( TComPPS* pcPPS )
184{
185#if ENC_DEC_TRACE 
186  xTracePPSHeader (pcPPS);
187#endif
188 
189  WRITE_UVLC( pcPPS->getPPSId(),                             "pic_parameter_set_id" );
190  WRITE_UVLC( pcPPS->getSPSId(),                             "seq_parameter_set_id" );
191
192  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
193  WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
194  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
195  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
196
197  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "pic_init_qp_minus26");
198  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
199#if PPS_TS_FLAG
200  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" ); 
201#endif
202#if !REMOVE_FGS
203  WRITE_CODE( pcPPS->getSliceGranularity(), 2,               "slice_granularity");
204#endif
205#if CU_DQP_ENABLE_FLAG
206  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
207  if ( pcPPS->getUseDQP() )
208  {
209#if REMOVE_FGS
210    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
211#else
212    WRITE_UVLC( pcPPS->getMaxCuDQPDepth() - pcPPS->getSliceGranularity(), "diff_cu_qp_delta_depth" );
213#endif
214  }
215#else
216#if REMOVE_FGS
217  WRITE_UVLC( pcPPS->getMaxCuDQPDepth() + pcPPS->getUseDQP(),                   "diff_cu_qp_delta_depth" );
218#else
219  WRITE_UVLC( pcPPS->getMaxCuDQPDepth() - pcPPS->getSliceGranularity() + pcPPS->getUseDQP(),                   "diff_cu_qp_delta_depth" );
220#endif
221#endif
222  WRITE_SVLC( pcPPS->getChromaCbQpOffset(),                   "cb_qp_offset" );
223  WRITE_SVLC( pcPPS->getChromaCrQpOffset(),                   "cr_qp_offset" );
224#if CHROMA_QP_EXTENSION
225  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "slicelevel_chroma_qp_flag" );
226#endif
227
228  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
229  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
230  WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,  "output_flag_present_flag" );
231#if !TILES_WPP_ENTROPYSLICES_FLAGS
232#if DEPENDENT_SLICES
233  WRITE_FLAG( pcPPS->getDependentSliceEnabledFlag() ? 1 : 0, "dependent_slices_enabled_flag" );
234#endif
235#endif
236  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
237
238#if TILES_WPP_ENTROPYSLICES_FLAGS
239#if DEPENDENT_SLICES
240  WRITE_FLAG( pcPPS->getDependentSliceEnabledFlag()    ? 1 : 0, "dependent_slice_enabled_flag" );
241#endif
242  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
243  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
244  WRITE_FLAG( pcPPS->getEntropySliceEnabledFlag()      ? 1 : 0, "entropy_slice_enabled_flag" );
245  if( pcPPS->getTilesEnabledFlag() )
246#else
247  Int tilesOrEntropyCodingSyncIdc = 0;
248  if ( pcPPS->getNumColumnsMinus1() > 0 || pcPPS->getNumRowsMinus1() > 0)
249  {
250    tilesOrEntropyCodingSyncIdc = 1;
251  }
252  else if ( pcPPS->getNumSubstreams() > 1 )
253  {
254    tilesOrEntropyCodingSyncIdc = 2;
255  }
256#if DEPENDENT_SLICES
257  else if( pcPPS->getDependentSliceEnabledFlag() )
258  {
259    if(pcPPS->getTilesOrEntropyCodingSyncIdc() != 2)
260    {
261      tilesOrEntropyCodingSyncIdc = 3;
262    }
263    else
264    {
265      tilesOrEntropyCodingSyncIdc = 2;
266    }
267  }
268#endif
269  pcPPS->setTilesOrEntropyCodingSyncIdc( tilesOrEntropyCodingSyncIdc );
270  WRITE_CODE(tilesOrEntropyCodingSyncIdc, 2, "tiles_or_entropy_coding_sync_idc");
271
272  if(pcPPS->getTilesOrEntropyCodingSyncIdc()==1)
273#endif
274  {
275    WRITE_UVLC( pcPPS->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
276    WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
277    WRITE_FLAG( pcPPS->getUniformSpacingFlag(),                                  "uniform_spacing_flag" );
278    if( pcPPS->getUniformSpacingFlag() == 0 )
279    {
280      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
281      {
282        WRITE_UVLC( pcPPS->getColumnWidth(i)-1,                                  "column_width_minus1" );
283      }
284      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
285      {
286        WRITE_UVLC( pcPPS->getRowHeight(i)-1,                                    "row_height_minus1" );
287      }
288    }
289    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=0)
290    {
291      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
292    }
293  }
294#if !TILES_WPP_ENTROPYSLICES_FLAGS
295#if DEPENDENT_SLICES
296  else if( pcPPS->getTilesOrEntropyCodingSyncIdc()==3 )
297  {
298    WRITE_FLAG( pcPPS->getCabacIndependentFlag()? 1 : 0,            "cabac_independent_flag" );
299  }
300#endif
301#endif
302#if MOVE_LOOP_FILTER_SLICES_FLAG
303  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
304#endif
305  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
306  if(pcPPS->getDeblockingFilterControlPresentFlag())
307  {
308    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" ); 
309    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag(),               "pic_disable_deblocking_filter_flag" );
310    if(!pcPPS->getPicDisableDeblockingFilterFlag())
311    {
312      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
313      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
314    }
315  }
316  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
317  if( pcPPS->getScalingListPresentFlag() )
318  {
319#if SCALING_LIST_OUTPUT_RESULT
320    printf("PPS\n");
321#endif
322    codeScalingList( m_pcSlice->getScalingList() );
323  }
324  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
325#if SLICE_HEADER_EXTENSION
326  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag(), "slice_header_extension_present_flag");
327#endif
328  WRITE_FLAG( 0, "pps_extension_flag" );
329}
330
331#if SUPPORT_FOR_VUI
332Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
333{
334#if ENC_DEC_TRACE
335  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
336#endif
337  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
338  if (pcVUI->getAspectRatioInfoPresentFlag())
339  {
340    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
341    if (pcVUI->getAspectRatioIdc() == 255)
342    {
343      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
344      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
345    }
346  }
347  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
348  if (pcVUI->getOverscanInfoPresentFlag())
349  {
350    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
351  }
352  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
353  if (pcVUI->getVideoSignalTypePresentFlag())
354  {
355    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
356    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
357    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
358    if (pcVUI->getColourDescriptionPresentFlag())
359    {
360      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
361      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
362      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
363    }
364  }
365
366  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
367  if (pcVUI->getChromaLocInfoPresentFlag())
368  {
369    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
370    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
371  }
372
373  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
374  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
375  assert(pcVUI->getFieldSeqFlag() == 0);                        // not currently supported
376  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
377#if !BUFFERING_PERIOD_AND_TIMING_SEI
378  assert(pcVUI->getHrdParametersPresentFlag() == 0);            // not currently supported
379#else
380  if( pcVUI->getHrdParametersPresentFlag() )
381  {
382    WRITE_FLAG(pcVUI->getTimingInfoPresentFlag(),               "timing_info_present_flag");
383    if( pcVUI->getTimingInfoPresentFlag() )
384    {
385      WRITE_CODE(pcVUI->getNumUnitsInTick(), 32,                "num_units_in_tick");
386      WRITE_CODE(pcVUI->getTimeScale(),      32,                "time_scale");
387    }
388    WRITE_FLAG(pcVUI->getNalHrdParametersPresentFlag(),         "nal_hrd_parameters_present_flag");
389    WRITE_FLAG(pcVUI->getVclHrdParametersPresentFlag(),         "vcl_hrd_parameters_present_flag");
390    if( pcVUI->getNalHrdParametersPresentFlag() || pcVUI->getVclHrdParametersPresentFlag() )
391    {
392      WRITE_FLAG(pcVUI->getSubPicCpbParamsPresentFlag(),        "sub_pic_cpb_params_present_flag");
393      if( pcVUI->getSubPicCpbParamsPresentFlag() )
394      {
395        WRITE_CODE(pcVUI->getTickDivisorMinus2(), 8,            "tick_divisor_minus2");
396        WRITE_CODE(pcVUI->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1");
397      }
398      WRITE_CODE(pcVUI->getBitRateScale(), 4,                   "bit_rate_scale");
399      WRITE_CODE(pcVUI->getCpbSizeScale(), 4,                   "cpb_size_scale");
400      WRITE_CODE(pcVUI->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1");
401      WRITE_CODE(pcVUI->getCpbRemovalDelayLengthMinus1(),        5, "cpb_removal_delay_length_minus1");
402      WRITE_CODE(pcVUI->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1");
403    }
404    Int i, j, nalOrVcl;
405    for( i = 0; i <= pcSPS->getMaxTLayers(); i ++ )
406    {
407      WRITE_FLAG(pcVUI->getFixedPicRateFlag(i),                 "fixed_pic_rate_flag");
408      if( pcVUI->getFixedPicRateFlag( i ) )
409      {
410        WRITE_UVLC(pcVUI->getPicDurationInTcMinus1(i),          "pic_duration_in_tc_minus1");
411      }
412      WRITE_FLAG(pcVUI->getLowDelayHrdFlag(i),                  "low_delay_hrd_flag");
413      WRITE_UVLC(pcVUI->getCpbCntMinus1(i),                     "cpb_cnt_minus1");
414     
415      for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
416      {
417        if( ( ( nalOrVcl == 0 ) && ( pcVUI->getNalHrdParametersPresentFlag() ) ) ||
418            ( ( nalOrVcl == 1 ) && ( pcVUI->getVclHrdParametersPresentFlag() ) ) )
419        {
420          for( j = 0; j < ( pcVUI->getCpbCntMinus1( i ) + 1 ); j ++ )
421          {
422            WRITE_UVLC(pcVUI->getBitRateValueMinus1(i, j, nalOrVcl), "bit_size_value_minus1");
423            WRITE_UVLC(pcVUI->getCpbSizeValueMinus1(i, j, nalOrVcl), "cpb_size_value_minus1");
424            WRITE_FLAG(pcVUI->getCbrFlag(i, j, nalOrVcl),            "cbr_flag");
425          }
426        }
427      }
428    }
429  }
430#endif
431  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
432  if (pcVUI->getBitstreamRestrictionFlag())
433  {
434    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
435    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
436    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
437    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
438    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
439    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
440  }
441
442}
443#endif
444
445Void TEncCavlc::codeSPS( TComSPS* pcSPS )
446{
447#if ENC_DEC_TRACE 
448  xTraceSPSHeader (pcSPS);
449#endif
450#if SPS_SYNTAX_CHANGES
451  WRITE_CODE( pcSPS->getVPSId (),          4,       "video_parameter_set_id" );
452  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
453  WRITE_FLAG( 0,                                    "sps_reserved_zero_bit");
454  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
455  WRITE_UVLC( pcSPS->getSPSId (),                   "seq_parameter_set_id" );
456  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
457  assert(pcSPS->getChromaFormatIdc () == 1);
458  // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
459  if( pcSPS->getChromaFormatIdc () == 3 )
460  {
461    WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
462  }
463
464#else
465  WRITE_CODE( pcSPS->getProfileSpace (),   3,       "profile_space" );
466  WRITE_CODE( pcSPS->getProfileIdc (),     5,       "profile_idc" );
467  WRITE_CODE( pcSPS->getRsvdIndFlags(),   16,       "reserved_indicator_flags" );
468  WRITE_CODE( pcSPS->getLevelIdc (),       8,       "level_idc" );
469  WRITE_CODE( pcSPS->getProfileCompat (), 32,       "profile_compatibility" );
470  WRITE_UVLC( pcSPS->getSPSId (),                   "seq_parameter_set_id" );
471  WRITE_UVLC( pcSPS->getVPSId (),                   "video_parameter_set_id" );
472  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
473  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "max_temporal_layers_minus1" );
474#endif
475  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
476  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
477  WRITE_FLAG( pcSPS->getPicCroppingFlag(),          "pic_cropping_flag" );
478  if (pcSPS->getPicCroppingFlag())
479  {
480    WRITE_UVLC( pcSPS->getPicCropLeftOffset()   / TComSPS::getCropUnitX(pcSPS->getChromaFormatIdc() ), "pic_crop_left_offset" );
481    WRITE_UVLC( pcSPS->getPicCropRightOffset()  / TComSPS::getCropUnitX(pcSPS->getChromaFormatIdc() ), "pic_crop_right_offset" );
482    WRITE_UVLC( pcSPS->getPicCropTopOffset()    / TComSPS::getCropUnitY(pcSPS->getChromaFormatIdc() ), "pic_crop_top_offset" );
483    WRITE_UVLC( pcSPS->getPicCropBottomOffset() / TComSPS::getCropUnitY(pcSPS->getChromaFormatIdc() ), "pic_crop_bottom_offset" );
484  }
485
486#if FULL_NBIT
487  WRITE_UVLC( pcSPS->getBitDepth() - 8,             "bit_depth_luma_minus8" );
488#else
489  WRITE_UVLC( pcSPS->getBitIncrement(),             "bit_depth_luma_minus8" );
490#endif
491#if FULL_NBIT
492  WRITE_UVLC( pcSPS->getBitDepth() - 8,             "bit_depth_chroma_minus8" );
493#else
494  WRITE_UVLC( pcSPS->getBitIncrement(),             "bit_depth_chroma_minus8" );
495#endif
496
497  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                   "pcm_enabled_flag");
498
499  if( pcSPS->getUsePCM() )
500  {
501  WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,   "pcm_bit_depth_luma_minus1" );
502  WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4, "pcm_bit_depth_chroma_minus1" );
503  }
504
505  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
506  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
507  {
508    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i),           "max_dec_pic_buffering[i]" );
509    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "num_reorder_pics[i]" );
510    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "max_latency_increase[i]" );
511  }
512  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
513 
514  UInt MinCUSize = pcSPS->getMaxCUWidth() >> ( pcSPS->getMaxCUDepth()-g_uiAddCUDepth );
515  UInt log2MinCUSize = 0;
516  while(MinCUSize > 1)
517  {
518    MinCUSize >>= 1;
519    log2MinCUSize++;
520  }
521
522  WRITE_FLAG( pcSPS->getRestrictedRefPicListsFlag(),                                 "restricted_ref_pic_lists_flag" );
523  if( pcSPS->getRestrictedRefPicListsFlag() )
524  {
525    WRITE_FLAG( pcSPS->getListsModificationPresentFlag(),                            "lists_modification_present_flag" );
526  }
527  WRITE_UVLC( log2MinCUSize - 3,                                                     "log2_min_coding_block_size_minus3" );
528  WRITE_UVLC( pcSPS->getMaxCUDepth()-g_uiAddCUDepth,                                 "log2_diff_max_min_coding_block_size" );
529  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
530  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
531  if( pcSPS->getUsePCM() )
532  {
533    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_coding_block_size_minus3" );
534    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_coding_block_size" );
535  }
536  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
537  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
538  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
539  if(pcSPS->getScalingListFlag())
540  {
541    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
542    if(pcSPS->getScalingListPresentFlag())
543    {
544#if SCALING_LIST_OUTPUT_RESULT
545    printf("SPS\n");
546#endif
547      codeScalingList( m_pcSlice->getScalingList() );
548    }
549  }
550#if !REMOVE_LMCHROMA
551  WRITE_FLAG( pcSPS->getUseLMChroma () ? 1 : 0,                                      "chroma_pred_from_luma_enabled_flag" );
552#endif
553#if !PPS_TS_FLAG
554  WRITE_FLAG( pcSPS->getUseTransformSkip () ? 1 : 0,                                 "transform_skip_enabled_flag" );
555#endif
556#if !MOVE_LOOP_FILTER_SLICES_FLAG
557  WRITE_FLAG( pcSPS->getLFCrossSliceBoundaryFlag()?1 : 0,                            "seq_loop_filter_across_slices_enabled_flag");
558#endif
559  WRITE_FLAG( pcSPS->getUseAMP(),                                                    "asymmetric_motion_partitions_enabled_flag" );
560#if !REMOVE_NSQT
561  WRITE_FLAG( pcSPS->getUseNSQT(),                                                   "non_square_quadtree_enabled_flag" );
562#endif
563  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
564#if !REMOVE_ALF
565  WRITE_FLAG( pcSPS->getUseALF () ? 1 : 0,                                           "adaptive_loop_filter_enabled_flag");
566#endif
567  if( pcSPS->getUsePCM() )
568  {
569  WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                                "pcm_loop_filter_disable_flag");
570  }
571
572  assert( pcSPS->getMaxTLayers() > 0 );         
573
574  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "temporal_id_nesting_flag" );
575
576  TComRPSList* rpsList = pcSPS->getRPSList();
577  TComReferencePictureSet*      rps;
578
579  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
580  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
581  {
582    rps = rpsList->getReferencePictureSet(i);
583#if J0234_INTER_RPS_SIMPL
584    codeShortTermRefPicSet(pcSPS,rps,false);
585#else
586    codeShortTermRefPicSet(pcSPS,rps);
587#endif
588  }   
589  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
590#if LTRP_IN_SPS
591  if (pcSPS->getLongTermRefsPresent()) 
592  {
593    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
594    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
595    {
596      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
597      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
598    }
599  }
600#endif
601  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
602#if REF_IDX_MFM
603  if( pcSPS->getLayerId() > 0 )
604  {
605    assert(pcSPS->getMFMEnabledFlag());
606    WRITE_FLAG( pcSPS->getMFMEnabledFlag() ? 1 : 0,          "sps_enh_mfm_enable_flag" );
607  }
608#endif
609#if SUPPORT_FOR_VUI
610  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
611  if (pcSPS->getVuiParametersPresentFlag())
612  {
613      codeVUI(pcSPS->getVuiParameters(), pcSPS);
614  }
615#endif
616#if !SPS_AMVP_CLEANUP
617  // AMVP mode for each depth
618  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
619  {
620    xWriteFlag( pcSPS->getAMVPMode(i) ? 1 : 0);
621  }
622#endif
623  WRITE_FLAG( 0, "sps_extension_flag" );
624}
625
626Void TEncCavlc::codeVPS( TComVPS* pcVPS )
627{
628#if VPS_SYNTAX_CHANGES
629  WRITE_CODE( pcVPS->getVPSId(),                    4,        "video_parameter_set_id" );
630  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
631  WRITE_CODE( 0,                                    2,        "vps_reserved_zero_2bits" );
632  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
633  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
634  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
635  WRITE_CODE( 0,                                   12,        "vps_reserved_zero_12bits" );
636#else
637  WRITE_CODE( pcVPS->getMaxTLayers() - 1,     3,        "vps_max_temporal_layers_minus1" );
638  WRITE_CODE( pcVPS->getMaxLayers() - 1,      5,        "vps_max_layers_minus1" );
639  WRITE_UVLC( pcVPS->getVPSId(),                        "video_parameter_set_id" );
640  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),          "vps_temporal_id_nesting_flag" );
641#endif
642  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
643  {
644    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "vps_max_dec_pic_buffering[i]" );
645    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
646    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase[i]" );
647  }
648#if VPS_SYNTAX_CHANGES
649  WRITE_UVLC( 0,                                           "vps_num_hrd_parameters" );
650  // hrd_parameters
651#endif
652  WRITE_FLAG( 0,                     "vps_extension_flag" );
653 
654  //future extensions here..
655 
656  return;
657}
658
659Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
660{
661#if ENC_DEC_TRACE 
662  xTraceSliceHeader (pcSlice);
663#endif
664
665  //calculate number of bits required for slice address
666  Int maxAddrOuter = pcSlice->getPic()->getNumCUsInFrame();
667  Int reqBitsOuter = 0;
668  while(maxAddrOuter>(1<<reqBitsOuter)) 
669  {
670    reqBitsOuter++;
671  }
672  Int maxAddrInner = pcSlice->getPic()->getNumPartInCU()>>(2);
673#if REMOVE_FGS
674  maxAddrInner = 1;
675#else
676  maxAddrInner = (1<<(pcSlice->getPPS()->getSliceGranularity()<<1));
677#endif
678  Int reqBitsInner = 0;
679 
680  while(maxAddrInner>(1<<reqBitsInner))
681  {
682    reqBitsInner++;
683  }
684  Int lCUAddress;
685  Int innerAddress;
686  if (pcSlice->isNextSlice())
687  {
688    // Calculate slice address
689    lCUAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
690#if REMOVE_FGS
691    innerAddress = 0;
692#else
693    innerAddress = (pcSlice->getSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
694#endif
695  }
696  else
697  {
698    // Calculate slice address
699    lCUAddress = (pcSlice->getDependentSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
700#if REMOVE_FGS
701    innerAddress = 0;
702#else
703    innerAddress = (pcSlice->getDependentSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
704#endif
705   
706  }
707  //write slice address
708  Int address = (pcSlice->getPic()->getPicSym()->getCUOrderMap(lCUAddress) << reqBitsInner) + innerAddress;
709  WRITE_FLAG( address==0, "first_slice_in_pic_flag" );
710#if SPLICING_FRIENDLY_PARAMS
711  if ( pcSlice->getRapPicFlag() )
712  {
713    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
714  }
715#endif
716  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "pic_parameter_set_id" );
717  if(address>0) 
718  {
719    WRITE_CODE( address, reqBitsOuter+reqBitsInner, "slice_address" );
720  }
721
722#if SLICEHEADER_SYNTAX_FIX
723  pcSlice->setDependentSliceFlag(!pcSlice->isNextSlice());
724  if ( pcSlice->getPPS()->getDependentSliceEnabledFlag() && (address!=0) )
725  {
726    WRITE_FLAG( pcSlice->getDependentSliceFlag() ? 1 : 0, "dependent_slice_flag" );
727  }
728  if ( !pcSlice->getDependentSliceFlag() )
729  {
730#endif
731
732    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
733
734#if !SLICEHEADER_SYNTAX_FIX
735  Bool bDependentSlice = (!pcSlice->isNextSlice());
736  WRITE_FLAG( bDependentSlice ? 1 : 0, "dependent_slice_flag" );
737 
738#if DEPENDENT_SLICES
739  if( pcSlice->getPPS()->getDependentSliceEnabledFlag() && bDependentSlice )
740    return;
741#endif
742
743  if (!bDependentSlice)
744  {
745#endif
746    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
747    {
748      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
749    }
750
751    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
752    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
753    // if( separate_colour_plane_flag  ==  1 )
754    //   colour_plane_id                                      u(2)
755
756#if !SPLICING_FRIENDLY_PARAMS
757    if(   pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
758#if SUPPORT_FOR_RAP_N_LP
759       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
760       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
761#endif
762       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
763       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
764#if !NAL_UNIT_TYPES_J1003_D7
765       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT
766#endif
767       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )
768    {
769      WRITE_UVLC( 0, "rap_pic_id" );
770      WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
771    }
772#endif
773#if SUPPORT_FOR_RAP_N_LP
774    if( !pcSlice->getIdrPicFlag() )
775#else
776    if( pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR )
777#endif
778    {
779      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
780      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
781      TComReferencePictureSet* rps = pcSlice->getRPS();
782      if(pcSlice->getRPSidx() < 0)
783      {
784        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
785#if J0234_INTER_RPS_SIMPL
786        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true);
787#else
788        codeShortTermRefPicSet(pcSlice->getSPS(), rps);
789#endif
790      }
791      else
792      {
793        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
794        WRITE_UVLC( pcSlice->getRPSidx(), "short_term_ref_pic_set_idx" );
795      }
796      if(pcSlice->getSPS()->getLongTermRefsPresent())
797      {
798#if LTRP_IN_SPS
799        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
800        Int ltrpInSPS[MAX_NUM_REF_PICS];
801        Int numLtrpInSPS = 0;
802        UInt ltrpIndex;
803        Int counter = 0;
804        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
805        {
806          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
807          {
808            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
809            numLtrpInSPS++;
810          }
811          else
812          {
813            counter++;
814          }
815        }
816        numLtrpInSH -= numLtrpInSPS;
817
818        Int bitsForLtrpInSPS = 1;
819        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
820        {
821          bitsForLtrpInSPS++;
822        }
823        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
824        {
825          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
826        }
827        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
828#else
829        WRITE_UVLC( rps->getNumberOfLongtermPictures(), "num_long_term_pics");
830#endif
831        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
832        // Not sorted here because LT ref indices will be used in setRefPicList()
833        Int prevDeltaMSB = 0, prevLSB = 0;
834        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
835        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
836        {
837#if LTRP_IN_SPS
838          if (counter < numLtrpInSPS)
839          {
840            WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
841          }
842          else 
843          {
844            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
845            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
846          }
847#else
848          WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
849#endif
850          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
851
852          if(rps->getDeltaPocMSBPresentFlag(i))
853          {
854            Bool deltaFlag = false;
855#if LTRP_IN_SPS
856            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
857            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
858#else
859            //   First LTRP                         ||  curr LSB            != prev LSB
860            if( (i == rps->getNumberOfPictures()-1) || (rps->getPocLSBLT(i) != prevLSB) )
861#endif
862            {
863              deltaFlag = true;
864            }
865            if(deltaFlag)
866            {
867              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
868            }
869            else
870            {             
871              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
872              assert(differenceInDeltaMSB >= 0);
873              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
874            }
875            prevLSB = rps->getPocLSBLT(i);
876            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
877          }
878#if !LTRP_IN_SPS
879          WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
880#endif
881        }
882      }
883    }
884#if REMOVE_ALF
885    if(pcSlice->getSPS()->getUseSAO())
886#else
887    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
888#endif
889    {
890      if (pcSlice->getSPS()->getUseSAO())
891      {
892         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
893#if !SAO_LUM_CHROMA_ONOFF_FLAGS
894         if (pcSlice->getSaoEnabledFlag() )
895#endif
896         {
897#if REMOVE_APS
898           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
899#else
900           SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
901#endif
902#if SAO_TYPE_SHARING
903          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
904#else
905          WRITE_FLAG( saoParam->bSaoFlag[1], "SAO on/off flag for Cb in slice header" );
906          WRITE_FLAG( saoParam->bSaoFlag[2], "SAO on/off flag for Cr in slice header" );
907#endif
908         }
909      }
910#if !REMOVE_APS
911      WRITE_UVLC( pcSlice->getAPS()->getAPSID(), "aps_id");
912#endif
913    }
914
915    //check if numrefidxes match the defaults. If not, override
916    if (!pcSlice->isIntra())
917    {
918      if (pcSlice->getSPS()->getTMVPFlagsPresent())
919      {
920        WRITE_FLAG( pcSlice->getEnableTMVPFlag(), "enable_temporal_mvp_flag" );
921      }
922      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
923      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
924      if (overrideFlag) 
925      {
926        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
927        if (pcSlice->isInterB())
928        {
929          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
930        }
931        else
932        {
933          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
934        }
935      }
936    }
937    else
938    {
939      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
940      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
941    }
942    if( pcSlice->getSPS()->getListsModificationPresentFlag() )
943    {
944      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
945      if(!pcSlice->isIntra())
946      {
947        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
948        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
949        {
950          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
951          if (numRpsCurrTempList0 > 1)
952          {
953            Int length = 1;
954            numRpsCurrTempList0 --;
955            while ( numRpsCurrTempList0 >>= 1) 
956            {
957              length ++;
958            }
959            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
960            {
961              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
962            }
963          }
964        }
965      }
966      if(pcSlice->isInterB())
967      {   
968        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
969        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
970        {
971          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
972          if ( numRpsCurrTempList1 > 1 )
973          {
974            Int length = 1;
975            numRpsCurrTempList1 --;
976            while ( numRpsCurrTempList1 >>= 1)
977            {
978              length ++;
979            }
980            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
981            {
982              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
983            }
984          }
985        }
986      }
987    }
988#if !SLICEHEADER_SYNTAX_FIX
989  }
990#endif
991   
992    if (pcSlice->isInterB())
993    {
994      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
995    }
996
997    if(!pcSlice->isIntra())
998    {
999      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
1000      {
1001        SliceType sliceType   = pcSlice->getSliceType();
1002        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
1003        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
1004        pcSlice->setCabacInitFlag( encCabacInitFlag );
1005        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
1006      }
1007    }
1008
1009#if !SLICEHEADER_SYNTAX_FIX
1010  // if( !lightweight_slice_flag ) {
1011  if (!bDependentSlice)
1012  {
1013#else
1014    if ( pcSlice->getEnableTMVPFlag() )
1015    {
1016      if ( pcSlice->getSliceType() == B_SLICE )
1017      {
1018        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1019      }
1020
1021      if ( pcSlice->getSliceType() != I_SLICE &&
1022        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1023        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1024      {
1025        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1026      }
1027    }
1028    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1029    {
1030      xCodePredWeightTable( pcSlice );
1031    }
1032    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1033    WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1034#endif
1035    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1036    WRITE_SVLC( iCode, "slice_qp_delta" ); 
1037#if CHROMA_QP_EXTENSION
1038    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1039    {
1040      iCode = pcSlice->getSliceQpDeltaCb();
1041      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
1042      iCode = pcSlice->getSliceQpDeltaCr();
1043      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
1044    }
1045#endif
1046    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1047    {
1048      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1049      {
1050        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1051      }
1052      if (pcSlice->getDeblockingFilterOverrideFlag())
1053      {
1054        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1055        if(!pcSlice->getDeblockingFilterDisable())
1056        {
1057          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "beta_offset_div2");
1058          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "tc_offset_div2");
1059        }
1060      }
1061    }
1062#if !SLICEHEADER_SYNTAX_FIX
1063    if ( pcSlice->getEnableTMVPFlag() )
1064    {
1065      if ( pcSlice->getSliceType() == B_SLICE )
1066      {
1067        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1068      }
1069
1070      if ( pcSlice->getSliceType() != I_SLICE &&
1071         ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1072         (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1073      {
1074        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1075      }
1076    }
1077    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1078    {
1079      xCodePredWeightTable( pcSlice );
1080    }
1081  }
1082    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1083    WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1084#endif
1085
1086#if !REMOVE_ALF
1087  if (!bDependentSlice)
1088  {
1089    if (pcSlice->getSPS()->getUseALF())
1090    {
1091      char syntaxString[50];
1092      for(Int compIdx=0; compIdx< 3; compIdx++)
1093      {
1094        sprintf(syntaxString, "alf_slice_filter_flag[%d]", compIdx);
1095        WRITE_FLAG( pcSlice->getAlfEnabledFlag(compIdx)?1:0, syntaxString );
1096      }
1097    }
1098  }
1099#endif
1100#if !SLICEHEADER_SYNTAX_FIX
1101  if(!bDependentSlice)
1102  {
1103#endif
1104#if !REMOVE_ALF
1105    Bool isAlfEnabled = (!pcSlice->getSPS()->getUseALF())?(false):(pcSlice->getAlfEnabledFlag(0)||pcSlice->getAlfEnabledFlag(1)||pcSlice->getAlfEnabledFlag(2));
1106#endif
1107#if !SAO_LUM_CHROMA_ONOFF_FLAGS
1108    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag());
1109#else
1110    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
1111#endif
1112    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1113
1114#if REMOVE_ALF
1115#if MOVE_LOOP_FILTER_SLICES_FLAG
1116    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1117#else
1118    if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isSAOEnabled || isDBFEnabled ))
1119#endif
1120#else
1121    if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isAlfEnabled || isSAOEnabled || isDBFEnabled ))
1122#endif
1123    {
1124      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1125    }
1126  }
1127#if SLICE_HEADER_EXTENSION
1128  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1129  {
1130    WRITE_UVLC(0,"slice_header_extension_length");
1131  }
1132#endif
1133}
1134
1135#if PROFILE_TIER_LEVEL_SYNTAX
1136Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1137{
1138  if(profilePresentFlag)
1139  {
1140    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1141  }
1142  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
1143
1144  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1145  {
1146    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1147    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1148    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1149    {
1150      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1151    }
1152    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1153    {
1154      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
1155    }
1156  }
1157}
1158Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1159{
1160  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1161  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
1162  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
1163  for(Int j = 0; j < 32; j++)
1164  {
1165    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
1166  }
1167  WRITE_CODE(0 , 16, "XXX_reserved_zero_16bits[]"); 
1168}
1169#endif
1170
1171/**
1172 - write wavefront substreams sizes for the slice header.
1173 .
1174 \param pcSlice Where we find the substream size information.
1175 */
1176Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1177{
1178#if TILES_WPP_ENTROPYSLICES_FLAGS
1179  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1180#else
1181  Int tilesOrEntropyCodingSyncIdc = pSlice->getPPS()->getTilesOrEntropyCodingSyncIdc();
1182  if ( tilesOrEntropyCodingSyncIdc == 0 )
1183#endif
1184  {
1185    return;
1186  }
1187  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
1188  Int  numZeroSubstreamsAtStartOfSlice  = 0;
1189  UInt *entryPointOffset = NULL;
1190#if TILES_WPP_ENTROPYSLICES_FLAGS
1191  if ( pSlice->getPPS()->getTilesEnabledFlag() )
1192#else
1193  if (tilesOrEntropyCodingSyncIdc == 1) // tiles
1194#endif
1195  {
1196    numEntryPointOffsets = pSlice->getTileLocationCount();
1197    entryPointOffset     = new UInt[numEntryPointOffsets];
1198    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
1199    {
1200      if ( idx == 0 )
1201      {
1202        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
1203      }
1204      else
1205      {
1206        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
1207      }
1208
1209      if ( entryPointOffset[ idx ] > maxOffset )
1210      {
1211        maxOffset = entryPointOffset[ idx ];
1212      }
1213    }
1214  }
1215#if TILES_WPP_ENTROPYSLICES_FLAGS
1216  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
1217#else
1218  else if (tilesOrEntropyCodingSyncIdc == 2) // wavefront
1219#endif
1220  {
1221    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
1222    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
1223#if DEPENDENT_SLICES
1224    numZeroSubstreamsAtStartOfSlice       = pSlice->getDependentSliceCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1225    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getDependentSliceCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1226#else
1227    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1228    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1229#endif
1230    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
1231    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
1232    entryPointOffset           = new UInt[numEntryPointOffsets];
1233    for (Int idx=0; idx<numEntryPointOffsets; idx++)
1234    {
1235      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
1236      if ( entryPointOffset[ idx ] > maxOffset )
1237      {
1238        maxOffset = entryPointOffset[ idx ];
1239      }
1240    }
1241  }
1242  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1243  offsetLenMinus1 = 0;
1244  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1245  {
1246    offsetLenMinus1++;
1247    assert(offsetLenMinus1 + 1 < 32);   
1248  }
1249
1250  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
1251  if (numEntryPointOffsets>0)
1252  {
1253    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1254  }
1255
1256  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
1257  {
1258    WRITE_CODE(entryPointOffset[ idx ], offsetLenMinus1+1, "entry_point_offset");
1259  }
1260
1261  delete [] entryPointOffset;
1262}
1263
1264Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1265{
1266}
1267
1268Void TEncCavlc::codeSliceFinish ()
1269{
1270}
1271
1272Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1273{
1274  assert(0);
1275}
1276
1277Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1278{
1279  assert(0);
1280}
1281
1282Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1283{
1284  assert(0);
1285}
1286
1287Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1288{
1289  assert(0);
1290}
1291
1292Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1293{
1294  assert(0);
1295}
1296
1297Void TEncCavlc::codeApsExtensionFlag ()
1298{
1299  WRITE_FLAG(0, "aps_extension_flag");
1300}
1301
1302Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1303{
1304  assert(0);
1305}
1306
1307Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1308{
1309  assert(0);
1310}
1311
1312Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1313{
1314  assert(0);
1315}
1316
1317#if INTRA_BL
1318Void TEncCavlc::codeIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1319{
1320  assert(0);
1321}
1322
1323#endif
1324Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1325{
1326  assert(0);
1327}
1328
1329Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1330{
1331  assert(0);
1332}
1333
1334Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1335{
1336  assert(0);
1337}
1338
1339Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1340{
1341  assert(0);
1342}
1343
1344#if TU_ZERO_CBF_RDO
1345Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1346{
1347  assert(0);
1348}
1349Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx )
1350{
1351  assert(0);
1352}
1353#endif
1354
1355Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType )
1356{
1357  assert(0);
1358}
1359
1360/** Code I_PCM information.
1361 * \param pcCU pointer to CU
1362 * \param uiAbsPartIdx CU index
1363 * \param numIPCM the number of succesive IPCM blocks with the same size
1364 * \param firstIPCMFlag
1365 * \returns Void
1366 */
1367Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag)
1368{
1369  assert(0);
1370}
1371
1372Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1373{
1374  assert(0);
1375}
1376
1377Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
1378{
1379  assert(0);
1380}
1381
1382Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
1383{
1384  assert(0);
1385}
1386
1387Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1388{
1389  assert(0);
1390}
1391
1392Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1393{
1394  assert(0);
1395}
1396
1397Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
1398{
1399  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
1400
1401  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
1402  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
1403
1404  xWriteSvlc( iDQp );
1405 
1406  return;
1407}
1408
1409Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
1410{
1411  assert(0);
1412}
1413
1414Void TEncCavlc::xGolombEncode(Int coeff, Int k)
1415{
1416  xWriteEpExGolomb((UInt)abs(coeff), k);
1417  if(coeff != 0)
1418  {
1419    Int sign = (coeff > 0)? 1: 0;
1420    xWriteFlag(sign);
1421  }
1422#if ENC_DEC_TRACE
1423  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
1424  fprintf( g_hTrace, "%-40s se(v) : %d\n", "alf_filt_coeff", coeff ); 
1425#endif
1426
1427}
1428
1429#if !REMOVE_ALF
1430Void TEncCavlc::codeAlfParam(ALFParam* alfParam)
1431{
1432  char syntaxString[50];
1433  sprintf(syntaxString, "alf_aps_filter_flag[%d]", alfParam->componentID);
1434  WRITE_FLAG(alfParam->alf_flag, syntaxString);
1435  if(alfParam->alf_flag == 0)
1436  {
1437    return;
1438  }
1439
1440  const Int numCoeff = (Int)ALF_MAX_NUM_COEF;
1441  switch(alfParam->componentID)
1442  {
1443  case ALF_Cb:
1444  case ALF_Cr:
1445    {
1446      for(Int pos=0; pos< numCoeff; pos++)
1447      {
1448        WRITE_SVLC(alfParam->coeffmulti[0][pos], "alf_filt_coeff");
1449      }
1450    }
1451    break;
1452  case ALF_Y:
1453    {
1454      Int noFilters = min(alfParam->filters_per_group-1, 2);
1455      WRITE_UVLC(noFilters, "alf_no_filters_minus1");
1456      if(noFilters == 1)
1457      {
1458        WRITE_UVLC(alfParam->startSecondFilter, "alf_start_second_filter");
1459      }
1460      else if (noFilters == 2)
1461      {
1462        Int numMergeFlags = 16;
1463        for (Int i=1; i<numMergeFlags; i++) 
1464        {
1465          WRITE_FLAG(alfParam->filterPattern[i], "alf_filter_pattern");
1466        }
1467      }
1468      for(Int f=0; f< alfParam->filters_per_group; f++)
1469      {
1470        for(Int pos=0; pos< numCoeff; pos++)
1471        {
1472          xGolombEncode(alfParam->coeffmulti[f][pos], kTableTabShapes[ALF_CROSS9x7_SQUARE3x3][pos]);
1473        }
1474      }
1475    }
1476    break;
1477  default:
1478    {
1479      printf("Not a legal component ID\n");
1480      assert(0);
1481      exit(-1);
1482    }
1483  }
1484
1485}
1486#endif
1487
1488Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
1489{
1490  // printf("error : no VLC mode support in this version\n");
1491  return;
1492}
1493
1494// ====================================================================================================================
1495// Protected member functions
1496// ====================================================================================================================
1497
1498
1499/** Write PCM alignment bits.
1500 * \returns Void
1501 */
1502Void  TEncCavlc::xWritePCMAlignZero    ()
1503{
1504  m_pcBitIf->writeAlignZero();
1505}
1506
1507Void TEncCavlc::xWriteUnaryMaxSymbol( UInt uiSymbol, UInt uiMaxSymbol )
1508{
1509  if (uiMaxSymbol == 0)
1510  {
1511    return;
1512  }
1513  xWriteFlag( uiSymbol ? 1 : 0 );
1514  if ( uiSymbol == 0 )
1515  {
1516    return;
1517  }
1518 
1519  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
1520 
1521  while( --uiSymbol )
1522  {
1523    xWriteFlag( 1 );
1524  }
1525  if( bCodeLast )
1526  {
1527    xWriteFlag( 0 );
1528  }
1529  return;
1530}
1531
1532Void TEncCavlc::xWriteExGolombLevel( UInt uiSymbol )
1533{
1534  if( uiSymbol )
1535  {
1536    xWriteFlag( 1 );
1537    UInt uiCount = 0;
1538    Bool bNoExGo = (uiSymbol < 13);
1539   
1540    while( --uiSymbol && ++uiCount < 13 )
1541    {
1542      xWriteFlag( 1 );
1543    }
1544    if( bNoExGo )
1545    {
1546      xWriteFlag( 0 );
1547    }
1548    else
1549    {
1550      xWriteEpExGolomb( uiSymbol, 0 );
1551    }
1552  }
1553  else
1554  {
1555    xWriteFlag( 0 );
1556  }
1557  return;
1558}
1559
1560Void TEncCavlc::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
1561{
1562  while( uiSymbol >= (UInt)(1<<uiCount) )
1563  {
1564    xWriteFlag( 1 );
1565    uiSymbol -= 1<<uiCount;
1566    uiCount  ++;
1567  }
1568  xWriteFlag( 0 );
1569  while( uiCount-- )
1570  {
1571    xWriteFlag( (uiSymbol>>uiCount) & 1 );
1572  }
1573  return;
1574}
1575
1576/** code explicit wp tables
1577 * \param TComSlice* pcSlice
1578 * \returns Void
1579 */
1580Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
1581{
1582  wpScalingParam  *wp;
1583  Bool            bChroma     = true; // color always present in HEVC ?
1584  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
1585  Bool            bDenomCoded  = false;
1586  UInt            uiMode = 0;
1587#if NUM_WP_LIMIT
1588  UInt            uiTotalSignalledWeightFlags = 0;
1589#endif
1590  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
1591  {
1592    uiMode = 1; // explicit
1593  }
1594  if(uiMode == 1)
1595  {
1596
1597    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
1598    {
1599      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1600
1601      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1602      {
1603        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1604        if ( !bDenomCoded ) 
1605        {
1606          Int iDeltaDenom;
1607          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
1608
1609          if( bChroma )
1610          {
1611            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
1612            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
1613          }
1614          bDenomCoded = true;
1615        }
1616        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
1617#if NUM_WP_LIMIT
1618        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
1619      }
1620      if (bChroma) 
1621      {
1622        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1623        {
1624          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1625          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1626          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
1627        }
1628      }
1629
1630      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1631      {
1632        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1633#endif
1634        if ( wp[0].bPresentFlag ) 
1635        {
1636          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
1637          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
1638          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
1639        }
1640
1641        if ( bChroma ) 
1642        {
1643#if !NUM_WP_LIMIT
1644          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1645#endif
1646          if ( wp[1].bPresentFlag )
1647          {
1648            for ( Int j=1 ; j<3 ; j++ ) 
1649            {
1650              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
1651              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
1652
1653              Int shift = ((1<<(g_uiBitDepth+g_uiBitIncrement-1)));
1654              Int pred = ( shift - ( ( shift*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
1655              Int iDeltaChroma = (wp[j].iOffset - pred);
1656              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
1657            }
1658          }
1659        }
1660      }
1661    }
1662#if NUM_WP_LIMIT
1663    assert(uiTotalSignalledWeightFlags<=24);
1664#endif
1665  }
1666}
1667
1668/** code quantization matrix
1669 *  \param scalingList quantization matrix information
1670 */
1671Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
1672{
1673  UInt listId,sizeId;
1674  Bool scalingListPredModeFlag;
1675
1676#if SCALING_LIST_OUTPUT_RESULT
1677  Int startBit;
1678  Int startTotalBit;
1679  startBit = m_pcBitIf->getNumberOfWrittenBits();
1680  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
1681#endif
1682
1683    //for each size
1684    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
1685    {
1686      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
1687      {
1688#if SCALING_LIST_OUTPUT_RESULT
1689        startBit = m_pcBitIf->getNumberOfWrittenBits();
1690#endif
1691        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
1692        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
1693        if(!scalingListPredModeFlag)// Copy Mode
1694        {
1695          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
1696        }
1697        else// DPCM Mode
1698        {
1699          xCodeScalingList(scalingList, sizeId, listId);
1700        }
1701#if SCALING_LIST_OUTPUT_RESULT
1702        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
1703#endif
1704      }
1705    }
1706#if SCALING_LIST_OUTPUT_RESULT
1707  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
1708#endif
1709  return;
1710}
1711/** code DPCM
1712 * \param scalingList quantization matrix information
1713 * \param sizeIdc size index
1714 * \param listIdc list index
1715 */
1716Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
1717{
1718  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
1719#if REMOVE_ZIGZAG_SCAN
1720  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
1721#else
1722  UInt* scan    = g_auiFrameScanXY [ (sizeId == 0)? 1 : 2];
1723#endif
1724  Int nextCoef = SCALING_LIST_START_VALUE;
1725  Int data;
1726  Int *src = scalingList->getScalingListAddress(sizeId, listId);
1727    if( sizeId > SCALING_LIST_8x8 )
1728    {
1729      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
1730      nextCoef = scalingList->getScalingListDC(sizeId,listId);
1731    }
1732    for(Int i=0;i<coefNum;i++)
1733    {
1734      data = src[scan[i]] - nextCoef;
1735      nextCoef = src[scan[i]];
1736      if(data > 127)
1737      {
1738        data = data - 256;
1739      }
1740      if(data < -128)
1741      {
1742        data = data + 256;
1743      }
1744
1745      WRITE_SVLC( data,  "scaling_list_delta_coef");
1746    }
1747}
1748#if LTRP_IN_SPS
1749Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
1750{
1751  // bool state = true, state2 = false;
1752  Int lsb = ltrpPOC % (1<<pcSlice->getSPS()->getBitsForPOC());
1753  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
1754  {
1755    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
1756    {
1757      *ltrpsIndex = k;
1758      return true;
1759    }
1760  }
1761  return false;
1762}
1763#endif
1764Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
1765{
1766  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
1767  {
1768    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
1769      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
1770     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
1771    {
1772      setRefMatrixId(sizeId, listId, predListIdx);
1773      return false;
1774    }
1775  }
1776  return true;
1777}
1778//! \}
Note: See TracBrowser for help on using the repository browser.