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

Last change on this file since 1256 was 1256, checked in by liu, 9 years ago

-Integration of QTL

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