source: 3DVCSoftware/trunk/source/Lib/TLibEncoder/TEncSbac.cpp

Last change on this file was 1413, checked in by tech, 6 years ago

Merged HTM-16.2-dev@1412

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