source: 3DVCSoftware/branches/HTM-15.1-MV-draft-4/source/Lib/TLibEncoder/TEncSbac.cpp @ 1389

Last change on this file since 1389 was 1325, checked in by tech, 10 years ago

Removed 3D-HEVC.

  • Property svn:eol-style set to native
File size: 72.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-2015, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncSbac.cpp
35    \brief    SBAC encoder class
36*/
37
38#include "TEncTop.h"
39#include "TEncSbac.h"
40#include "TLibCommon/TComTU.h"
41
42#include <map>
43#include <algorithm>
44
45#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
46#include "../TLibCommon/Debug.h"
47#endif
48
49
50//! \ingroup TLibEncoder
51//! \{
52
53// ====================================================================================================================
54// Constructor / destructor / create / destroy
55// ====================================================================================================================
56
57TEncSbac::TEncSbac()
58// new structure here
59: m_pcBitIf                            ( NULL )
60, m_pcBinIf                            ( NULL )
61, m_numContextModels                   ( 0 )
62, m_cCUSplitFlagSCModel                ( 1,             1,                      NUM_SPLIT_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
63, m_cCUSkipFlagSCModel                 ( 1,             1,                      NUM_SKIP_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
64, m_cCUMergeFlagExtSCModel             ( 1,             1,                      NUM_MERGE_FLAG_EXT_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
65, m_cCUMergeIdxExtSCModel              ( 1,             1,                      NUM_MERGE_IDX_EXT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
66, m_cCUPartSizeSCModel                 ( 1,             1,                      NUM_PART_SIZE_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
67, m_cCUPredModeSCModel                 ( 1,             1,                      NUM_PRED_MODE_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
68, m_cCUIntraPredSCModel                ( 1,             1,                      NUM_INTRA_PREDICT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
69, m_cCUChromaPredSCModel               ( 1,             1,                      NUM_CHROMA_PRED_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
70, m_cCUDeltaQpSCModel                  ( 1,             1,                      NUM_DELTA_QP_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
71, m_cCUInterDirSCModel                 ( 1,             1,                      NUM_INTER_DIR_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
72, m_cCURefPicSCModel                   ( 1,             1,                      NUM_REF_NO_CTX                       , m_contextModels + m_numContextModels, m_numContextModels)
73, m_cCUMvdSCModel                      ( 1,             1,                      NUM_MV_RES_CTX                       , m_contextModels + m_numContextModels, m_numContextModels)
74, m_cCUQtCbfSCModel                    ( 1,             NUM_QT_CBF_CTX_SETS,    NUM_QT_CBF_CTX_PER_SET               , m_contextModels + m_numContextModels, m_numContextModels)
75, m_cCUTransSubdivFlagSCModel          ( 1,             1,                      NUM_TRANS_SUBDIV_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
76, m_cCUQtRootCbfSCModel                ( 1,             1,                      NUM_QT_ROOT_CBF_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
77, m_cCUSigCoeffGroupSCModel            ( 1,             2,                      NUM_SIG_CG_FLAG_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
78, m_cCUSigSCModel                      ( 1,             1,                      NUM_SIG_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
79, m_cCuCtxLastX                        ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
80, m_cCuCtxLastY                        ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
81, m_cCUOneSCModel                      ( 1,             1,                      NUM_ONE_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
82, m_cCUAbsSCModel                      ( 1,             1,                      NUM_ABS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
83, m_cMVPIdxSCModel                     ( 1,             1,                      NUM_MVP_IDX_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
84, m_cSaoMergeSCModel                   ( 1,             1,                      NUM_SAO_MERGE_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
85, m_cSaoTypeIdxSCModel                 ( 1,             1,                      NUM_SAO_TYPE_IDX_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
86, m_cTransformSkipSCModel              ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_TRANSFORMSKIP_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
87, m_CUTransquantBypassFlagSCModel      ( 1,             1,                      NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
88, m_explicitRdpcmFlagSCModel           ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_FLAG_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
89, m_explicitRdpcmDirSCModel            ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_DIR_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
90, m_cCrossComponentPredictionSCModel   ( 1,             1,                      NUM_CROSS_COMPONENT_PREDICTION_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
91, m_ChromaQpAdjFlagSCModel             ( 1,             1,                      NUM_CHROMA_QP_ADJ_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
92, m_ChromaQpAdjIdcSCModel              ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
93
94{
95  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
96}
97
98TEncSbac::~TEncSbac()
99{
100}
101
102// ====================================================================================================================
103// Public member functions
104// ====================================================================================================================
105
106Void TEncSbac::resetEntropy           (const TComSlice *pSlice)
107{
108  Int  iQp              = pSlice->getSliceQp();
109  SliceType eSliceType  = pSlice->getSliceType();
110
111  SliceType encCABACTableIdx = pSlice->getEncCABACTableIdx();
112  if (!pSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && pSlice->getPPS()->getCabacInitPresentFlag())
113  {
114    eSliceType = encCABACTableIdx;
115  }
116
117  m_cCUSplitFlagSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
118  m_cCUSkipFlagSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
119  m_cCUMergeFlagExtSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
120  m_cCUMergeIdxExtSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
121  m_cCUPartSizeSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
122  m_cCUPredModeSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
123  m_cCUIntraPredSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
124  m_cCUChromaPredSCModel.initBuffer               ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
125  m_cCUInterDirSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
126  m_cCUMvdSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_MVD );
127  m_cCURefPicSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
128  m_cCUDeltaQpSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DQP );
129  m_cCUQtCbfSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
130  m_cCUQtRootCbfSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
131  m_cCUSigCoeffGroupSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
132  m_cCUSigSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
133  m_cCuCtxLastX.initBuffer                        ( eSliceType, iQp, (UChar*)INIT_LAST );
134  m_cCuCtxLastY.initBuffer                        ( eSliceType, iQp, (UChar*)INIT_LAST );
135  m_cCUOneSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
136  m_cCUAbsSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
137  m_cMVPIdxSCModel.initBuffer                     ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
138  m_cCUTransSubdivFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
139  m_cSaoMergeSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
140  m_cSaoTypeIdxSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
141  m_cTransformSkipSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
142  m_CUTransquantBypassFlagSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
143  m_explicitRdpcmFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
144  m_explicitRdpcmDirSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
145  m_cCrossComponentPredictionSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION  );
146  m_ChromaQpAdjFlagSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
147  m_ChromaQpAdjIdcSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
148
149
150  for (UInt statisticIndex = 0; statisticIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS ; statisticIndex++)
151  {
152    m_golombRiceAdaptationStatistics[statisticIndex] = 0;
153  }
154
155  m_pcBinIf->start();
156
157  return;
158}
159
160/** The function does the following:
161 * If current slice type is P/B then it determines the distance of initialisation type 1 and 2 from the current CABAC states and
162 * stores the index of the closest table.  This index is used for the next P/B slice when cabac_init_present_flag is true.
163 */
164SliceType TEncSbac::determineCabacInitIdx(const TComSlice *pSlice)
165{
166  Int  qp              = pSlice->getSliceQp();
167
168  if (!pSlice->isIntra())
169  {
170    SliceType aSliceTypeChoices[] = {B_SLICE, P_SLICE};
171
172    UInt bestCost             = MAX_UINT;
173    SliceType bestSliceType   = aSliceTypeChoices[0];
174    for (UInt idx=0; idx<2; idx++)
175    {
176      UInt curCost          = 0;
177      SliceType curSliceType  = aSliceTypeChoices[idx];
178
179      curCost  = m_cCUSplitFlagSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG );
180      curCost += m_cCUSkipFlagSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG );
181      curCost += m_cCUMergeFlagExtSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
182      curCost += m_cCUMergeIdxExtSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
183      curCost += m_cCUPartSizeSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
184      curCost += m_cCUPredModeSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
185      curCost += m_cCUIntraPredSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
186      curCost += m_cCUChromaPredSCModel.calcCost               ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
187      curCost += m_cCUInterDirSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_INTER_DIR );
188      curCost += m_cCUMvdSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_MVD );
189      curCost += m_cCURefPicSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_REF_PIC );
190      curCost += m_cCUDeltaQpSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DQP );
191      curCost += m_cCUQtCbfSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_QT_CBF );
192      curCost += m_cCUQtRootCbfSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
193      curCost += m_cCUSigCoeffGroupSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
194      curCost += m_cCUSigSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_SIG_FLAG );
195      curCost += m_cCuCtxLastX.calcCost                        ( curSliceType, qp, (UChar*)INIT_LAST );
196      curCost += m_cCuCtxLastY.calcCost                        ( curSliceType, qp, (UChar*)INIT_LAST );
197      curCost += m_cCUOneSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_ONE_FLAG );
198      curCost += m_cCUAbsSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_ABS_FLAG );
199      curCost += m_cMVPIdxSCModel.calcCost                     ( curSliceType, qp, (UChar*)INIT_MVP_IDX );
200      curCost += m_cCUTransSubdivFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
201      curCost += m_cSaoMergeSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
202      curCost += m_cSaoTypeIdxSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
203      curCost += m_cTransformSkipSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
204      curCost += m_CUTransquantBypassFlagSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
205      curCost += m_explicitRdpcmFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
206      curCost += m_explicitRdpcmDirSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
207      curCost += m_cCrossComponentPredictionSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION );
208      curCost += m_ChromaQpAdjFlagSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
209      curCost += m_ChromaQpAdjIdcSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
210
211      if (curCost < bestCost)
212      {
213        bestSliceType = curSliceType;
214        bestCost      = curCost;
215      }
216    }
217    return bestSliceType;
218  }
219  else
220  {
221    return I_SLICE;
222  }
223}
224
225
226Void TEncSbac::codeVPS( const TComVPS* /*pcVPS*/ )
227{
228  assert (0);
229  return;
230}
231
232Void TEncSbac::codeSPS( const TComSPS* /*pcSPS*/ )
233{
234  assert (0);
235  return;
236}
237
238Void TEncSbac::codePPS( const TComPPS* /*pcPPS*/ )
239{
240  assert (0);
241  return;
242}
243
244Void TEncSbac::codeSliceHeader( TComSlice* /*pcSlice*/ )
245{
246  assert (0);
247  return;
248}
249
250Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* /*pSlice*/ )
251{
252  assert (0);
253  return;
254}
255
256Void TEncSbac::codeTerminatingBit( UInt uilsLast )
257{
258  m_pcBinIf->encodeBinTrm( uilsLast );
259}
260
261Void TEncSbac::codeSliceFinish()
262{
263  m_pcBinIf->finish();
264}
265
266Void TEncSbac::xWriteUnarySymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset )
267{
268  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[0] );
269
270  if( 0 == uiSymbol)
271  {
272    return;
273  }
274
275  while( uiSymbol-- )
276  {
277    m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ iOffset ] );
278  }
279
280  return;
281}
282
283Void TEncSbac::xWriteUnaryMaxSymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
284{
285  if (uiMaxSymbol == 0)
286  {
287    return;
288  }
289
290  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ 0 ] );
291
292  if ( uiSymbol == 0 )
293  {
294    return;
295  }
296
297  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
298
299  while( --uiSymbol )
300  {
301    m_pcBinIf->encodeBin( 1, pcSCModel[ iOffset ] );
302  }
303  if( bCodeLast )
304  {
305    m_pcBinIf->encodeBin( 0, pcSCModel[ iOffset ] );
306  }
307
308  return;
309}
310
311Void TEncSbac::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
312{
313  UInt bins = 0;
314  Int numBins = 0;
315
316  while( uiSymbol >= (UInt)(1<<uiCount) )
317  {
318    bins = 2 * bins + 1;
319    numBins++;
320    uiSymbol -= 1 << uiCount;
321    uiCount  ++;
322  }
323  bins = 2 * bins + 0;
324  numBins++;
325
326  bins = (bins << uiCount) | uiSymbol;
327  numBins += uiCount;
328
329  assert( numBins <= 32 );
330  m_pcBinIf->encodeBinsEP( bins, numBins );
331}
332
333
334
335/** Coding of coeff_abs_level_minus3
336 * \param symbol                  value of coeff_abs_level_minus3
337 * \param rParam                  reference to Rice parameter
338 * \param useLimitedPrefixLength
339 * \param maxLog2TrDynamicRange
340 */
341Void TEncSbac::xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange )
342{
343  Int codeNumber  = (Int)symbol;
344  UInt length;
345
346  if (codeNumber < (COEF_REMAIN_BIN_REDUCTION << rParam))
347  {
348    length = codeNumber>>rParam;
349    m_pcBinIf->encodeBinsEP( (1<<(length+1))-2 , length+1);
350    m_pcBinIf->encodeBinsEP((codeNumber%(1<<rParam)),rParam);
351  }
352  else if (useLimitedPrefixLength)
353  {
354    const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange));
355
356    UInt prefixLength = 0;
357    UInt suffixLength = MAX_UINT;
358    UInt codeValue    = (symbol >> rParam) - COEF_REMAIN_BIN_REDUCTION;
359
360    if (codeValue >= ((1 << maximumPrefixLength) - 1))
361    {
362      prefixLength = maximumPrefixLength;
363      suffixLength = maxLog2TrDynamicRange - rParam;
364    }
365    else
366    {
367      while (codeValue > ((2 << prefixLength) - 2))
368      {
369        prefixLength++;
370      }
371
372      suffixLength = prefixLength + 1; //+1 for the separator bit
373    }
374
375    const UInt suffix = codeValue - ((1 << prefixLength) - 1);
376
377    const UInt totalPrefixLength = prefixLength + COEF_REMAIN_BIN_REDUCTION;
378    const UInt prefix            = (1 << totalPrefixLength) - 1;
379    const UInt rParamBitMask     = (1 << rParam) - 1;
380
381    m_pcBinIf->encodeBinsEP(  prefix,                                        totalPrefixLength      ); //prefix
382    m_pcBinIf->encodeBinsEP(((suffix << rParam) | (symbol & rParamBitMask)), (suffixLength + rParam)); //separator, suffix, and rParam bits
383  }
384  else
385  {
386    length = rParam;
387    codeNumber  = codeNumber - ( COEF_REMAIN_BIN_REDUCTION << rParam);
388
389    while (codeNumber >= (1<<length))
390    {
391      codeNumber -=  (1<<(length++));
392    }
393
394    m_pcBinIf->encodeBinsEP((1<<(COEF_REMAIN_BIN_REDUCTION+length+1-rParam))-2,COEF_REMAIN_BIN_REDUCTION+length+1-rParam);
395    m_pcBinIf->encodeBinsEP(codeNumber,length);
396  }
397}
398// SBAC RD
399Void  TEncSbac::load ( const TEncSbac* pSrc)
400{
401  this->xCopyFrom(pSrc);
402}
403
404Void  TEncSbac::loadIntraDirMode( const TEncSbac* pSrc, const ChannelType chType )
405{
406  m_pcBinIf->copyState( pSrc->m_pcBinIf );
407  if (isLuma(chType))
408  {
409    this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
410  }
411  else
412  {
413    this->m_cCUChromaPredSCModel     .copyFrom( &pSrc->m_cCUChromaPredSCModel      );
414  }
415}
416
417
418
419Void  TEncSbac::store( TEncSbac* pDest) const
420{
421  pDest->xCopyFrom( this );
422}
423
424
425Void TEncSbac::xCopyFrom( const TEncSbac* pSrc )
426{
427  m_pcBinIf->copyState( pSrc->m_pcBinIf );
428  xCopyContextsFrom(pSrc);
429}
430
431Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
432{
433  Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx);
434  Int iNum = AMVP_MAX_NUM_CANDS;
435
436  xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1);
437#if H_MV_ENC_DEC_TRAC
438#if ENC_DEC_TRACE
439  if ( eRefList == REF_PIC_LIST_0 )
440  {
441    DTRACE_PU("mvp_l0_flag", iSymbol)
442  }
443  else
444  {
445    DTRACE_PU("mvp_l1_flag", iSymbol)
446  }
447#endif
448#endif
449}
450
451Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
452{
453  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
454  const UInt log2DiffMaxMinCodingBlockSize = pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize();
455
456  if ( pcCU->isIntra( uiAbsPartIdx ) )
457  {
458    if( uiDepth == log2DiffMaxMinCodingBlockSize )
459    {
460      m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
461#if H_MV_ENC_DEC_TRAC
462      DTRACE_CU("part_mode", eSize == SIZE_2Nx2N? 1 : 0)
463#endif       
464
465    }
466    return;
467  }
468#if H_MV_ENC_DEC_TRAC         
469  DTRACE_CU("part_mode", eSize )
470#endif       
471
472  switch(eSize)
473  {
474    case SIZE_2Nx2N:
475    {
476      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
477      break;
478    }
479    case SIZE_2NxN:
480    case SIZE_2NxnU:
481    case SIZE_2NxnD:
482    {
483      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
484      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
485      if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
486      {
487        if (eSize == SIZE_2NxN)
488        {
489          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
490        }
491        else
492        {
493          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
494          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
495        }
496      }
497      break;
498    }
499    case SIZE_Nx2N:
500    case SIZE_nLx2N:
501    case SIZE_nRx2N:
502    {
503      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
504      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
505
506      if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
507      {
508        m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
509      }
510
511      if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
512      {
513        if (eSize == SIZE_Nx2N)
514        {
515          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
516        }
517        else
518        {
519          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
520          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
521        }
522      }
523      break;
524    }
525    case SIZE_NxN:
526    {
527      if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
528      {
529        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
530        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
531        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
532      }
533      break;
534    }
535    default:
536    {
537      assert(0);
538      break;
539    }
540  }
541
542}
543
544
545/** code prediction mode
546 * \param pcCU
547 * \param uiAbsPartIdx
548 * \returns Void
549 */
550Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
551{
552  // get context function is here
553  m_pcBinIf->encodeBin( pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
554#if H_MV_ENC_DEC_TRAC
555  DTRACE_CU("pred_mode_flag", pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0); 
556#endif
557
558}
559
560Void TEncSbac::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
561{
562  UInt uiSymbol = pcCU->getCUTransquantBypass(uiAbsPartIdx);
563  m_pcBinIf->encodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
564#if H_MV_ENC_DEC_TRAC
565  DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
566#endif
567
568}
569
570/** code skip flag
571 * \param pcCU
572 * \param uiAbsPartIdx
573 * \returns Void
574 */
575Void TEncSbac::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
576{
577  // get context function is here
578  UInt uiSymbol = pcCU->isSkipped( uiAbsPartIdx ) ? 1 : 0;
579  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx ) ;
580  m_pcBinIf->encodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
581#if !H_MV_ENC_DEC_TRAC
582  DTRACE_CABAC_VL( g_nSymbolCounter++ );
583  DTRACE_CABAC_T( "\tSkipFlag" );
584  DTRACE_CABAC_T( "\tuiCtxSkip: ");
585  DTRACE_CABAC_V( uiCtxSkip );
586  DTRACE_CABAC_T( "\tuiSymbol: ");
587  DTRACE_CABAC_V( uiSymbol );
588  DTRACE_CABAC_T( "\n");
589#else
590  DTRACE_CU("cu_skip_flag", uiSymbol); 
591#endif
592}
593
594/** code merge flag
595 * \param pcCU
596 * \param uiAbsPartIdx
597 * \returns Void
598 */
599Void TEncSbac::codeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
600{
601  const UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0;
602  m_pcBinIf->encodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
603
604#if H_MV_ENC_DEC_TRAC
605  DTRACE_PU("merge_flag", uiSymbol); 
606#else
607  DTRACE_CABAC_VL( g_nSymbolCounter++ );
608  DTRACE_CABAC_T( "\tMergeFlag: " );
609  DTRACE_CABAC_V( uiSymbol );
610  DTRACE_CABAC_T( "\tAddress: " );
611  DTRACE_CABAC_V( pcCU->getCtuRsAddr() );
612  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
613  DTRACE_CABAC_V( uiAbsPartIdx );
614  DTRACE_CABAC_T( "\n" );
615#endif
616}
617
618/** code merge index
619 * \param pcCU
620 * \param uiAbsPartIdx
621 * \returns Void
622 */
623Void TEncSbac::codeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx )
624{
625  UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx );
626  UInt uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
627  if ( uiNumCand > 1 )
628  {
629    for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
630    {
631      const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1;
632      if ( ui==0 )
633      {
634        m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
635      }
636      else
637      {
638        m_pcBinIf->encodeBinEP( uiSymbol );
639      }
640      if( uiSymbol == 0 )
641      {
642        break;
643      }
644    }
645#if H_MV_ENC_DEC_TRAC
646    DTRACE_PU("merge_idx", uiUnaryIdx); 
647#endif
648  }
649#if !H_MV_ENC_DEC_TRAC
650  DTRACE_CABAC_VL( g_nSymbolCounter++ );
651  DTRACE_CABAC_T( "\tparseMergeIndex()" );
652  DTRACE_CABAC_T( "\tuiMRGIdx= " );
653  DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) );
654  DTRACE_CABAC_T( "\n" );
655#endif
656}
657
658
659
660
661Void TEncSbac::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
662{
663  if( uiDepth == pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize() )
664  {
665    return;
666  }
667
668  UInt uiCtx           = pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth );
669  UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
670
671  assert( uiCtx < 3 );
672
673  m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
674#if !H_MV_ENC_DEC_TRAC
675  DTRACE_CABAC_VL( g_nSymbolCounter++ )
676  DTRACE_CABAC_T( "\tSplitFlag\n" )
677#else
678  DTRACE_CU("split_cu_flag", uiCurrSplitFlag ); 
679#endif
680  return;
681}
682
683Void TEncSbac::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
684{
685  m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) );
686#if !H_MV_ENC_DEC_TRAC
687  DTRACE_CABAC_VL( g_nSymbolCounter++ )
688  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
689  DTRACE_CABAC_T( "\tsymbol=" )
690  DTRACE_CABAC_V( uiSymbol )
691  DTRACE_CABAC_T( "\tctx=" )
692  DTRACE_CABAC_V( uiCtx )
693  DTRACE_CABAC_T( "\n" )
694#else
695  DTRACE_TU("split_transform_flag", uiSymbol )
696#endif
697
698}
699
700
701Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple)
702{
703  UInt dir[4],j;
704  Int preds[4][NUM_MOST_PROBABLE_MODES] = {{-1, -1, -1},{-1, -1, -1},{-1, -1, -1},{-1, -1, -1}};
705  Int predIdx[4] ={ -1,-1,-1,-1};
706  PartSize mode = pcCU->getPartitionSize( absPartIdx );
707  UInt partNum = isMultiple?(mode==SIZE_NxN?4:1):1;
708  UInt partOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
709  for (j=0;j<partNum;j++)
710  {
711    dir[j] = pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx+partOffset*j );
712    pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds[j], COMPONENT_Y);
713    for(UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++)
714    {
715      if(dir[j] == preds[j][i])
716      {
717        predIdx[j] = i;
718      }
719    }
720    m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
721#if H_MV_ENC_DEC_TRAC
722      DTRACE_CU("prev_intra_luma_pred_flag", (predIdx[j] != -1)? 1 : 0); 
723#endif
724
725  }
726  for (j=0;j<partNum;j++)
727  {
728    if(predIdx[j] != -1)
729    {
730      m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
731      if (predIdx[j])
732      {
733        m_pcBinIf->encodeBinEP( predIdx[j]-1 );
734      }
735#if H_MV_ENC_DEC_TRAC
736        DTRACE_CU("mpm_idx", predIdx[j] ); 
737#endif
738    }
739    else
740    {
741      if (preds[j][0] > preds[j][1])
742      {
743        std::swap(preds[j][0], preds[j][1]);
744      }
745      if (preds[j][0] > preds[j][2])
746      {
747        std::swap(preds[j][0], preds[j][2]);
748      }
749      if (preds[j][1] > preds[j][2])
750      {
751        std::swap(preds[j][1], preds[j][2]);
752      }
753      for(Int i = (Int(NUM_MOST_PROBABLE_MODES) - 1); i >= 0; i--)
754      {
755        dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
756      }
757      m_pcBinIf->encodeBinsEP( dir[j], 5 );
758#if H_MV_ENC_DEC_TRAC
759        DTRACE_CU("rem_intra_luma_pred_mode", dir[j] ); 
760#endif
761    }
762  }
763  return;
764}
765
766Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
767{
768  UInt uiIntraDirChroma = pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx );
769
770  if( uiIntraDirChroma == DM_CHROMA_IDX )
771  {
772    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
773#if H_MV_ENC_DEC_TRAC
774    DTRACE_CU("intra_chroma_pred_mode", 0 ); 
775#endif
776  }
777  else
778  {
779    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
780
781    UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
782    pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
783
784    for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ )
785    {
786      if( uiIntraDirChroma == uiAllowedChromaDir[i] )
787      {
788        uiIntraDirChroma = i;
789        break;
790      }
791    }
792
793    m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 );
794#if H_MV_ENC_DEC_TRAC
795    DTRACE_CU("intra_chroma_pred_mode", uiIntraDirChroma ); 
796#endif
797
798  }
799
800  return;
801}
802
803Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
804{
805  const UInt uiInterDir = pcCU->getInterDir( uiAbsPartIdx ) - 1;
806  const UInt uiCtx      = pcCU->getCtxInterDir( uiAbsPartIdx );
807  ContextModel *pCtx    = m_cCUInterDirSCModel.get( 0 );
808
809  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
810  {
811    m_pcBinIf->encodeBin( uiInterDir == 2 ? 1 : 0, *( pCtx + uiCtx ) );
812  }
813
814  if (uiInterDir < 2)
815  {
816    m_pcBinIf->encodeBin( uiInterDir, *( pCtx + 4 ) );
817  }
818#if H_MV_ENC_DEC_TRAC
819  DTRACE_PU("inter_pred_idc", uiInterDir ); 
820#endif
821
822  return;
823}
824
825Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
826{
827  Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
828  ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
829  m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
830
831  if( iRefFrame > 0 )
832  {
833    UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
834    pCtx++;
835    iRefFrame--;
836    for( UInt ui = 0; ui < uiRefNum; ++ui )
837    {
838      const UInt uiSymbol = ui == iRefFrame ? 0 : 1;
839      if( ui == 0 )
840      {
841        m_pcBinIf->encodeBin( uiSymbol, *pCtx );
842      }
843      else
844      {
845        m_pcBinIf->encodeBinEP( uiSymbol );
846      }
847      if( uiSymbol == 0 )
848      {
849        break;
850      }
851    }
852  }
853#if H_MV_ENC_DEC_TRAC
854#if ENC_DEC_TRACE
855    iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ); 
856    if ( eRefList == REF_PIC_LIST_0 )
857    {
858      DTRACE_PU("ref_idx_l0", iRefFrame)
859    }
860    else
861    {
862      DTRACE_PU("ref_idx_l1", iRefFrame)
863    }
864#endif
865#endif
866  return;
867}
868
869Void TEncSbac::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
870{
871  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
872  {
873    return;
874  }
875
876  const TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList );
877  const Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor();
878  const Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer();
879  ContextModel* pCtx = m_cCUMvdSCModel.get( 0 );
880
881  m_pcBinIf->encodeBin( iHor != 0 ? 1 : 0, *pCtx );
882  m_pcBinIf->encodeBin( iVer != 0 ? 1 : 0, *pCtx );
883
884  const Bool bHorAbsGr0 = iHor != 0;
885  const Bool bVerAbsGr0 = iVer != 0;
886  const UInt uiHorAbs   = 0 > iHor ? -iHor : iHor;
887  const UInt uiVerAbs   = 0 > iVer ? -iVer : iVer;
888  pCtx++;
889
890  if( bHorAbsGr0 )
891  {
892    m_pcBinIf->encodeBin( uiHorAbs > 1 ? 1 : 0, *pCtx );
893  }
894
895  if( bVerAbsGr0 )
896  {
897    m_pcBinIf->encodeBin( uiVerAbs > 1 ? 1 : 0, *pCtx );
898  }
899
900  if( bHorAbsGr0 )
901  {
902    if( uiHorAbs > 1 )
903    {
904      xWriteEpExGolomb( uiHorAbs-2, 1 );
905    }
906
907    m_pcBinIf->encodeBinEP( 0 > iHor ? 1 : 0 );
908  }
909
910  if( bVerAbsGr0 )
911  {
912    if( uiVerAbs > 1 )
913    {
914      xWriteEpExGolomb( uiVerAbs-2, 1 );
915    }
916
917    m_pcBinIf->encodeBinEP( 0 > iVer ? 1 : 0 );
918  }
919
920  return;
921}
922
923Void TEncSbac::codeCrossComponentPrediction( TComTU &rTu, ComponentID compID )
924{
925  TComDataCU *pcCU = rTu.getCU();
926
927  if( isLuma(compID) || !pcCU->getSlice()->getPPS()->getPpsRangeExtension().getCrossComponentPredictionEnabledFlag() )
928  {
929    return;
930  }
931
932  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
933
934  if (!pcCU->isIntra(uiAbsPartIdx) || (pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx ) == DM_CHROMA_IDX))
935  {
936    DTRACE_CABAC_VL( g_nSymbolCounter++ )
937    DTRACE_CABAC_T("\tparseCrossComponentPrediction()")
938    DTRACE_CABAC_T( "\tAddr=" )
939    DTRACE_CABAC_V( compID )
940    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
941    DTRACE_CABAC_V( uiAbsPartIdx )
942
943    Int alpha = pcCU->getCrossComponentPredictionAlpha( uiAbsPartIdx, compID );
944    ContextModel *pCtx = m_cCrossComponentPredictionSCModel.get(0, 0) + ((compID == COMPONENT_Cr) ? (NUM_CROSS_COMPONENT_PREDICTION_CTX >> 1) : 0);
945    m_pcBinIf->encodeBin(((alpha != 0) ? 1 : 0), pCtx[0]);
946
947    if (alpha != 0)
948    {
949      static const Int log2AbsAlphaMinus1Table[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
950      assert(abs(alpha) <= 8);
951
952      if (abs(alpha)>1)
953      {
954        m_pcBinIf->encodeBin(1, pCtx[1]);
955        xWriteUnaryMaxSymbol( log2AbsAlphaMinus1Table[abs(alpha) - 1] - 1, (pCtx + 2), 1, 2 );
956      }
957      else
958      {
959        m_pcBinIf->encodeBin(0, pCtx[1]);
960      }
961      m_pcBinIf->encodeBin( ((alpha < 0) ? 1 : 0), pCtx[4] );
962    }
963    DTRACE_CABAC_T( "\tAlpha=" )
964    DTRACE_CABAC_V( pcCU->getCrossComponentPredictionAlpha( uiAbsPartIdx, compID ) )
965    DTRACE_CABAC_T( "\n" )
966  }
967}
968
969Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
970{
971  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
972
973  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
974  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
975
976  UInt uiAbsDQp = (UInt)((iDQp > 0)? iDQp  : (-iDQp));
977  UInt TUValue = min((Int)uiAbsDQp, CU_DQP_TU_CMAX);
978  xWriteUnaryMaxSymbol( TUValue, &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX);
979  if( uiAbsDQp >= CU_DQP_TU_CMAX )
980  {
981    xWriteEpExGolomb( uiAbsDQp - CU_DQP_TU_CMAX, CU_DQP_EG_k );
982  }
983
984  if ( uiAbsDQp > 0)
985  {
986    UInt uiSign = (iDQp > 0 ? 0 : 1);
987    m_pcBinIf->encodeBinEP(uiSign);
988  }
989
990  return;
991}
992
993/** code chroma qp adjustment, converting from the internal table representation
994 * \returns Void
995 */
996Void TEncSbac::codeChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx )
997{
998  Int internalIdc = cu->getChromaQpAdj( absPartIdx );
999  Int chromaQpOffsetListLen = cu->getSlice()->getPPS()->getPpsRangeExtension().getChromaQpOffsetListLen();
1000  /* internal_idc == 0 => flag = 0
1001   * internal_idc > 1 => code idc value (if table size warrents) */
1002  m_pcBinIf->encodeBin( internalIdc > 0, m_ChromaQpAdjFlagSCModel.get( 0, 0, 0 ) );
1003
1004  if (internalIdc > 0 && chromaQpOffsetListLen > 1)
1005  {
1006    xWriteUnaryMaxSymbol( internalIdc - 1, &m_ChromaQpAdjIdcSCModel.get( 0, 0, 0 ), 0, chromaQpOffsetListLen - 1 );
1007  }
1008}
1009
1010Void TEncSbac::codeQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
1011{
1012  TComDataCU* pcCU = rTu.getCU();
1013
1014  const UInt absPartIdx   = rTu.GetAbsPartIdxTU(compID);
1015  const UInt TUDepth      = rTu.GetTransformDepthRel();
1016        UInt uiCtx        = pcCU->getCtxQtCbf( rTu, toChannelType(compID) );
1017  const UInt contextSet   = toChannelType(compID);
1018
1019  const UInt width        = rTu.getRect(compID).width;
1020  const UInt height       = rTu.getRect(compID).height;
1021  const Bool canQuadSplit = (width >= (MIN_TU_SIZE * 2)) && (height >= (MIN_TU_SIZE * 2));
1022
1023  //             Since the CBF for chroma is coded at the highest level possible, if sub-TUs are
1024  //             to be coded for a 4x8 chroma TU, their CBFs must be coded at the highest 4x8 level
1025  //             (i.e. where luma TUs are 8x8 rather than 4x4)
1026  //    ___ ___
1027  //   |   |   | <- 4 x (8x8 luma + 4x8 4:2:2 chroma)
1028  //   |___|___|    each quadrant has its own chroma CBF
1029  //   |   |   | _ _ _ _
1030  //   |___|___|        |
1031  //   <--16--->        V
1032  //                   _ _
1033  //                  |_|_| <- 4 x 4x4 luma + 1 x 4x8 4:2:2 chroma
1034  //                  |_|_|    no chroma CBF is coded - instead the parent CBF is inherited
1035  //                  <-8->    if sub-TUs are present, their CBFs had to be coded at the parent level
1036
1037  const UInt lowestTUDepth = TUDepth + ((!lowestLevel && !canQuadSplit) ? 1 : 0); //unsplittable TUs inherit their parent's CBF
1038
1039  if ((width != height) && (lowestLevel || !canQuadSplit)) //if sub-TUs are present
1040  {
1041    const UInt subTUDepth        = lowestTUDepth + 1;                      //if this is the lowest level of the TU-tree, the sub-TUs are directly below. Otherwise, this must be the level above the lowest level (as specified above)
1042    const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
1043
1044    for (UInt subTU = 0; subTU < 2; subTU++)
1045    {
1046      const UInt subTUAbsPartIdx = absPartIdx + (subTU * partIdxesPerSubTU);
1047      const UInt uiCbf           = pcCU->getCbf(subTUAbsPartIdx, compID, subTUDepth);
1048
1049      m_pcBinIf->encodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx));
1050#if !H_MV_ENC_DEC_TRAC
1051      DTRACE_CABAC_VL( g_nSymbolCounter++ )
1052      DTRACE_CABAC_T( "\tparseQtCbf()" )
1053      DTRACE_CABAC_T( "\tsub-TU=" )
1054      DTRACE_CABAC_V( subTU )
1055      DTRACE_CABAC_T( "\tsymbol=" )
1056      DTRACE_CABAC_V( uiCbf )
1057      DTRACE_CABAC_T( "\tctx=" )
1058      DTRACE_CABAC_V( uiCtx )
1059      DTRACE_CABAC_T( "\tetype=" )
1060      DTRACE_CABAC_V( compID )
1061      DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
1062      DTRACE_CABAC_V( subTUAbsPartIdx )
1063      DTRACE_CABAC_T( "\n" )
1064#else
1065      if ( compID == COMPONENT_Cb )
1066      {
1067        DTRACE_TU("cbf_cb", uiCbf )
1068      }
1069      else if ( compID == COMPONENT_Cr )
1070      {
1071        DTRACE_TU("cbf_cr", uiCbf )
1072      }
1073      else
1074      {
1075        DTRACE_TU("cbf_luma", uiCbf )
1076      }
1077#endif
1078    }
1079  }
1080  else
1081  {
1082    const UInt uiCbf = pcCU->getCbf( absPartIdx, compID, lowestTUDepth );
1083    m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, contextSet, uiCtx ) );
1084#if !H_MV_ENC_DEC_TRAC
1085    DTRACE_CABAC_VL( g_nSymbolCounter++ )
1086    DTRACE_CABAC_T( "\tparseQtCbf()" )
1087    DTRACE_CABAC_T( "\tsymbol=" )
1088    DTRACE_CABAC_V( uiCbf )
1089    DTRACE_CABAC_T( "\tctx=" )
1090    DTRACE_CABAC_V( uiCtx )
1091    DTRACE_CABAC_T( "\tetype=" )
1092    DTRACE_CABAC_V( compID )
1093    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
1094    DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
1095    DTRACE_CABAC_T( "\n" )
1096#else
1097    if ( compID == COMPONENT_Cb )
1098    {
1099      DTRACE_TU("cbf_cb", uiCbf )
1100    }
1101    else if ( compID == COMPONENT_Cr )
1102    {
1103      DTRACE_TU("cbf_cr", uiCbf )
1104    }
1105    else
1106    {
1107      DTRACE_TU("cbf_luma", uiCbf )
1108    }
1109#endif
1110
1111  }
1112}
1113
1114
1115Void TEncSbac::codeTransformSkipFlags (TComTU &rTu, ComponentID component )
1116{
1117  TComDataCU* pcCU=rTu.getCU();
1118  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
1119
1120  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
1121  {
1122    return;
1123  }
1124
1125  if (!TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(component), pcCU->getSlice()->getPPS()->getPpsRangeExtension().getLog2MaxTransformSkipBlockSize()))
1126  {
1127    return;
1128  }
1129
1130  UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,component);
1131  m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, toChannelType(component), 0 ) );
1132#if !H_MV_ENC_DEC_TRAC
1133  DTRACE_CABAC_VL( g_nSymbolCounter++ )
1134  DTRACE_CABAC_T("\tparseTransformSkip()");
1135  DTRACE_CABAC_T( "\tsymbol=" )
1136  DTRACE_CABAC_V( useTransformSkip )
1137  DTRACE_CABAC_T( "\tAddr=" )
1138  DTRACE_CABAC_V( pcCU->getCtuRsAddr() )
1139  DTRACE_CABAC_T( "\tetype=" )
1140  DTRACE_CABAC_V( component )
1141  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
1142  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU() )
1143  DTRACE_CABAC_T( "\n" )
1144#endif
1145}
1146
1147
1148/** Code I_PCM information.
1149 * \param pcCU pointer to CU
1150 * \param uiAbsPartIdx CU index
1151 * \returns Void
1152 */
1153Void TEncSbac::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
1154{
1155  UInt uiIPCM = (pcCU->getIPCMFlag(uiAbsPartIdx) == true)? 1 : 0;
1156
1157  Bool writePCMSampleFlag = pcCU->getIPCMFlag(uiAbsPartIdx);
1158
1159  m_pcBinIf->encodeBinTrm (uiIPCM);
1160#if H_MV_ENC_DEC_TRAC         
1161  DTRACE_CU("pcm_flag", uiIPCM)
1162#endif
1163  if (writePCMSampleFlag)
1164  {
1165    m_pcBinIf->encodePCMAlignBits();
1166
1167    const UInt minCoeffSizeY = pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight();
1168    const UInt offsetY       = minCoeffSizeY * uiAbsPartIdx;
1169    for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
1170    {
1171      const ComponentID compID = ComponentID(ch);
1172      const UInt offset = offsetY >> (pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID));
1173      Pel * pPCMSample  = pcCU->getPCMSample(compID) + offset;
1174      const UInt width  = pcCU->getWidth (uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleX(compID);
1175      const UInt height = pcCU->getHeight(uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleY(compID);
1176      const UInt sampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
1177      for (UInt y=0; y<height; y++)
1178      {
1179        for (UInt x=0; x<width; x++)
1180        {
1181          UInt sample = pPCMSample[x];
1182          m_pcBinIf->xWritePCMCode(sample, sampleBits);
1183        }
1184        pPCMSample += width;
1185      }
1186    }
1187    m_pcBinIf->resetBac();
1188  }
1189}
1190
1191Void TEncSbac::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
1192{
1193  UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx );
1194  UInt uiCtx = 0;
1195  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
1196#if !H_MV_ENC_DEC_TRAC
1197  DTRACE_CABAC_VL( g_nSymbolCounter++ )
1198  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
1199  DTRACE_CABAC_T( "\tsymbol=" )
1200  DTRACE_CABAC_V( uiCbf )
1201  DTRACE_CABAC_T( "\tctx=" )
1202  DTRACE_CABAC_V( uiCtx )
1203  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
1204  DTRACE_CABAC_V( uiAbsPartIdx )
1205  DTRACE_CABAC_T( "\n" )
1206#else
1207  DTRACE_CU( "rqt_root_cbf", uiCbf )
1208#endif
1209}
1210
1211Void TEncSbac::codeQtCbfZero( TComTU & rTu, const ChannelType chType )
1212{
1213  // this function is only used to estimate the bits when cbf is 0
1214  // and will never be called when writing the bistream. do not need to write log
1215  UInt uiCbf = 0;
1216  UInt uiCtx = rTu.getCU()->getCtxQtCbf( rTu, chType );
1217
1218  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, chType, uiCtx ) );
1219}
1220
1221Void TEncSbac::codeQtRootCbfZero( )
1222{
1223  // this function is only used to estimate the bits when cbf is 0
1224  // and will never be called when writing the bistream. do not need to write log
1225  UInt uiCbf = 0;
1226  UInt uiCtx = 0;
1227  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
1228}
1229
1230/** Encode (X,Y) position of the last significant coefficient
1231 * \param uiPosX     X component of last coefficient
1232 * \param uiPosY     Y component of last coefficient
1233 * \param width      Block width
1234 * \param height     Block height
1235 * \param component  chroma component ID
1236 * \param uiScanIdx  scan type (zig-zag, hor, ver)
1237 * This method encodes the X and Y component within a block of the last significant coefficient.
1238 */
1239Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, Int width, Int height, ComponentID component, UInt uiScanIdx )
1240{
1241  // swap
1242  if( uiScanIdx == SCAN_VER )
1243  {
1244    swap( uiPosX, uiPosY );
1245    swap( width,  height );
1246  }
1247
1248  UInt uiCtxLast;
1249  UInt uiGroupIdxX    = g_uiGroupIdx[ uiPosX ];
1250  UInt uiGroupIdxY    = g_uiGroupIdx[ uiPosY ];
1251
1252  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, toChannelType(component) );
1253  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, toChannelType(component) );
1254
1255  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
1256  getLastSignificantContextParameters(component, width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
1257
1258  //------------------
1259
1260  // posX
1261
1262  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxX; uiCtxLast++ )
1263  {
1264    m_pcBinIf->encodeBin( 1, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
1265  }
1266  if( uiGroupIdxX < g_uiGroupIdx[ width - 1 ])
1267  {
1268    m_pcBinIf->encodeBin( 0, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
1269  }
1270
1271  // posY
1272
1273  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxY; uiCtxLast++ )
1274  {
1275    m_pcBinIf->encodeBin( 1, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
1276  }
1277  if( uiGroupIdxY < g_uiGroupIdx[ height - 1 ])
1278  {
1279    m_pcBinIf->encodeBin( 0, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
1280  }
1281
1282  // EP-coded part
1283
1284  if ( uiGroupIdxX > 3 )
1285  {
1286    UInt uiCount = ( uiGroupIdxX - 2 ) >> 1;
1287    uiPosX       = uiPosX - g_uiMinInGroup[ uiGroupIdxX ];
1288    for (Int i = uiCount - 1 ; i >= 0; i-- )
1289    {
1290      m_pcBinIf->encodeBinEP( ( uiPosX >> i ) & 1 );
1291    }
1292  }
1293  if ( uiGroupIdxY > 3 )
1294  {
1295    UInt uiCount = ( uiGroupIdxY - 2 ) >> 1;
1296    uiPosY       = uiPosY - g_uiMinInGroup[ uiGroupIdxY ];
1297    for ( Int i = uiCount - 1 ; i >= 0; i-- )
1298    {
1299      m_pcBinIf->encodeBinEP( ( uiPosY >> i ) & 1 );
1300    }
1301  }
1302}
1303
1304
1305Void TEncSbac::codeCoeffNxN( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID )
1306{
1307  TComDataCU* pcCU=rTu.getCU();
1308  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(compID);
1309  const TComRectangle &tuRect=rTu.getRect(compID);
1310  const UInt uiWidth=tuRect.width;
1311  const UInt uiHeight=tuRect.height;
1312  const TComSPS &sps=*(pcCU->getSlice()->getSPS());
1313#if !H_MV_ENC_DEC_TRAC
1314
1315  DTRACE_CABAC_VL( g_nSymbolCounter++ )
1316  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
1317  DTRACE_CABAC_V( compID )
1318  DTRACE_CABAC_T( "\twidth=" )
1319  DTRACE_CABAC_V( uiWidth )
1320  DTRACE_CABAC_T( "\theight=" )
1321  DTRACE_CABAC_V( uiHeight )
1322  DTRACE_CABAC_T( "\tdepth=" )
1323//  DTRACE_CABAC_V( rTu.GetTransformDepthTotalAdj(compID) )
1324  DTRACE_CABAC_V( rTu.GetTransformDepthTotal() )
1325  DTRACE_CABAC_T( "\tabspartidx=" )
1326  DTRACE_CABAC_V( uiAbsPartIdx )
1327  DTRACE_CABAC_T( "\ttoCU-X=" )
1328  DTRACE_CABAC_V( pcCU->getCUPelX() )
1329  DTRACE_CABAC_T( "\ttoCU-Y=" )
1330  DTRACE_CABAC_V( pcCU->getCUPelY() )
1331  DTRACE_CABAC_T( "\tCU-addr=" )
1332  DTRACE_CABAC_V(  pcCU->getCtuRsAddr() )
1333  DTRACE_CABAC_T( "\tinCU-X=" )
1334//  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
1335  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
1336  DTRACE_CABAC_T( "\tinCU-Y=" )
1337// DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
1338  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
1339  DTRACE_CABAC_T( "\tpredmode=" )
1340  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
1341  DTRACE_CABAC_T( "\n" )
1342#endif
1343
1344  //--------------------------------------------------------------------------------------------------
1345
1346  if( uiWidth > sps.getMaxTrSize() )
1347  {
1348    std::cerr << "ERROR: codeCoeffNxN was passed a TU with dimensions larger than the maximum allowed size" << std::endl;
1349    assert(false);
1350    exit(1);
1351  }
1352
1353  // compute number of significant coefficients
1354  UInt uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
1355
1356  if ( uiNumSig == 0 )
1357  {
1358    std::cerr << "ERROR: codeCoeffNxN called for empty TU!" << std::endl;
1359    assert(false);
1360    exit(1);
1361  }
1362
1363  //--------------------------------------------------------------------------------------------------
1364
1365  //set parameters
1366
1367  const ChannelType  chType            = toChannelType(compID);
1368  const UInt         uiLog2BlockWidth  = g_aucConvertToBit[ uiWidth  ] + 2;
1369  const UInt         uiLog2BlockHeight = g_aucConvertToBit[ uiHeight ] + 2;
1370
1371  const ChannelType  channelType       = toChannelType(compID);
1372  const Bool         extendedPrecision = sps.getSpsRangeExtension().getExtendedPrecisionProcessingFlag();
1373
1374  const Bool         alignCABACBeforeBypass = sps.getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag();
1375  const Int          maxLog2TrDynamicRange  = sps.getMaxLog2TrDynamicRange(channelType);
1376
1377  Bool beValid;
1378
1379  {
1380    Int uiIntraMode = -1;
1381    const Bool       bIsLuma = isLuma(compID);
1382    Int isIntra = pcCU->isIntra(uiAbsPartIdx) ? 1 : 0;
1383    if ( isIntra )
1384    {
1385      uiIntraMode = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
1386
1387      const UInt partsPerMinCU = 1<<(2*(sps.getMaxTotalCUDepth() - sps.getLog2DiffMaxMinCodingBlockSize()));
1388      uiIntraMode = (uiIntraMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, rTu.GetChromaFormat(), partsPerMinCU)) : uiIntraMode;
1389      uiIntraMode = ((rTu.GetChromaFormat() == CHROMA_422) && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiIntraMode] : uiIntraMode;
1390    }
1391
1392    Int transformSkip = pcCU->getTransformSkip( uiAbsPartIdx,compID) ? 1 : 0;
1393    Bool rdpcm_lossy = ( transformSkip && isIntra && ( (uiIntraMode == HOR_IDX) || (uiIntraMode == VER_IDX) ) ) && pcCU->isRDPCMEnabled(uiAbsPartIdx);
1394
1395    if ( (pcCU->getCUTransquantBypass(uiAbsPartIdx)) || rdpcm_lossy )
1396    {
1397      beValid = false;
1398      if ( (!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
1399      {
1400        codeExplicitRdpcmMode( rTu, compID);
1401      }
1402    }
1403    else
1404    {
1405      beValid = pcCU->getSlice()->getPPS()->getSignHideFlag();
1406    }
1407  }
1408
1409  //--------------------------------------------------------------------------------------------------
1410
1411  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
1412  {
1413    codeTransformSkipFlags(rTu, compID);
1414    if(pcCU->getTransformSkip(uiAbsPartIdx, compID) && !pcCU->isIntra(uiAbsPartIdx) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
1415    {
1416      //  This TU has coefficients and is transform skipped. Check whether is inter coded and if yes encode the explicit RDPCM mode
1417      codeExplicitRdpcmMode( rTu, compID);
1418
1419      if(pcCU->getExplicitRdpcmMode(compID, uiAbsPartIdx) != RDPCM_OFF)
1420      {
1421        //  Sign data hiding is avoided for horizontal and vertical explicit RDPCM modes
1422        beValid = false;
1423      }
1424    }
1425  }
1426
1427  //--------------------------------------------------------------------------------------------------
1428
1429  const Bool  bUseGolombRiceParameterAdaptation = sps.getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag();
1430        UInt &currentGolombRiceStatistic        = m_golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)];
1431
1432  //select scans
1433  TUEntropyCodingParameters codingParameters;
1434  getTUEntropyCodingParameters(codingParameters, rTu, compID);
1435
1436  //----- encode significance map -----
1437
1438  // Find position of last coefficient
1439  Int scanPosLast = -1;
1440  Int posLast;
1441
1442
1443  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
1444
1445  memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
1446  do
1447  {
1448    posLast = codingParameters.scan[ ++scanPosLast ];
1449
1450    if( pcCoef[ posLast ] != 0 )
1451    {
1452      // get L1 sig map
1453      UInt uiPosY   = posLast >> uiLog2BlockWidth;
1454      UInt uiPosX   = posLast - ( uiPosY << uiLog2BlockWidth );
1455
1456      UInt uiBlkIdx = (codingParameters.widthInGroups * (uiPosY >> MLS_CG_LOG2_HEIGHT)) + (uiPosX >> MLS_CG_LOG2_WIDTH);
1457      uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
1458
1459      uiNumSig--;
1460    }
1461  } while ( uiNumSig > 0 );
1462
1463  // Code position of last coefficient
1464  Int posLastY = posLast >> uiLog2BlockWidth;
1465  Int posLastX = posLast - ( posLastY << uiLog2BlockWidth );
1466  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, compID, codingParameters.scanType);
1467
1468  //===== code significance flag =====
1469  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, chType );
1470  ContextModel * const baseCtx = m_cCUSigSCModel.get( 0, 0 ) + getSignificanceMapContextOffset(compID);
1471
1472  const Int  iLastScanSet  = scanPosLast >> MLS_CG_SIZE;
1473
1474  UInt c1                  = 1;
1475  UInt uiGoRiceParam       = 0;
1476  Int  iScanPosSig         = scanPosLast;
1477
1478  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
1479  {
1480    Int numNonZero = 0;
1481    Int  iSubPos   = iSubSet << MLS_CG_SIZE;
1482    uiGoRiceParam  = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
1483    Bool updateGolombRiceStatistics = bUseGolombRiceParameterAdaptation; //leave the statistics at 0 when not using the adaptation system
1484    UInt coeffSigns = 0;
1485
1486    Int absCoeff[1 << MLS_CG_SIZE];
1487
1488    Int lastNZPosInCG  = -1;
1489    Int firstNZPosInCG = 1 << MLS_CG_SIZE;
1490
1491    Bool escapeDataPresentInGroup = false;
1492
1493    if( iScanPosSig == scanPosLast )
1494    {
1495      absCoeff[ 0 ] = Int(abs( pcCoef[ posLast ] ));
1496      coeffSigns    = ( pcCoef[ posLast ] < 0 );
1497      numNonZero    = 1;
1498      lastNZPosInCG  = iScanPosSig;
1499      firstNZPosInCG = iScanPosSig;
1500      iScanPosSig--;
1501    }
1502
1503    // encode significant_coeffgroup_flag
1504    Int iCGBlkPos = codingParameters.scanCG[ iSubSet ];
1505    Int iCGPosY   = iCGBlkPos / codingParameters.widthInGroups;
1506    Int iCGPosX   = iCGBlkPos - (iCGPosY * codingParameters.widthInGroups);
1507
1508    if( iSubSet == iLastScanSet || iSubSet == 0)
1509    {
1510      uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
1511    }
1512    else
1513    {
1514      UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
1515      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
1516      m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
1517    }
1518
1519    // encode significant_coeff_flag
1520    if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
1521    {
1522      const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
1523
1524      UInt uiBlkPos, uiSig, uiCtxSig;
1525      for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
1526      {
1527        uiBlkPos  = codingParameters.scan[ iScanPosSig ];
1528        uiSig     = (pcCoef[ uiBlkPos ] != 0);
1529        if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
1530        {
1531          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, codingParameters, iScanPosSig, uiLog2BlockWidth, uiLog2BlockHeight, chType );
1532          m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
1533        }
1534        if( uiSig )
1535        {
1536          absCoeff[ numNonZero ] = Int(abs( pcCoef[ uiBlkPos ] ));
1537          coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 );
1538          numNonZero++;
1539          if( lastNZPosInCG == -1 )
1540          {
1541            lastNZPosInCG = iScanPosSig;
1542          }
1543          firstNZPosInCG = iScanPosSig;
1544        }
1545      }
1546    }
1547    else
1548    {
1549      iScanPosSig = iSubPos - 1;
1550    }
1551
1552    if( numNonZero > 0 )
1553    {
1554      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
1555
1556      const UInt uiCtxSet = getContextSetIndex(compID, iSubSet, (c1 == 0));
1557      c1 = 1;
1558
1559      ContextModel *baseCtxMod = m_cCUOneSCModel.get( 0, 0 ) + (NUM_ONE_FLAG_CTX_PER_SET * uiCtxSet);
1560
1561      Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
1562      Int firstC2FlagIdx = -1;
1563      for( Int idx = 0; idx < numC1Flag; idx++ )
1564      {
1565        UInt uiSymbol = absCoeff[ idx ] > 1;
1566        m_pcBinIf->encodeBin( uiSymbol, baseCtxMod[c1] );
1567        if( uiSymbol )
1568        {
1569          c1 = 0;
1570
1571          if (firstC2FlagIdx == -1)
1572          {
1573            firstC2FlagIdx = idx;
1574          }
1575          else //if a greater-than-one has been encountered already this group
1576          {
1577            escapeDataPresentInGroup = true;
1578          }
1579        }
1580        else if( (c1 < 3) && (c1 > 0) )
1581        {
1582          c1++;
1583        }
1584      }
1585
1586      if (c1 == 0)
1587      {
1588        baseCtxMod = m_cCUAbsSCModel.get( 0, 0 ) + (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet);
1589        if ( firstC2FlagIdx != -1)
1590        {
1591          UInt symbol = absCoeff[ firstC2FlagIdx ] > 2;
1592          m_pcBinIf->encodeBin( symbol, baseCtxMod[0] );
1593          if (symbol != 0)
1594          {
1595            escapeDataPresentInGroup = true;
1596          }
1597        }
1598      }
1599
1600      escapeDataPresentInGroup = escapeDataPresentInGroup || (numNonZero > C1FLAG_NUMBER);
1601
1602      if (escapeDataPresentInGroup && alignCABACBeforeBypass)
1603      {
1604        m_pcBinIf->align();
1605      }
1606
1607      if( beValid && signHidden )
1608      {
1609        m_pcBinIf->encodeBinsEP( (coeffSigns >> 1), numNonZero-1 );
1610      }
1611      else
1612      {
1613        m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero );
1614      }
1615
1616      Int iFirstCoeff2 = 1;
1617      if (escapeDataPresentInGroup)
1618      {
1619        for ( Int idx = 0; idx < numNonZero; idx++ )
1620        {
1621          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2 ) : 1;
1622
1623          if( absCoeff[ idx ] >= baseLevel)
1624          {
1625            const UInt escapeCodeValue = absCoeff[idx] - baseLevel;
1626
1627            xWriteCoefRemainExGolomb( escapeCodeValue, uiGoRiceParam, extendedPrecision, maxLog2TrDynamicRange );
1628
1629            if (absCoeff[idx] > (3 << uiGoRiceParam))
1630            {
1631              uiGoRiceParam = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::min<UInt>((uiGoRiceParam + 1), 4));
1632            }
1633
1634            if (updateGolombRiceStatistics)
1635            {
1636              const UInt initialGolombRiceParameter = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
1637
1638              if (escapeCodeValue >= (3 << initialGolombRiceParameter))
1639              {
1640                currentGolombRiceStatistic++;
1641              }
1642              else if (((escapeCodeValue * 2) < (1 << initialGolombRiceParameter)) && (currentGolombRiceStatistic > 0))
1643              {
1644                currentGolombRiceStatistic--;
1645              }
1646
1647              updateGolombRiceStatistics = false;
1648            }
1649          }
1650
1651          if(absCoeff[ idx ] >= 2)
1652          {
1653            iFirstCoeff2 = 0;
1654          }
1655        }
1656      }
1657    }
1658  }
1659#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
1660  printSBACCoeffData(posLastX, posLastY, uiWidth, uiHeight, compID, uiAbsPartIdx, codingParameters.scanType, pcCoef, pcCU->getSlice()->getFinalized());
1661#endif
1662
1663  return;
1664}
1665
1666/** code SAO offset sign
1667 * \param code sign value
1668 */
1669Void TEncSbac::codeSAOSign( UInt code )
1670{
1671  m_pcBinIf->encodeBinEP( code );
1672}
1673
1674Void TEncSbac::codeSaoMaxUvlc    ( UInt code, UInt maxSymbol )
1675{
1676  if (maxSymbol == 0)
1677  {
1678    return;
1679  }
1680
1681  Int i;
1682  Bool bCodeLast = ( maxSymbol > code );
1683
1684  if ( code == 0 )
1685  {
1686    m_pcBinIf->encodeBinEP( 0 );
1687  }
1688  else
1689  {
1690    m_pcBinIf->encodeBinEP( 1 );
1691    for ( i=0; i<code-1; i++ )
1692    {
1693      m_pcBinIf->encodeBinEP( 1 );
1694    }
1695    if( bCodeLast )
1696    {
1697      m_pcBinIf->encodeBinEP( 0 );
1698    }
1699  }
1700}
1701
1702/** Code SAO EO class or BO band position
1703 */
1704Void TEncSbac::codeSaoUflc       ( UInt uiLength, UInt uiCode )
1705{
1706  m_pcBinIf->encodeBinsEP ( uiCode, uiLength );
1707}
1708
1709/** Code SAO merge flags
1710 */
1711Void TEncSbac::codeSaoMerge       ( UInt uiCode )
1712{
1713  m_pcBinIf->encodeBin(((uiCode == 0) ? 0 : 1),  m_cSaoMergeSCModel.get( 0, 0, 0 ));
1714}
1715
1716/** Code SAO type index
1717 */
1718Void TEncSbac::codeSaoTypeIdx       ( UInt uiCode)
1719{
1720  if (uiCode == 0)
1721  {
1722    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
1723  }
1724  else
1725  {
1726    m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
1727    m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
1728  }
1729}
1730
1731Void TEncSbac::codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled, const Int channelBitDepth)
1732{
1733  UInt uiSymbol;
1734  if(!sliceEnabled)
1735  {
1736    assert(ctbParam.modeIdc == SAO_MODE_OFF);
1737    return;
1738  }
1739  const Bool bIsFirstCompOfChType = (getFirstComponentOfChannel(toChannelType(compIdx)) == compIdx);
1740
1741  //type
1742  if(bIsFirstCompOfChType)
1743  {
1744    //sao_type_idx_luma or sao_type_idx_chroma
1745    if(ctbParam.modeIdc == SAO_MODE_OFF)
1746    {
1747      uiSymbol =0;
1748    }
1749    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
1750    {
1751      uiSymbol = 1;
1752    }
1753    else
1754    {
1755      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
1756      uiSymbol = 2;
1757    }
1758    codeSaoTypeIdx(uiSymbol);
1759  }
1760
1761  if(ctbParam.modeIdc == SAO_MODE_NEW)
1762  {
1763    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES;
1764    Int offset[4];
1765    Int k=0;
1766    for(Int i=0; i< numClasses; i++)
1767    {
1768      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
1769      {
1770        continue;
1771      }
1772      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
1773      offset[k] = ctbParam.offset[classIdx];
1774      k++;
1775    }
1776
1777    const Int  maxOffsetQVal = TComSampleAdaptiveOffset::getMaxOffsetQVal(channelBitDepth);
1778    for(Int i=0; i< 4; i++)
1779    {
1780      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  maxOffsetQVal ); //sao_offset_abs
1781    }
1782
1783
1784    if(ctbParam.typeIdc == SAO_TYPE_BO)
1785    {
1786      for(Int i=0; i< 4; i++)
1787      {
1788        if(offset[i] != 0)
1789        {
1790          codeSAOSign((offset[i]< 0)?1:0);
1791        }
1792      }
1793
1794      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
1795    }
1796    else //EO
1797    {
1798      if(bIsFirstCompOfChType)
1799      {
1800        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
1801        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
1802      }
1803    }
1804
1805  }
1806}
1807
1808
1809Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam, const BitDepths &bitDepths
1810                              , Bool* sliceEnabled
1811                              , Bool leftMergeAvail
1812                              , Bool aboveMergeAvail
1813                              , Bool onlyEstMergeInfo // = false
1814                              )
1815{
1816
1817  Bool isLeftMerge = false;
1818  Bool isAboveMerge= false;
1819
1820  if(leftMergeAvail)
1821  {
1822    isLeftMerge = ((saoBlkParam[COMPONENT_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[COMPONENT_Y].typeIdc == SAO_MERGE_LEFT));
1823    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
1824  }
1825
1826  if( aboveMergeAvail && !isLeftMerge)
1827  {
1828    isAboveMerge = ((saoBlkParam[COMPONENT_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[COMPONENT_Y].typeIdc == SAO_MERGE_ABOVE));
1829    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
1830  }
1831
1832  if(onlyEstMergeInfo)
1833  {
1834    return; //only for RDO
1835  }
1836
1837  if(!isLeftMerge && !isAboveMerge) //not merge mode
1838  {
1839    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
1840    {
1841      codeSAOOffsetParam(ComponentID(compIdx), saoBlkParam[compIdx], sliceEnabled[compIdx], bitDepths.recon[toChannelType(ComponentID(compIdx))]);
1842    }
1843  }
1844}
1845
1846/*!
1847 ****************************************************************************
1848 * \brief
1849 *   estimate bit cost for CBP, significant map and significant coefficients
1850 ****************************************************************************
1851 */
1852Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
1853{
1854  estCBFBit( pcEstBitsSbac );
1855
1856  estSignificantCoeffGroupMapBit( pcEstBitsSbac, chType );
1857
1858  // encode significance map
1859  estSignificantMapBit( pcEstBitsSbac, width, height, chType );
1860
1861  // encode last significant position
1862  estLastSignificantPositionBit( pcEstBitsSbac, width, height, chType );
1863
1864  // encode significant coefficients
1865  estSignificantCoefficientsBit( pcEstBitsSbac, chType );
1866
1867  memcpy(pcEstBitsSbac->golombRiceAdaptationStatistics, m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
1868}
1869
1870/*!
1871 ****************************************************************************
1872 * \brief
1873 *    estimate bit cost for each CBP bit
1874 ****************************************************************************
1875 */
1876Void TEncSbac::estCBFBit( estBitsSbacStruct* pcEstBitsSbac )
1877{
1878  ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 );
1879
1880  for( UInt uiCtxInc = 0; uiCtxInc < (NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET); uiCtxInc++ )
1881  {
1882    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
1883    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
1884  }
1885
1886  pCtx = m_cCUQtRootCbfSCModel.get( 0 );
1887
1888  for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ )
1889  {
1890    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
1891    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
1892  }
1893}
1894
1895
1896/*!
1897 ****************************************************************************
1898 * \brief
1899 *    estimate SAMBAC bit cost for significant coefficient group map
1900 ****************************************************************************
1901 */
1902Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType )
1903{
1904  Int firstCtx = 0, numCtx = NUM_SIG_CG_FLAG_CTX;
1905
1906  for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
1907  {
1908    for( UInt uiBin = 0; uiBin < 2; uiBin++ )
1909    {
1910      pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get(  0, chType, ctxIdx ).getEntropyBits( uiBin );
1911    }
1912  }
1913}
1914
1915
1916/*!
1917 ****************************************************************************
1918 * \brief
1919 *    estimate SAMBAC bit cost for significant coefficient map
1920 ****************************************************************************
1921 */
1922Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
1923{
1924  //--------------------------------------------------------------------------------------------------
1925
1926  //set up the number of channels and context variables
1927
1928  const UInt firstComponent = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
1929  const UInt lastComponent  = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
1930
1931  //----------------------------------------------------------
1932
1933  Int firstCtx = MAX_INT;
1934  Int numCtx   = MAX_INT;
1935
1936  if      ((width == 4) && (height == 4))
1937  {
1938    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_4x4];
1939    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_4x4];
1940  }
1941  else if ((width == 8) && (height == 8))
1942  {
1943    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_8x8];
1944    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_8x8];
1945  }
1946  else
1947  {
1948    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_NxN];
1949    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_NxN];
1950  }
1951
1952  //--------------------------------------------------------------------------------------------------
1953
1954  //fill the data for the significace map
1955
1956  for (UInt component = firstComponent; component <= lastComponent; component++)
1957  {
1958    const UInt contextOffset = getSignificanceMapContextOffset(ComponentID(component));
1959
1960    if (firstCtx > 0)
1961    {
1962      for( UInt bin = 0; bin < 2; bin++ ) //always get the DC
1963      {
1964        pcEstBitsSbac->significantBits[ contextOffset ][ bin ] = m_cCUSigSCModel.get( 0, 0, contextOffset ).getEntropyBits( bin );
1965      }
1966    }
1967
1968    // This could be made optional, but would require this function to have knowledge of whether the
1969    // TU is transform-skipped or transquant-bypassed and whether the SPS flag is set
1970    for( UInt bin = 0; bin < 2; bin++ )
1971    {
1972      const Int ctxIdx = significanceMapContextSetStart[chType][CONTEXT_TYPE_SINGLE];
1973      pcEstBitsSbac->significantBits[ contextOffset + ctxIdx ][ bin ] = m_cCUSigSCModel.get( 0, 0, (contextOffset + ctxIdx) ).getEntropyBits( bin );
1974    }
1975
1976    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
1977    {
1978      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
1979      {
1980        pcEstBitsSbac->significantBits[ contextOffset + ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, (contextOffset + ctxIdx) ).getEntropyBits( uiBin );
1981      }
1982    }
1983  }
1984
1985  //--------------------------------------------------------------------------------------------------
1986}
1987
1988
1989/*!
1990 ****************************************************************************
1991 * \brief
1992 *    estimate bit cost of significant coefficient
1993 ****************************************************************************
1994 */
1995
1996Void TEncSbac::estLastSignificantPositionBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
1997{
1998  //--------------------------------------------------------------------------------------------------.
1999
2000  //set up the number of channels
2001
2002  const UInt firstComponent = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
2003  const UInt lastComponent  = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
2004
2005  //--------------------------------------------------------------------------------------------------
2006
2007  //fill the data for the last-significant-coefficient position
2008
2009  for (UInt componentIndex = firstComponent; componentIndex <= lastComponent; componentIndex++)
2010  {
2011    const ComponentID component = ComponentID(componentIndex);
2012
2013    Int iBitsX = 0, iBitsY = 0;
2014
2015    Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
2016    getLastSignificantContextParameters(ComponentID(component), width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
2017
2018    Int ctx;
2019
2020    const ChannelType channelType = toChannelType(ComponentID(component));
2021
2022    ContextModel *const pCtxX = m_cCuCtxLastX.get( 0, channelType );
2023    ContextModel *const pCtxY = m_cCuCtxLastY.get( 0, channelType );
2024    Int          *const lastXBitsArray = pcEstBitsSbac->lastXBits[channelType];
2025    Int          *const lastYBitsArray = pcEstBitsSbac->lastYBits[channelType];
2026
2027    //------------------------------------------------
2028
2029    //X-coordinate
2030
2031    for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
2032    {
2033      Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX);
2034      lastXBitsArray[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
2035      iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
2036    }
2037
2038    lastXBitsArray[ctx] = iBitsX;
2039
2040    //------------------------------------------------
2041
2042    //Y-coordinate
2043
2044    for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
2045    {
2046      Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY);
2047      lastYBitsArray[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
2048      iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
2049    }
2050
2051    lastYBitsArray[ctx] = iBitsY;
2052
2053  } //end of component loop
2054
2055  //--------------------------------------------------------------------------------------------------
2056}
2057
2058
2059/*!
2060 ****************************************************************************
2061 * \brief
2062 *    estimate bit cost of significant coefficient
2063 ****************************************************************************
2064 */
2065Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType )
2066{
2067  ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0);
2068  ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0);
2069
2070  const UInt oneStartIndex = ((isLuma(chType)) ? (0)                     : (NUM_ONE_FLAG_CTX_LUMA));
2071  const UInt oneStopIndex  = ((isLuma(chType)) ? (NUM_ONE_FLAG_CTX_LUMA) : (NUM_ONE_FLAG_CTX));
2072  const UInt absStartIndex = ((isLuma(chType)) ? (0)                     : (NUM_ABS_FLAG_CTX_LUMA));
2073  const UInt absStopIndex  = ((isLuma(chType)) ? (NUM_ABS_FLAG_CTX_LUMA) : (NUM_ABS_FLAG_CTX));
2074
2075  for (Int ctxIdx = oneStartIndex; ctxIdx < oneStopIndex; ctxIdx++)
2076  {
2077    pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
2078    pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );
2079  }
2080
2081  for (Int ctxIdx = absStartIndex; ctxIdx < absStopIndex; ctxIdx++)
2082  {
2083    pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
2084    pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );
2085  }
2086}
2087
2088/**
2089 - Initialize our context information from the nominated source.
2090 .
2091 \param pSrc From where to copy context information.
2092 */
2093Void TEncSbac::xCopyContextsFrom( const TEncSbac* pSrc )
2094{
2095  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
2096  memcpy(m_golombRiceAdaptationStatistics, pSrc->m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
2097}
2098
2099Void  TEncSbac::loadContexts ( const TEncSbac* pSrc)
2100{
2101  xCopyContextsFrom(pSrc);
2102}
2103
2104/** Performs CABAC encoding of the explicit RDPCM mode
2105 * \param rTu current TU data structure
2106 * \param compID component identifier
2107 */
2108Void TEncSbac::codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID )
2109{
2110  TComDataCU *cu = rTu.getCU();
2111  const TComRectangle &rect = rTu.getRect(compID);
2112  const UInt absPartIdx   = rTu.GetAbsPartIdxTU(compID);
2113  const UInt tuHeight = g_aucConvertToBit[rect.height];
2114  const UInt tuWidth  = g_aucConvertToBit[rect.width];
2115
2116  assert(tuHeight == tuWidth);
2117  assert(tuHeight < 4);
2118
2119  UInt explicitRdpcmMode = cu->getExplicitRdpcmMode(compID, absPartIdx);
2120
2121  if( explicitRdpcmMode == RDPCM_OFF )
2122  {
2123    m_pcBinIf->encodeBin (0, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0));
2124  }
2125  else if( explicitRdpcmMode == RDPCM_HOR || explicitRdpcmMode == RDPCM_VER )
2126  {
2127    m_pcBinIf->encodeBin (1, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0));
2128    if(explicitRdpcmMode == RDPCM_HOR)
2129    {
2130      m_pcBinIf->encodeBin ( 0, m_explicitRdpcmDirSCModel.get(0, toChannelType(compID), 0));
2131    }
2132    else
2133    {
2134      m_pcBinIf->encodeBin ( 1, m_explicitRdpcmDirSCModel.get(0, toChannelType(compID), 0));
2135    }
2136  }
2137  else
2138  {
2139    assert(0);
2140  }
2141}
2142
2143
2144
2145
2146
2147//! \}
Note: See TracBrowser for help on using the repository browser.