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

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

Update to HM-16.5.
Starting point for further re-activation of 3D-tools.

Includes:

active:

  • MV-HEVC
  • 3D-HLS (apart from DLT)
  • VSO

inactive:

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