source: 3DVCSoftware/branches/HTM-14.1-update-dev1-MediaTek/source/Lib/TLibEncoder/TEncSbac.cpp @ 1258

Last change on this file since 1258 was 1258, checked in by mediatek-htm, 9 years ago

The reactivation of depth intra skip mode (DIS), the MACRO is "NH_3D_DIS".

by Yi-Wen Chen (yiwen.chen@…)

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