source: SHVCSoftware/trunk/source/Lib/TLibEncoder/TEncCavlc.cpp @ 8

Last change on this file since 8 was 2, checked in by seregin, 12 years ago

Initial import by Vadim Seregin <vseregin@…>

File size: 63.6 KB
RevLine 
[2]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 SUPPORT_FOR_VUI
603  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
604  if (pcSPS->getVuiParametersPresentFlag())
605  {
606      codeVUI(pcSPS->getVuiParameters(), pcSPS);
607  }
608#endif
609#if !SPS_AMVP_CLEANUP
610  // AMVP mode for each depth
611  for (Int i = 0; i < pcSPS->getMaxCUDepth(); i++)
612  {
613    xWriteFlag( pcSPS->getAMVPMode(i) ? 1 : 0);
614  }
615#endif
616  WRITE_FLAG( 0, "sps_extension_flag" );
617}
618
619Void TEncCavlc::codeVPS( TComVPS* pcVPS )
620{
621#if VPS_SYNTAX_CHANGES
622  WRITE_CODE( pcVPS->getVPSId(),                    4,        "video_parameter_set_id" );
623  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
624  WRITE_CODE( 0,                                    2,        "vps_reserved_zero_2bits" );
625  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
626  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
627  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
628  WRITE_CODE( 0,                                   12,        "vps_reserved_zero_12bits" );
629#else
630  WRITE_CODE( pcVPS->getMaxTLayers() - 1,     3,        "vps_max_temporal_layers_minus1" );
631  WRITE_CODE( pcVPS->getMaxLayers() - 1,      5,        "vps_max_layers_minus1" );
632  WRITE_UVLC( pcVPS->getVPSId(),                        "video_parameter_set_id" );
633  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),          "vps_temporal_id_nesting_flag" );
634#endif
635  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
636  {
637    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "vps_max_dec_pic_buffering[i]" );
638    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
639    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase[i]" );
640  }
641#if VPS_SYNTAX_CHANGES
642  WRITE_UVLC( 0,                                           "vps_num_hrd_parameters" );
643  // hrd_parameters
644#endif
645  WRITE_FLAG( 0,                     "vps_extension_flag" );
646 
647  //future extensions here..
648 
649  return;
650}
651
652Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
653{
654#if ENC_DEC_TRACE 
655  xTraceSliceHeader (pcSlice);
656#endif
657
658  //calculate number of bits required for slice address
659  Int maxAddrOuter = pcSlice->getPic()->getNumCUsInFrame();
660  Int reqBitsOuter = 0;
661  while(maxAddrOuter>(1<<reqBitsOuter)) 
662  {
663    reqBitsOuter++;
664  }
665  Int maxAddrInner = pcSlice->getPic()->getNumPartInCU()>>(2);
666#if REMOVE_FGS
667  maxAddrInner = 1;
668#else
669  maxAddrInner = (1<<(pcSlice->getPPS()->getSliceGranularity()<<1));
670#endif
671  Int reqBitsInner = 0;
672 
673  while(maxAddrInner>(1<<reqBitsInner))
674  {
675    reqBitsInner++;
676  }
677  Int lCUAddress;
678  Int innerAddress;
679  if (pcSlice->isNextSlice())
680  {
681    // Calculate slice address
682    lCUAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
683#if REMOVE_FGS
684    innerAddress = 0;
685#else
686    innerAddress = (pcSlice->getSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
687#endif
688  }
689  else
690  {
691    // Calculate slice address
692    lCUAddress = (pcSlice->getDependentSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
693#if REMOVE_FGS
694    innerAddress = 0;
695#else
696    innerAddress = (pcSlice->getDependentSliceCurStartCUAddr()%(pcSlice->getPic()->getNumPartInCU()))>>((pcSlice->getSPS()->getMaxCUDepth()-pcSlice->getPPS()->getSliceGranularity())<<1);
697#endif
698   
699  }
700  //write slice address
701  Int address = (pcSlice->getPic()->getPicSym()->getCUOrderMap(lCUAddress) << reqBitsInner) + innerAddress;
702  WRITE_FLAG( address==0, "first_slice_in_pic_flag" );
703#if SPLICING_FRIENDLY_PARAMS
704  if ( pcSlice->getRapPicFlag() )
705  {
706    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
707  }
708#endif
709  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "pic_parameter_set_id" );
710  if(address>0) 
711  {
712    WRITE_CODE( address, reqBitsOuter+reqBitsInner, "slice_address" );
713  }
714
715#if SLICEHEADER_SYNTAX_FIX
716  pcSlice->setDependentSliceFlag(!pcSlice->isNextSlice());
717  if ( pcSlice->getPPS()->getDependentSliceEnabledFlag() && (address!=0) )
718  {
719    WRITE_FLAG( pcSlice->getDependentSliceFlag() ? 1 : 0, "dependent_slice_flag" );
720  }
721  if ( !pcSlice->getDependentSliceFlag() )
722  {
723#endif
724
725    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
726
727#if !SLICEHEADER_SYNTAX_FIX
728  Bool bDependentSlice = (!pcSlice->isNextSlice());
729  WRITE_FLAG( bDependentSlice ? 1 : 0, "dependent_slice_flag" );
730 
731#if DEPENDENT_SLICES
732  if( pcSlice->getPPS()->getDependentSliceEnabledFlag() && bDependentSlice )
733    return;
734#endif
735
736  if (!bDependentSlice)
737  {
738#endif
739    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
740    {
741      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
742    }
743
744    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
745    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
746    // if( separate_colour_plane_flag  ==  1 )
747    //   colour_plane_id                                      u(2)
748
749#if !SPLICING_FRIENDLY_PARAMS
750    if(   pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
751#if SUPPORT_FOR_RAP_N_LP
752       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
753       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
754#endif
755       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
756       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
757#if !NAL_UNIT_TYPES_J1003_D7
758       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRANT
759#endif
760       || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )
761    {
762      WRITE_UVLC( 0, "rap_pic_id" );
763      WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
764    }
765#endif
766#if SUPPORT_FOR_RAP_N_LP
767    if( !pcSlice->getIdrPicFlag() )
768#else
769    if( pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR )
770#endif
771    {
772      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
773      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
774      TComReferencePictureSet* rps = pcSlice->getRPS();
775      if(pcSlice->getRPSidx() < 0)
776      {
777        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
778#if J0234_INTER_RPS_SIMPL
779        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true);
780#else
781        codeShortTermRefPicSet(pcSlice->getSPS(), rps);
782#endif
783      }
784      else
785      {
786        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
787        WRITE_UVLC( pcSlice->getRPSidx(), "short_term_ref_pic_set_idx" );
788      }
789      if(pcSlice->getSPS()->getLongTermRefsPresent())
790      {
791#if LTRP_IN_SPS
792        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
793        Int ltrpInSPS[MAX_NUM_REF_PICS];
794        Int numLtrpInSPS = 0;
795        UInt ltrpIndex;
796        Int counter = 0;
797        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
798        {
799          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
800          {
801            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
802            numLtrpInSPS++;
803          }
804          else
805          {
806            counter++;
807          }
808        }
809        numLtrpInSH -= numLtrpInSPS;
810
811        Int bitsForLtrpInSPS = 1;
812        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
813        {
814          bitsForLtrpInSPS++;
815        }
816        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
817        {
818          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
819        }
820        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
821#else
822        WRITE_UVLC( rps->getNumberOfLongtermPictures(), "num_long_term_pics");
823#endif
824        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
825        // Not sorted here because LT ref indices will be used in setRefPicList()
826        Int prevDeltaMSB = 0, prevLSB = 0;
827        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
828        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
829        {
830#if LTRP_IN_SPS
831          if (counter < numLtrpInSPS)
832          {
833            WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
834          }
835          else 
836          {
837            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
838            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
839          }
840#else
841          WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
842#endif
843          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
844
845          if(rps->getDeltaPocMSBPresentFlag(i))
846          {
847            Bool deltaFlag = false;
848#if LTRP_IN_SPS
849            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
850            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
851#else
852            //   First LTRP                         ||  curr LSB            != prev LSB
853            if( (i == rps->getNumberOfPictures()-1) || (rps->getPocLSBLT(i) != prevLSB) )
854#endif
855            {
856              deltaFlag = true;
857            }
858            if(deltaFlag)
859            {
860              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
861            }
862            else
863            {             
864              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
865              assert(differenceInDeltaMSB >= 0);
866              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
867            }
868            prevLSB = rps->getPocLSBLT(i);
869            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
870          }
871#if !LTRP_IN_SPS
872          WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
873#endif
874        }
875      }
876    }
877#if REMOVE_ALF
878    if(pcSlice->getSPS()->getUseSAO())
879#else
880    if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
881#endif
882    {
883      if (pcSlice->getSPS()->getUseSAO())
884      {
885         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
886#if !SAO_LUM_CHROMA_ONOFF_FLAGS
887         if (pcSlice->getSaoEnabledFlag() )
888#endif
889         {
890#if REMOVE_APS
891           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
892#else
893           SAOParam *saoParam = pcSlice->getAPS()->getSaoParam();
894#endif
895#if SAO_TYPE_SHARING
896          WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
897#else
898          WRITE_FLAG( saoParam->bSaoFlag[1], "SAO on/off flag for Cb in slice header" );
899          WRITE_FLAG( saoParam->bSaoFlag[2], "SAO on/off flag for Cr in slice header" );
900#endif
901         }
902      }
903#if !REMOVE_APS
904      WRITE_UVLC( pcSlice->getAPS()->getAPSID(), "aps_id");
905#endif
906    }
907
908    //check if numrefidxes match the defaults. If not, override
909    if (!pcSlice->isIntra())
910    {
911      if (pcSlice->getSPS()->getTMVPFlagsPresent())
912      {
913        WRITE_FLAG( pcSlice->getEnableTMVPFlag(), "enable_temporal_mvp_flag" );
914      }
915      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
916      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
917      if (overrideFlag) 
918      {
919        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
920        if (pcSlice->isInterB())
921        {
922          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
923        }
924        else
925        {
926          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
927        }
928      }
929    }
930    else
931    {
932      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
933      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
934    }
935    if( pcSlice->getSPS()->getListsModificationPresentFlag() )
936    {
937      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
938      if(!pcSlice->isIntra())
939      {
940        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
941        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
942        {
943          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
944          if (numRpsCurrTempList0 > 1)
945          {
946            Int length = 1;
947            numRpsCurrTempList0 --;
948            while ( numRpsCurrTempList0 >>= 1) 
949            {
950              length ++;
951            }
952            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
953            {
954              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
955            }
956          }
957        }
958      }
959      if(pcSlice->isInterB())
960      {   
961        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
962        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
963        {
964          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
965          if ( numRpsCurrTempList1 > 1 )
966          {
967            Int length = 1;
968            numRpsCurrTempList1 --;
969            while ( numRpsCurrTempList1 >>= 1)
970            {
971              length ++;
972            }
973            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
974            {
975              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
976            }
977          }
978        }
979      }
980    }
981#if !SLICEHEADER_SYNTAX_FIX
982  }
983#endif
984   
985    if (pcSlice->isInterB())
986    {
987      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
988    }
989
990    if(!pcSlice->isIntra())
991    {
992      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
993      {
994        SliceType sliceType   = pcSlice->getSliceType();
995        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
996        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
997        pcSlice->setCabacInitFlag( encCabacInitFlag );
998        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
999      }
1000    }
1001
1002#if !SLICEHEADER_SYNTAX_FIX
1003  // if( !lightweight_slice_flag ) {
1004  if (!bDependentSlice)
1005  {
1006#else
1007    if ( pcSlice->getEnableTMVPFlag() )
1008    {
1009      if ( pcSlice->getSliceType() == B_SLICE )
1010      {
1011        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1012      }
1013
1014      if ( pcSlice->getSliceType() != I_SLICE &&
1015        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1016        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1017      {
1018        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1019      }
1020    }
1021    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1022    {
1023      xCodePredWeightTable( pcSlice );
1024    }
1025    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1026    WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1027#endif
1028    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
1029    WRITE_SVLC( iCode, "slice_qp_delta" ); 
1030#if CHROMA_QP_EXTENSION
1031    if (pcSlice->getPPS()->getSliceChromaQpFlag())
1032    {
1033      iCode = pcSlice->getSliceQpDeltaCb();
1034      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
1035      iCode = pcSlice->getSliceQpDeltaCr();
1036      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
1037    }
1038#endif
1039    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
1040    {
1041      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
1042      {
1043        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
1044      }
1045      if (pcSlice->getDeblockingFilterOverrideFlag())
1046      {
1047        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
1048        if(!pcSlice->getDeblockingFilterDisable())
1049        {
1050          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "beta_offset_div2");
1051          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "tc_offset_div2");
1052        }
1053      }
1054    }
1055#if !SLICEHEADER_SYNTAX_FIX
1056    if ( pcSlice->getEnableTMVPFlag() )
1057    {
1058      if ( pcSlice->getSliceType() == B_SLICE )
1059      {
1060        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
1061      }
1062
1063      if ( pcSlice->getSliceType() != I_SLICE &&
1064         ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
1065         (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
1066      {
1067        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
1068      }
1069    }
1070    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
1071    {
1072      xCodePredWeightTable( pcSlice );
1073    }
1074  }
1075    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
1076    WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
1077#endif
1078
1079#if !REMOVE_ALF
1080  if (!bDependentSlice)
1081  {
1082    if (pcSlice->getSPS()->getUseALF())
1083    {
1084      char syntaxString[50];
1085      for(Int compIdx=0; compIdx< 3; compIdx++)
1086      {
1087        sprintf(syntaxString, "alf_slice_filter_flag[%d]", compIdx);
1088        WRITE_FLAG( pcSlice->getAlfEnabledFlag(compIdx)?1:0, syntaxString );
1089      }
1090    }
1091  }
1092#endif
1093#if !SLICEHEADER_SYNTAX_FIX
1094  if(!bDependentSlice)
1095  {
1096#endif
1097#if !REMOVE_ALF
1098    Bool isAlfEnabled = (!pcSlice->getSPS()->getUseALF())?(false):(pcSlice->getAlfEnabledFlag(0)||pcSlice->getAlfEnabledFlag(1)||pcSlice->getAlfEnabledFlag(2));
1099#endif
1100#if !SAO_LUM_CHROMA_ONOFF_FLAGS
1101    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag());
1102#else
1103    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
1104#endif
1105    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
1106
1107#if REMOVE_ALF
1108#if MOVE_LOOP_FILTER_SLICES_FLAG
1109    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
1110#else
1111    if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isSAOEnabled || isDBFEnabled ))
1112#endif
1113#else
1114    if(pcSlice->getSPS()->getLFCrossSliceBoundaryFlag() && ( isAlfEnabled || isSAOEnabled || isDBFEnabled ))
1115#endif
1116    {
1117      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
1118    }
1119  }
1120#if SLICE_HEADER_EXTENSION
1121  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
1122  {
1123    WRITE_UVLC(0,"slice_header_extension_length");
1124  }
1125#endif
1126}
1127
1128#if PROFILE_TIER_LEVEL_SYNTAX
1129Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
1130{
1131  if(profilePresentFlag)
1132  {
1133    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
1134  }
1135  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
1136
1137  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
1138  {
1139    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
1140    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
1141    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
1142    {
1143      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
1144    }
1145    if( pcPTL->getSubLayerLevelPresentFlag(i) )
1146    {
1147      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
1148    }
1149  }
1150}
1151Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
1152{
1153  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
1154  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
1155  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
1156  for(Int j = 0; j < 32; j++)
1157  {
1158    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
1159  }
1160  WRITE_CODE(0 , 16, "XXX_reserved_zero_16bits[]"); 
1161}
1162#endif
1163
1164/**
1165 - write wavefront substreams sizes for the slice header.
1166 .
1167 \param pcSlice Where we find the substream size information.
1168 */
1169Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
1170{
1171#if TILES_WPP_ENTROPYSLICES_FLAGS
1172  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1173#else
1174  Int tilesOrEntropyCodingSyncIdc = pSlice->getPPS()->getTilesOrEntropyCodingSyncIdc();
1175  if ( tilesOrEntropyCodingSyncIdc == 0 )
1176#endif
1177  {
1178    return;
1179  }
1180  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
1181  Int  numZeroSubstreamsAtStartOfSlice  = 0;
1182  UInt *entryPointOffset = NULL;
1183#if TILES_WPP_ENTROPYSLICES_FLAGS
1184  if ( pSlice->getPPS()->getTilesEnabledFlag() )
1185#else
1186  if (tilesOrEntropyCodingSyncIdc == 1) // tiles
1187#endif
1188  {
1189    numEntryPointOffsets = pSlice->getTileLocationCount();
1190    entryPointOffset     = new UInt[numEntryPointOffsets];
1191    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
1192    {
1193      if ( idx == 0 )
1194      {
1195        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
1196      }
1197      else
1198      {
1199        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
1200      }
1201
1202      if ( entryPointOffset[ idx ] > maxOffset )
1203      {
1204        maxOffset = entryPointOffset[ idx ];
1205      }
1206    }
1207  }
1208#if TILES_WPP_ENTROPYSLICES_FLAGS
1209  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
1210#else
1211  else if (tilesOrEntropyCodingSyncIdc == 2) // wavefront
1212#endif
1213  {
1214    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
1215    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
1216#if DEPENDENT_SLICES
1217    numZeroSubstreamsAtStartOfSlice       = pSlice->getDependentSliceCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1218    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getDependentSliceCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1219#else
1220    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
1221    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
1222#endif
1223    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
1224    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
1225    entryPointOffset           = new UInt[numEntryPointOffsets];
1226    for (Int idx=0; idx<numEntryPointOffsets; idx++)
1227    {
1228      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
1229      if ( entryPointOffset[ idx ] > maxOffset )
1230      {
1231        maxOffset = entryPointOffset[ idx ];
1232      }
1233    }
1234  }
1235  // Determine number of bits "offsetLenMinus1+1" required for entry point information
1236  offsetLenMinus1 = 0;
1237  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
1238  {
1239    offsetLenMinus1++;
1240    assert(offsetLenMinus1 + 1 < 32);   
1241  }
1242
1243  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
1244  if (numEntryPointOffsets>0)
1245  {
1246    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
1247  }
1248
1249  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
1250  {
1251    WRITE_CODE(entryPointOffset[ idx ], offsetLenMinus1+1, "entry_point_offset");
1252  }
1253
1254  delete [] entryPointOffset;
1255}
1256
1257Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
1258{
1259}
1260
1261Void TEncCavlc::codeSliceFinish ()
1262{
1263}
1264
1265Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1266{
1267  assert(0);
1268}
1269
1270Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1271{
1272  assert(0);
1273}
1274
1275Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
1276{
1277  assert(0);
1278}
1279
1280Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1281{
1282  assert(0);
1283}
1284
1285Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
1286{
1287  assert(0);
1288}
1289
1290Void TEncCavlc::codeApsExtensionFlag ()
1291{
1292  WRITE_FLAG(0, "aps_extension_flag");
1293}
1294
1295Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
1296{
1297  assert(0);
1298}
1299
1300Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1301{
1302  assert(0);
1303}
1304
1305Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1306{
1307  assert(0);
1308}
1309
1310#if INTRA_BL
1311Void TEncCavlc::codeIntraBLFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
1312{
1313  assert(0);
1314}
1315
1316#endif
1317Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
1318{
1319  assert(0);
1320}
1321
1322Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
1323{
1324  assert(0);
1325}
1326
1327Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1328{
1329  assert(0);
1330}
1331
1332Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1333{
1334  assert(0);
1335}
1336
1337#if TU_ZERO_CBF_RDO
1338Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
1339{
1340  assert(0);
1341}
1342Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU, UInt uiAbsPartIdx )
1343{
1344  assert(0);
1345}
1346#endif
1347
1348Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType )
1349{
1350  assert(0);
1351}
1352
1353/** Code I_PCM information.
1354 * \param pcCU pointer to CU
1355 * \param uiAbsPartIdx CU index
1356 * \param numIPCM the number of succesive IPCM blocks with the same size
1357 * \param firstIPCMFlag
1358 * \returns Void
1359 */
1360Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Int numIPCM, Bool firstIPCMFlag)
1361{
1362  assert(0);
1363}
1364
1365Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
1366{
1367  assert(0);
1368}
1369
1370Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
1371{
1372  assert(0);
1373}
1374
1375Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
1376{
1377  assert(0);
1378}
1379
1380Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1381{
1382  assert(0);
1383}
1384
1385Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
1386{
1387  assert(0);
1388}
1389
1390Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
1391{
1392  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
1393
1394  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
1395  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
1396
1397  xWriteSvlc( iDQp );
1398 
1399  return;
1400}
1401
1402Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
1403{
1404  assert(0);
1405}
1406
1407Void TEncCavlc::xGolombEncode(Int coeff, Int k)
1408{
1409  xWriteEpExGolomb((UInt)abs(coeff), k);
1410  if(coeff != 0)
1411  {
1412    Int sign = (coeff > 0)? 1: 0;
1413    xWriteFlag(sign);
1414  }
1415#if ENC_DEC_TRACE
1416  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
1417  fprintf( g_hTrace, "%-40s se(v) : %d\n", "alf_filt_coeff", coeff ); 
1418#endif
1419
1420}
1421
1422#if !REMOVE_ALF
1423Void TEncCavlc::codeAlfParam(ALFParam* alfParam)
1424{
1425  char syntaxString[50];
1426  sprintf(syntaxString, "alf_aps_filter_flag[%d]", alfParam->componentID);
1427  WRITE_FLAG(alfParam->alf_flag, syntaxString);
1428  if(alfParam->alf_flag == 0)
1429  {
1430    return;
1431  }
1432
1433  const Int numCoeff = (Int)ALF_MAX_NUM_COEF;
1434  switch(alfParam->componentID)
1435  {
1436  case ALF_Cb:
1437  case ALF_Cr:
1438    {
1439      for(Int pos=0; pos< numCoeff; pos++)
1440      {
1441        WRITE_SVLC(alfParam->coeffmulti[0][pos], "alf_filt_coeff");
1442      }
1443    }
1444    break;
1445  case ALF_Y:
1446    {
1447      Int noFilters = min(alfParam->filters_per_group-1, 2);
1448      WRITE_UVLC(noFilters, "alf_no_filters_minus1");
1449      if(noFilters == 1)
1450      {
1451        WRITE_UVLC(alfParam->startSecondFilter, "alf_start_second_filter");
1452      }
1453      else if (noFilters == 2)
1454      {
1455        Int numMergeFlags = 16;
1456        for (Int i=1; i<numMergeFlags; i++) 
1457        {
1458          WRITE_FLAG(alfParam->filterPattern[i], "alf_filter_pattern");
1459        }
1460      }
1461      for(Int f=0; f< alfParam->filters_per_group; f++)
1462      {
1463        for(Int pos=0; pos< numCoeff; pos++)
1464        {
1465          xGolombEncode(alfParam->coeffmulti[f][pos], kTableTabShapes[ALF_CROSS9x7_SQUARE3x3][pos]);
1466        }
1467      }
1468    }
1469    break;
1470  default:
1471    {
1472      printf("Not a legal component ID\n");
1473      assert(0);
1474      exit(-1);
1475    }
1476  }
1477
1478}
1479#endif
1480
1481Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
1482{
1483  // printf("error : no VLC mode support in this version\n");
1484  return;
1485}
1486
1487// ====================================================================================================================
1488// Protected member functions
1489// ====================================================================================================================
1490
1491
1492/** Write PCM alignment bits.
1493 * \returns Void
1494 */
1495Void  TEncCavlc::xWritePCMAlignZero    ()
1496{
1497  m_pcBitIf->writeAlignZero();
1498}
1499
1500Void TEncCavlc::xWriteUnaryMaxSymbol( UInt uiSymbol, UInt uiMaxSymbol )
1501{
1502  if (uiMaxSymbol == 0)
1503  {
1504    return;
1505  }
1506  xWriteFlag( uiSymbol ? 1 : 0 );
1507  if ( uiSymbol == 0 )
1508  {
1509    return;
1510  }
1511 
1512  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
1513 
1514  while( --uiSymbol )
1515  {
1516    xWriteFlag( 1 );
1517  }
1518  if( bCodeLast )
1519  {
1520    xWriteFlag( 0 );
1521  }
1522  return;
1523}
1524
1525Void TEncCavlc::xWriteExGolombLevel( UInt uiSymbol )
1526{
1527  if( uiSymbol )
1528  {
1529    xWriteFlag( 1 );
1530    UInt uiCount = 0;
1531    Bool bNoExGo = (uiSymbol < 13);
1532   
1533    while( --uiSymbol && ++uiCount < 13 )
1534    {
1535      xWriteFlag( 1 );
1536    }
1537    if( bNoExGo )
1538    {
1539      xWriteFlag( 0 );
1540    }
1541    else
1542    {
1543      xWriteEpExGolomb( uiSymbol, 0 );
1544    }
1545  }
1546  else
1547  {
1548    xWriteFlag( 0 );
1549  }
1550  return;
1551}
1552
1553Void TEncCavlc::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
1554{
1555  while( uiSymbol >= (UInt)(1<<uiCount) )
1556  {
1557    xWriteFlag( 1 );
1558    uiSymbol -= 1<<uiCount;
1559    uiCount  ++;
1560  }
1561  xWriteFlag( 0 );
1562  while( uiCount-- )
1563  {
1564    xWriteFlag( (uiSymbol>>uiCount) & 1 );
1565  }
1566  return;
1567}
1568
1569/** code explicit wp tables
1570 * \param TComSlice* pcSlice
1571 * \returns Void
1572 */
1573Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
1574{
1575  wpScalingParam  *wp;
1576  Bool            bChroma     = true; // color always present in HEVC ?
1577  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
1578  Bool            bDenomCoded  = false;
1579  UInt            uiMode = 0;
1580#if NUM_WP_LIMIT
1581  UInt            uiTotalSignalledWeightFlags = 0;
1582#endif
1583  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
1584  {
1585    uiMode = 1; // explicit
1586  }
1587  if(uiMode == 1)
1588  {
1589
1590    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
1591    {
1592      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1593
1594      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1595      {
1596        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1597        if ( !bDenomCoded ) 
1598        {
1599          Int iDeltaDenom;
1600          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
1601
1602          if( bChroma )
1603          {
1604            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
1605            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
1606          }
1607          bDenomCoded = true;
1608        }
1609        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
1610#if NUM_WP_LIMIT
1611        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
1612      }
1613      if (bChroma) 
1614      {
1615        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1616        {
1617          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1618          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1619          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
1620        }
1621      }
1622
1623      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
1624      {
1625        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
1626#endif
1627        if ( wp[0].bPresentFlag ) 
1628        {
1629          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
1630          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
1631          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
1632        }
1633
1634        if ( bChroma ) 
1635        {
1636#if !NUM_WP_LIMIT
1637          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
1638#endif
1639          if ( wp[1].bPresentFlag )
1640          {
1641            for ( Int j=1 ; j<3 ; j++ ) 
1642            {
1643              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
1644              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
1645
1646              Int shift = ((1<<(g_uiBitDepth+g_uiBitIncrement-1)));
1647              Int pred = ( shift - ( ( shift*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
1648              Int iDeltaChroma = (wp[j].iOffset - pred);
1649              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
1650            }
1651          }
1652        }
1653      }
1654    }
1655#if NUM_WP_LIMIT
1656    assert(uiTotalSignalledWeightFlags<=24);
1657#endif
1658  }
1659}
1660
1661/** code quantization matrix
1662 *  \param scalingList quantization matrix information
1663 */
1664Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
1665{
1666  UInt listId,sizeId;
1667  Bool scalingListPredModeFlag;
1668
1669#if SCALING_LIST_OUTPUT_RESULT
1670  Int startBit;
1671  Int startTotalBit;
1672  startBit = m_pcBitIf->getNumberOfWrittenBits();
1673  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
1674#endif
1675
1676    //for each size
1677    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
1678    {
1679      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
1680      {
1681#if SCALING_LIST_OUTPUT_RESULT
1682        startBit = m_pcBitIf->getNumberOfWrittenBits();
1683#endif
1684        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
1685        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
1686        if(!scalingListPredModeFlag)// Copy Mode
1687        {
1688          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
1689        }
1690        else// DPCM Mode
1691        {
1692          xCodeScalingList(scalingList, sizeId, listId);
1693        }
1694#if SCALING_LIST_OUTPUT_RESULT
1695        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
1696#endif
1697      }
1698    }
1699#if SCALING_LIST_OUTPUT_RESULT
1700  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
1701#endif
1702  return;
1703}
1704/** code DPCM
1705 * \param scalingList quantization matrix information
1706 * \param sizeIdc size index
1707 * \param listIdc list index
1708 */
1709Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
1710{
1711  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
1712#if REMOVE_ZIGZAG_SCAN
1713  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
1714#else
1715  UInt* scan    = g_auiFrameScanXY [ (sizeId == 0)? 1 : 2];
1716#endif
1717  Int nextCoef = SCALING_LIST_START_VALUE;
1718  Int data;
1719  Int *src = scalingList->getScalingListAddress(sizeId, listId);
1720    if( sizeId > SCALING_LIST_8x8 )
1721    {
1722      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
1723      nextCoef = scalingList->getScalingListDC(sizeId,listId);
1724    }
1725    for(Int i=0;i<coefNum;i++)
1726    {
1727      data = src[scan[i]] - nextCoef;
1728      nextCoef = src[scan[i]];
1729      if(data > 127)
1730      {
1731        data = data - 256;
1732      }
1733      if(data < -128)
1734      {
1735        data = data + 256;
1736      }
1737
1738      WRITE_SVLC( data,  "scaling_list_delta_coef");
1739    }
1740}
1741#if LTRP_IN_SPS
1742Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
1743{
1744  // bool state = true, state2 = false;
1745  Int lsb = ltrpPOC % (1<<pcSlice->getSPS()->getBitsForPOC());
1746  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
1747  {
1748    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
1749    {
1750      *ltrpsIndex = k;
1751      return true;
1752    }
1753  }
1754  return false;
1755}
1756#endif
1757Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
1758{
1759  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
1760  {
1761    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
1762      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
1763     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
1764    {
1765      setRefMatrixId(sizeId, listId, predListIdx);
1766      return false;
1767    }
1768  }
1769  return true;
1770}
1771//! \}
Note: See TracBrowser for help on using the repository browser.