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

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