source: 3DVCSoftware/branches/HTM-14.1-update-dev2/source/Lib/TLibEncoder/TEncSbac.cpp @ 1274

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

Merged HTM-14.1-update-dev3@1273.

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