Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/EncoderLib/CABACWriter.cpp
Line
Count
Source
1
/* -----------------------------------------------------------------------------
2
The copyright in this software is being made available under the Clear BSD
3
License, included below. No patent rights, trademark rights and/or 
4
other Intellectual Property Rights other than the copyrights concerning 
5
the Software are granted under this license.
6
7
The Clear BSD License
8
9
Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors.
10
All rights reserved.
11
12
Redistribution and use in source and binary forms, with or without modification,
13
are permitted (subject to the limitations in the disclaimer below) provided that
14
the following conditions are met:
15
16
     * Redistributions of source code must retain the above copyright notice,
17
     this list of conditions and the following disclaimer.
18
19
     * Redistributions in binary form must reproduce the above copyright
20
     notice, this list of conditions and the following disclaimer in the
21
     documentation and/or other materials provided with the distribution.
22
23
     * Neither the name of the copyright holder nor the names of its
24
     contributors may be used to endorse or promote products derived from this
25
     software without specific prior written permission.
26
27
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
28
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
31
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
32
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
36
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38
POSSIBILITY OF SUCH DAMAGE.
39
40
41
------------------------------------------------------------------------------------------- */
42
43
44
/** \file     CABACWriter.cpp
45
 *  \brief    Writer for low level syntax
46
 */
47
48
#include "CABACWriter.h"
49
#include "EncLib.h"
50
#include "CommonLib/Contexts.h"
51
#include "CommonLib/UnitTools.h"
52
#include "CommonLib/SampleAdaptiveOffset.h"
53
#include "CommonLib/dtrace_buffer.h"
54
55
#include <map>
56
#include <algorithm>
57
58
//! \ingroup EncoderLib
59
//! \{
60
61
namespace vvenc {
62
63
void CABACWriter::initCtxModels( const Slice& slice )
64
14.5k
{
65
14.5k
  int       qp                = slice.sliceQp;
66
14.5k
  SliceType sliceType         = slice.sliceType;
67
14.5k
  SliceType encCABACTableIdx  = slice.encCABACTableIdx;
68
14.5k
  if( !slice.isIntra() && (encCABACTableIdx==VVENC_B_SLICE || encCABACTableIdx==VVENC_P_SLICE) && slice.pps->cabacInitPresent )
69
0
  {
70
0
    sliceType = encCABACTableIdx;
71
0
  }
72
14.5k
  m_BinEncoder.reset( qp, (int)sliceType );
73
14.5k
}
74
75
76
77
SliceType xGetCtxInitId( const Slice& slice, const BinEncIf& binEncoder, Ctx& ctxTest )
78
0
{
79
0
  const CtxStore& ctxStoreTest = static_cast<const CtxStore&>( ctxTest );
80
0
  const CtxStore& ctxStoreRef  = static_cast<const CtxStore&>( binEncoder.getCtx() );
81
0
  int qp = slice.sliceQp;
82
0
  if( !slice.isIntra() )
83
0
  {
84
0
    SliceType aSliceTypeChoices[] = { VVENC_B_SLICE, VVENC_P_SLICE };
85
0
    uint64_t  bestCost                 = std::numeric_limits<uint64_t>::max();
86
0
    SliceType bestSliceType       = aSliceTypeChoices[0];
87
0
    for (uint32_t idx=0; idx<2; idx++)
88
0
    {
89
0
      uint64_t  curCost           = 0;
90
0
      SliceType curSliceType = aSliceTypeChoices[idx];
91
0
      ctxTest.init( qp, (int)curSliceType );
92
0
      for( int k = 0; k < Ctx::NumberOfContexts; k++ )
93
0
      {
94
0
        if( binEncoder.getNumBins(k) > 0 )
95
0
        {
96
0
          curCost += uint64_t( binEncoder.getNumBins(k) ) * ctxStoreRef[k].estFracExcessBits( ctxStoreTest[k] );
97
0
        }
98
0
      }
99
0
      if (curCost < bestCost)
100
0
      {
101
0
        bestSliceType = curSliceType;
102
0
        bestCost      = curCost;
103
0
      }
104
0
    }
105
0
    return bestSliceType;
106
0
  }
107
0
  else
108
0
  {
109
0
    return VVENC_I_SLICE;
110
0
  }
111
0
}
112
113
114
SliceType CABACWriter::getCtxInitId( const Slice& slice )
115
0
{
116
0
  return  xGetCtxInitId( slice, m_BinEncoder, m_TestCtx );
117
0
}
118
119
120
unsigned estBits( BinEncIf& binEnc, const std::vector<bool>& bins, const Ctx& ctx, const int ctxId, const uint8_t winSize )
121
0
{
122
0
  binEnc.initCtxAndWinSize( ctxId, ctx, winSize );
123
0
  binEnc.start();
124
0
  const std::size_t numBins   = bins.size();
125
0
  unsigned          startBits = binEnc.getNumWrittenBits();
126
0
  for( std::size_t binId = 0; binId < numBins; binId++ )
127
0
  {
128
0
    unsigned  bin = ( bins[binId] ? 1 : 0 );
129
0
    binEnc.encodeBin( bin, ctxId );
130
0
  }
131
0
  unsigned endBits    = binEnc.getNumWrittenBits();
132
0
  unsigned codedBits  = endBits - startBits;
133
0
  return   codedBits;
134
0
}
135
136
137
//================================================================================
138
//  clause 7.3.8.1
139
//--------------------------------------------------------------------------------
140
//    void  end_of_slice()
141
//================================================================================
142
143
void CABACWriter::end_of_slice()
144
1.43k
{
145
1.43k
  m_BinEncoder.encodeBinTrm ( 1 );
146
1.43k
  m_BinEncoder.finish       ();
147
1.43k
}
148
149
150
//================================================================================
151
//  clause 7.3.8.2
152
//--------------------------------------------------------------------------------
153
//    bool  coding_tree_unit( cs, area, qp, ctuRsAddr, skipSao, skipAlf )
154
//================================================================================
155
156
void CABACWriter::coding_tree_unit( CodingStructure& cs, const UnitArea& area, int (&qps)[2], unsigned ctuRsAddr, bool skipSao /* = false */, bool skipAlf /* = false */ )
157
9.30k
{
158
9.30k
  CUCtx cuCtx( qps[CH_L] );
159
9.30k
  Partitioner *partitioner = &m_partitioner[0];
160
161
9.30k
  partitioner->initCtu( area, CH_L, *cs.slice );
162
163
9.30k
  if( !skipSao )
164
4.65k
  {
165
4.65k
    sao( *cs.slice, ctuRsAddr );
166
4.65k
  }
167
168
9.30k
  if (!skipAlf)
169
4.65k
  {
170
18.6k
    for (int compIdx = 0; compIdx < MAX_NUM_COMP; compIdx++)
171
13.9k
    {
172
13.9k
      if(cs.slice->alfEnabled[compIdx])
173
0
      {
174
0
        codeAlfCtuEnabledFlag(cs, ctuRsAddr, compIdx);
175
0
        if (isLuma(ComponentID(compIdx)))
176
0
        {
177
0
          codeAlfCtuFilterIndex(cs, ctuRsAddr);
178
0
        }
179
0
        if (isChroma(ComponentID(compIdx)))
180
0
        {
181
0
          codeAlfCtuAlternative(cs, ctuRsAddr, compIdx, &cs.slice->alfAps[cs.slice->chromaApsId]->alfParam );
182
0
        }
183
0
      }
184
13.9k
    }
185
4.65k
  }
186
187
9.30k
  if ( !skipAlf )
188
4.65k
  {
189
13.9k
    for ( int compIdx = 1; compIdx < getNumberValidComponents( cs.pcv->chrFormat ); compIdx++ )
190
9.30k
    {
191
9.30k
      if (cs.slice->ccAlfFilterParam.ccAlfFilterEnabled[compIdx - 1])
192
0
      {
193
0
        const int filterCount   = cs.slice->ccAlfFilterParam.ccAlfFilterCount[compIdx - 1];
194
195
0
        const int      ry = ctuRsAddr / cs.pcv->widthInCtus;
196
0
        const int      rx = ctuRsAddr % cs.pcv->widthInCtus;
197
0
        const Position lumaPos(rx * cs.pcv->maxCUSize, ry * cs.pcv->maxCUSize);
198
199
0
        codeCcAlfFilterControlIdc(cs.slice->ccAlfFilterControl[compIdx - 1][ctuRsAddr], cs, ComponentID(compIdx),
200
0
                                  ctuRsAddr, cs.slice->ccAlfFilterControl[compIdx - 1], lumaPos, filterCount);
201
0
      }
202
9.30k
    }
203
4.65k
  }
204
205
9.30k
  if ( CS::isDualITree(cs) && cs.pcv->chrFormat != CHROMA_400 && cs.pcv->maxCUSize > 64 )
206
9.30k
  {
207
9.30k
    CUCtx chromaCuCtx(qps[CH_C]);
208
9.30k
    Partitioner *chromaPartitioner = &m_partitioner[1];
209
9.30k
    chromaPartitioner->initCtu(area, CH_C, *cs.slice);
210
9.30k
    coding_tree(cs, *partitioner, cuCtx, chromaPartitioner, &chromaCuCtx);
211
9.30k
    qps[CH_L] = cuCtx.qp;
212
9.30k
    qps[CH_C] = chromaCuCtx.qp;
213
9.30k
  }
214
0
  else
215
0
  {
216
0
    coding_tree( cs, *partitioner, cuCtx );
217
0
    qps[CH_L] = cuCtx.qp;
218
0
    if( CS::isDualITree( cs ) && cs.pcv->chrFormat != CHROMA_400 )
219
0
    {
220
0
      CUCtx cuCtxChroma( qps[CH_C] );
221
0
      partitioner->initCtu( area, CH_C, *cs.slice );
222
0
      coding_tree( cs, *partitioner, cuCtxChroma );
223
0
      qps[CH_C] = cuCtxChroma.qp;
224
0
    }
225
0
  }
226
9.30k
}
227
228
229
//================================================================================
230
//  clause 7.3.8.3
231
//--------------------------------------------------------------------------------
232
//    void  sao             ( slice, ctuRsAddr )
233
//    void  sao_block_pars  ( saoPars, bitDepths, sliceEnabled, leftMergeAvail, aboveMergeAvail, onlyEstMergeInfo )
234
//    void  sao_offset_pars ( ctbPars, compID, sliceEnabled, bitDepth )
235
//================================================================================
236
237
void CABACWriter::sao( const Slice& slice, unsigned ctuRsAddr )
238
4.65k
{
239
4.65k
  const SPS& sps = *slice.sps;
240
4.65k
  if( !sps.saoEnabled )
241
0
  {
242
0
    return;
243
0
  }
244
245
4.65k
  CodingStructure&     cs                     = *slice.pic->cs;
246
4.65k
  const PreCalcValues& pcv                    = *cs.pcv;
247
4.65k
  const SAOBlkParam&  sao_ctu_pars            = cs.picture->getSAO()[ctuRsAddr];
248
4.65k
  bool                slice_sao_luma_flag     = ( slice.saoEnabled[ CH_L ] );
249
4.65k
  bool                slice_sao_chroma_flag   = ( slice.saoEnabled[ CH_C ] && sps.chromaFormatIdc != CHROMA_400 );
250
4.65k
  if( !slice_sao_luma_flag && !slice_sao_chroma_flag )
251
0
  {
252
0
    return;
253
0
  }
254
255
4.65k
  bool                sliceEnabled[3]         = { slice_sao_luma_flag, slice_sao_chroma_flag, slice_sao_chroma_flag };
256
4.65k
  int                 frame_width_in_ctus     = pcv.widthInCtus;
257
4.65k
  int                 ry                      = ctuRsAddr      / frame_width_in_ctus;
258
4.65k
  int                 rx                      = ctuRsAddr - ry * frame_width_in_ctus;
259
4.65k
  const Position      pos                     ( rx * cs.pcv->maxCUSize, ry * cs.pcv->maxCUSize );
260
4.65k
  const unsigned      curSliceIdx             = slice.independentSliceIdx;
261
4.65k
  const unsigned      curTileIdx              = cs.pps->getTileIdx( pos );
262
4.65k
  bool                leftMergeAvail          = cs.getCURestricted( pos.offset( -(int)pcv.maxCUSize, 0  ), pos, curSliceIdx, curTileIdx, CH_L, TREE_D ) ? true : false;
263
4.65k
  bool                aboveMergeAvail         = cs.getCURestricted( pos.offset( 0, -(int)pcv.maxCUSize ), pos, curSliceIdx, curTileIdx, CH_L, TREE_D ) ? true : false;
264
4.65k
  sao_block_pars( sao_ctu_pars, sps.bitDepths, sliceEnabled, leftMergeAvail, aboveMergeAvail, false );
265
4.65k
}
266
267
268
void CABACWriter::sao_block_pars( const SAOBlkParam& saoPars, const BitDepths& bitDepths, const bool* sliceEnabled, bool leftMergeAvail, bool aboveMergeAvail, bool onlyEstMergeInfo )
269
18.2k
{
270
18.2k
  bool isLeftMerge  = false;
271
18.2k
  bool isAboveMerge = false;
272
18.2k
  if( leftMergeAvail )
273
9.41k
  {
274
    // sao_merge_left_flag
275
9.41k
    isLeftMerge   = ( saoPars[COMP_Y].modeIdc == SAO_MODE_MERGE && saoPars[COMP_Y].typeIdc == SAO_MERGE_LEFT );
276
9.41k
    m_BinEncoder.encodeBin( (isLeftMerge), Ctx::SaoMergeFlag() );
277
9.41k
  }
278
18.2k
  if( aboveMergeAvail && !isLeftMerge )
279
7.60k
  {
280
    // sao_merge_above_flag
281
7.60k
    isAboveMerge  = ( saoPars[COMP_Y].modeIdc == SAO_MODE_MERGE && saoPars[COMP_Y].typeIdc == SAO_MERGE_ABOVE );
282
7.60k
    m_BinEncoder.encodeBin( (isAboveMerge), Ctx::SaoMergeFlag() );
283
7.60k
  }
284
18.2k
  if( onlyEstMergeInfo )
285
4.65k
  {
286
4.65k
    return; //only for RDO
287
4.65k
  }
288
13.5k
  if( !isLeftMerge && !isAboveMerge )
289
6.08k
  {
290
    // explicit parameters
291
24.3k
    for( int compIdx=0; compIdx < MAX_NUM_COMP; compIdx++ )
292
18.2k
    {
293
18.2k
      sao_offset_pars( saoPars[compIdx], ComponentID(compIdx), sliceEnabled[compIdx], bitDepths[ toChannelType(ComponentID(compIdx)) ] );
294
18.2k
    }
295
6.08k
  }
296
13.5k
}
297
298
299
void CABACWriter::sao_offset_pars( const SAOOffset& ctbPars, ComponentID compID, bool sliceEnabled, int bitDepth )
300
102k
{
301
102k
  if( !sliceEnabled )
302
0
  {
303
0
    CHECK( ctbPars.modeIdc != SAO_MODE_OFF, "Sao must be off, if it is disabled on slice level" );
304
0
    return;
305
0
  }
306
102k
  const bool isFirstCompOfChType = ( getFirstComponentOfChannel( toChannelType(compID) ) == compID );
307
308
102k
  if( isFirstCompOfChType )
309
68.0k
  {
310
    // sao_type_idx_luma / sao_type_idx_chroma
311
68.0k
    if( ctbPars.modeIdc == SAO_MODE_OFF )
312
21.4k
    {
313
21.4k
      m_BinEncoder.encodeBin  ( 0, Ctx::SaoTypeIdx() );
314
21.4k
    }
315
46.5k
    else if( ctbPars.typeIdc == SAO_TYPE_BO )
316
9.34k
    {
317
9.34k
      m_BinEncoder.encodeBin  ( 1, Ctx::SaoTypeIdx() );
318
9.34k
      m_BinEncoder.encodeBinEP( 0 );
319
9.34k
    }
320
37.2k
    else
321
37.2k
    {
322
37.2k
      CHECK(!( ctbPars.typeIdc < SAO_TYPE_START_BO ), "Unspecified error");
323
37.2k
      m_BinEncoder.encodeBin  ( 1, Ctx::SaoTypeIdx() );
324
37.2k
      m_BinEncoder.encodeBinEP( 1 );
325
37.2k
    }
326
68.0k
  }
327
328
102k
  if( ctbPars.modeIdc == SAO_MODE_NEW )
329
69.8k
  {
330
69.8k
    const int maxOffsetQVal = SampleAdaptiveOffset::getMaxOffsetQVal( bitDepth );
331
69.8k
    int       numClasses    = ( ctbPars.typeIdc == SAO_TYPE_BO ? 4 : NUM_SAO_EO_CLASSES );
332
69.8k
    int       k             = 0;
333
69.8k
    int       offset[4];
334
405k
    for( int i = 0; i < numClasses; i++ )
335
335k
    {
336
335k
      if( ctbPars.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN )
337
55.8k
      {
338
55.8k
        continue;
339
55.8k
      }
340
279k
      int classIdx = ( ctbPars.typeIdc == SAO_TYPE_BO ? ( ctbPars.typeAuxInfo + i ) % NUM_SAO_BO_CLASSES : i );
341
279k
      offset[k++]  = ctbPars.offset[classIdx];
342
279k
    }
343
344
    // sao_offset_abs
345
349k
    for( int i = 0; i < 4; i++ )
346
279k
    {
347
279k
      unsigned absOffset = ( offset[i] < 0 ? -offset[i] : offset[i] );
348
279k
      unary_max_eqprob( absOffset, maxOffsetQVal );
349
279k
    }
350
351
    // band offset mode
352
69.8k
    if( ctbPars.typeIdc == SAO_TYPE_BO )
353
14.0k
    {
354
      // sao_offset_sign
355
70.0k
      for( int i = 0; i < 4; i++ )
356
56.0k
      {
357
56.0k
        if( offset[i] )
358
277
        {
359
277
          m_BinEncoder.encodeBinEP( (offset[i] < 0) );
360
277
        }
361
56.0k
      }
362
      // sao_band_position
363
14.0k
      m_BinEncoder.encodeBinsEP( ctbPars.typeAuxInfo, NUM_SAO_BO_CLASSES_LOG2 );
364
14.0k
    }
365
    // edge offset mode
366
55.8k
    else
367
55.8k
    {
368
55.8k
      if( isFirstCompOfChType )
369
37.2k
      {
370
        // sao_eo_class_luma / sao_eo_class_chroma
371
37.2k
        CHECK( ctbPars.typeIdc - SAO_TYPE_START_EO < 0, "sao edge offset class is outside valid range" );
372
37.2k
        m_BinEncoder.encodeBinsEP( ctbPars.typeIdc - SAO_TYPE_START_EO, NUM_SAO_EO_TYPES_LOG2 );
373
37.2k
      }
374
55.8k
    }
375
69.8k
  }
376
102k
}
377
378
379
//================================================================================
380
//  clause 7.3.8.4
381
//--------------------------------------------------------------------------------
382
//    void  coding_tree       ( cs, partitioner, cuCtx )
383
//    void  split_cu_flag     ( split, cs, partitioner )
384
//    void  split_cu_mode_mt  ( split, cs, partitioner )
385
//================================================================================
386
387
void CABACWriter::coding_tree(const CodingStructure& cs, Partitioner& partitioner, CUCtx& cuCtx, Partitioner* pPartitionerChroma, CUCtx* pCuCtxChroma)
388
197k
{
389
197k
  const PPS      &pps         = *cs.pps;
390
197k
  const UnitArea& currArea    = partitioner.currArea();
391
197k
  const CodingUnit &cu        = *cs.getCU( currArea.blocks[partitioner.chType], partitioner.chType, partitioner.treeType );
392
393
  // Reset delta QP coding flag and ChromaQPAdjustemt coding flag
394
  //Note: do not reset qg at chroma CU
395
197k
  if( pps.useDQP && partitioner.currQgEnable() && !isChroma( partitioner.chType ) )
396
17.6k
  {
397
17.6k
    cuCtx.qgStart    = true;
398
17.6k
    cuCtx.isDQPCoded          = false;
399
17.6k
  }
400
197k
  if( cs.slice->chromaQpAdjEnabled && partitioner.currQgChromaEnable() )
401
0
  {
402
0
    cuCtx.isChromaQpAdjCoded  = false;
403
0
  }
404
  // Reset delta QP coding flag and ChromaQPAdjustemt coding flag
405
197k
  if (CS::isDualITree(cs) && pPartitionerChroma != nullptr)
406
9.30k
  {
407
9.30k
    if (pps.useDQP && pPartitionerChroma->currQgEnable())
408
9.30k
    {
409
9.30k
      pCuCtxChroma->qgStart    = true;
410
9.30k
      pCuCtxChroma->isDQPCoded = false;
411
9.30k
    }
412
9.30k
    if (cs.slice->chromaQpAdjEnabled && pPartitionerChroma->currQgChromaEnable())
413
0
    {
414
0
      pCuCtxChroma->isChromaQpAdjCoded = false;
415
0
    }
416
9.30k
  }
417
418
197k
  determineNeighborCus( cs, partitioner.currArea(), partitioner.chType, partitioner.treeType );
419
420
197k
  const PartSplit splitMode = CU::getSplitAtDepth( cu, partitioner.currDepth );
421
422
197k
  split_cu_mode( splitMode, cs, partitioner );
423
424
197k
  CHECK( !partitioner.canSplit( splitMode, cs ), "The chosen split mode is invalid!" );
425
426
197k
  if( splitMode != CU_DONT_SPLIT )
427
102k
  {
428
102k
    if (CS::isDualITree(cs) && pPartitionerChroma != nullptr && (partitioner.currArea().lwidth() >= 64 || partitioner.currArea().lheight() >= 64))
429
9.30k
    {
430
9.30k
      partitioner.splitCurrArea(CU_QUAD_SPLIT, cs);
431
9.30k
      pPartitionerChroma->splitCurrArea(CU_QUAD_SPLIT, cs);
432
9.30k
      bool beContinue = true;
433
9.30k
      bool lumaContinue = true;
434
9.30k
      bool chromaContinue = true;
435
436
46.5k
      while (beContinue)
437
37.2k
      {
438
37.2k
        if (partitioner.currArea().lwidth() > 64 || partitioner.currArea().lheight() > 64)
439
0
        {
440
0
          if (cs.picture->blocks[partitioner.chType].contains(partitioner.currArea().blocks[partitioner.chType].pos()))
441
0
          {
442
0
            coding_tree(cs, partitioner, cuCtx, pPartitionerChroma, pCuCtxChroma);
443
0
          }
444
0
          lumaContinue = partitioner.nextPart(cs);
445
0
          chromaContinue = pPartitionerChroma->nextPart(cs);
446
0
          CHECK(lumaContinue != chromaContinue, "luma chroma partition should be matched");
447
0
          beContinue = lumaContinue;
448
0
        }
449
37.2k
        else
450
37.2k
        {
451
          //dual tree coding under 64x64 block
452
37.2k
          if (cs.picture->blocks[partitioner.chType].contains(partitioner.currArea().blocks[partitioner.chType].pos()))
453
25.2k
          {
454
25.2k
            coding_tree(cs, partitioner, cuCtx);
455
25.2k
          }
456
37.2k
          lumaContinue = partitioner.nextPart(cs);
457
37.2k
          if (cs.picture->blocks[pPartitionerChroma->chType].contains(pPartitionerChroma->currArea().blocks[pPartitionerChroma->chType].pos()))
458
25.2k
          {
459
25.2k
            coding_tree(cs, *pPartitionerChroma, *pCuCtxChroma);
460
25.2k
          }
461
37.2k
          chromaContinue = pPartitionerChroma->nextPart(cs);
462
37.2k
          CHECK(lumaContinue != chromaContinue, "luma chroma partition should be matched");
463
37.2k
          beContinue = lumaContinue;
464
37.2k
        }
465
37.2k
      }
466
9.30k
      partitioner.exitCurrSplit();
467
9.30k
      pPartitionerChroma->exitCurrSplit();
468
469
9.30k
    }
470
93.1k
    else
471
93.1k
    {
472
93.1k
      const ModeType modeTypeParent = partitioner.modeType;
473
93.1k
      const ModeType modeTypeChild = CU::getModeTypeAtDepth( cu, partitioner.currDepth );
474
93.1k
      mode_constraint( splitMode, cs, partitioner, modeTypeChild );
475
93.1k
      partitioner.modeType = modeTypeChild;
476
477
93.1k
      bool chromaNotSplit = modeTypeParent == MODE_TYPE_ALL && modeTypeChild == MODE_TYPE_INTRA ? true : false;
478
93.1k
      CHECK( chromaNotSplit && partitioner.chType != CH_L, "chType must be luma" );
479
93.1k
      if( partitioner.treeType == TREE_D )
480
93.1k
      {
481
93.1k
        partitioner.treeType = chromaNotSplit ? TREE_L : TREE_D;
482
93.1k
      }
483
93.1k
      partitioner.splitCurrArea( splitMode, cs );
484
485
93.1k
      do
486
230k
      {
487
230k
        if( cs.picture->blocks[partitioner.chType].contains( partitioner.currArea().blocks[partitioner.chType].pos() ) )
488
137k
        {
489
137k
          coding_tree( cs, partitioner, cuCtx );
490
137k
        }
491
230k
      } while( partitioner.nextPart( cs ) );
492
493
93.1k
      partitioner.exitCurrSplit();
494
93.1k
      if( chromaNotSplit )
495
0
      {
496
0
        if (isChromaEnabled(cs.pcv->chrFormat))
497
0
        {
498
0
          CHECK( partitioner.chType != CH_L, "must be luma status" );
499
0
          partitioner.chType = CH_C;
500
0
          partitioner.treeType = TREE_C;
501
502
0
          if( cs.picture->blocks[partitioner.chType].contains( partitioner.currArea().blocks[partitioner.chType].pos() ) )
503
0
          {
504
0
            coding_tree( cs, partitioner, cuCtx );
505
0
          }
506
0
        }
507
        //recover
508
0
        partitioner.chType = CH_L;
509
0
        partitioner.treeType = TREE_D;
510
0
      }
511
93.1k
      partitioner.modeType = modeTypeParent;
512
93.1k
    }
513
102k
    return;
514
102k
  }
515
516
  // Predict QP on start of quantization group
517
95.2k
  if( cuCtx.qgStart )
518
23.8k
  {
519
23.8k
    cuCtx.qgStart = false;
520
23.8k
    cuCtx.qp = CU::predictQP( cu, cuCtx.qp );
521
23.8k
  }
522
95.2k
  CHECK( cu.treeType != partitioner.treeType, "treeType mismatch" );
523
524
525
  // coding unit
526
95.2k
  coding_unit( cu, partitioner, cuCtx );
527
528
95.2k
  if( cu.chType == CH_C )
529
38.2k
  {
530
38.2k
    DTRACE_COND( (isEncoding()), g_trace_ctx, D_QP, "[chroma CU]x=%d, y=%d, w=%d, h=%d, qp=%d\n", cu.Cb().x, cu.Cb().y, cu.Cb().width, cu.Cb().height, cu.qp );
531
38.2k
  }
532
56.9k
  else
533
56.9k
  {
534
56.9k
    DTRACE_COND( ( isEncoding() ), g_trace_ctx, D_QP, "x=%d, y=%d, w=%d, h=%d, qp=%d\n", cu.Y().x, cu.Y().y, cu.Y().width, cu.Y().height, cu.qp );
535
56.9k
  }
536
95.2k
  DTRACE_BLOCK_REC_COND( ( !isEncoding() ), cs.picture->getRecoBuf( cu ), cu, cu.predMode );
537
95.2k
}
538
539
540
void CABACWriter::mode_constraint( const PartSplit split, const CodingStructure& cs, Partitioner& partitioner, const ModeType modeType )
541
306k
{
542
306k
  CHECK( split == CU_DONT_SPLIT, "splitMode shall not be no split" );
543
306k
  int val = CS::signalModeCons( cs, partitioner.currArea(), split, partitioner.modeType);
544
306k
  if( val == LDT_MODE_TYPE_SIGNAL )
545
0
  {
546
0
    CHECK( modeType == MODE_TYPE_ALL, "shall not be no constraint case" );
547
0
    bool flag = modeType == MODE_TYPE_INTRA;
548
0
    int ctxIdx = DeriveCtx::CtxModeConsFlag();
549
0
    m_BinEncoder.encodeBin( flag, Ctx::ModeConsFlag( ctxIdx ) );
550
0
    DTRACE( g_trace_ctx, D_SYNTAX, "mode_cons_flag() flag=%d\n", flag );
551
0
  }
552
306k
  else if( val == LDT_MODE_TYPE_INFER )
553
0
  {
554
0
    CHECK( modeType != MODE_TYPE_INTRA, "Wrong mode type" );
555
0
  }
556
306k
  else
557
306k
  {
558
306k
    CHECK( modeType != partitioner.modeType, "Wrong mode type" );
559
306k
  }
560
306k
}
561
562
563
void CABACWriter::split_cu_mode( const PartSplit split, const CodingStructure& cs, Partitioner& partitioner )
564
536k
{
565
536k
  bool canNo, canQt, canBh, canBv, canTh, canTv;
566
536k
  partitioner.canSplit( cs, canNo, canQt, canBh, canBv, canTh, canTv );
567
568
536k
  const bool canSpl[6] = { canNo, canQt, canBh, canBv, canTh, canTv };
569
570
536k
  unsigned ctxSplit = 0, ctxQtSplit = 0, ctxBttHV = 0, ctxBttH12 = 0, ctxBttV12;
571
536k
  DeriveCtx::CtxSplit( partitioner, ctxSplit, ctxQtSplit, ctxBttHV, ctxBttH12, ctxBttV12, canSpl );
572
573
536k
  const bool canSplit = canBh || canBv || canTh || canTv || canQt;
574
536k
  const bool isNo     = split == CU_DONT_SPLIT;
575
576
536k
  if( canNo && canSplit )
577
326k
  {
578
326k
    m_BinEncoder.encodeBin( !isNo, Ctx::SplitFlag( ctxSplit ) );
579
326k
  }
580
581
536k
  DTRACE( g_trace_ctx, D_SYNTAX, "split_cu_mode() ctx=%d split=%d\n", ctxSplit, !isNo );
582
583
536k
  if( isNo )
584
220k
  {
585
220k
    return;
586
220k
  }
587
588
316k
  const bool canBtt = canBh || canBv || canTh || canTv;
589
316k
  const bool isQt   = split == CU_QUAD_SPLIT;
590
591
316k
  if( canQt && canBtt )
592
124k
  {
593
124k
    m_BinEncoder.encodeBin( isQt, Ctx::SplitQtFlag( ctxQtSplit ) );
594
124k
  }
595
596
316k
  DTRACE( g_trace_ctx, D_SYNTAX, "split_cu_mode() ctx=%d qt=%d\n", ctxQtSplit, isQt );
597
598
316k
  if( isQt )
599
81.1k
  {
600
81.1k
    return;
601
81.1k
  }
602
603
234k
  const bool canHor = canBh || canTh;
604
234k
  const bool canVer = canBv || canTv;
605
234k
  const bool  isVer = split == CU_VERT_SPLIT || split == CU_TRIV_SPLIT;
606
607
234k
  if( canVer && canHor )
608
120k
  {
609
120k
    m_BinEncoder.encodeBin( isVer, Ctx::SplitHvFlag( ctxBttHV ) );
610
120k
  }
611
612
234k
  const bool can14 = isVer ? canTv : canTh;
613
234k
  const bool can12 = isVer ? canBv : canBh;
614
234k
  const bool  is12 = isVer ? ( split == CU_VERT_SPLIT ) : ( split == CU_HORZ_SPLIT );
615
616
234k
  if( can12 && can14 )
617
63.7k
  {
618
63.7k
    m_BinEncoder.encodeBin( is12, Ctx::Split12Flag( isVer ? ctxBttV12 : ctxBttH12 ) );
619
63.7k
  }
620
621
234k
  DTRACE( g_trace_ctx, D_SYNTAX, "split_cu_mode() ctxHv=%d ctx12=%d mode=%d\n", ctxBttHV, isVer ? ctxBttV12 : ctxBttH12, split );
622
234k
}
623
624
625
//================================================================================
626
//  clause 7.3.8.5
627
//--------------------------------------------------------------------------------
628
//    void  coding_unit               ( cu, partitioner, cuCtx )
629
//    void  cu_skip_flag              ( cu )
630
//    void  pred_mode                 ( cu )
631
//    void  part_mode                 ( cu )
632
//    void  cu_pred_data              ( pus )
633
//    void  cu_lic_flag               ( cu )
634
//    void  intra_luma_pred_modes     ( pus )
635
//    void  intra_chroma_pred_mode    ( cu )
636
//    void  cu_residual               ( cu, partitioner, cuCtx )
637
//    void  rqt_root_cbf              ( cu )
638
//    void  end_of_ctu                ( cu, cuCtx )
639
//================================================================================
640
641
void CABACWriter::coding_unit( const CodingUnit& cu, Partitioner& partitioner, CUCtx& cuCtx )
642
95.2k
{
643
95.2k
  DTRACE( g_trace_ctx, D_SYNTAX, "coding_unit() treeType=%d modeType=%d\n", cu.treeType, cu.modeType );
644
95.2k
  STAT_COUNT_CU_MODES( isEncoding() && partitioner.chType == CH_L, g_cuCounters1D[CU_CODED_FINALLY][0][!cu.slice->isIntra() + cu.slice->depth] );
645
95.2k
  STAT_COUNT_CU_MODES( isEncoding() && partitioner.chType == CH_L && !cu.slice->isIntra(), g_cuCounters2D[CU_CODED_FINALLY][Log2( cu.lheight() )][Log2( cu.lwidth() )] );
646
647
95.2k
  CodingStructure& cs = *cu.cs;
648
649
  // skip flag
650
95.2k
  if ((!cs.slice->isIntra() || cs.slice->sps->IBC) && cu.Y().valid())
651
56.9k
  {
652
56.9k
    cu_skip_flag( cu );
653
56.9k
  }
654
  
655
  // skip data
656
95.2k
  if( cu.skip )
657
0
  {
658
0
    CHECK( !cu.mergeFlag, "Merge flag has to be on!" );
659
0
    prediction_unit ( cu );
660
0
    CHECK(cu.colorTransform, "ACT should not be enabled for skip mode");
661
0
    end_of_ctu      ( cu, cuCtx );
662
0
    return;
663
0
  }
664
665
  // prediction mode and partitioning data
666
95.2k
  pred_mode ( cu );
667
95.2k
  if (CU::isIntra(cu))
668
95.2k
  {
669
95.2k
    adaptive_color_transform(cu);
670
95.2k
  }
671
95.2k
  if (CU::isPLT(cu))
672
0
  {
673
0
    THROW("no support");
674
0
    return;
675
0
  }
676
677
  // prediction data ( intra prediction modes / reference indexes + motion vectors )
678
95.2k
  cu_pred_data( cu );
679
680
  // residual data ( coded block flags + transform coefficient levels )
681
95.2k
  cu_residual( cu, partitioner, cuCtx );
682
683
  // end of cu
684
95.2k
  end_of_ctu( cu, cuCtx );
685
95.2k
}
686
687
688
void CABACWriter::cu_skip_flag( const CodingUnit& cu )
689
113k
{
690
113k
  unsigned ctxId = DeriveCtx::CtxSkipFlag();
691
692
113k
  if ((cu.slice->isIntra() || CU::isConsIntra(cu)) && cu.cs->slice->sps->IBC)
693
113k
  {
694
113k
    if (cu.lwidth() < 128 && cu.lheight() < 128) // disable IBC mode larger than 64x64
695
113k
    {
696
113k
      m_BinEncoder.encodeBin((cu.skip), Ctx::SkipFlag(ctxId));
697
113k
      DTRACE(g_trace_ctx, D_SYNTAX, "cu_skip_flag() ctx=%d skip=%d\n", ctxId, cu.skip ? 1 : 0);
698
113k
    }
699
113k
    return;
700
113k
  }
701
0
  if ( !cu.cs->slice->sps->IBC && cu.lwidth() == 4 && cu.lheight() == 4 )
702
0
  {
703
0
    return;
704
0
  }
705
0
  if( !cu.cs->slice->sps->IBC && CU::isConsIntra(cu) )
706
0
  {
707
0
    return;
708
0
  }
709
0
  m_BinEncoder.encodeBin( ( cu.skip ), Ctx::SkipFlag( ctxId ) );
710
711
0
  DTRACE( g_trace_ctx, D_SYNTAX, "cu_skip_flag() ctx=%d skip=%d\n", ctxId, cu.skip ? 1 : 0 );
712
0
  if (cu.skip && cu.cs->slice->sps->IBC)
713
0
  {
714
0
    if (cu.lwidth() < 128 && cu.lheight() < 128 && !CU::isConsInter(cu)) // disable IBC mode larger than 64x64 and disable IBC when only allowing inter mode
715
0
    {
716
0
      if ( cu.lwidth() == 4 && cu.lheight() == 4 )
717
0
      {
718
0
        return;
719
0
      }
720
0
      unsigned ctxidx = DeriveCtx::CtxIBCFlag(cu);
721
0
      m_BinEncoder.encodeBin(CU::isIBC(cu) ? 1 : 0, Ctx::IBCFlag(ctxidx));
722
0
      DTRACE(g_trace_ctx, D_SYNTAX, "ibc() ctx=%d cu.predMode=%d\n", ctxidx, cu.predMode);
723
0
    }
724
0
  }
725
0
}
726
727
728
void CABACWriter::pred_mode( const CodingUnit& cu )
729
426k
{
730
426k
  if (cu.cs->slice->sps->IBC && cu.chType != CH_C)
731
319k
  {
732
319k
    if( CU::isConsInter(cu) )
733
0
    {
734
0
      assert( CU::isInter( cu ) );
735
0
      return;
736
0
    }
737
738
319k
    if ( cu.cs->slice->isIntra() || ( cu.lwidth() == 4 && cu.lheight() == 4 ) || CU::isConsIntra(cu) )
739
319k
    {
740
319k
      if (cu.lwidth() < 128 && cu.lheight() < 128) // disable IBC mode larger than 64x64
741
319k
      {
742
319k
        unsigned ctxidx = DeriveCtx::CtxIBCFlag(cu);
743
319k
        m_BinEncoder.encodeBin(CU::isIBC(cu), Ctx::IBCFlag(ctxidx));
744
319k
      }
745
319k
      if (!CU::isIBC(cu) && cu.cs->slice->sps->PLT && cu.lwidth() <= 64 && cu.lheight() <= 64 && (cu.lumaSize().width * cu.lumaSize().height > 16))
746
0
      {
747
0
        m_BinEncoder.encodeBin(CU::isPLT(cu), Ctx::PLTFlag(0));
748
0
      }
749
319k
    }
750
18.4E
    else
751
18.4E
    {
752
18.4E
      if( CU::isConsInter(cu) )
753
0
      {
754
0
        return;
755
0
      }
756
18.4E
      m_BinEncoder.encodeBin((CU::isIntra(cu) || CU::isPLT(cu)), Ctx::PredMode(DeriveCtx::CtxPredModeFlag()));
757
18.4E
      if (CU::isIntra(cu) || CU::isPLT(cu))
758
0
      {
759
0
        if (cu.cs->slice->sps->PLT && cu.lwidth() <= 64 && cu.lheight() <= 64 && (cu.lumaSize().width * cu.lumaSize().height > 16))
760
0
        {
761
0
          m_BinEncoder.encodeBin(CU::isPLT(cu), Ctx::PLTFlag(0));
762
0
        }
763
0
      }
764
18.4E
      else
765
18.4E
      {
766
18.4E
        if (cu.lwidth() < 128 && cu.lheight() < 128) // disable IBC mode larger than 64x64
767
0
        {
768
0
          unsigned ctxidx = DeriveCtx::CtxIBCFlag(cu);
769
0
          m_BinEncoder.encodeBin(CU::isIBC(cu), Ctx::IBCFlag(ctxidx));
770
0
        }
771
18.4E
      }
772
18.4E
    }
773
319k
  }
774
106k
  else
775
106k
  {
776
106k
    if( CU::isConsInter(cu) )
777
0
    {
778
0
      assert( CU::isInter( cu ) );
779
0
      return;
780
0
    }
781
782
106k
    if ( cu.cs->slice->isIntra() || ( cu.lwidth() == 4 && cu.lheight() == 4 ) || CU::isConsIntra(cu) )
783
106k
    {
784
106k
      if (cu.cs->slice->sps->PLT && cu.lwidth() <= 64 && cu.lheight() <= 64 && ( ( (!isLuma(cu.chType)) && (cu.chromaSize().width * cu.chromaSize().height > 16) ) || ((isLuma(cu.chType)) && ((cu.lumaSize().width * cu.lumaSize().height) > 16 ) ) ) && (!CU::isLocalSepTree(cu) || isLuma(cu.chType) ) )
785
0
      {
786
0
        m_BinEncoder.encodeBin((CU::isPLT(cu)), Ctx::PLTFlag(0));
787
0
      }
788
106k
      return;
789
106k
    }
790
0
    m_BinEncoder.encodeBin((CU::isIntra(cu) || CU::isPLT(cu)), Ctx::PredMode(DeriveCtx::CtxPredModeFlag()));
791
0
    if ((CU::isIntra(cu) || CU::isPLT(cu)) && cu.cs->slice->sps->PLT && cu.lwidth() <= 64 && cu.lheight() <= 64&& ( ( (!isLuma(cu.chType)) && (cu.chromaSize().width * cu.chromaSize().height > 16) ) || ((isLuma(cu.chType)) && ((cu.lumaSize().width * cu.lumaSize().height) > 16 ) ) ) && (!CU::isLocalSepTree(cu) || isLuma(cu.chType)  ) )
792
0
    {
793
0
      m_BinEncoder.encodeBin((CU::isPLT(cu)), Ctx::PLTFlag(0));
794
0
    }
795
0
  }
796
426k
}
797
798
799
void CABACWriter::bdpcm_mode( const CodingUnit& cu, const ComponentID compID )
800
737k
{
801
737k
  if( !cu.cs->sps->BDPCM) return;
802
737k
  if( !CU::bdpcmAllowed( cu, compID ) ) return;
803
804
328k
  int bdpcmMode = cu.bdpcmM[toChannelType(compID)];
805
806
328k
  unsigned ctxId = isLuma(compID) ? 0 : 2; 
807
328k
  m_BinEncoder.encodeBin(bdpcmMode > 0 ? 1 : 0, Ctx::BDPCMMode(ctxId));
808
328k
  if (bdpcmMode)
809
59.2k
  {
810
59.2k
    m_BinEncoder.encodeBin(bdpcmMode > 1 ? 1 : 0, Ctx::BDPCMMode(ctxId+1));
811
59.2k
  }
812
328k
  if (isLuma(compID))
813
45.1k
  {
814
45.1k
    DTRACE(g_trace_ctx, D_SYNTAX, "bdpcm_mode(%d) x=%d, y=%d, w=%d, h=%d, bdpcm=%d\n", CH_L, cu.lumaPos().x, cu.lumaPos().y, cu.lwidth(), cu.lheight(), cu.bdpcmM[CH_L]);
815
45.1k
  }
816
283k
  else
817
283k
  {
818
283k
    DTRACE(g_trace_ctx, D_SYNTAX, "bdpcm_mode(%d) x=%d, y=%d, w=%d, h=%d, bdpcm=%d\n", CH_C, cu.chromaPos().x, cu.chromaPos().y, cu.chromaSize().width, cu.chromaSize().height, cu.bdpcmM[CH_C]);
819
283k
  }
820
328k
}
821
822
823
void CABACWriter::cu_pred_data( const CodingUnit& cu )
824
220k
{
825
220k
  if( CU::isIntra( cu ) )
826
193k
  {
827
193k
    if( cu.Y().valid() )
828
86.9k
    {
829
86.9k
      bdpcm_mode( cu, COMP_Y );
830
86.9k
    }
831
193k
    intra_luma_pred_modes  ( cu );
832
193k
    if( ( !cu.Y().valid() || ( !CU::isSepTree(cu) && cu.Y().valid() ) ) && isChromaEnabled(cu.chromaFormat) )
833
106k
    {
834
106k
      bdpcm_mode( cu, ComponentID(CH_C) );
835
106k
    } 
836
193k
    intra_chroma_pred_modes( cu );
837
193k
    return;
838
193k
  }
839
26.8k
  if (!cu.Y().valid()) // dual tree chroma CU
840
0
  {
841
0
    return;
842
0
  }
843
844
26.8k
  prediction_unit ( cu );
845
26.8k
  imv_mode        ( cu );
846
26.8k
  affine_amvr_mode( cu );
847
26.8k
  cu_bcw_flag     ( cu );
848
26.8k
}
849
850
851
void CABACWriter::cu_bcw_flag(const CodingUnit& cu)
852
26.8k
{
853
26.8k
  if(!CU::isBcwIdxCoded(cu))
854
26.8k
  {
855
26.8k
    return;
856
26.8k
  }
857
858
0
  CHECK(!(BCW_NUM > 1 && (BCW_NUM == 2 || (BCW_NUM & 0x01) == 1)), " !( BCW_NUM > 1 && ( BCW_NUM == 2 || ( BCW_NUM & 0x01 ) == 1 ) ) ");
859
0
  const uint8_t bcwCodingIdx = (uint8_t)g_BcwCodingOrder[CU::getValidBcwIdx(cu)];
860
861
0
  const int32_t numBcw = (cu.slice->checkLDC) ? 5 : 3;
862
0
  m_BinEncoder.encodeBin((bcwCodingIdx == 0 ? 0 : 1), Ctx::BcwIdx(0));
863
0
  if(numBcw > 2 && bcwCodingIdx != 0)
864
0
  {
865
0
    const uint32_t prefixNumBits = numBcw - 2;
866
0
    const uint32_t step = 1;
867
868
0
    uint8_t idx = 1;
869
0
    for(int ui = 0; ui < prefixNumBits; ++ui)
870
0
    {
871
0
      if (bcwCodingIdx == idx)
872
0
      {
873
0
        m_BinEncoder.encodeBinEP(0);
874
0
        break;
875
0
      }
876
0
      else
877
0
      {
878
0
        m_BinEncoder.encodeBinEP(1);
879
0
        idx += step;
880
0
      }
881
0
    }
882
0
  }
883
884
0
  DTRACE(g_trace_ctx, D_SYNTAX, "cu_bcw_flag() bcw_idx=%d\n", cu.BcwIdx ? 1 : 0);
885
0
}
886
887
888
void CABACWriter::xWriteTruncBinCode(uint32_t symbol, uint32_t maxSymbol)
889
998k
{
890
998k
  int thresh;
891
998k
  if (maxSymbol > 256)
892
0
  {
893
0
    int threshVal = 1 << 8;
894
0
    thresh = 8;
895
0
    while (threshVal <= maxSymbol)
896
0
    {
897
0
      thresh++;
898
0
      threshVal <<= 1;
899
0
    }
900
0
    thresh--;
901
0
  }
902
998k
  else
903
998k
  {
904
998k
    thresh = g_tbMax[maxSymbol];
905
998k
  }
906
907
998k
  int val = 1 << thresh;
908
998k
  assert(val <= maxSymbol);
909
998k
  assert((val << 1) > maxSymbol);
910
998k
  assert(symbol < maxSymbol);
911
998k
  int b = maxSymbol - val;
912
998k
  assert(b < val);
913
998k
  if (symbol < val - b)
914
309k
  {
915
309k
    m_BinEncoder.encodeBinsEP(symbol, thresh);
916
309k
  }
917
689k
  else
918
689k
  {
919
689k
    symbol += val - b;
920
689k
    assert(symbol < (val << 1));
921
689k
    assert((symbol >> 1) >= val - b);
922
689k
    m_BinEncoder.encodeBinsEP(symbol, thresh + 1);
923
689k
  }
924
998k
}
925
926
927
void CABACWriter::extend_ref_line(const CodingUnit& cu)
928
1.07M
{
929
1.07M
  if ( !cu.Y().valid() || cu.predMode != MODE_INTRA || !isLuma(cu.chType) || cu.bdpcmM[CH_L] )
930
0
  {
931
0
    return;
932
0
  }
933
1.07M
  if( !cu.cs->sps->MRL )
934
0
  {
935
0
    return;
936
0
  }
937
938
1.07M
  bool isFirstLineOfCtu = (((cu.block(COMP_Y).y)&((cu.cs->sps)->CTUSize - 1)) == 0);
939
1.07M
  if (isFirstLineOfCtu)
940
359k
  {
941
359k
    return;
942
359k
  }
943
712k
  int multiRefIdx = cu.multiRefIdx;
944
712k
  if (MRL_NUM_REF_LINES > 1)
945
712k
  {
946
712k
    m_BinEncoder.encodeBin(multiRefIdx != MULTI_REF_LINE_IDX[0], Ctx::MultiRefLineIdx(0));
947
712k
    if (MRL_NUM_REF_LINES > 2 && multiRefIdx != MULTI_REF_LINE_IDX[0])
948
194k
    {
949
194k
      m_BinEncoder.encodeBin(multiRefIdx != MULTI_REF_LINE_IDX[1], Ctx::MultiRefLineIdx(1));
950
194k
    }
951
712k
  }
952
712k
}
953
954
955
void CABACWriter::intra_luma_pred_modes( const CodingUnit& cu )
956
193k
{
957
193k
  if( !cu.Y().valid() || cu.bdpcmM[CH_L] )
958
112k
  {
959
112k
    return;
960
112k
  }
961
962
81.0k
  mip_flag(cu);
963
81.0k
  if (cu.mipFlag)
964
1.67k
  {
965
1.67k
    mip_pred_modes(cu);
966
1.67k
    return;
967
1.67k
  }
968
79.4k
  extend_ref_line( cu );
969
970
79.4k
  isp_mode( cu );
971
972
79.4k
  const int numMPMs   = NUM_MOST_PROBABLE_MODES;
973
79.4k
  unsigned  mpm_pred   [numMPMs];
974
79.4k
  unsigned  mpm_idx;
975
79.4k
  unsigned  ipred_mode ;
976
977
  // prev_intra_luma_pred_flag
978
79.4k
  {
979
79.4k
    CU::getIntraMPMs( cu, mpm_pred );
980
981
79.4k
    ipred_mode = cu.intraDir[0];
982
79.4k
    mpm_idx    = numMPMs;
983
79.4k
    for( unsigned idx = 0; idx < numMPMs; idx++ )
984
79.4k
    {
985
79.4k
      if( ipred_mode == mpm_pred[idx] )
986
79.4k
      {
987
79.4k
        mpm_idx = idx;
988
79.4k
        break;
989
79.4k
      }
990
79.4k
    }
991
79.4k
    if ( cu.multiRefIdx )
992
0
    {
993
0
      CHECK(mpm_idx >= numMPMs, "use of non-MPM");
994
0
    }
995
79.4k
    else
996
79.4k
    {
997
79.4k
      m_BinEncoder.encodeBin(mpm_idx < numMPMs, Ctx::IntraLumaMpmFlag());
998
79.4k
    }
999
79.4k
  }
1000
1001
  // mpm_idx / rem_intra_luma_pred_mode
1002
79.4k
  {
1003
79.4k
    if( mpm_idx < numMPMs )
1004
79.4k
    {
1005
79.4k
      {
1006
79.4k
        unsigned ctx = (cu.ispMode == NOT_INTRA_SUBPARTITIONS ? 1 : 0);
1007
79.4k
        if (cu.multiRefIdx == 0)
1008
79.4k
          m_BinEncoder.encodeBin(mpm_idx > 0, Ctx::IntraLumaPlanarFlag(ctx));
1009
79.4k
        if( mpm_idx )
1010
81
        {
1011
81
          m_BinEncoder.encodeBinEP( mpm_idx > 1 );
1012
81
        }
1013
79.4k
        if (mpm_idx > 1)
1014
0
        {
1015
0
          m_BinEncoder.encodeBinEP(mpm_idx > 2);
1016
0
        }
1017
79.4k
        if (mpm_idx > 2)
1018
0
        {
1019
0
          m_BinEncoder.encodeBinEP(mpm_idx > 3);
1020
0
        }
1021
79.4k
        if (mpm_idx > 3)
1022
0
        {
1023
0
          m_BinEncoder.encodeBinEP(mpm_idx > 4);
1024
0
        }
1025
79.4k
      }
1026
79.4k
    }
1027
0
    else
1028
0
    {
1029
      // sorting of MPMs
1030
0
      std::sort( mpm_pred, mpm_pred + numMPMs );
1031
1032
0
      {
1033
0
        for (int idx = numMPMs - 1; idx >= 0; idx--)
1034
0
        {
1035
0
          if (ipred_mode > mpm_pred[idx])
1036
0
          {
1037
0
            ipred_mode--;
1038
0
          }
1039
0
        }
1040
0
        CHECK(ipred_mode >= 64, "Incorrect mode");
1041
0
        xWriteTruncBinCode(ipred_mode, NUM_LUMA_MODE - NUM_MOST_PROBABLE_MODES);  // Remaining mode is truncated binary coded
1042
0
      }
1043
0
    }
1044
1045
79.4k
    DTRACE( g_trace_ctx, D_SYNTAX, "intra_luma_pred_modes() idx=%d pos=(%d,%d) mode=%d\n", 0, cu.lumaPos().x, cu.lumaPos().y, cu.intraDir[0] );
1046
79.4k
  }
1047
79.4k
}
1048
1049
1050
void CABACWriter::intra_luma_pred_mode( const CodingUnit& cu, const unsigned *mpmLst )
1051
1.32M
{
1052
1.32M
  if( cu.bdpcmM[CH_L] ) 
1053
8.29k
  {
1054
8.29k
    return;
1055
8.29k
  }
1056
1057
1.31M
  mip_flag(cu);
1058
1.31M
  if (cu.mipFlag)
1059
322k
  {
1060
322k
    mip_pred_mode(cu);
1061
322k
    return;
1062
322k
  }
1063
992k
  extend_ref_line( cu );
1064
1065
992k
  isp_mode( cu );
1066
1067
  // prev_intra_luma_pred_flag
1068
992k
  unsigned ipred_mode = cu.intraDir[0];
1069
992k
  static constexpr int numMPMs = NUM_MOST_PROBABLE_MODES;
1070
992k
  unsigned mpm_idx = numMPMs;
1071
992k
  unsigned  mpm_pred[numMPMs];
1072
1073
992k
  if (mpmLst)
1074
992k
  {
1075
992k
    memcpy(mpm_pred, mpmLst, sizeof(unsigned) * numMPMs);
1076
992k
  }
1077
18.4E
  else
1078
18.4E
  {
1079
18.4E
    CU::getIntraMPMs(cu, mpm_pred);
1080
18.4E
  }
1081
1082
5.23M
  for (int idx = 0; idx < numMPMs; idx++)
1083
4.63M
  {
1084
4.63M
    if (ipred_mode == mpm_pred[idx])
1085
392k
    {
1086
392k
      mpm_idx = idx;
1087
392k
      break;
1088
392k
    }
1089
4.63M
  }
1090
992k
  if (cu.multiRefIdx)
1091
194k
  {
1092
194k
    CHECK(mpm_idx >= numMPMs, "use of non-MPM");
1093
194k
  }
1094
797k
  else
1095
797k
  {
1096
797k
    m_BinEncoder.encodeBin(mpm_idx < numMPMs, Ctx::IntraLumaMpmFlag());
1097
797k
  }
1098
1099
  // mpm_idx / rem_intra_luma_pred_mode
1100
992k
  if( mpm_idx < numMPMs )
1101
392k
  {
1102
392k
    unsigned ctx = (cu.ispMode == NOT_INTRA_SUBPARTITIONS ? 1 : 0);
1103
392k
    if (cu.multiRefIdx == 0)
1104
197k
      m_BinEncoder.encodeBin( mpm_idx > 0, Ctx::IntraLumaPlanarFlag(ctx) );
1105
392k
    if( mpm_idx )
1106
265k
    {
1107
265k
      m_BinEncoder.encodeBinEP( mpm_idx > 1 );
1108
265k
    }
1109
392k
    if (mpm_idx > 1)
1110
150k
    {
1111
150k
      m_BinEncoder.encodeBinEP(mpm_idx > 2);
1112
150k
    }
1113
392k
    if (mpm_idx > 2)
1114
111k
    {
1115
111k
      m_BinEncoder.encodeBinEP(mpm_idx > 3);
1116
111k
    }
1117
392k
    if (mpm_idx > 3)
1118
74.2k
    {
1119
74.2k
      m_BinEncoder.encodeBinEP(mpm_idx > 4);
1120
74.2k
    }
1121
392k
  }
1122
599k
  else
1123
599k
  {
1124
    // mpm_pred[0] is always 0, i.e. PLANAR, so its always first in the list
1125
599k
    std::sort( mpm_pred + 1, mpm_pred + numMPMs );
1126
1127
4.19M
    for (int idx = numMPMs - 1; idx >= 0; idx--)
1128
3.60M
    {
1129
3.60M
      if (ipred_mode > mpm_pred[idx])
1130
1.94M
      {
1131
1.94M
        ipred_mode--;
1132
1.94M
      }
1133
3.60M
    }
1134
1135
599k
    xWriteTruncBinCode(ipred_mode, NUM_LUMA_MODE - NUM_MOST_PROBABLE_MODES);  // Remaining mode is truncated binary coded
1136
599k
  }
1137
992k
}
1138
1139
1140
void CABACWriter::intra_chroma_pred_modes( const CodingUnit& cu )
1141
193k
{
1142
193k
  if( cu.chromaFormat == CHROMA_400 || ( CU::isSepTree(cu) && cu.chType == CH_L ) || cu.bdpcmM[CH_C] )
1143
86.9k
  {
1144
86.9k
    return;
1145
86.9k
  }
1146
1147
106k
  intra_chroma_pred_mode( cu );
1148
106k
}
1149
1150
1151
void CABACWriter::intra_chroma_lmc_mode(const CodingUnit& cu)
1152
39.0k
{
1153
39.0k
  const unsigned intraDir = cu.intraDir[1];
1154
39.0k
  int lmModeList[10];
1155
39.0k
  CU::getLMSymbolList(cu, lmModeList);
1156
39.0k
  int symbol = -1;
1157
39.0k
  for (int k = 0; k < LM_SYMBOL_NUM; k++)
1158
39.0k
  {
1159
39.0k
    if (lmModeList[k] == intraDir)
1160
39.0k
    {
1161
39.0k
      symbol = k;
1162
39.0k
      break;
1163
39.0k
    }
1164
39.0k
  }
1165
39.0k
  CHECK(symbol < 0, "invalid symbol found");
1166
1167
39.0k
  m_BinEncoder.encodeBin(symbol == 0 ? 0 : 1, Ctx::CclmModeIdx(0));
1168
1169
39.0k
  if (symbol > 0)
1170
0
  {
1171
0
    CHECK(symbol > 2, "invalid symbol for MMLM");
1172
0
    unsigned int symbol_minus_1 = symbol - 1;
1173
0
    m_BinEncoder.encodeBinEP(symbol_minus_1);
1174
0
  }
1175
39.0k
}
1176
1177
1178
void CABACWriter::intra_chroma_pred_mode(const CodingUnit& cu)
1179
444k
{
1180
444k
  if (cu.colorTransform)
1181
0
  {
1182
0
    CHECK(cu.intraDir[CH_C] != DM_CHROMA_IDX, "chroma should use DM for adaptive color transform");
1183
0
    return;
1184
0
  }
1185
1186
444k
  const unsigned intraDir = cu.intraDir[1];
1187
444k
  if (cu.cs->sps->LMChroma && CU::checkCCLMAllowed(cu))
1188
304k
  {
1189
304k
    m_BinEncoder.encodeBin(CU::isLMCMode(intraDir) ? 1 : 0, Ctx::CclmModeFlag(0));
1190
304k
    if (CU::isLMCMode(intraDir))
1191
39.0k
    {
1192
39.0k
      intra_chroma_lmc_mode(cu);
1193
39.0k
      return;
1194
39.0k
    }
1195
304k
  }
1196
1197
405k
  const bool     isDerivedMode = intraDir == DM_CHROMA_IDX;
1198
405k
  m_BinEncoder.encodeBin(isDerivedMode ? 0 : 1, Ctx::IntraChromaPredMode(0));
1199
405k
  if (isDerivedMode)
1200
91.4k
  {
1201
91.4k
    return;
1202
91.4k
  }
1203
1204
  // chroma candidate index
1205
313k
  unsigned chromaCandModes[NUM_CHROMA_MODE];
1206
313k
  CU::getIntraChromaCandModes(cu, chromaCandModes);
1207
1208
313k
  int candId = 0;
1209
743k
  for (; candId < NUM_CHROMA_MODE; candId++)
1210
743k
  {
1211
743k
    if (intraDir == chromaCandModes[candId])
1212
313k
    {
1213
313k
      break;
1214
313k
    }
1215
743k
  }
1216
1217
313k
  CHECK(candId >= NUM_CHROMA_MODE, "Chroma prediction mode index out of bounds");
1218
313k
  CHECK(chromaCandModes[candId] == DM_CHROMA_IDX, "The intra dir cannot be DM_CHROMA for this path");
1219
313k
  {
1220
313k
    m_BinEncoder.encodeBinsEP(candId, 2);
1221
313k
  }
1222
313k
}
1223
1224
1225
void CABACWriter::cu_residual( const CodingUnit& cu, Partitioner& partitioner, CUCtx& cuCtx )
1226
220k
{
1227
220k
  if (!CU::isIntra(cu))
1228
26.8k
  {
1229
26.8k
    if( !cu.mergeFlag )
1230
26.8k
    {
1231
26.8k
      rqt_root_cbf( cu );
1232
26.8k
    }
1233
26.8k
    if( cu.rootCbf )
1234
139
    {
1235
139
      sbt_mode( cu );
1236
139
    }
1237
1238
26.8k
    if( !cu.rootCbf )
1239
26.7k
    {
1240
26.7k
      CHECK(cu.colorTransform, "ACT should not be enabled for root_cbf = 0");
1241
26.7k
      return;
1242
26.7k
    }
1243
26.8k
  }
1244
1245
193k
  if( CU::isInter( cu ) || CU::isIBC( cu ) )
1246
139
  {
1247
139
    adaptive_color_transform(cu);
1248
139
  }
1249
1250
193k
  cuCtx.violatesLfnstConstrained[CH_L] = false;
1251
193k
  cuCtx.violatesLfnstConstrained[CH_C] = false;
1252
193k
  cuCtx.lfnstLastScanPos               = false;
1253
193k
  cuCtx.violatesMtsCoeffConstraint     = false;
1254
193k
  cuCtx.mtsLastScanPos                                = false;
1255
1256
193k
  if( cu.ispMode && isLuma( partitioner.chType ) )
1257
49
  {
1258
49
    transform_tree( *cu.cs, partitioner, cuCtx, CU::getISPType( cu, getFirstComponentOfChannel( partitioner.chType ) ), 0 );
1259
49
  }
1260
193k
  else
1261
193k
  {
1262
193k
    transform_tree( *cu.cs, partitioner, cuCtx );
1263
193k
  }
1264
1265
193k
  residual_lfnst_mode( cu, cuCtx );
1266
193k
  mts_idx            ( cu, &cuCtx );
1267
193k
}
1268
1269
1270
void CABACWriter::rqt_root_cbf( const CodingUnit& cu )
1271
53.7k
{
1272
53.7k
  m_BinEncoder.encodeBin( cu.rootCbf, Ctx::QtRootCbf() );
1273
1274
53.7k
  DTRACE( g_trace_ctx, D_SYNTAX, "rqt_root_cbf() ctx=0 root_cbf=%d pos=(%d,%d)\n", cu.rootCbf ? 1 : 0, cu.lumaPos().x, cu.lumaPos().y );
1275
53.7k
}
1276
1277
1278
void CABACWriter::adaptive_color_transform(const CodingUnit& cu)
1279
95.3k
{
1280
95.3k
  if (!cu.slice->sps->useColorTrans )
1281
95.3k
  {
1282
95.3k
    return;
1283
95.3k
  }
1284
1285
0
  if (CU::isSepTree(cu))
1286
0
  {
1287
0
    CHECK(cu.colorTransform, "adaptive color transform should be disabled when dualtree and localtree are enabled");
1288
0
    return;
1289
0
  }
1290
1291
0
  if (CU::isInter(cu) || CU::isIBC(cu) || CU::isIntra(cu))
1292
0
  {
1293
0
    m_BinEncoder.encodeBin(cu.colorTransform, Ctx::ACTFlag());
1294
0
  }
1295
0
}
1296
1297
1298
void CABACWriter::sbt_mode( const CodingUnit& cu )
1299
139
{
1300
139
  uint8_t sbtAllowed = CU::checkAllowedSbt(cu);
1301
139
  if( !sbtAllowed )
1302
139
  {
1303
139
    return;
1304
139
  }
1305
1306
0
  SizeType cuWidth = cu.lwidth();
1307
0
  SizeType cuHeight = cu.lheight();
1308
0
  uint8_t sbtIdx = CU::getSbtIdx( cu.sbtInfo );
1309
0
  uint8_t sbtPos = CU::getSbtPos( cu.sbtInfo );
1310
1311
  //bin - flag
1312
0
  bool sbtFlag = cu.sbtInfo != 0;
1313
0
  uint8_t ctxIdx = ( cuWidth * cuHeight <= 256 ) ? 1 : 0;
1314
0
  m_BinEncoder.encodeBin( sbtFlag, Ctx::SbtFlag( ctxIdx ) );
1315
0
  if( !sbtFlag )
1316
0
  {
1317
0
    return;
1318
0
  }
1319
1320
0
  bool sbtQuadFlag = sbtIdx == SBT_HOR_QUAD || sbtIdx == SBT_VER_QUAD;
1321
0
  bool sbtHorFlag = sbtIdx == SBT_HOR_HALF || sbtIdx == SBT_HOR_QUAD;
1322
0
  bool sbtPosFlag = sbtPos == SBT_POS1;
1323
1324
0
  uint8_t sbtVerHalfAllow = CU::targetSbtAllowed( SBT_VER_HALF, sbtAllowed );
1325
0
  uint8_t sbtHorHalfAllow = CU::targetSbtAllowed( SBT_HOR_HALF, sbtAllowed );
1326
0
  uint8_t sbtVerQuadAllow = CU::targetSbtAllowed( SBT_VER_QUAD, sbtAllowed );
1327
0
  uint8_t sbtHorQuadAllow = CU::targetSbtAllowed( SBT_HOR_QUAD, sbtAllowed );
1328
  //bin - type
1329
0
  if( ( sbtHorHalfAllow || sbtVerHalfAllow ) && ( sbtHorQuadAllow || sbtVerQuadAllow ) )
1330
0
  {
1331
0
    m_BinEncoder.encodeBin( sbtQuadFlag, Ctx::SbtQuadFlag( 0 ) );
1332
0
  }
1333
0
  else
1334
0
  {
1335
0
    assert( sbtQuadFlag == 0 );
1336
0
  }
1337
1338
  //bin - dir
1339
0
  if( ( sbtQuadFlag && sbtVerQuadAllow && sbtHorQuadAllow ) || ( !sbtQuadFlag && sbtVerHalfAllow && sbtHorHalfAllow ) ) //both direction allowed
1340
0
  {
1341
0
    uint8_t ctxIdx = ( cuWidth == cuHeight ) ? 0 : ( cuWidth < cuHeight ? 1 : 2 );
1342
0
    m_BinEncoder.encodeBin( sbtHorFlag, Ctx::SbtHorFlag( ctxIdx ) );
1343
0
  }
1344
0
  else
1345
0
  {
1346
0
    assert( sbtHorFlag == ( ( sbtQuadFlag && sbtHorQuadAllow ) || ( !sbtQuadFlag && sbtHorHalfAllow ) ) );
1347
0
  }
1348
1349
  //bin - pos
1350
0
  m_BinEncoder.encodeBin( sbtPosFlag, Ctx::SbtPosFlag( 0 ) );
1351
1352
0
  DTRACE( g_trace_ctx, D_SYNTAX, "sbt_mode() pos=(%d,%d) sbtInfo=%d\n", cu.lx(), cu.ly(), (int)cu.sbtInfo );
1353
0
}
1354
1355
1356
void CABACWriter::end_of_ctu( const CodingUnit& cu, CUCtx& cuCtx )
1357
95.2k
{
1358
95.2k
  const bool    isLastSubCUOfCtu  = CU::isLastSubCUOfCtu( cu );
1359
1360
95.2k
  if ( isLastSubCUOfCtu
1361
18.6k
    && ( !CU::isSepTree(cu) || cu.chromaFormat == CHROMA_400 || isChroma( cu.chType ) )
1362
95.2k
      )
1363
9.30k
  {
1364
9.30k
    cuCtx.isDQPCoded = ( cu.cs->pps->useDQP && !cuCtx.isDQPCoded );
1365
1366
9.30k
  }
1367
95.2k
}
1368
1369
1370
void CABACWriter::cu_palette_info(const CodingUnit& cu, ComponentID compBegin, uint32_t numComp, CUCtx& cuCtx)
1371
0
{
1372
0
  THROW("no support");
1373
0
}
1374
1375
1376
//================================================================================
1377
//  clause 7.3.8.6
1378
//--------------------------------------------------------------------------------
1379
//    void  prediction_unit ( cu );
1380
//    void  merge_flag      ( cu );
1381
//    void  merge_idx       ( cu );
1382
//    void  inter_pred_idc  ( cu );
1383
//    void  ref_idx         ( cu, refList );
1384
//    void  mvp_flag        ( cu, refList );
1385
//================================================================================
1386
1387
void CABACWriter::prediction_unit( const CodingUnit& cu )
1388
26.8k
{
1389
26.8k
  CHECK( cu.treeType == TREE_C, "cannot be chroma CU" );
1390
26.8k
  if( cu.skip )
1391
0
  {
1392
0
    CHECK( !cu.mergeFlag, "merge_flag must be true for skipped CUs" );
1393
0
  }
1394
26.8k
  else
1395
26.8k
  {
1396
26.8k
    merge_flag( cu );
1397
26.8k
  }
1398
26.8k
  if( cu.mergeFlag )
1399
0
  {
1400
0
    merge_data(cu);
1401
0
  }
1402
26.8k
  else if (CU::isIBC(cu))
1403
26.8k
  {
1404
26.8k
    ref_idx(cu, REF_PIC_LIST_0);
1405
26.8k
    Mv mvd = cu.mvd[REF_PIC_LIST_0][0];
1406
26.8k
    mvd.changeIbcPrecInternal2Amvr(cu.imv);
1407
26.8k
    mvd_coding(mvd, 0); // already changed to signaling precision
1408
26.8k
    if ( cu.slice->sps->maxNumIBCMergeCand == 1 )
1409
0
    {
1410
0
      CHECK( cu.mvpIdx[REF_PIC_LIST_0], "mvpIdx for IBC mode should be 0" );
1411
0
    }
1412
26.8k
    else
1413
26.8k
    mvp_flag(cu, REF_PIC_LIST_0);
1414
26.8k
  }
1415
0
  else
1416
0
  {
1417
0
    inter_pred_idc( cu );
1418
0
    affine_flag   ( cu );
1419
0
    smvd_mode( cu );
1420
0
    if( cu.interDir != 2 /* PRED_L1 */ )
1421
0
    {
1422
0
      ref_idx     ( cu, REF_PIC_LIST_0 );
1423
0
      if ( cu.affine )
1424
0
      {
1425
0
        Mv mvd = cu.mvd[REF_PIC_LIST_0][0];
1426
0
        mvd.changeAffinePrecInternal2Amvr(cu.imv);
1427
0
        mvd_coding(mvd, 0); // already changed to signaling precision
1428
0
        mvd = cu.mvd[REF_PIC_LIST_0][1];
1429
0
        mvd.changeAffinePrecInternal2Amvr(cu.imv);
1430
0
        mvd_coding(mvd, 0); // already changed to signaling precision
1431
0
        if ( cu.affineType == AFFINEMODEL_6PARAM )
1432
0
        {
1433
0
          mvd = cu.mvd[REF_PIC_LIST_0][2];
1434
0
          mvd.changeAffinePrecInternal2Amvr(cu.imv);
1435
0
          mvd_coding(mvd, 0); // already changed to signaling precision
1436
0
        }
1437
0
      }
1438
0
      else
1439
0
      {
1440
0
        Mv mvd = cu.mvd[REF_PIC_LIST_0][0];
1441
0
        mvd.changeTransPrecInternal2Amvr(cu.imv);
1442
0
        mvd_coding(mvd, 0); // already changed to signaling precision
1443
0
      }
1444
0
      mvp_flag    ( cu, REF_PIC_LIST_0 );
1445
0
    }
1446
0
    if( cu.interDir != 1 /* PRED_L0 */ )
1447
0
    {
1448
0
      if ( cu.smvdMode != 1 )
1449
0
      {
1450
0
        ref_idx     ( cu, REF_PIC_LIST_1 );
1451
0
        if( !cu.cs->picHeader->mvdL1Zero || cu.interDir != 3 /* PRED_BI */ )
1452
0
        {
1453
0
          if ( cu.affine )
1454
0
          {
1455
0
            Mv mvd = cu.mvd[REF_PIC_LIST_1][0];
1456
0
            mvd.changeAffinePrecInternal2Amvr(cu.imv);
1457
0
            mvd_coding(mvd, 0); // already changed to signaling precision
1458
0
            mvd = cu.mvd[REF_PIC_LIST_1][1];
1459
0
            mvd.changeAffinePrecInternal2Amvr(cu.imv);
1460
0
            mvd_coding(mvd, 0); // already changed to signaling precision
1461
0
            if ( cu.affineType == AFFINEMODEL_6PARAM )
1462
0
            {
1463
0
              mvd = cu.mvd[REF_PIC_LIST_1][2];
1464
0
              mvd.changeAffinePrecInternal2Amvr(cu.imv);
1465
0
              mvd_coding(mvd, 0); // already changed to signaling precision
1466
0
            }
1467
0
          }
1468
0
          else
1469
0
          {
1470
0
            Mv mvd = cu.mvd[REF_PIC_LIST_1][0];
1471
0
            mvd.changeTransPrecInternal2Amvr(cu.imv);
1472
0
            mvd_coding(mvd, 0); // already changed to signaling precision
1473
0
          }
1474
0
        }
1475
0
      }
1476
0
      mvp_flag    ( cu, REF_PIC_LIST_1 );
1477
0
    }
1478
0
  }
1479
26.8k
}
1480
1481
1482
void CABACWriter::smvd_mode( const CodingUnit& cu )
1483
0
{
1484
0
  if ( cu.interDir != 3 || cu.affine )
1485
0
  {
1486
0
    return;
1487
0
  }
1488
1489
0
  if ( cu.cs->slice->biDirPred == false )
1490
0
  {
1491
0
    return;
1492
0
  }
1493
1494
0
  m_BinEncoder.encodeBin( cu.smvdMode ? 1 : 0, Ctx::SmvdFlag() );
1495
1496
0
  DTRACE( g_trace_ctx, D_SYNTAX, "symmvd_flag() symmvd=%d pos=(%d,%d) size=%dx%d\n", cu.smvdMode ? 1 : 0, cu.lumaPos().x, cu.lumaPos().y, cu.lumaSize().width, cu.lumaSize().height );
1497
0
}
1498
1499
1500
void CABACWriter::subblock_merge_flag( const CodingUnit& cu )
1501
0
{
1502
1503
0
  if ( !cu.cs->slice->isIntra() && (cu.slice->picHeader->maxNumAffineMergeCand > 0) && cu.lumaSize().width >= 8 && cu.lumaSize().height >= 8 )
1504
0
  {
1505
0
    unsigned ctxId = DeriveCtx::CtxAffineFlag();
1506
0
    m_BinEncoder.encodeBin( cu.affine, Ctx::SubblockMergeFlag( ctxId ) );
1507
0
    DTRACE( g_trace_ctx, D_SYNTAX, "subblock_merge_flag() subblock_merge_flag=%d ctx=%d pos=(%d,%d)\n", cu.affine ? 1 : 0, ctxId, cu.Y().x, cu.Y().y );
1508
0
  }
1509
0
}
1510
1511
1512
void CABACWriter::affine_flag( const CodingUnit& cu )
1513
0
{
1514
0
  if ( !cu.cs->slice->isIntra() && cu.cs->sps->Affine && cu.lumaSize().width > 8 && cu.lumaSize().height > 8 )
1515
0
  {
1516
0
    unsigned ctxId = DeriveCtx::CtxAffineFlag();
1517
0
    m_BinEncoder.encodeBin( cu.affine, Ctx::AffineFlag( ctxId ) );
1518
0
    DTRACE( g_trace_ctx, D_SYNTAX, "affine_flag() affine=%d ctx=%d pos=(%d,%d)\n", cu.affine ? 1 : 0, ctxId, cu.Y().x, cu.Y().y );
1519
1520
0
    if ( cu.affine && cu.cs->sps->AffineType )
1521
0
    {
1522
0
      unsigned ctxId = 0;
1523
0
      m_BinEncoder.encodeBin( cu.affineType, Ctx::AffineType( ctxId ) );
1524
0
      DTRACE( g_trace_ctx, D_SYNTAX, "affine_type() affine_type=%d ctx=%d pos=(%d,%d)\n", cu.affineType ? 1 : 0, ctxId, cu.Y().x, cu.Y().y );
1525
0
    }
1526
0
  }
1527
0
}
1528
1529
1530
void CABACWriter::merge_flag( const CodingUnit& cu )
1531
26.8k
{
1532
26.8k
  m_BinEncoder.encodeBin( cu.mergeFlag, Ctx::MergeFlag() );
1533
1534
26.8k
  DTRACE( g_trace_ctx, D_SYNTAX, "merge_flag() merge=%d pos=(%d,%d) size=%dx%d\n", cu.mergeFlag ? 1 : 0, cu.lumaPos().x, cu.lumaPos().y, cu.lumaSize().width, cu.lumaSize().height );
1535
26.8k
}
1536
1537
1538
void CABACWriter::merge_data(const CodingUnit& cu)
1539
0
{
1540
0
  if (CU::isIBC(cu))
1541
0
  {
1542
0
    merge_idx(cu);
1543
0
    return;
1544
0
  }
1545
0
  subblock_merge_flag(cu);
1546
0
  if (cu.affine)
1547
0
  {
1548
0
    merge_idx(cu);
1549
0
    return;
1550
0
  }
1551
1552
0
  const bool ciipAvailable = cu.cs->sps->CIIP && !cu.skip && cu.Y().maxDim() < MAX_CU_SIZE && cu.Y().area() >= 64;
1553
0
  const bool geoAvailable = cu.cs->slice->sps->GEO && cu.cs->slice->isInterB() && cu.cs->sps->maxNumGeoCand > 1
1554
0
                                                   && cu.Y().minDim() >= GEO_MIN_CU_SIZE && cu.Y().maxDim() <= GEO_MAX_CU_SIZE
1555
0
                                                   && cu.Y().maxDim() < 8 * cu.Y().minDim();
1556
1557
0
  if (geoAvailable || ciipAvailable)
1558
0
  {
1559
0
    m_BinEncoder.encodeBin(!cu.geo && !cu.ciip, Ctx::RegularMergeFlag(cu.skip ? 0 : 1));
1560
0
  }
1561
0
  if (!cu.geo && !cu.ciip)
1562
0
  {
1563
0
    if (cu.cs->sps->MMVD)
1564
0
    {
1565
0
      m_BinEncoder.encodeBin(cu.mmvdMergeFlag, Ctx::MmvdFlag(0));
1566
0
      DTRACE(g_trace_ctx, D_SYNTAX, "mmvd_merge_flag() mmvd_merge=%d pos=(%d,%d) size=%dx%d\n", cu.mmvdMergeFlag ? 1 : 0, cu.lumaPos().x, cu.lumaPos().y, cu.lumaSize().width, cu.lumaSize().height);
1567
0
    }
1568
0
    if (cu.mmvdMergeFlag || cu.mmvdSkip)
1569
0
    {
1570
0
      mmvd_merge_idx(cu);
1571
0
    }
1572
0
    else
1573
0
    {
1574
0
      merge_idx(cu);
1575
0
    }
1576
0
  }
1577
0
  else
1578
0
  {
1579
0
    if (geoAvailable && ciipAvailable)
1580
0
    {
1581
0
      ciip_flag(cu);
1582
0
    }
1583
0
    merge_idx(cu);
1584
0
  }
1585
0
}
1586
1587
1588
void CABACWriter::imv_mode( const CodingUnit& cu )
1589
26.8k
{
1590
26.8k
  const SPS *sps = cu.cs->sps;
1591
1592
26.8k
  if( !sps->AMVR )
1593
0
  {
1594
0
    return;
1595
0
  }
1596
26.8k
  if ( cu.affine )
1597
0
  {
1598
0
    return;
1599
0
  }
1600
1601
26.8k
  bool bNonZeroMvd = CU::hasSubCUNonZeroMVd( cu );
1602
26.8k
  if( !bNonZeroMvd )
1603
0
  {
1604
0
    return;
1605
0
  }
1606
1607
26.8k
  if (CU::isIBC(cu) == false)
1608
0
    m_BinEncoder.encodeBin( (cu.imv > 0), Ctx::ImvFlag( 0 ) );
1609
26.8k
  DTRACE( g_trace_ctx, D_SYNTAX, "imv_mode() value=%d ctx=%d\n", (cu.imv > 0), 0 );
1610
1611
26.8k
  if( sps->AMVR && cu.imv > 0 )
1612
26.8k
  {
1613
26.8k
    if (!CU::isIBC(cu))
1614
0
    {
1615
0
      m_BinEncoder.encodeBin(cu.imv < IMV_HPEL, Ctx::ImvFlag(4));
1616
0
      DTRACE(g_trace_ctx, D_SYNTAX, "imv_mode() value=%d ctx=%d\n", cu.imv < 3, 4);
1617
0
    }
1618
26.8k
    if (cu.imv < IMV_HPEL)
1619
26.8k
    {
1620
26.8k
    m_BinEncoder.encodeBin( (cu.imv > 1), Ctx::ImvFlag( 1 ) );
1621
26.8k
    DTRACE( g_trace_ctx, D_SYNTAX, "imv_mode() value=%d ctx=%d\n", (cu.imv > 1), 1 );
1622
26.8k
    }
1623
26.8k
  }
1624
1625
26.8k
  DTRACE( g_trace_ctx, D_SYNTAX, "imv_mode() IMVFlag=%d\n", cu.imv );
1626
26.8k
}
1627
1628
1629
void CABACWriter::affine_amvr_mode( const CodingUnit& cu )
1630
26.8k
{
1631
26.8k
  const SPS* sps = cu.slice->sps;
1632
1633
26.8k
  if( !sps->AffineAmvr || !cu.affine )
1634
26.8k
  {
1635
26.8k
    return;
1636
26.8k
  }
1637
1638
0
  if ( !CU::hasSubCUNonZeroAffineMVd( cu ) )
1639
0
  {
1640
0
    return;
1641
0
  }
1642
1643
0
  m_BinEncoder.encodeBin( (cu.imv > 0), Ctx::ImvFlag( 2 ) );
1644
0
  DTRACE( g_trace_ctx, D_SYNTAX, "affine_amvr_mode() value=%d ctx=%d\n", (cu.imv > 0), 2 );
1645
1646
0
  if( cu.imv > 0 )
1647
0
  {
1648
0
    m_BinEncoder.encodeBin( (cu.imv > 1), Ctx::ImvFlag( 3 ) );
1649
0
    DTRACE( g_trace_ctx, D_SYNTAX, "affine_amvr_mode() value=%d ctx=%d\n", (cu.imv > 1), 3 );
1650
0
  }
1651
0
  DTRACE( g_trace_ctx, D_SYNTAX, "affine_amvr_mode() IMVFlag=%d\n", cu.imv );
1652
0
}
1653
1654
1655
void CABACWriter::merge_idx( const CodingUnit& cu )
1656
0
{
1657
0
  if ( cu.affine )
1658
0
  {
1659
0
    int numCandminus1 = int( cu.cs->picHeader->maxNumAffineMergeCand ) - 1;
1660
0
    if ( numCandminus1 > 0 )
1661
0
    {
1662
0
      if ( cu.mergeIdx == 0 )
1663
0
      {
1664
0
        m_BinEncoder.encodeBin( 0, Ctx::AffMergeIdx() );
1665
0
        DTRACE( g_trace_ctx, D_SYNTAX, "aff_merge_idx() aff_merge_idx=%d\n", cu.mergeIdx );
1666
0
        return;
1667
0
      }
1668
0
      else
1669
0
      {
1670
0
        m_BinEncoder.encodeBin( 1, Ctx::AffMergeIdx() );
1671
0
        for ( unsigned idx = 1; idx < numCandminus1; idx++ )
1672
0
        {
1673
0
            m_BinEncoder.encodeBinEP( cu.mergeIdx == idx ? 0 : 1 );
1674
0
          if ( cu.mergeIdx == idx )
1675
0
          {
1676
0
            break;
1677
0
          }
1678
0
        }
1679
0
      }
1680
0
    }
1681
0
    DTRACE( g_trace_ctx, D_SYNTAX, "aff_merge_idx() aff_merge_idx=%d\n", cu.mergeIdx );
1682
0
  }
1683
0
  else
1684
0
  {
1685
0
    if( cu.geo )
1686
0
    {
1687
0
      uint8_t splitDir = cu.geoSplitDir;
1688
0
      uint8_t candIdx0 = cu.geoMergeIdx[0];
1689
0
      uint8_t candIdx1 = cu.geoMergeIdx[1];
1690
0
      DTRACE( g_trace_ctx, D_SYNTAX, "merge_idx() geo_split_dir=%d\n", splitDir );
1691
0
      DTRACE( g_trace_ctx, D_SYNTAX, "merge_idx() geo_idx0=%d\n", candIdx0 );
1692
0
      DTRACE( g_trace_ctx, D_SYNTAX, "merge_idx() geo_idx1=%d\n", candIdx1 );
1693
0
      xWriteTruncBinCode(splitDir, GEO_NUM_PARTITION_MODE);
1694
0
      candIdx1 -= candIdx1 < candIdx0 ? 0 : 1;
1695
0
      const int maxNumGeoCand = cu.cs->sps->maxNumGeoCand;
1696
0
      CHECK(maxNumGeoCand < 2, "Incorrect max number of geo candidates");
1697
0
      CHECK(candIdx0 >= maxNumGeoCand, "Incorrect candIdx0");
1698
0
      CHECK(candIdx1 >= maxNumGeoCand, "Incorrect candIdx1");
1699
0
      int numCandminus2 = maxNumGeoCand - 2;
1700
0
      m_BinEncoder.encodeBin( candIdx0 == 0 ? 0 : 1, Ctx::MergeIdx() );
1701
0
      if( candIdx0 > 0 )
1702
0
      {
1703
0
        unary_max_eqprob(candIdx0 - 1, numCandminus2);
1704
0
      }
1705
0
      if (numCandminus2 > 0)
1706
0
      {
1707
0
        m_BinEncoder.encodeBin(candIdx1 == 0 ? 0 : 1, Ctx::MergeIdx());
1708
0
        if (candIdx1 > 0)
1709
0
        {
1710
0
          unary_max_eqprob(candIdx1 - 1, numCandminus2 - 1);
1711
0
        }
1712
0
      }
1713
0
      return;
1714
0
    }
1715
0
    int numCandminus1 = (cu.predMode == MODE_IBC) ? (int(cu.cs->sps->maxNumIBCMergeCand) - 1) : (int(cu.cs->sps->maxNumMergeCand) - 1);
1716
0
    if( numCandminus1 > 0 )
1717
0
    {
1718
0
      if( cu.mergeIdx == 0 )
1719
0
      {
1720
0
        m_BinEncoder.encodeBin( 0, Ctx::MergeIdx() );
1721
0
        DTRACE( g_trace_ctx, D_SYNTAX, "merge_idx() merge_idx=%d\n", cu.mergeIdx );
1722
0
        return;
1723
0
      }
1724
0
      else
1725
0
      {
1726
0
        m_BinEncoder.encodeBin( 1, Ctx::MergeIdx() );
1727
0
        for( unsigned idx = 1; idx < numCandminus1; idx++ )
1728
0
        {
1729
0
          m_BinEncoder.encodeBinEP( cu.mergeIdx == idx ? 0 : 1 );
1730
0
          if( cu.mergeIdx == idx )
1731
0
          {
1732
0
            break;
1733
0
          }
1734
0
        }
1735
0
      }
1736
0
    }
1737
0
    DTRACE( g_trace_ctx, D_SYNTAX, "merge_idx() merge_idx=%d\n", cu.mergeIdx );
1738
0
  }
1739
0
}
1740
1741
1742
void CABACWriter::mmvd_merge_idx( const CodingUnit &cu )
1743
0
{
1744
0
  const int mvdBaseIdx  = cu.mmvdMergeIdx.pos.baseIdx;
1745
0
  const int mvdStep     = cu.mmvdMergeIdx.pos.step;
1746
0
  const int mvdPosition = cu.mmvdMergeIdx.pos.position;
1747
1748
0
  if( cu.cs->sps->maxNumMergeCand > 1 )
1749
0
  {
1750
0
    static_assert( MMVD_BASE_MV_NUM == 2, "" );
1751
0
    CHECK( mvdBaseIdx >= 2, "Invalid mvdBaseIdx" );
1752
0
    m_BinEncoder.encodeBin( mvdBaseIdx, Ctx::MmvdMergeIdx() );
1753
0
  }
1754
0
  DTRACE( g_trace_ctx, D_SYNTAX, "base_mvp_idx() base_mvp_idx=%d\n", mvdBaseIdx );
1755
1756
0
  int numCandminus1_step = MMVD_REFINE_STEP - 1;
1757
0
  if( numCandminus1_step > 0 )
1758
0
  {
1759
0
    if( mvdStep == 0 )
1760
0
    {
1761
0
      m_BinEncoder.encodeBin( 0, Ctx::MmvdStepMvpIdx() );
1762
0
    }
1763
0
    else
1764
0
    {
1765
0
      m_BinEncoder.encodeBin( 1, Ctx::MmvdStepMvpIdx() );
1766
0
      for( unsigned idx = 1; idx < numCandminus1_step; idx++ )
1767
0
      {
1768
0
        m_BinEncoder.encodeBinEP( mvdStep == idx ? 0 : 1 );
1769
0
        if( mvdStep == idx )
1770
0
        {
1771
0
          break;
1772
0
        }
1773
0
      }
1774
0
    }
1775
0
  }
1776
0
  DTRACE( g_trace_ctx, D_SYNTAX, "MmvdStepMvpIdx() MmvdStepMvpIdx=%d\n", mvdStep );
1777
1778
0
  m_BinEncoder.encodeBinsEP( mvdPosition, 2 );
1779
1780
0
  DTRACE( g_trace_ctx, D_SYNTAX, "pos() pos=%d\n", mvdPosition );
1781
0
  DTRACE( g_trace_ctx, D_SYNTAX, "mmvd_merge_idx() mmvd_merge_idx=%d\n", cu.mmvdMergeIdx.val );
1782
0
}
1783
1784
1785
void CABACWriter::inter_pred_idc( const CodingUnit& cu )
1786
0
{
1787
0
  if( !cu.cs->slice->isInterB() )
1788
0
  {
1789
0
    return;
1790
0
  }
1791
0
  if( !(CU::isBipredRestriction(cu)) )
1792
0
  {
1793
0
    unsigned ctxId = DeriveCtx::CtxInterDir(cu);
1794
0
    if( cu.interDir == 3 )
1795
0
    {
1796
0
      m_BinEncoder.encodeBin( 1, Ctx::InterDir(ctxId) );
1797
0
      DTRACE( g_trace_ctx, D_SYNTAX, "inter_pred_idc() ctx=%d value=%d pos=(%d,%d)\n", ctxId, cu.interDir, cu.lumaPos().x, cu.lumaPos().y );
1798
0
      return;
1799
0
    }
1800
0
    else
1801
0
    {
1802
0
      m_BinEncoder.encodeBin( 0, Ctx::InterDir(ctxId) );
1803
0
    }
1804
0
  }
1805
0
  m_BinEncoder.encodeBin( ( cu.interDir == 2 ), Ctx::InterDir( 5 ) );
1806
0
  DTRACE( g_trace_ctx, D_SYNTAX, "inter_pred_idc() ctx=5 value=%d pos=(%d,%d)\n", cu.interDir, cu.lumaPos().x, cu.lumaPos().y );
1807
0
}
1808
1809
1810
void CABACWriter::ref_idx( const CodingUnit& cu, RefPicList eRefList )
1811
26.8k
{
1812
26.8k
  if ( cu.smvdMode )
1813
0
  {
1814
0
    CHECK( cu.refIdx[eRefList] != cu.cs->slice->symRefIdx[ eRefList ], "Invalid reference index!\n" );
1815
0
    return;
1816
0
  }
1817
1818
26.8k
  int numRef  = cu.cs->slice->numRefIdx[eRefList];
1819
1820
26.8k
  if (eRefList == REF_PIC_LIST_0 && cu.cs->sps->IBC)
1821
26.8k
  {
1822
26.8k
    if (CU::isIBC(cu))
1823
26.8k
      return;
1824
26.8k
  }
1825
1826
0
  if( numRef <= 1 )
1827
0
  {
1828
0
    return;
1829
0
  }
1830
0
  int refIdx  = cu.refIdx[eRefList];
1831
0
  m_BinEncoder.encodeBin( (refIdx > 0), Ctx::RefPic() );
1832
0
  if( numRef <= 2 || refIdx == 0 )
1833
0
  {
1834
0
    DTRACE( g_trace_ctx, D_SYNTAX, "ref_idx() value=%d pos=(%d,%d)\n", refIdx, cu.lumaPos().x, cu.lumaPos().y );
1835
0
    return;
1836
0
  }
1837
0
  m_BinEncoder.encodeBin( (refIdx > 1), Ctx::RefPic(1) );
1838
0
  if( numRef <= 3 || refIdx == 1 )
1839
0
  {
1840
0
    DTRACE( g_trace_ctx, D_SYNTAX, "ref_idx() value=%d pos=(%d,%d)\n", refIdx, cu.lumaPos().x, cu.lumaPos().y );
1841
0
    return;
1842
0
  }
1843
0
  for( int idx = 3; idx < numRef; idx++ )
1844
0
  {
1845
0
    if( refIdx > idx - 1 )
1846
0
    {
1847
0
      m_BinEncoder.encodeBinEP( 1 );
1848
0
    }
1849
0
    else
1850
0
    {
1851
0
      m_BinEncoder.encodeBinEP( 0 );
1852
0
      break;
1853
0
    }
1854
0
  }
1855
0
  DTRACE( g_trace_ctx, D_SYNTAX, "ref_idx() value=%d pos=(%d,%d)\n", refIdx, cu.lumaPos().x, cu.lumaPos().y );
1856
0
}
1857
1858
1859
void CABACWriter::mvp_flag( const CodingUnit& cu, RefPicList eRefList )
1860
26.8k
{
1861
26.8k
  m_BinEncoder.encodeBin( cu.mvpIdx[eRefList], Ctx::MVPIdx() );
1862
26.8k
  DTRACE( g_trace_ctx, D_SYNTAX, "mvp_flag() value=%d pos=(%d,%d)\n", cu.mvpIdx[eRefList], cu.lumaPos().x, cu.lumaPos().y );
1863
26.8k
  DTRACE( g_trace_ctx, D_SYNTAX, "mvpIdx(refList:%d)=%d\n", eRefList, cu.mvpIdx[eRefList] );
1864
26.8k
}
1865
1866
1867
void CABACWriter::ciip_flag(const CodingUnit& cu)
1868
0
{
1869
0
  if (!cu.cs->sps->CIIP)
1870
0
  {
1871
0
    CHECK(cu.ciip == true, "invalid Ciip SPS");
1872
0
    return;
1873
0
  }
1874
0
  if (cu.skip)
1875
0
  {
1876
0
    CHECK(cu.ciip == true, "invalid Ciip and skip");
1877
0
    return;
1878
0
  }
1879
0
  m_BinEncoder.encodeBin(cu.ciip, Ctx::CiipFlag());
1880
0
  DTRACE(g_trace_ctx, D_SYNTAX, "Ciip_flag() Ciip=%d pos=(%d,%d) size=%dx%d\n", cu.ciip ? 1 : 0, cu.lumaPos().x, cu.lumaPos().y, cu.lumaSize().width, cu.lumaSize().height);
1881
0
}
1882
1883
1884
//================================================================================
1885
//  clause 7.3.8.8
1886
//--------------------------------------------------------------------------------
1887
//    void  transform_tree      ( cs, area, cuCtx, chromaCbfs )
1888
//    bool  split_transform_flag( split, depth )
1889
//    bool  cbf_comp            ( cbf, area, depth )
1890
//================================================================================
1891
1892
void CABACWriter::transform_tree( const CodingStructure& cs, Partitioner& partitioner, CUCtx& cuCtx, const PartSplit ispType, const int subTuIdx )
1893
193k
{
1894
193k
  const UnitArea&       area = partitioner.currArea();
1895
193k
  int             subTuCounter = subTuIdx;
1896
193k
  const TransformUnit&  tu = *cs.getTU(area.blocks[partitioner.chType].pos(), partitioner.chType, subTuIdx);
1897
193k
  const CodingUnit&     cu = *tu.cu;
1898
193k
  const unsigned        trDepth = partitioner.currTrDepth;
1899
193k
  const bool            split = (tu.depth > trDepth);
1900
193k
  if( split )
1901
49
  {
1902
49
    PartSplit partSplit;
1903
1904
49
    if( partitioner.canSplit( TU_MAX_TR_SPLIT, cs ) )
1905
0
    {
1906
#if ENABLE_TRACING
1907
      const CompArea& tuArea = partitioner.currArea().blocks[partitioner.chType];
1908
      DTRACE( g_trace_ctx, D_SYNTAX, "transform_tree() maxTrSplit chType=%d pos=(%d,%d) size=%dx%d\n", partitioner.chType, tuArea.x, tuArea.y, tuArea.width, tuArea.height );
1909
1910
#endif
1911
0
      partitioner.splitCurrArea( TU_MAX_TR_SPLIT, cs );
1912
0
    }
1913
49
    else if( cu.ispMode )
1914
49
    {
1915
49
      partitioner.splitCurrArea( ispType, cs );
1916
49
    }
1917
0
    else if( cu.sbtInfo && partitioner.canSplit( partSplit = CU::getSbtTuSplit( cu.sbtInfo ), cs ) )
1918
0
    {
1919
0
      partitioner.splitCurrArea( partSplit, cs );
1920
0
    }
1921
0
    else
1922
0
      THROW( "Implicit TU split not available" );
1923
1924
49
    do
1925
196
    {
1926
196
      transform_tree( cs, partitioner, cuCtx,                ispType, subTuCounter );
1927
196
      subTuCounter += subTuCounter != -1 ? 1 : 0;
1928
196
    } while( partitioner.nextPart( cs ) );
1929
1930
49
    partitioner.exitCurrSplit();
1931
49
  }
1932
193k
  else
1933
193k
  {
1934
    // split_transform_flag
1935
193k
    CHECK( partitioner.canSplit( TU_MAX_TR_SPLIT, cs ) || (cu.sbtInfo && partitioner.canSplit( CU::getSbtTuSplit( cu.sbtInfo ), cs)),  "transform split implied" );
1936
193k
    DTRACE( g_trace_ctx, D_SYNTAX, "transform_unit() pos=(%d,%d) size=%dx%d depth=%d trDepth=%d\n", tu.blocks[tu.chType].x, tu.blocks[tu.chType].y, tu.blocks[tu.chType].width, tu.blocks[tu.chType].height, cu.depth, partitioner.currTrDepth );
1937
1938
193k
    transform_unit( tu, cuCtx, partitioner, subTuCounter);
1939
193k
  }
1940
193k
}
1941
1942
1943
void CABACWriter::cbf_comp( const CodingUnit& cu, bool cbf, const CompArea& area, unsigned depth, const bool prevCbf, const bool useISP )
1944
3.67M
{
1945
3.67M
  const CtxSet&   ctxSet  = Ctx::QtCbf[ area.compID ];
1946
3.67M
  unsigned  ctxId;
1947
3.67M
  if( cu.bdpcmM[toChannelType(area.compID)] )
1948
231k
  {
1949
231k
    ctxId = (area.compID != COMP_Cr) ? 1 : 2;
1950
231k
    m_BinEncoder.encodeBin(cbf, ctxSet(ctxId));
1951
231k
  }
1952
3.43M
  else
1953
3.43M
  {
1954
3.43M
    ctxId = DeriveCtx::CtxQtCbf(area.compID, prevCbf, useISP && isLuma(area.compID));
1955
3.43M
    m_BinEncoder.encodeBin( cbf, ctxSet( ctxId ) );
1956
3.43M
  }
1957
3.67M
  DTRACE( g_trace_ctx, D_SYNTAX, "cbf_comp() etype=%d pos=(%d,%d) ctx=%d cbf=%d\n", area.compID, area.x, area.y, ctxId, cbf );
1958
3.67M
}
1959
1960
1961
1962
//================================================================================
1963
//  clause 7.3.8.9
1964
//--------------------------------------------------------------------------------
1965
//    void  mvd_coding( cu, refList )
1966
//================================================================================
1967
void CABACWriter::mvd_coding( const Mv &rMvd, int8_t imv )
1968
26.8k
{
1969
26.8k
  int       horMvd = rMvd.hor;
1970
26.8k
  int       verMvd = rMvd.ver;
1971
26.8k
  if ( imv > 0 )
1972
0
  {
1973
0
    int shift = 1;
1974
0
    if (imv < IMV_HPEL)
1975
0
    {
1976
0
      shift = 2;
1977
0
      if (imv == IMV_4PEL)
1978
0
      {
1979
0
        shift = 4;
1980
0
      }
1981
0
    }
1982
1983
0
    CHECK((horMvd % (1<<shift)) != 0 && (verMvd % (4<<shift)) != 0, "IMV: MVD is not a multiple of 2^N ");
1984
0
    horMvd >>= shift;
1985
0
    verMvd >>= shift;
1986
0
  }
1987
26.8k
  unsigned  horAbs  = unsigned( horMvd < 0 ? -horMvd : horMvd );
1988
26.8k
  unsigned  verAbs  = unsigned( verMvd < 0 ? -verMvd : verMvd );
1989
1990
1991
  // abs_mvd_greater0_flag[ 0 | 1 ]
1992
26.8k
  m_BinEncoder.encodeBin( (horAbs > 0), Ctx::Mvd() );
1993
26.8k
  m_BinEncoder.encodeBin( (verAbs > 0), Ctx::Mvd() );
1994
1995
  // abs_mvd_greater1_flag[ 0 | 1 ]
1996
26.8k
  if( horAbs > 0 )
1997
16.9k
  {
1998
16.9k
    m_BinEncoder.encodeBin( (horAbs > 1), Ctx::Mvd(1) );
1999
16.9k
  }
2000
26.8k
  if( verAbs > 0 )
2001
9.95k
  {
2002
9.95k
    m_BinEncoder.encodeBin( (verAbs > 1), Ctx::Mvd(1) );
2003
9.95k
  }
2004
2005
  // abs_mvd_minus2[ 0 | 1 ] and mvd_sign_flag[ 0 | 1 ]
2006
26.8k
  if( horAbs > 0 )
2007
16.9k
  {
2008
16.9k
    if( horAbs > 1 )
2009
16.9k
    {
2010
16.9k
      m_BinEncoder.encodeRemAbsEP(horAbs - 2, 1, 0, MV_BITS - 1);
2011
16.9k
    }
2012
16.9k
    m_BinEncoder.encodeBinEP( (horMvd < 0) );
2013
16.9k
  }
2014
26.8k
  if( verAbs > 0 )
2015
9.95k
  {
2016
9.95k
    if( verAbs > 1 )
2017
9.86k
    {
2018
9.86k
      m_BinEncoder.encodeRemAbsEP(verAbs - 2, 1, 0, MV_BITS - 1);
2019
9.86k
    }
2020
9.95k
    m_BinEncoder.encodeBinEP( (verMvd < 0) );
2021
9.95k
  }
2022
26.8k
}
2023
2024
2025
//================================================================================
2026
//  clause 7.3.8.10
2027
//--------------------------------------------------------------------------------
2028
//    void  transform_unit      ( tu, cuCtx, chromaCbfs )
2029
//    void  cu_qp_delta         ( cu )
2030
//    void  cu_chroma_qp_offset ( cu )
2031
//================================================================================
2032
void CABACWriter::transform_unit( const TransformUnit& tu, CUCtx& cuCtx, Partitioner& partitioner, const int subTuCounter)
2033
193k
{
2034
193k
  const CodingUnit&       cu = *tu.cu;
2035
193k
  const UnitArea&         area = partitioner.currArea();
2036
193k
  const unsigned          trDepth = partitioner.currTrDepth;
2037
193k
  ChromaCbfs              chromaCbfs;
2038
193k
  CHECK(tu.depth != trDepth, " transform unit should be not be futher partitioned");
2039
2040
  // cbf_cb & cbf_cr
2041
193k
  if (area.chromaFormat != CHROMA_400)
2042
193k
  {
2043
193k
    const bool              chromaCbfISP = area.blocks[COMP_Cb].valid() && cu.ispMode;
2044
193k
    if (area.blocks[COMP_Cb].valid() && (!CU::isSepTree(cu) || partitioner.chType == CH_C) && (!cu.ispMode || chromaCbfISP))
2045
106k
    {
2046
106k
      unsigned cbfDepth = chromaCbfISP ? trDepth - 1 : trDepth;
2047
106k
      {
2048
106k
        chromaCbfs.Cb = TU::getCbfAtDepth(tu, COMP_Cb, trDepth);
2049
        //if (!(cu.sbtInfo && trDepth == 1))
2050
106k
        if (!(cu.sbtInfo && tu.noResidual))
2051
106k
          cbf_comp(*tu.cu, chromaCbfs.Cb, area.blocks[COMP_Cb], cbfDepth);
2052
106k
      }
2053
2054
106k
      {
2055
106k
        chromaCbfs.Cr = TU::getCbfAtDepth(tu, COMP_Cr, trDepth);
2056
        //if (!(cu.sbtInfo && trDepth == 1))
2057
106k
        if (!(cu.sbtInfo && tu.noResidual))
2058
106k
          cbf_comp(*tu.cu, chromaCbfs.Cr, area.blocks[COMP_Cr], cbfDepth, chromaCbfs.Cb);
2059
106k
      }
2060
106k
    }
2061
87.2k
    else if (CU::isSepTree(cu))
2062
87.2k
    {
2063
87.2k
      chromaCbfs = ChromaCbfs(false);
2064
87.2k
    }
2065
193k
  }
2066
0
  else if (CU::isSepTree(cu))
2067
0
  {
2068
0
    chromaCbfs = ChromaCbfs(false);
2069
0
  }
2070
2071
193k
  if (!isChroma(partitioner.chType))
2072
87.2k
  {
2073
87.2k
    if (!CU::isIntra(cu) && trDepth == 0 && !chromaCbfs.sigChroma(area.chromaFormat))
2074
139
    {
2075
139
      CHECK(!TU::getCbfAtDepth(tu, COMP_Y, trDepth), "Luma cbf must be true for inter units with no chroma coeffs");
2076
139
    }
2077
87.1k
    else if (cu.sbtInfo && tu.noResidual)
2078
0
    {
2079
0
      CHECK(TU::getCbfAtDepth(tu, COMP_Y, trDepth), "Luma cbf must be false for inter sbt no-residual tu");
2080
0
    }
2081
87.1k
    else if (cu.sbtInfo && !chromaCbfs.sigChroma(area.chromaFormat))
2082
0
    {
2083
0
      assert(!tu.noResidual);
2084
0
      CHECK(!TU::getCbfAtDepth(tu, COMP_Y, trDepth), "Luma cbf must be true for inter sbt residual tu");
2085
0
    }
2086
87.1k
    else
2087
87.1k
    {
2088
87.1k
      bool previousCbf = false;
2089
87.1k
      bool rootCbfSoFar = false;
2090
87.1k
      bool lumaCbfIsInferredACT = (cu.colorTransform && cu.predMode == MODE_INTRA && trDepth == 0 && !chromaCbfs.sigChroma(area.chromaFormat));
2091
87.1k
      CHECK(lumaCbfIsInferredACT && !TU::getCbfAtDepth(tu, COMP_Y, trDepth), "adaptive color transform cannot have all zero coefficients");
2092
87.1k
      bool lastCbfIsInferred    = lumaCbfIsInferredACT; // ISP and ACT are mutually exclusive
2093
87.1k
      if (cu.ispMode)
2094
196
      {
2095
196
        uint32_t nTus = cu.ispMode == HOR_INTRA_SUBPARTITIONS ? cu.lheight() >> Log2(tu.lheight()) : cu.lwidth() >> Log2(tu.lwidth());
2096
196
        if (subTuCounter == nTus - 1)
2097
49
        {
2098
49
          TransformUnit* tuPointer = cu.firstTU;
2099
196
          for (int tuIdx = 0; tuIdx < subTuCounter; tuIdx++)
2100
147
          {
2101
147
            rootCbfSoFar |= TU::getCbfAtDepth(*tuPointer, COMP_Y, trDepth);
2102
147
            tuPointer = tuPointer->next;
2103
147
          }
2104
49
          if (!rootCbfSoFar)
2105
0
          {
2106
0
            lastCbfIsInferred = true;
2107
0
          }
2108
49
        }
2109
196
        if (!lastCbfIsInferred)
2110
196
        {
2111
196
          previousCbf = TU::getPrevTuCbfAtDepth(tu, COMP_Y, partitioner.currTrDepth);
2112
196
        }
2113
196
      }
2114
87.1k
      if (!lastCbfIsInferred)
2115
87.1k
      {
2116
87.1k
        cbf_comp(*tu.cu, TU::getCbfAtDepth(tu, COMP_Y, trDepth), tu.Y(), trDepth, previousCbf, cu.ispMode);
2117
87.1k
      }
2118
87.1k
    }
2119
87.2k
  }
2120
193k
  bool        lumaOnly  = ( cu.chromaFormat == CHROMA_400 || !tu.blocks[COMP_Cb].valid() );
2121
193k
  bool        cbf[3]    = { TU::getCbf( tu, COMP_Y ), chromaCbfs.Cb, chromaCbfs.Cr };
2122
193k
  bool        cbfLuma   = ( cbf[ COMP_Y ] != 0 );
2123
193k
  bool        cbfChroma = false;
2124
2125
193k
  if( !lumaOnly )
2126
106k
  {
2127
106k
    if( tu.blocks[COMP_Cb].valid() )
2128
106k
    {
2129
106k
      cbf   [ COMP_Cb  ] = TU::getCbf( tu, COMP_Cb );
2130
106k
      cbf   [ COMP_Cr  ] = TU::getCbf( tu, COMP_Cr );
2131
106k
    }
2132
106k
    cbfChroma = ( cbf[ COMP_Cb ] || cbf[ COMP_Cr ] );
2133
106k
  }
2134
2135
193k
  if( ( cu.lwidth() > 64 || cu.lheight() > 64 || cbfLuma || cbfChroma ) &&
2136
32.9k
    (!CU::isSepTree(*tu.cu) || isLuma(tu.chType)) )
2137
5.69k
  {
2138
5.69k
    if( cu.cs->pps->useDQP && !cuCtx.isDQPCoded )
2139
2.87k
    {
2140
2.87k
      cu_qp_delta(cu, cuCtx.qp, cu.qp);
2141
2.87k
      cuCtx.qp = cu.qp;
2142
2.87k
      cuCtx.isDQPCoded = true;
2143
2.87k
    }
2144
5.69k
  }
2145
193k
  if (cu.cs->slice->chromaQpAdjEnabled && cbfChroma && !cuCtx.isChromaQpAdjCoded)
2146
0
  {
2147
0
    cu_chroma_qp_offset( cu );
2148
0
    cuCtx.isChromaQpAdjCoded = true;
2149
0
  }
2150
2151
193k
  if( !lumaOnly )
2152
106k
  {
2153
106k
    joint_cb_cr( tu, ( cbf[COMP_Cb] ? 2 : 0 ) + ( cbf[COMP_Cr] ? 1 : 0 ) );
2154
106k
  }
2155
2156
193k
  if( cbfLuma )
2157
5.69k
  {
2158
5.69k
    if( m_tuResiBits && m_tuResiBits[COMP_Y] != TU_RESI_BITS_UNKNOWN )
2159
2.29k
    {
2160
2.29k
      addEstFracBits( m_tuResiBits[COMP_Y] );
2161
2.29k
      if( m_tuLumaResiFlags )
2162
2.15k
      {
2163
2.15k
        cuCtx.addResidualFlags( *m_tuLumaResiFlags );
2164
2.15k
      }
2165
2.29k
    }
2166
3.40k
    else
2167
3.40k
    {
2168
3.40k
      residual_coding( tu, COMP_Y, &cuCtx );
2169
3.40k
    }
2170
5.69k
  }
2171
193k
  if( !lumaOnly )
2172
106k
  {
2173
319k
    for( ComponentID compID = COMP_Cb; compID <= COMP_Cr; compID = ComponentID( compID + 1 ) )
2174
213k
    {
2175
213k
      if( cbf[ compID ] )
2176
54.0k
      {
2177
54.0k
        if( m_tuResiBits && m_tuResiBits[compID] != TU_RESI_BITS_UNKNOWN )
2178
0
        {
2179
0
          addEstFracBits( m_tuResiBits[compID] );
2180
0
        }
2181
54.0k
        else
2182
54.0k
        {
2183
54.0k
          residual_coding( tu, compID, &cuCtx );
2184
54.0k
        }
2185
54.0k
      }
2186
213k
    }
2187
106k
  }
2188
193k
}
2189
2190
2191
void CABACWriter::cu_qp_delta( const CodingUnit& cu, int predQP, const int8_t qp )
2192
4.31k
{
2193
4.31k
  CHECK(!( predQP != std::numeric_limits<int>::max()), "Unspecified error");
2194
4.31k
  int       DQp         = qp - predQP;
2195
4.31k
  int       qpBdOffsetY = cu.cs->sps->qpBDOffset[ CH_L ];
2196
4.31k
  DQp                   = ( DQp + (MAX_QP + 1) + (MAX_QP + 1) / 2 + qpBdOffsetY + (qpBdOffsetY / 2)) % ((MAX_QP + 1) + qpBdOffsetY) - (MAX_QP + 1) / 2 - (qpBdOffsetY / 2);
2197
4.31k
  unsigned  absDQP      = unsigned( DQp < 0 ? -DQp : DQp );
2198
4.31k
  unsigned  unaryDQP    = std::min<unsigned>( absDQP, CU_DQP_TU_CMAX );
2199
2200
4.31k
  unary_max_symbol( unaryDQP, Ctx::DeltaQP(), Ctx::DeltaQP(1), CU_DQP_TU_CMAX );
2201
4.31k
  if( absDQP >= CU_DQP_TU_CMAX )
2202
0
  {
2203
0
    exp_golomb_eqprob( absDQP - CU_DQP_TU_CMAX, CU_DQP_EG_k );
2204
0
  }
2205
4.31k
  if( absDQP > 0 )
2206
0
  {
2207
0
    m_BinEncoder.encodeBinEP( DQp < 0 );
2208
0
  }
2209
2210
4.31k
  DTRACE_COND( ( isEncoding() ), g_trace_ctx, D_DQP, "x=%d, y=%d, d=%d, pred_qp=%d, DQp=%d, qp=%d\n", cu.blocks[cu.chType].lumaPos().x, cu.blocks[cu.chType].lumaPos().y, cu.qtDepth, predQP, DQp, qp );
2211
4.31k
}
2212
2213
2214
void CABACWriter::cu_chroma_qp_offset( const CodingUnit& cu )
2215
0
{
2216
  // cu_chroma_qp_offset_flag
2217
0
  unsigned qpAdj = cu.chromaQpAdj;
2218
0
  if( qpAdj == 0 )
2219
0
  {
2220
0
    m_BinEncoder.encodeBin( 0, Ctx::ChromaQpAdjFlag() );
2221
0
  }
2222
0
  else
2223
0
  {
2224
0
    m_BinEncoder.encodeBin( 1, Ctx::ChromaQpAdjFlag() );
2225
0
    int length = cu.cs->pps->chromaQpOffsetListLen;
2226
0
    if( length > 1 )
2227
0
    {
2228
0
      unary_max_symbol( qpAdj-1, Ctx::ChromaQpAdjIdc(), Ctx::ChromaQpAdjIdc(), length-1 );
2229
0
    }
2230
0
  }
2231
0
}
2232
2233
2234
//================================================================================
2235
//  clause 7.3.8.11
2236
//--------------------------------------------------------------------------------
2237
//    void        residual_coding         ( tu, compID )
2238
//    void        transform_skip_flag     ( tu, compID )
2239
//    void        last_sig_coeff          ( coeffCtx )
2240
//    void        residual_coding_subblock( coeffCtx )
2241
//================================================================================
2242
2243
void CABACWriter::joint_cb_cr( const TransformUnit& tu, const int cbfMask )
2244
1.65M
{
2245
1.65M
  if ( !tu.cu->slice->sps->jointCbCr )
2246
0
  {
2247
0
    return;
2248
0
  }
2249
2250
1.65M
  CHECK( tu.jointCbCr && tu.jointCbCr != cbfMask, "wrong value of jointCbCr (" << (int)tu.jointCbCr << " vs " << (int)cbfMask << ")" );
2251
1.65M
  if( ( CU::isIntra( *tu.cu ) && cbfMask ) || ( cbfMask == 3 ) )
2252
780k
  {
2253
780k
    m_BinEncoder.encodeBin( tu.jointCbCr ? 1 : 0, Ctx::JointCbCrFlag( cbfMask - 1 ) );
2254
780k
  }
2255
1.65M
}
2256
2257
2258
void CABACWriter::residual_coding( const TransformUnit& tu, ComponentID compID, CUCtx* cuCtx )
2259
1.57M
{
2260
1.57M
  const CodingUnit& cu = *tu.cu;
2261
1.57M
  DTRACE( g_trace_ctx, D_SYNTAX, "residual_coding() etype=%d pos=(%d,%d) size=%dx%d predMode=%d\n", tu.blocks[compID].compID, tu.blocks[compID].x, tu.blocks[compID].y, tu.blocks[compID].width, tu.blocks[compID].height, cu.predMode );
2262
2263
1.57M
  if( compID == COMP_Cr && tu.jointCbCr == 3 )
2264
456k
  {
2265
456k
    return;
2266
456k
  }
2267
2268
1.12M
  ts_flag            ( tu, compID );
2269
2270
1.12M
  if( tu.mtsIdx[compID] == MTS_SKIP && !tu.cs->slice->tsResidualCodingDisabled )
2271
78.5k
  {
2272
78.5k
    residual_codingTS( tu, compID );
2273
78.5k
    return;
2274
78.5k
  }
2275
2276
  // determine sign hiding
2277
1.04M
  bool signHiding  = cu.cs->slice->signDataHidingEnabled;
2278
2279
  // init coeff coding context
2280
1.04M
  CoeffCodingContext  cctx    ( tu, compID, signHiding, false, m_tplBuf, tu.lastPos[compID] );
2281
1.04M
  const TCoeffSig*    coeff   = tu.getCoeffs( compID ).buf;
2282
2283
  // determine and set last coeff position and sig group flags
2284
1.04M
  int                      scanPosLast = tu.lastPos[compID];
2285
1.04M
  std::bitset<MLS_GRP_NUM> sigGroupFlags;
2286
2287
1.04M
  CHECK( scanPosLast < 0, "Coefficient coding called for empty TU" );
2288
2289
  // the last subset holds the last coefficient, which isn't zero
2290
1.04M
  const int lastSubSet = scanPosLast >> cctx.log2CGSize();
2291
1.04M
  sigGroupFlags.set( lastSubSet );
2292
2293
1.04M
  const bool     cg4x4 = cctx.log2CGWidth() == 2 && cctx.log2CGHeight() == 2;
2294
1.04M
  const unsigned width = cctx.width();
2295
1.04M
  static_assert( sizeof( TCoeffSig ) == 2, "four coefficients in 8 bytes" );
2296
2297
1.07M
  for( int subSetId = 0; subSetId < lastSubSet; subSetId++ )
2298
30.2k
  {
2299
30.2k
    const int scanPosStart = subSetId << cctx.log2CGSize();
2300
2301
30.2k
    if( cg4x4 )
2302
30.1k
    {
2303
      // the subset's first position is the top left of its 4x4 group: its four rows, read together
2304
30.1k
      const TCoeffSig* row = coeff + cctx.blockPos( scanPosStart );
2305
30.1k
      uint64_t r0, r1, r2, r3;
2306
30.1k
      memcpy( &r0, row, 8 );
2307
30.1k
      memcpy( &r1, row + width, 8 );
2308
30.1k
      memcpy( &r2, row + 2 * width, 8 );
2309
30.1k
      memcpy( &r3, row + 3 * width, 8 );
2310
30.1k
      if( r0 | r1 | r2 | r3 )
2311
20.1k
      {
2312
20.1k
        sigGroupFlags.set( subSetId );
2313
20.1k
      }
2314
30.1k
      continue;
2315
30.1k
    }
2316
2317
94
    const int scanPosEnd   = scanPosStart + ( 1 << cctx.log2CGSize() ) - 1;
2318
2319
188
    for( int scanPos = scanPosEnd; scanPos >= scanPosStart; scanPos-- )
2320
188
    {
2321
188
      unsigned blkPos = cctx.blockPos( scanPos );
2322
2323
188
      if( coeff[blkPos] )
2324
94
      {
2325
94
        sigGroupFlags.set( subSetId );
2326
94
        break;
2327
94
      }
2328
188
    }
2329
94
  }
2330
1.04M
  cctx.setScanPosLast(scanPosLast);
2331
2332
1.04M
  if( cuCtx && tu.mtsIdx[compID] != MTS_SKIP && tu.blocks[ compID ].height >= 4 && tu.blocks[ compID ].width >= 4 )
2333
918k
  {
2334
918k
    const int maxLfnstPos = ((tu.blocks[compID].height == 4 && tu.blocks[compID].width == 4) || (tu.blocks[compID].height == 8 && tu.blocks[compID].width == 8)) ? 7 : 15;
2335
918k
    cuCtx->violatesLfnstConstrained[ toChannelType(compID) ] |= cctx.scanPosLast() > maxLfnstPos;
2336
918k
  }
2337
1.04M
  if( cuCtx && tu.mtsIdx[compID] != MTS_SKIP && tu.blocks[ compID ].height >= 4 && tu.blocks[ compID ].width >= 4 )
2338
918k
  {
2339
918k
    const int lfnstLastScanPosTh = isLuma( compID ) ? LFNST_LAST_SIG_LUMA : LFNST_LAST_SIG_CHROMA;
2340
918k
    cuCtx->lfnstLastScanPos |= cctx.scanPosLast() >= lfnstLastScanPosTh;
2341
918k
  }
2342
1.04M
  if (cuCtx && isLuma(compID) && tu.mtsIdx[compID] != MTS_SKIP)
2343
19.9k
  {
2344
19.9k
    cuCtx->mtsLastScanPos |= cctx.scanPosLast() >= 1;
2345
19.9k
  }
2346
  
2347
  // code last coeff position
2348
1.04M
  last_sig_coeff( cctx, tu, compID );
2349
2350
  // code subblocks
2351
1.04M
  const int stateTab  = ( tu.cs->slice->depQuantEnabled ? 32040 : 0 );
2352
1.04M
  int       state     = 0;
2353
2354
1.04M
  int ctxBinSampleRatio = MAX_TU_LEVEL_CTX_CODED_BIN_CONSTRAINT;
2355
1.04M
  cctx.remRegBins = (tu.getTbAreaAfterCoefZeroOut(compID) * ctxBinSampleRatio) >> 4;
2356
2357
1.04M
  const bool zeroOutCheck  = isLuma( compID ) && tu.cs->sps->MTS && tu.cu->sbtInfo != 0 && tu.blocks[compID].height <= 32 && tu.blocks[compID].width <= 32;
2358
1.04M
  const bool zeroOutWidth  = tu.blocks[compID].width;
2359
1.04M
  const bool zeroOutHeight = tu.blocks[compID].height;
2360
2361
2.11M
  for( int subSetId = ( cctx.scanPosLast() >> cctx.log2CGSize() ); subSetId >= 0; subSetId--)
2362
1.07M
  {
2363
1.07M
    cctx.initSubblock( subSetId, sigGroupFlags[subSetId] );
2364
2365
1.07M
    if( zeroOutCheck )
2366
0
    {
2367
0
      if( ( zeroOutHeight && cctx.cgPosY() >= ( 16 >> cctx.log2CGHeight() ) ) || ( zeroOutWidth  && cctx.cgPosX() >= ( 16 >> cctx.log2CGWidth() ) ) )
2368
0
      {
2369
0
        continue;
2370
0
      }
2371
0
    }
2372
2373
1.07M
    residual_coding_subblock( cctx, coeff, stateTab, state );
2374
1.07M
    if ( cuCtx && isLuma(compID) && cctx.isSigGroup() && ( cctx.cgPosY() > 3 || cctx.cgPosX() > 3 ) )
2375
0
    {
2376
0
      cuCtx->violatesMtsCoeffConstraint = true;
2377
0
    }
2378
1.07M
  }
2379
1.04M
}
2380
2381
2382
void CABACWriter::ts_flag( const TransformUnit& tu, ComponentID compID )
2383
1.12M
{
2384
1.12M
  int tsFlag = tu.mtsIdx[compID] == MTS_SKIP ? 1 : 0;
2385
1.12M
  int ctxIdx = isLuma(compID) ? 0 : 1;
2386
  
2387
1.12M
  if( TU::isTSAllowed ( tu, compID ) )
2388
771k
  {
2389
771k
    m_BinEncoder.encodeBin( tsFlag, Ctx::TransformSkipFlag(ctxIdx));
2390
771k
  }
2391
1.12M
  DTRACE( g_trace_ctx, D_SYNTAX, "ts_flag() etype=%d pos=(%d,%d) mtsIdx=%d\n", COMP_Y, tu.cu->lx(), tu.cu->ly(), tsFlag );
2392
1.12M
}
2393
2394
2395
void CABACWriter::mts_idx( const CodingUnit& cu, CUCtx* cuCtx )
2396
211k
{
2397
211k
  TransformUnit &tu = *cu.firstTU;
2398
211k
  int        mtsIdx = tu.mtsIdx[COMP_Y];
2399
  
2400
211k
  if( CU::isMTSAllowed( cu, COMP_Y ) && cuCtx && !cuCtx->violatesMtsCoeffConstraint &&
2401
0
      cuCtx->mtsLastScanPos && cu.lfnstIdx == 0 && mtsIdx != MTS_SKIP)
2402
0
  {
2403
0
    int symbol = mtsIdx != MTS_DCT2_DCT2 ? 1 : 0;
2404
0
    int ctxIdx = 0;
2405
    
2406
0
    m_BinEncoder.encodeBin( symbol, Ctx::MTSIdx(ctxIdx));
2407
    
2408
0
    if( symbol )
2409
0
    {
2410
0
      ctxIdx = 1;
2411
0
      for( int i = 0; i < 3; i++, ctxIdx++ )
2412
0
      {
2413
0
        symbol = mtsIdx > i + MTS_DST7_DST7 ? 1 : 0;
2414
0
        m_BinEncoder.encodeBin( symbol, Ctx::MTSIdx(ctxIdx));
2415
        
2416
0
        if( !symbol )
2417
0
        {
2418
0
          break;
2419
0
        }
2420
0
      }
2421
0
    }
2422
0
  }
2423
211k
  DTRACE( g_trace_ctx, D_SYNTAX, "mts_idx() etype=%d pos=(%d,%d) mtsIdx=%d\n", COMP_Y, tu.cu->lx(), tu.cu->ly(), mtsIdx);
2424
211k
}
2425
2426
2427
void CABACWriter::isp_mode( const CodingUnit& cu )
2428
1.07M
{
2429
1.07M
  if( !CU::isIntra( cu ) || !isLuma( cu.chType ) || cu.multiRefIdx || !cu.cs->sps->ISP || cu.bdpcmM[CH_L] || !CU::canUseISP( cu, getFirstComponentOfChannel( cu.chType ) )  || cu.colorTransform)
2430
194k
  {
2431
194k
    CHECK( cu.ispMode != NOT_INTRA_SUBPARTITIONS, "cu.ispMode != 0" );
2432
194k
    return;
2433
194k
  }
2434
877k
  if ( cu.ispMode == NOT_INTRA_SUBPARTITIONS )
2435
865k
  {
2436
865k
    m_BinEncoder.encodeBin( 0, Ctx::ISPMode( 0 ) );
2437
865k
  }
2438
11.9k
  else
2439
11.9k
  {
2440
11.9k
    m_BinEncoder.encodeBin( 1, Ctx::ISPMode( 0 ) );
2441
11.9k
    m_BinEncoder.encodeBin( cu.ispMode - 1, Ctx::ISPMode( 1 ) );
2442
11.9k
  }
2443
877k
  DTRACE( g_trace_ctx, D_SYNTAX, "intra_subPartitions() etype=%d pos=(%d,%d) ispIdx=%d\n", cu.chType, cu.blocks[cu.chType].x, cu.blocks[cu.chType].y, (int)cu.ispMode );
2444
877k
}
2445
2446
2447
void CABACWriter::residual_lfnst_mode( const CodingUnit& cu, CUCtx& cuCtx )
2448
312k
{
2449
312k
  int chIdx = CS::isDualITree( *cu.cs ) && cu.chType == CH_C ? 1 : 0;
2450
312k
  if( ( cu.ispMode && !CU::canUseLfnstWithISP( cu, cu.chType ) ) ||
2451
312k
      (cu.cs->sps->LFNST && CU::isIntra(cu) && cu.mipFlag && !allowLfnstWithMip(cu.lumaSize())) ||
2452
310k
    ( CU::isSepTree(cu) && cu.chType == CH_C && std::min( cu.blocks[ 1 ].width, cu.blocks[ 1 ].height ) < 4 )
2453
307k
    || ( cu.blocks[ chIdx ].lumaSize().width > cu.cs->sps->getMaxTbSize() || cu.blocks[ chIdx ].lumaSize().height > cu.cs->sps->getMaxTbSize() )
2454
312k
    )
2455
5.49k
  {
2456
5.49k
    return;
2457
5.49k
  }
2458
2459
307k
  if( cu.cs->sps->LFNST && CU::isIntra( cu )  )
2460
307k
  {
2461
307k
    const bool lumaFlag                   = CU::isSepTree(cu) ? (   isLuma( cu.chType ) ? true : false ) : true;
2462
307k
    const bool chromaFlag                 = CU::isSepTree(cu) ? ( isChroma( cu.chType ) ? true : false ) : true;
2463
307k
          bool nonZeroCoeffNonTsCorner8x8 = ( lumaFlag && cuCtx.violatesLfnstConstrained[CH_L] ) || (chromaFlag && cuCtx.violatesLfnstConstrained[CH_C] );
2464
2465
307k
    bool isTrSkip = false;
2466
2467
307k
    for( const auto& currTU : cTUTraverser( cu.firstTU, cu.lastTU->next ) )
2468
312k
    {
2469
312k
      const uint32_t numValidComp = getNumberValidComponents(cu.chromaFormat);
2470
1.25M
      for (uint32_t compID = COMP_Y; compID < numValidComp; compID++)
2471
938k
      {
2472
938k
        if (currTU.blocks[compID].valid() && TU::getCbf(currTU, (ComponentID)compID) && currTU.mtsIdx[compID] == MTS_SKIP)
2473
78
        {
2474
78
          isTrSkip = true;
2475
78
          break;
2476
78
        }
2477
938k
      }
2478
312k
    }
2479
2480
307k
    if( (!cuCtx.lfnstLastScanPos && !cu.ispMode) || nonZeroCoeffNonTsCorner8x8 || isTrSkip )
2481
300k
    {
2482
300k
      return;
2483
300k
    }
2484
307k
  }
2485
140
  else
2486
140
  {
2487
140
    return;
2488
140
  }
2489
  
2490
6.96k
  unsigned cctx = 0;
2491
6.96k
  if ( CU::isSepTree(cu) ) cctx++;
2492
2493
6.96k
  const uint32_t idxLFNST = cu.lfnstIdx;
2494
6.96k
  assert( idxLFNST < 3 );
2495
6.96k
  m_BinEncoder.encodeBin( idxLFNST ? 1 : 0, Ctx::LFNSTIdx( cctx ) );
2496
2497
6.96k
  if( idxLFNST )
2498
6.55k
  {
2499
6.55k
    m_BinEncoder.encodeBin( (idxLFNST - 1) ? 1 : 0, Ctx::LFNSTIdx(2));
2500
6.55k
  }
2501
2502
6.96k
  DTRACE( g_trace_ctx, D_SYNTAX, "residual_lfnst_mode() etype=%d pos=(%d,%d) mode=%d\n", COMP_Y, cu.lx(), cu.ly(), ( int ) cu.lfnstIdx );
2503
6.96k
}
2504
2505
2506
void CABACWriter::last_sig_coeff( CoeffCodingContext& cctx, const TransformUnit& tu, ComponentID compID )
2507
1.04M
{
2508
1.04M
  unsigned blkPos = cctx.blockPos( cctx.scanPosLast() );
2509
1.04M
  unsigned posX, posY;
2510
1.04M
  {
2511
1.04M
    posY  = blkPos / cctx.width();
2512
1.04M
    posX  = blkPos - ( posY * cctx.width() );
2513
1.04M
  }
2514
2515
1.04M
  unsigned CtxLast;
2516
1.04M
  unsigned GroupIdxX = g_uiGroupIdx[ posX ];
2517
1.04M
  unsigned GroupIdxY = g_uiGroupIdx[ posY ];
2518
2519
1.04M
  unsigned maxLastPosX = cctx.maxLastPosX();
2520
1.04M
  unsigned maxLastPosY = cctx.maxLastPosY();
2521
2522
1.04M
  if( tu.cs->sps->MTS && tu.cu->sbtInfo != 0 && tu.blocks[ compID ].width <= 32 && tu.blocks[ compID ].height <= 32 && compID == COMP_Y )
2523
0
  {
2524
0
    maxLastPosX = ( tu.blocks[compID].width  == 32 ) ? g_uiGroupIdx[ 15 ] : maxLastPosX;
2525
0
    maxLastPosY = ( tu.blocks[compID].height == 32 ) ? g_uiGroupIdx[ 15 ] : maxLastPosY;
2526
0
  }
2527
2528
2.42M
  for( CtxLast = 0; CtxLast < GroupIdxX; CtxLast++ )
2529
1.38M
  {
2530
1.38M
    m_BinEncoder.encodeBin( 1, cctx.lastXCtxId( CtxLast ) );
2531
1.38M
  }
2532
1.04M
  if( GroupIdxX < maxLastPosX )
2533
997k
  {
2534
997k
    m_BinEncoder.encodeBin( 0, cctx.lastXCtxId( CtxLast ) );
2535
997k
  }
2536
2.49M
  for( CtxLast = 0; CtxLast < GroupIdxY; CtxLast++ )
2537
1.45M
  {
2538
1.45M
    m_BinEncoder.encodeBin( 1, cctx.lastYCtxId( CtxLast ) );
2539
1.45M
  }
2540
1.04M
  if( GroupIdxY < maxLastPosY )
2541
990k
  {
2542
990k
    m_BinEncoder.encodeBin( 0, cctx.lastYCtxId( CtxLast ) );
2543
990k
  }
2544
1.04M
  if( GroupIdxX > 3 )
2545
3.31k
  {
2546
3.31k
    posX -= g_uiMinInGroup[ GroupIdxX ];
2547
9.57k
    for (int i = ( ( GroupIdxX - 2 ) >> 1 ) - 1 ; i >= 0; i-- )
2548
6.25k
    {
2549
6.25k
      m_BinEncoder.encodeBinEP( ( posX >> i ) & 1 );
2550
6.25k
    }
2551
3.31k
  }
2552
1.04M
  if( GroupIdxY > 3 )
2553
2.57k
  {
2554
2.57k
    posY -= g_uiMinInGroup[ GroupIdxY ];
2555
6.91k
    for ( int i = ( ( GroupIdxY - 2 ) >> 1 ) - 1 ; i >= 0; i-- )
2556
4.34k
    {
2557
4.34k
      m_BinEncoder.encodeBinEP( ( posY >> i ) & 1 );
2558
4.34k
    }
2559
2.57k
  }
2560
1.04M
}
2561
2562
2563
namespace
2564
{
2565
  // Estimates the bits of bins exactly like BitEstimator (same context updates, same bits per bin; keep the two in
2566
  // sync), but sums them in its own member. As a local object whose address never escapes, its sum can stay in a
2567
  // register, while BitEstimator's sum is read and written in memory for every bin.
2568
  class LocalBitEstimate
2569
  {
2570
  public:
2571
1.06M
    explicit LocalBitEstimate( CtxStore& ctx ) : m_ctx( ctx ) {}
2572
2573
28.7M
    void encodeBin     ( unsigned bin, unsigned ctxId )        { m_ctx[ctxId].estFracBitsUpdate( bin, m_fracBits ); }
2574
1.05M
    void encodeBinsEP  ( unsigned /*bins*/, unsigned numBins ) { m_fracBits += BinProbModelBase::estFracBitsEP( numBins ); }
2575
    void encodeRemAbsEP( unsigned bins, unsigned goRicePar, unsigned cutoff, int maxLog2TrDynamicRange )
2576
5.56M
    {
2577
5.56M
      m_fracBits += BinProbModelBase::estFracBitsEP( BitEstimatorBase::numRemAbsEPBins( bins, goRicePar, cutoff, maxLog2TrDynamicRange ) );
2578
5.56M
    }
2579
2580
1.06M
    uint64_t fracBits() const { return m_fracBits; }
2581
2582
  private:
2583
    CtxStore& m_ctx;
2584
    uint64_t  m_fracBits = 0;
2585
  };
2586
2587
// CABACWriter::residual_coding_subblock with the bins coded by binCoder: the writer's BinEncIf, or a LocalBitEstimate
2588
template<class BinCoder>
2589
void residual_coding_subblock_bins( CoeffCodingContext& cctx, const TCoeffSig* coeff, const int stateTransTable, int& state, BinCoder& binCoder )
2590
1.07M
{
2591
  //===== init =====
2592
1.07M
  const int   minSubPos   = cctx.minSubPos();
2593
1.07M
  const bool  isLast      = cctx.isLast();
2594
1.07M
  int         firstSigPos = ( isLast ? cctx.scanPosLast() : cctx.maxSubPos() );
2595
1.07M
  int         nextSigPos  = firstSigPos;
2596
2597
  //===== encode significant_coeffgroup_flag =====
2598
1.07M
  if( !isLast && cctx.isNotFirst() )
2599
25.0k
  {
2600
25.0k
    if( cctx.isSigGroup() )
2601
15.1k
    {
2602
15.1k
      binCoder.encodeBin( 1, cctx.sigGroupCtxId() );
2603
15.1k
    }
2604
9.98k
    else
2605
9.98k
    {
2606
9.98k
      binCoder.encodeBin( 0, cctx.sigGroupCtxId() );
2607
9.98k
      return;
2608
9.98k
    }
2609
25.0k
  }
2610
2611
  //===== encode absolute values =====
2612
1.06M
  const int inferSigPos   = nextSigPos != cctx.scanPosLast() ? ( cctx.isNotFirst() ? minSubPos : -1 ) : nextSigPos;
2613
1.06M
  int       firstNZPos    = nextSigPos;
2614
1.06M
  int       lastNZPos     = -1;
2615
1.06M
  int       remAbsLevel   = -1;
2616
1.06M
  int       numNonZero    =  0;
2617
1.06M
  unsigned  signPattern   =  0;
2618
1.06M
  int       remRegBins    = cctx.remRegBins;
2619
1.06M
  int       firstPosMode2 = minSubPos - 1;
2620
1.06M
  unsigned  absLevelsOr   = 0;
2621
2622
9.49M
  for( ; nextSigPos >= minSubPos && remRegBins >= 4; nextSigPos-- )
2623
8.43M
  {
2624
8.43M
    const int blkPos     = cctx.blockPos( nextSigPos );
2625
8.43M
    TCoeff    Coeff      = coeff[ blkPos ];
2626
8.43M
    unsigned  sigFlag    = ( Coeff != 0 );
2627
8.43M
    if( numNonZero || nextSigPos != inferSigPos )
2628
7.39M
    {
2629
7.39M
      const unsigned sigCtxId = cctx.sigCtxIdAbsOnly( nextSigPos, state );
2630
7.39M
      binCoder.encodeBin( sigFlag, sigCtxId );
2631
7.39M
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "sig_bin() bin=%d ctx=%d\n", sigFlag, sigCtxId );
2632
7.39M
      remRegBins--;
2633
7.39M
    }
2634
2635
8.43M
    if( sigFlag )
2636
7.79M
    {
2637
7.79M
      uint8_t ctxOff = nextSigPos != cctx.scanPosLast() ? cctx.ctxOffsetAbsAt( nextSigPos ) : uint8_t( 0 );   // the last position has no selection before it
2638
7.79M
      numNonZero++;
2639
7.79M
      firstNZPos  = nextSigPos;
2640
7.79M
      lastNZPos   = std::max<int>( lastNZPos, nextSigPos );
2641
7.79M
      int absLevel= abs( Coeff );
2642
7.79M
      absLevelsOr |= absLevel;
2643
7.79M
      remAbsLevel = absLevel - 1;
2644
2645
7.79M
      if( nextSigPos != cctx.scanPosLast() ) signPattern <<= 1;
2646
7.79M
      if( Coeff < 0 )                        signPattern++;
2647
2648
7.79M
      unsigned gt1 = !!remAbsLevel;
2649
7.79M
      binCoder.encodeBin( gt1, cctx.greater1CtxIdAbs(ctxOff) );
2650
7.79M
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "gt1_flag() bin=%d ctx=%d\n", gt1, cctx.greater1CtxIdAbs(ctxOff) );
2651
7.79M
      remRegBins--;
2652
2653
7.79M
      if( gt1 )
2654
6.79M
      {
2655
6.79M
        remAbsLevel  -= 1;
2656
6.79M
        binCoder.encodeBin( remAbsLevel&1, cctx.parityCtxIdAbs( ctxOff ) );
2657
6.79M
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "par_flag() bin=%d ctx=%d\n", remAbsLevel&1, cctx.parityCtxIdAbs( ctxOff ) );
2658
6.79M
        remAbsLevel >>= 1;
2659
2660
6.79M
        remRegBins--;
2661
6.79M
        unsigned gt2 = !!remAbsLevel;
2662
6.79M
        binCoder.encodeBin(gt2, cctx.greater2CtxIdAbs(ctxOff));
2663
6.79M
        DTRACE(g_trace_ctx, D_SYNTAX_RESI, "gt2_flag() bin=%d ctx=%d\n", gt2, cctx.greater2CtxIdAbs(ctxOff));
2664
6.79M
        remRegBins--;
2665
6.79M
      }
2666
2667
7.79M
      cctx.absVal1stPass( nextSigPos, std::min<TCoeff>( 4 + ( absLevel & 1 ), absLevel ) );
2668
7.79M
    }
2669
2670
8.43M
    state = ( stateTransTable >> ((state<<2)+((Coeff&1)<<1)) ) & 3;
2671
8.43M
  }
2672
1.06M
  firstPosMode2 = nextSigPos;
2673
1.06M
  cctx.remRegBins = remRegBins;
2674
2675
2676
  //===== 2nd PASS: Go-rice codes =====
2677
  // only a level of 4 or more has bins here, and most subblocks have none
2678
1.06M
  if( absLevelsOr >= 4 )
2679
1.03M
  {
2680
9.38M
    for( int scanPos = firstSigPos; scanPos > firstPosMode2; scanPos-- )
2681
8.34M
    {
2682
8.34M
      unsigned absLevel = abs( coeff[cctx.blockPos( scanPos )] );
2683
2684
8.34M
      if( absLevel >= 4 )
2685
5.44M
      {
2686
5.44M
        int      sumAll   = cctx.templateAbsSum( scanPos, coeff, 4 );
2687
5.44M
        unsigned ricePar  = g_auiGoRiceParsCoeff[sumAll];
2688
5.44M
        unsigned rem      = ( absLevel - 4 ) >> 1;
2689
5.44M
        binCoder.encodeRemAbsEP( rem, ricePar, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2690
5.44M
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "rem_val() bin=%d ctx=%d\n", rem, ricePar );
2691
5.44M
      }
2692
8.34M
    }
2693
1.03M
  }
2694
2695
  //===== coeff bypass ====
2696
1.18M
  for( int scanPos = firstPosMode2; scanPos >= minSubPos; scanPos-- )
2697
123k
  {
2698
123k
    TCoeff    Coeff     = coeff[ cctx.blockPos( scanPos ) ];
2699
123k
    unsigned  absLevel  = abs( Coeff );
2700
123k
    int       sumAll    = cctx.templateAbsSum(scanPos, coeff, 0);
2701
123k
    int       rice      = g_auiGoRiceParsCoeff[sumAll];
2702
123k
    int       pos0      = g_auiGoRicePosCoeff0(state, rice);
2703
123k
    unsigned  rem       = ( absLevel == 0 ? pos0 : absLevel <= pos0 ? absLevel-1 : absLevel );
2704
123k
    binCoder.encodeRemAbsEP( rem, rice, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2705
123k
    DTRACE( g_trace_ctx, D_SYNTAX_RESI, "rem_val() bin=%d ctx=%d\n", rem, rice );
2706
123k
    state = ( stateTransTable >> ((state<<2)+((absLevel&1)<<1)) ) & 3;
2707
123k
    if( absLevel )
2708
122k
    {
2709
122k
      numNonZero++;
2710
122k
      firstNZPos = scanPos;
2711
122k
      lastNZPos   = std::max<int>( lastNZPos, scanPos );
2712
122k
      signPattern <<= 1;
2713
122k
      if( Coeff < 0 ) signPattern++;
2714
122k
    }
2715
123k
  }
2716
2717
  //===== encode sign's =====
2718
1.06M
  unsigned numSigns = numNonZero;
2719
1.06M
  if( cctx.hideSign( firstNZPos, lastNZPos ) )
2720
0
  {
2721
0
    numSigns    --;
2722
0
    signPattern >>= 1;
2723
0
  }
2724
1.06M
  binCoder.encodeBinsEP( signPattern, numSigns );
2725
1.06M
}
CABACWriter.cpp:void vvenc::(anonymous namespace)::residual_coding_subblock_bins<vvenc::BinEncIf>(vvenc::CoeffCodingContext&, short const*, int, int&, vvenc::BinEncIf&)
Line
Count
Source
2590
3.06k
{
2591
  //===== init =====
2592
3.06k
  const int   minSubPos   = cctx.minSubPos();
2593
3.06k
  const bool  isLast      = cctx.isLast();
2594
3.06k
  int         firstSigPos = ( isLast ? cctx.scanPosLast() : cctx.maxSubPos() );
2595
3.06k
  int         nextSigPos  = firstSigPos;
2596
2597
  //===== encode significant_coeffgroup_flag =====
2598
3.06k
  if( !isLast && cctx.isNotFirst() )
2599
0
  {
2600
0
    if( cctx.isSigGroup() )
2601
0
    {
2602
0
      binCoder.encodeBin( 1, cctx.sigGroupCtxId() );
2603
0
    }
2604
0
    else
2605
0
    {
2606
0
      binCoder.encodeBin( 0, cctx.sigGroupCtxId() );
2607
0
      return;
2608
0
    }
2609
0
  }
2610
2611
  //===== encode absolute values =====
2612
3.06k
  const int inferSigPos   = nextSigPos != cctx.scanPosLast() ? ( cctx.isNotFirst() ? minSubPos : -1 ) : nextSigPos;
2613
3.06k
  int       firstNZPos    = nextSigPos;
2614
3.06k
  int       lastNZPos     = -1;
2615
3.06k
  int       remAbsLevel   = -1;
2616
3.06k
  int       numNonZero    =  0;
2617
3.06k
  unsigned  signPattern   =  0;
2618
3.06k
  int       remRegBins    = cctx.remRegBins;
2619
3.06k
  int       firstPosMode2 = minSubPos - 1;
2620
3.06k
  unsigned  absLevelsOr   = 0;
2621
2622
6.13k
  for( ; nextSigPos >= minSubPos && remRegBins >= 4; nextSigPos-- )
2623
3.06k
  {
2624
3.06k
    const int blkPos     = cctx.blockPos( nextSigPos );
2625
3.06k
    TCoeff    Coeff      = coeff[ blkPos ];
2626
3.06k
    unsigned  sigFlag    = ( Coeff != 0 );
2627
3.06k
    if( numNonZero || nextSigPos != inferSigPos )
2628
0
    {
2629
0
      const unsigned sigCtxId = cctx.sigCtxIdAbsOnly( nextSigPos, state );
2630
0
      binCoder.encodeBin( sigFlag, sigCtxId );
2631
0
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "sig_bin() bin=%d ctx=%d\n", sigFlag, sigCtxId );
2632
0
      remRegBins--;
2633
0
    }
2634
2635
3.06k
    if( sigFlag )
2636
3.06k
    {
2637
3.06k
      uint8_t ctxOff = nextSigPos != cctx.scanPosLast() ? cctx.ctxOffsetAbsAt( nextSigPos ) : uint8_t( 0 );   // the last position has no selection before it
2638
3.06k
      numNonZero++;
2639
3.06k
      firstNZPos  = nextSigPos;
2640
3.06k
      lastNZPos   = std::max<int>( lastNZPos, nextSigPos );
2641
3.06k
      int absLevel= abs( Coeff );
2642
3.06k
      absLevelsOr |= absLevel;
2643
3.06k
      remAbsLevel = absLevel - 1;
2644
2645
3.06k
      if( nextSigPos != cctx.scanPosLast() ) signPattern <<= 1;
2646
3.06k
      if( Coeff < 0 )                        signPattern++;
2647
2648
3.06k
      unsigned gt1 = !!remAbsLevel;
2649
3.06k
      binCoder.encodeBin( gt1, cctx.greater1CtxIdAbs(ctxOff) );
2650
3.06k
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "gt1_flag() bin=%d ctx=%d\n", gt1, cctx.greater1CtxIdAbs(ctxOff) );
2651
3.06k
      remRegBins--;
2652
2653
3.06k
      if( gt1 )
2654
2.86k
      {
2655
2.86k
        remAbsLevel  -= 1;
2656
2.86k
        binCoder.encodeBin( remAbsLevel&1, cctx.parityCtxIdAbs( ctxOff ) );
2657
2.86k
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "par_flag() bin=%d ctx=%d\n", remAbsLevel&1, cctx.parityCtxIdAbs( ctxOff ) );
2658
2.86k
        remAbsLevel >>= 1;
2659
2660
2.86k
        remRegBins--;
2661
2.86k
        unsigned gt2 = !!remAbsLevel;
2662
2.86k
        binCoder.encodeBin(gt2, cctx.greater2CtxIdAbs(ctxOff));
2663
2.86k
        DTRACE(g_trace_ctx, D_SYNTAX_RESI, "gt2_flag() bin=%d ctx=%d\n", gt2, cctx.greater2CtxIdAbs(ctxOff));
2664
2.86k
        remRegBins--;
2665
2.86k
      }
2666
2667
3.06k
      cctx.absVal1stPass( nextSigPos, std::min<TCoeff>( 4 + ( absLevel & 1 ), absLevel ) );
2668
3.06k
    }
2669
2670
3.06k
    state = ( stateTransTable >> ((state<<2)+((Coeff&1)<<1)) ) & 3;
2671
3.06k
  }
2672
3.06k
  firstPosMode2 = nextSigPos;
2673
3.06k
  cctx.remRegBins = remRegBins;
2674
2675
2676
  //===== 2nd PASS: Go-rice codes =====
2677
  // only a level of 4 or more has bins here, and most subblocks have none
2678
3.06k
  if( absLevelsOr >= 4 )
2679
2.86k
  {
2680
5.72k
    for( int scanPos = firstSigPos; scanPos > firstPosMode2; scanPos-- )
2681
2.86k
    {
2682
2.86k
      unsigned absLevel = abs( coeff[cctx.blockPos( scanPos )] );
2683
2684
2.86k
      if( absLevel >= 4 )
2685
2.86k
      {
2686
2.86k
        int      sumAll   = cctx.templateAbsSum( scanPos, coeff, 4 );
2687
2.86k
        unsigned ricePar  = g_auiGoRiceParsCoeff[sumAll];
2688
2.86k
        unsigned rem      = ( absLevel - 4 ) >> 1;
2689
2.86k
        binCoder.encodeRemAbsEP( rem, ricePar, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2690
2.86k
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "rem_val() bin=%d ctx=%d\n", rem, ricePar );
2691
2.86k
      }
2692
2.86k
    }
2693
2.86k
  }
2694
2695
  //===== coeff bypass ====
2696
3.06k
  for( int scanPos = firstPosMode2; scanPos >= minSubPos; scanPos-- )
2697
0
  {
2698
0
    TCoeff    Coeff     = coeff[ cctx.blockPos( scanPos ) ];
2699
0
    unsigned  absLevel  = abs( Coeff );
2700
0
    int       sumAll    = cctx.templateAbsSum(scanPos, coeff, 0);
2701
0
    int       rice      = g_auiGoRiceParsCoeff[sumAll];
2702
0
    int       pos0      = g_auiGoRicePosCoeff0(state, rice);
2703
0
    unsigned  rem       = ( absLevel == 0 ? pos0 : absLevel <= pos0 ? absLevel-1 : absLevel );
2704
0
    binCoder.encodeRemAbsEP( rem, rice, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2705
0
    DTRACE( g_trace_ctx, D_SYNTAX_RESI, "rem_val() bin=%d ctx=%d\n", rem, rice );
2706
0
    state = ( stateTransTable >> ((state<<2)+((absLevel&1)<<1)) ) & 3;
2707
0
    if( absLevel )
2708
0
    {
2709
0
      numNonZero++;
2710
0
      firstNZPos = scanPos;
2711
0
      lastNZPos   = std::max<int>( lastNZPos, scanPos );
2712
0
      signPattern <<= 1;
2713
0
      if( Coeff < 0 ) signPattern++;
2714
0
    }
2715
0
  }
2716
2717
  //===== encode sign's =====
2718
3.06k
  unsigned numSigns = numNonZero;
2719
3.06k
  if( cctx.hideSign( firstNZPos, lastNZPos ) )
2720
0
  {
2721
0
    numSigns    --;
2722
0
    signPattern >>= 1;
2723
0
  }
2724
3.06k
  binCoder.encodeBinsEP( signPattern, numSigns );
2725
3.06k
}
CABACWriter.cpp:void vvenc::(anonymous namespace)::residual_coding_subblock_bins<vvenc::(anonymous namespace)::LocalBitEstimate>(vvenc::CoeffCodingContext&, short const*, int, int&, vvenc::(anonymous namespace)::LocalBitEstimate&)
Line
Count
Source
2590
1.06M
{
2591
  //===== init =====
2592
1.06M
  const int   minSubPos   = cctx.minSubPos();
2593
1.06M
  const bool  isLast      = cctx.isLast();
2594
1.06M
  int         firstSigPos = ( isLast ? cctx.scanPosLast() : cctx.maxSubPos() );
2595
1.06M
  int         nextSigPos  = firstSigPos;
2596
2597
  //===== encode significant_coeffgroup_flag =====
2598
1.06M
  if( !isLast && cctx.isNotFirst() )
2599
25.0k
  {
2600
25.0k
    if( cctx.isSigGroup() )
2601
15.1k
    {
2602
15.1k
      binCoder.encodeBin( 1, cctx.sigGroupCtxId() );
2603
15.1k
    }
2604
9.98k
    else
2605
9.98k
    {
2606
9.98k
      binCoder.encodeBin( 0, cctx.sigGroupCtxId() );
2607
9.98k
      return;
2608
9.98k
    }
2609
25.0k
  }
2610
2611
  //===== encode absolute values =====
2612
1.05M
  const int inferSigPos   = nextSigPos != cctx.scanPosLast() ? ( cctx.isNotFirst() ? minSubPos : -1 ) : nextSigPos;
2613
1.05M
  int       firstNZPos    = nextSigPos;
2614
1.05M
  int       lastNZPos     = -1;
2615
1.05M
  int       remAbsLevel   = -1;
2616
1.05M
  int       numNonZero    =  0;
2617
1.05M
  unsigned  signPattern   =  0;
2618
1.05M
  int       remRegBins    = cctx.remRegBins;
2619
1.05M
  int       firstPosMode2 = minSubPos - 1;
2620
1.05M
  unsigned  absLevelsOr   = 0;
2621
2622
9.49M
  for( ; nextSigPos >= minSubPos && remRegBins >= 4; nextSigPos-- )
2623
8.43M
  {
2624
8.43M
    const int blkPos     = cctx.blockPos( nextSigPos );
2625
8.43M
    TCoeff    Coeff      = coeff[ blkPos ];
2626
8.43M
    unsigned  sigFlag    = ( Coeff != 0 );
2627
8.43M
    if( numNonZero || nextSigPos != inferSigPos )
2628
7.39M
    {
2629
7.39M
      const unsigned sigCtxId = cctx.sigCtxIdAbsOnly( nextSigPos, state );
2630
7.39M
      binCoder.encodeBin( sigFlag, sigCtxId );
2631
7.39M
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "sig_bin() bin=%d ctx=%d\n", sigFlag, sigCtxId );
2632
7.39M
      remRegBins--;
2633
7.39M
    }
2634
2635
8.43M
    if( sigFlag )
2636
7.79M
    {
2637
7.79M
      uint8_t ctxOff = nextSigPos != cctx.scanPosLast() ? cctx.ctxOffsetAbsAt( nextSigPos ) : uint8_t( 0 );   // the last position has no selection before it
2638
7.79M
      numNonZero++;
2639
7.79M
      firstNZPos  = nextSigPos;
2640
7.79M
      lastNZPos   = std::max<int>( lastNZPos, nextSigPos );
2641
7.79M
      int absLevel= abs( Coeff );
2642
7.79M
      absLevelsOr |= absLevel;
2643
7.79M
      remAbsLevel = absLevel - 1;
2644
2645
7.79M
      if( nextSigPos != cctx.scanPosLast() ) signPattern <<= 1;
2646
7.79M
      if( Coeff < 0 )                        signPattern++;
2647
2648
7.79M
      unsigned gt1 = !!remAbsLevel;
2649
7.79M
      binCoder.encodeBin( gt1, cctx.greater1CtxIdAbs(ctxOff) );
2650
7.79M
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "gt1_flag() bin=%d ctx=%d\n", gt1, cctx.greater1CtxIdAbs(ctxOff) );
2651
7.79M
      remRegBins--;
2652
2653
7.79M
      if( gt1 )
2654
6.79M
      {
2655
6.79M
        remAbsLevel  -= 1;
2656
6.79M
        binCoder.encodeBin( remAbsLevel&1, cctx.parityCtxIdAbs( ctxOff ) );
2657
6.79M
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "par_flag() bin=%d ctx=%d\n", remAbsLevel&1, cctx.parityCtxIdAbs( ctxOff ) );
2658
6.79M
        remAbsLevel >>= 1;
2659
2660
6.79M
        remRegBins--;
2661
6.79M
        unsigned gt2 = !!remAbsLevel;
2662
6.79M
        binCoder.encodeBin(gt2, cctx.greater2CtxIdAbs(ctxOff));
2663
6.79M
        DTRACE(g_trace_ctx, D_SYNTAX_RESI, "gt2_flag() bin=%d ctx=%d\n", gt2, cctx.greater2CtxIdAbs(ctxOff));
2664
6.79M
        remRegBins--;
2665
6.79M
      }
2666
2667
7.79M
      cctx.absVal1stPass( nextSigPos, std::min<TCoeff>( 4 + ( absLevel & 1 ), absLevel ) );
2668
7.79M
    }
2669
2670
8.43M
    state = ( stateTransTable >> ((state<<2)+((Coeff&1)<<1)) ) & 3;
2671
8.43M
  }
2672
1.05M
  firstPosMode2 = nextSigPos;
2673
1.05M
  cctx.remRegBins = remRegBins;
2674
2675
2676
  //===== 2nd PASS: Go-rice codes =====
2677
  // only a level of 4 or more has bins here, and most subblocks have none
2678
1.05M
  if( absLevelsOr >= 4 )
2679
1.03M
  {
2680
9.37M
    for( int scanPos = firstSigPos; scanPos > firstPosMode2; scanPos-- )
2681
8.34M
    {
2682
8.34M
      unsigned absLevel = abs( coeff[cctx.blockPos( scanPos )] );
2683
2684
8.34M
      if( absLevel >= 4 )
2685
5.44M
      {
2686
5.44M
        int      sumAll   = cctx.templateAbsSum( scanPos, coeff, 4 );
2687
5.44M
        unsigned ricePar  = g_auiGoRiceParsCoeff[sumAll];
2688
5.44M
        unsigned rem      = ( absLevel - 4 ) >> 1;
2689
5.44M
        binCoder.encodeRemAbsEP( rem, ricePar, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2690
5.44M
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "rem_val() bin=%d ctx=%d\n", rem, ricePar );
2691
5.44M
      }
2692
8.34M
    }
2693
1.03M
  }
2694
2695
  //===== coeff bypass ====
2696
1.18M
  for( int scanPos = firstPosMode2; scanPos >= minSubPos; scanPos-- )
2697
123k
  {
2698
123k
    TCoeff    Coeff     = coeff[ cctx.blockPos( scanPos ) ];
2699
123k
    unsigned  absLevel  = abs( Coeff );
2700
123k
    int       sumAll    = cctx.templateAbsSum(scanPos, coeff, 0);
2701
123k
    int       rice      = g_auiGoRiceParsCoeff[sumAll];
2702
123k
    int       pos0      = g_auiGoRicePosCoeff0(state, rice);
2703
123k
    unsigned  rem       = ( absLevel == 0 ? pos0 : absLevel <= pos0 ? absLevel-1 : absLevel );
2704
123k
    binCoder.encodeRemAbsEP( rem, rice, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2705
123k
    DTRACE( g_trace_ctx, D_SYNTAX_RESI, "rem_val() bin=%d ctx=%d\n", rem, rice );
2706
123k
    state = ( stateTransTable >> ((state<<2)+((absLevel&1)<<1)) ) & 3;
2707
123k
    if( absLevel )
2708
122k
    {
2709
122k
      numNonZero++;
2710
122k
      firstNZPos = scanPos;
2711
122k
      lastNZPos   = std::max<int>( lastNZPos, scanPos );
2712
122k
      signPattern <<= 1;
2713
122k
      if( Coeff < 0 ) signPattern++;
2714
122k
    }
2715
123k
  }
2716
2717
  //===== encode sign's =====
2718
1.05M
  unsigned numSigns = numNonZero;
2719
1.05M
  if( cctx.hideSign( firstNZPos, lastNZPos ) )
2720
0
  {
2721
0
    numSigns    --;
2722
0
    signPattern >>= 1;
2723
0
  }
2724
1.05M
  binCoder.encodeBinsEP( signPattern, numSigns );
2725
1.05M
}
2726
}   // namespace
2727
2728
void CABACWriter::residual_coding_subblock( CoeffCodingContext& cctx, const TCoeffSig* coeff, const int stateTransTable, int& state )
2729
1.07M
{
2730
1.07M
  if( m_BinEncoder.isEncoding() )
2731
3.06k
  {
2732
3.06k
    residual_coding_subblock_bins( cctx, coeff, stateTransTable, state, m_BinEncoder );
2733
3.06k
  }
2734
1.06M
  else
2735
1.06M
  {
2736
    // only estimating bits (m_BinEncoder is a BitEstimator): sum the subblock's bits locally, add them once
2737
1.06M
    LocalBitEstimate estimate( static_cast<CtxStore&>( m_BinEncoder.getCtx() ) );
2738
1.06M
    residual_coding_subblock_bins( cctx, coeff, stateTransTable, state, estimate );
2739
1.06M
    static_cast<BitEstimatorBase&>( m_BinEncoder ).addEstFracBits( estimate.fracBits() );
2740
1.06M
  }
2741
1.07M
}
2742
2743
2744
void CABACWriter::residual_codingTS( const TransformUnit& tu, ComponentID compID )
2745
78.5k
{
2746
78.5k
  DTRACE( g_trace_ctx, D_SYNTAX, "residual_codingTS() etype=%d pos=(%d,%d) size=%dx%d\n", tu.blocks[compID].compID, tu.blocks[compID].x, tu.blocks[compID].y, tu.blocks[compID].width, tu.blocks[compID].height );
2747
2748
  // init coeff coding context
2749
78.5k
  CoeffCodingContext  cctx    ( tu, compID, false, tu.cu->bdpcmM[toChannelType(compID)] );
2750
78.5k
  const TCoeffSig*    coeff   = tu.getCoeffs( compID ).buf;
2751
78.5k
  int maxCtxBins = (cctx.maxNumCoeff() * 7) >> 2;
2752
78.5k
  cctx.remRegBins = maxCtxBins;
2753
2754
  // determine and set last coeff position and sig group flags
2755
78.5k
  std::bitset<MLS_GRP_NUM> sigGroupFlags;
2756
7.41M
  for( int scanPos = 0; scanPos < cctx.maxNumCoeff(); scanPos++)
2757
7.33M
  {
2758
7.33M
    unsigned blkPos = cctx.blockPos( scanPos );
2759
7.33M
    if( coeff[blkPos] )
2760
773k
    {
2761
773k
      sigGroupFlags.set( scanPos >> cctx.log2CGSize() );
2762
773k
    }
2763
7.33M
  }
2764
2765
  // code subblocks
2766
537k
  for( int subSetId = 0; subSetId <= ( cctx.maxNumCoeff() - 1 ) >> cctx.log2CGSize(); subSetId++ )
2767
458k
  {
2768
458k
    cctx.initSubblock         ( subSetId, sigGroupFlags[subSetId] );
2769
458k
    residual_coding_subblockTS( cctx, coeff );
2770
458k
  }
2771
78.5k
}
2772
2773
2774
void CABACWriter::residual_coding_subblockTS( CoeffCodingContext& cctx, const TCoeffSig* coeff )
2775
458k
{
2776
  //===== init =====
2777
458k
  const int   minSubPos   = cctx.maxSubPos();
2778
458k
  int         firstSigPos = cctx.minSubPos();
2779
458k
  int         nextSigPos  = firstSigPos;
2780
2781
  //===== encode significant_coeffgroup_flag =====
2782
458k
  if( !cctx.isLastSubSet() || !cctx.only1stSigGroup() )
2783
446k
  {
2784
446k
    if( cctx.isSigGroup() )
2785
171k
    {
2786
171k
        m_BinEncoder.encodeBin( 1, cctx.sigGroupCtxId( true ) );
2787
171k
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "ts_sigGroup() bin=%d ctx=%d\n", 1, cctx.sigGroupCtxId() );
2788
171k
    }
2789
275k
    else
2790
275k
    {
2791
275k
        m_BinEncoder.encodeBin( 0, cctx.sigGroupCtxId( true ) );
2792
275k
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "ts_sigGroup() bin=%d ctx=%d\n", 0, cctx.sigGroupCtxId() );
2793
275k
      return;
2794
275k
    }
2795
446k
  }
2796
2797
  //===== encode absolute values =====
2798
183k
  const int inferSigPos   = minSubPos;
2799
183k
  int       remAbsLevel   = -1;
2800
183k
  int       numNonZero    =  0;
2801
2802
183k
  int rightPixel, belowPixel, modAbsCoeff;
2803
2804
183k
  int lastScanPosPass1 = -1;
2805
183k
  int lastScanPosPass2 = -1;
2806
2.87M
  for (; nextSigPos <= minSubPos && cctx.remRegBins >= 4; nextSigPos++)
2807
2.69M
  {
2808
2.69M
    TCoeff    Coeff      = coeff[ cctx.blockPos( nextSigPos ) ];
2809
2.69M
    unsigned  sigFlag    = ( Coeff != 0 );
2810
2.69M
    if( numNonZero || nextSigPos != inferSigPos )
2811
2.69M
    {
2812
2.69M
      const unsigned sigCtxId = cctx.sigCtxIdAbsTS( nextSigPos, coeff );
2813
2.69M
      m_BinEncoder.encodeBin( sigFlag, sigCtxId );
2814
2.69M
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "ts_sig_bin() bin=%d ctx=%d\n", sigFlag, sigCtxId );
2815
2.69M
      cctx.remRegBins--;
2816
2.69M
    }
2817
2818
2.69M
    if( sigFlag )
2819
718k
    {
2820
      //===== encode sign's =====
2821
718k
      int sign = Coeff < 0;
2822
718k
      const unsigned signCtxId = cctx.signCtxIdAbsTS(nextSigPos, coeff, cctx.bdpcm());
2823
718k
      m_BinEncoder.encodeBin(sign, signCtxId);
2824
718k
      cctx.remRegBins--;
2825
718k
      numNonZero++;
2826
718k
      cctx.neighTS(rightPixel, belowPixel, nextSigPos, coeff);
2827
718k
      modAbsCoeff = cctx.deriveModCoeff(rightPixel, belowPixel, abs(Coeff), cctx.bdpcm());
2828
718k
      remAbsLevel = modAbsCoeff - 1;
2829
2830
718k
      unsigned gt1 = !!remAbsLevel;
2831
718k
      const unsigned gt1CtxId = cctx.lrg1CtxIdAbsTS(nextSigPos, coeff, cctx.bdpcm());
2832
718k
      m_BinEncoder.encodeBin(gt1, gt1CtxId);
2833
718k
      DTRACE(g_trace_ctx, D_SYNTAX_RESI, "ts_gt1_flag() bin=%d ctx=%d\n", gt1, gt1CtxId);
2834
718k
      cctx.remRegBins--;
2835
2836
718k
      if( gt1 )
2837
708k
      {
2838
708k
        remAbsLevel  -= 1;
2839
708k
        m_BinEncoder.encodeBin( remAbsLevel&1, cctx.parityCtxIdAbsTS() );
2840
708k
        DTRACE( g_trace_ctx, D_SYNTAX_RESI, "ts_par_flag() bin=%d ctx=%d\n", remAbsLevel&1, cctx.parityCtxIdAbsTS() );
2841
708k
        cctx.remRegBins--;
2842
708k
      }
2843
718k
    }
2844
2.69M
    lastScanPosPass1 = nextSigPos;
2845
2.69M
  }
2846
2847
183k
  int cutoffVal = 2;
2848
183k
  int numGtBins = 4;
2849
2850
2.64M
  for (int scanPos = firstSigPos; scanPos <= minSubPos && cctx.remRegBins >= 4; scanPos++)
2851
2.46M
  {
2852
2.46M
    unsigned absLevel;
2853
2.46M
    cctx.neighTS(rightPixel, belowPixel, scanPos, coeff);
2854
2.46M
    absLevel = cctx.deriveModCoeff(rightPixel, belowPixel, abs(coeff[cctx.blockPos(scanPos)]), cctx.bdpcm());
2855
2.46M
    cutoffVal = 2;
2856
12.3M
    for (int i = 0; i < numGtBins; i++)
2857
9.85M
    {
2858
9.85M
      if (absLevel >= cutoffVal)
2859
1.77M
      {
2860
1.77M
        unsigned gt2 = (absLevel >= (cutoffVal + 2));
2861
1.77M
        m_BinEncoder.encodeBin(gt2, cctx.greaterXCtxIdAbsTS(cutoffVal >> 1));
2862
1.77M
        DTRACE(g_trace_ctx, D_SYNTAX_RESI, "ts_gt%d_flag() bin=%d ctx=%d sp=%d coeff=%d\n", i, gt2, cctx.greaterXCtxIdAbsTS(cutoffVal >> 1), scanPos, std::min<int>(absLevel, cutoffVal + 2));
2863
1.77M
        cctx.remRegBins--;
2864
1.77M
      }
2865
9.85M
      cutoffVal += 2;
2866
9.85M
    }
2867
2.46M
    lastScanPosPass2 = scanPos;
2868
2.46M
  }
2869
2870
  //===== coeff bypass ====
2871
3.11M
  for( int scanPos = firstSigPos; scanPos <= minSubPos; scanPos++ )
2872
2.93M
  {
2873
2.93M
    unsigned absLevel;
2874
2.93M
    cctx.neighTS(rightPixel, belowPixel, scanPos, coeff);
2875
2.93M
    cutoffVal = (scanPos <= lastScanPosPass2 ? 10 : (scanPos <= lastScanPosPass1 ? 2 : 0));
2876
2.93M
    absLevel = cctx.deriveModCoeff(rightPixel, belowPixel, abs(coeff[cctx.blockPos(scanPos)]), cctx.bdpcm()||!cutoffVal);
2877
2.93M
    if( absLevel >= cutoffVal )
2878
630k
    {
2879
      //int       rice = cctx.templateAbsSumTS( scanPos, coeff );
2880
630k
      int       rice = 1;
2881
630k
      unsigned  rem = scanPos <= lastScanPosPass1 ? (absLevel - cutoffVal) >> 1 : absLevel;
2882
630k
      m_BinEncoder.encodeRemAbsEP( rem, rice, COEF_REMAIN_BIN_REDUCTION, cctx.maxLog2TrDRange() );
2883
630k
      DTRACE( g_trace_ctx, D_SYNTAX_RESI, "ts_rem_val() bin=%d ctx=%d sp=%d\n", rem, rice, scanPos );
2884
2885
630k
      if (absLevel && scanPos > lastScanPosPass1)
2886
54.8k
      {
2887
54.8k
        int sign = coeff[cctx.blockPos(scanPos)] < 0;
2888
54.8k
        m_BinEncoder.encodeBinEP(sign);
2889
54.8k
      }
2890
630k
    }
2891
2.93M
  }
2892
183k
}
2893
2894
2895
//================================================================================
2896
//  helper functions
2897
//--------------------------------------------------------------------------------
2898
//    void  unary_max_symbol  ( symbol, ctxId0, ctxIdN, maxSymbol )
2899
//    void  unary_max_eqprob  ( symbol,                 maxSymbol )
2900
//    void  exp_golomb_eqprob ( symbol, count )
2901
//================================================================================
2902
2903
void CABACWriter::unary_max_symbol( unsigned symbol, unsigned ctxId0, unsigned ctxIdN, unsigned maxSymbol )
2904
4.31k
{
2905
4.31k
  CHECK( symbol > maxSymbol, "symbol > maxSymbol" );
2906
4.31k
  const unsigned totalBinsToWrite = std::min( symbol + 1, maxSymbol );
2907
8.62k
  for( unsigned binsWritten = 0; binsWritten < totalBinsToWrite; ++binsWritten )
2908
4.31k
  {
2909
4.31k
    const unsigned nextBin = symbol > binsWritten;
2910
4.31k
    m_BinEncoder.encodeBin( nextBin, binsWritten == 0 ? ctxId0 : ctxIdN );
2911
4.31k
  }
2912
4.31k
}
2913
2914
2915
void CABACWriter::unary_max_eqprob( unsigned symbol, unsigned maxSymbol )
2916
279k
{
2917
279k
  if( maxSymbol == 0 )
2918
0
  {
2919
0
    return;
2920
0
  }
2921
279k
  bool     codeLast = ( maxSymbol > symbol );
2922
279k
  unsigned bins     = 0;
2923
279k
  unsigned numBins  = 0;
2924
279k
  while( symbol-- )
2925
315
  {
2926
315
    bins   <<= 1;
2927
315
    bins   ++;
2928
315
    numBins++;
2929
315
  }
2930
279k
  if( codeLast )
2931
279k
  {
2932
279k
    bins  <<= 1;
2933
279k
    numBins++;
2934
279k
  }
2935
279k
  CHECK(!( numBins <= 32 ), "Unspecified error");
2936
279k
  m_BinEncoder.encodeBinsEP( bins, numBins );
2937
279k
}
2938
2939
2940
void CABACWriter::exp_golomb_eqprob( unsigned symbol, unsigned count )
2941
0
{
2942
0
  unsigned bins    = 0;
2943
0
  unsigned numBins = 0;
2944
0
  while( symbol >= (unsigned)(1<<count) )
2945
0
  {
2946
0
    bins <<= 1;
2947
0
    bins++;
2948
0
    numBins++;
2949
0
    symbol -= 1 << count;
2950
0
    count++;
2951
0
  }
2952
0
  bins <<= 1;
2953
0
  numBins++;
2954
0
  bins = (bins << count) | symbol;
2955
0
  numBins += count;
2956
0
  CHECK(!( numBins <= 32 ), "Unspecified error");
2957
0
  m_BinEncoder.encodeBinsEP( bins, numBins );
2958
0
}
2959
2960
2961
void CABACWriter::codeAlfCtuEnabled( CodingStructure& cs, ChannelType channel, AlfParam* alfParam, const int numCtus )
2962
17.8k
{
2963
17.8k
  if( isLuma( channel ) )
2964
2.86k
  {
2965
2.86k
    if (alfParam->alfEnabled[COMP_Y])
2966
2.86k
      codeAlfCtuEnabled( cs, COMP_Y, alfParam, numCtus );
2967
2.86k
  }
2968
14.9k
  else
2969
14.9k
  {
2970
14.9k
    if (alfParam->alfEnabled[COMP_Cb])
2971
14.9k
      codeAlfCtuEnabled( cs, COMP_Cb, alfParam, numCtus );
2972
14.9k
    if (alfParam->alfEnabled[COMP_Cr])
2973
14.9k
      codeAlfCtuEnabled( cs, COMP_Cr, alfParam, numCtus );
2974
14.9k
  }
2975
17.8k
}
2976
2977
2978
void CABACWriter::codeAlfCtuEnabled( CodingStructure& cs, ComponentID compID, AlfParam* alfParam, const int numCtus )
2979
32.7k
{
2980
165k
  for( int ctuIdx = 0; ctuIdx < numCtus; ctuIdx++ )
2981
132k
  {
2982
132k
    codeAlfCtuEnabledFlag( cs, ctuIdx, compID );
2983
132k
  }
2984
32.7k
}
2985
2986
2987
void CABACWriter::codeAlfCtuEnabledFlag( CodingStructure& cs, uint32_t ctuRsAddr, const int compIdx)
2988
477k
{
2989
477k
  CHECKD( !cs.sps->alfEnabled, "ALF is disabled in SPS" ); 
2990
2991
477k
  const PreCalcValues& pcv = *cs.pcv;
2992
477k
  int                 frame_width_in_ctus = pcv.widthInCtus;
2993
477k
  int                 ry = ctuRsAddr / frame_width_in_ctus;
2994
477k
  int                 rx = ctuRsAddr - ry * frame_width_in_ctus;
2995
477k
  const Position      pos( rx * cs.pcv->maxCUSize, ry * cs.pcv->maxCUSize );
2996
477k
  const uint32_t      curSliceIdx = cs.slice->independentSliceIdx;
2997
477k
  const uint32_t      curTileIdx  = cs.pps->getTileIdx( pos );
2998
477k
  bool                leftAvail   = cs.getCURestricted( pos.offset( -(int)pcv.maxCUSize, 0 ), pos, curSliceIdx, curTileIdx, CH_L, TREE_D ) ? true : false;
2999
477k
  bool                aboveAvail  = cs.getCURestricted( pos.offset( 0, -(int)pcv.maxCUSize ), pos, curSliceIdx, curTileIdx, CH_L, TREE_D ) ? true : false;
3000
3001
477k
  int leftCTUAddr = leftAvail ? ctuRsAddr - 1 : -1;
3002
477k
  int aboveCTUAddr = aboveAvail ? ctuRsAddr - frame_width_in_ctus : -1;
3003
3004
477k
  const uint8_t* ctbAlfFlag = cs.slice->pic->m_alfCtuEnabled[ compIdx ].data();
3005
477k
  int ctx = 0;
3006
477k
  ctx += leftCTUAddr > -1 ? ( ctbAlfFlag[leftCTUAddr] ? 1 : 0 ) : 0;
3007
477k
  ctx += aboveCTUAddr > -1 ? ( ctbAlfFlag[aboveCTUAddr] ? 1 : 0 ) : 0;
3008
477k
  m_BinEncoder.encodeBin( ctbAlfFlag[ctuRsAddr], Ctx::ctbAlfFlag( compIdx * 3 + ctx ) );
3009
477k
}
3010
3011
3012
void CABACWriter::codeCcAlfFilterControlIdc(uint8_t idcVal, CodingStructure &cs, const ComponentID compID,
3013
                                            const int curIdx, const uint8_t *filterControlIdc, Position lumaPos,
3014
                                            const int filterCount)
3015
0
{
3016
0
  CHECK(idcVal > filterCount, "Filter index is too large");
3017
3018
0
  const uint32_t curSliceIdx    = cs.slice->independentSliceIdx;
3019
0
  const uint32_t curTileIdx     = cs.pps->getTileIdx( lumaPos );
3020
0
  Position       leftLumaPos    = lumaPos.offset(-(int)cs.pcv->maxCUSize, 0);
3021
0
  Position       aboveLumaPos   = lumaPos.offset(0, -(int)cs.pcv->maxCUSize);
3022
0
  bool           leftAvail      = cs.getCURestricted( leftLumaPos,  lumaPos, curSliceIdx, curTileIdx, CH_L, TREE_D ) ? true : false;
3023
0
  bool           aboveAvail     = cs.getCURestricted( aboveLumaPos, lumaPos, curSliceIdx, curTileIdx, CH_L, TREE_D ) ? true : false;
3024
0
  int            ctxt           = 0;
3025
3026
0
  if (leftAvail)
3027
0
  {
3028
0
    ctxt += ( filterControlIdc[curIdx - 1]) ? 1 : 0;
3029
0
  }
3030
0
  if (aboveAvail)
3031
0
  {
3032
0
    ctxt += (filterControlIdc[curIdx - cs.pcv->widthInCtus]) ? 1 : 0;
3033
0
  }
3034
0
  ctxt += ( compID == COMP_Cr ) ? 3 : 0;
3035
3036
0
  m_BinEncoder.encodeBin( ( idcVal == 0 ) ? 0 : 1, Ctx::CcAlfFilterControlFlag( ctxt ) ); // ON/OFF flag is context coded
3037
0
  if ( idcVal > 0 )
3038
0
  {
3039
0
    int val = (idcVal - 1);
3040
0
    while ( val )
3041
0
    {
3042
0
      m_BinEncoder.encodeBinEP( 1 );
3043
0
      val--;
3044
0
    }
3045
0
    if ( idcVal < filterCount )
3046
0
    {
3047
0
      m_BinEncoder.encodeBinEP( 0 );
3048
0
    }
3049
0
  }
3050
0
  DTRACE( g_trace_ctx, D_SYNTAX, "ccAlfFilterControlIdc() compID=%d pos=(%d,%d) ctxt=%d, filterCount=%d, idcVal=%d\n", compID, lumaPos.x, lumaPos.y, ctxt, filterCount, idcVal );
3051
0
}
3052
3053
3054
void CABACWriter::mip_flag( const CodingUnit& cu )
3055
1.39M
{
3056
1.39M
  if( !cu.Y().valid() )
3057
0
  {
3058
0
    return;
3059
0
  }
3060
1.39M
  if( !cu.cs->sps->MIP )
3061
0
  {
3062
0
    return;
3063
0
  }
3064
3065
1.39M
  unsigned ctxId = DeriveCtx::CtxMipFlag( cu );
3066
1.39M
  m_BinEncoder.encodeBin( cu.mipFlag, Ctx::MipFlag( ctxId ) );
3067
1.39M
  DTRACE( g_trace_ctx, D_SYNTAX, "mip_flag() pos=(%d,%d) mode=%d\n", cu.lumaPos().x, cu.lumaPos().y, cu.mipFlag ? 1 : 0 );
3068
1.39M
}
3069
3070
3071
void CABACWriter::mip_pred_modes( const CodingUnit& cu )
3072
1.67k
{
3073
1.67k
  if( !cu.Y().valid() )
3074
0
  {
3075
0
    return;
3076
0
  }
3077
3078
1.67k
  mip_pred_mode( cu );
3079
1.67k
}
3080
3081
3082
void CABACWriter::mip_pred_mode( const CodingUnit& cu )
3083
323k
{
3084
323k
  m_BinEncoder.encodeBinEP( (cu.mipTransposedFlag ? 1 : 0) );
3085
3086
323k
  const int numModes = getNumModesMip( cu.Y() );
3087
323k
  CHECKD( cu.intraDir[CH_L] < 0 || cu.intraDir[CH_L] >= numModes, "Invalid MIP mode" );
3088
323k
  xWriteTruncBinCode( cu.intraDir[CH_L], numModes );
3089
3090
323k
  DTRACE( g_trace_ctx, D_SYNTAX, "mip_pred_mode() pos=(%d,%d) mode=%d transposed=%d\n", cu.lumaPos().x, cu.lumaPos().y, cu.intraDir[CH_L], cu.mipTransposedFlag ? 1 : 0 );
3091
323k
}
3092
3093
3094
void CABACWriter::codeAlfCtuFilterIndex(CodingStructure& cs, uint32_t ctuRsAddr)
3095
93.0k
{
3096
93.0k
  const uint8_t* ctbAlfFlag = cs.slice->pic->m_alfCtuEnabled[ COMP_Y ].data();
3097
93.0k
  if (!ctbAlfFlag[ctuRsAddr])
3098
0
  {
3099
0
    return;
3100
0
  }
3101
3102
93.0k
  const short* alfCtbFilterIndex = cs.slice->pic->m_alfCtbFilterIndex.data();
3103
93.0k
  const unsigned filterSetIdx = alfCtbFilterIndex[ctuRsAddr];
3104
93.0k
  unsigned numAps = cs.slice->numAps;
3105
93.0k
  unsigned numAvailableFiltSets = numAps + NUM_FIXED_FILTER_SETS;
3106
93.0k
  if (numAvailableFiltSets > NUM_FIXED_FILTER_SETS)
3107
18.6k
  {
3108
18.6k
    int useTemporalFilt = (filterSetIdx >= NUM_FIXED_FILTER_SETS) ? 1 : 0;
3109
18.6k
    m_BinEncoder.encodeBin(useTemporalFilt, Ctx::AlfUseTemporalFilt());
3110
18.6k
    if (useTemporalFilt)
3111
18.6k
    {
3112
18.6k
      CHECK((filterSetIdx - NUM_FIXED_FILTER_SETS) >= (numAvailableFiltSets - NUM_FIXED_FILTER_SETS), "temporal non-latest set");
3113
18.6k
      if (numAps > 1)
3114
0
      {
3115
0
        xWriteTruncBinCode(filterSetIdx - NUM_FIXED_FILTER_SETS, numAvailableFiltSets - NUM_FIXED_FILTER_SETS);
3116
0
      }
3117
18.6k
    }
3118
0
    else
3119
0
    {
3120
0
      CHECK(filterSetIdx >= NUM_FIXED_FILTER_SETS, "fixed set larger than temporal");
3121
0
      xWriteTruncBinCode(filterSetIdx, NUM_FIXED_FILTER_SETS);
3122
0
    }
3123
18.6k
  }
3124
74.4k
  else
3125
74.4k
  {
3126
74.4k
    CHECK(filterSetIdx >= NUM_FIXED_FILTER_SETS, "fixed set numavail < num_fixed");
3127
74.4k
    xWriteTruncBinCode(filterSetIdx, NUM_FIXED_FILTER_SETS);
3128
74.4k
  }
3129
93.0k
}
3130
3131
3132
void CABACWriter::codeAlfCtuAlternatives( CodingStructure& cs, ChannelType channel, AlfParam* alfParam, const int numCtus )
3133
17.8k
{
3134
17.8k
  if( isChroma( channel ) )
3135
14.9k
  {
3136
14.9k
    if (alfParam->alfEnabled[COMP_Cb])
3137
14.9k
      codeAlfCtuAlternatives( cs, COMP_Cb, alfParam, numCtus );
3138
14.9k
    if (alfParam->alfEnabled[COMP_Cr])
3139
14.9k
      codeAlfCtuAlternatives( cs, COMP_Cr, alfParam, numCtus );
3140
14.9k
  }
3141
17.8k
}
3142
3143
3144
void CABACWriter::codeAlfCtuAlternatives( CodingStructure& cs, ComponentID compID, AlfParam* alfParam, const int numCtus)
3145
29.8k
{
3146
29.8k
  if( compID == COMP_Y )
3147
0
    return;
3148
29.8k
  const uint8_t* ctbAlfFlag = cs.slice->pic->m_alfCtuEnabled[ compID ].data();
3149
3150
153k
  for( int ctuIdx = 0; ctuIdx < numCtus; ctuIdx++ )
3151
123k
  {
3152
123k
    if( ctbAlfFlag[ctuIdx] )
3153
123k
    {
3154
123k
      codeAlfCtuAlternative( cs, ctuIdx, compID, alfParam );
3155
123k
    }
3156
123k
  }
3157
29.8k
}
3158
3159
3160
void CABACWriter::codeAlfCtuAlternative( CodingStructure& cs, uint32_t ctuRsAddr, const int compIdx, const AlfParam* alfParam)
3161
631k
{
3162
631k
  if( compIdx == COMP_Y )
3163
0
    return;
3164
3165
631k
  {
3166
631k
    const uint8_t* ctbAlfFlag = cs.slice->pic->m_alfCtuEnabled[ compIdx ].data();
3167
3168
631k
    if( ctbAlfFlag[ctuRsAddr] )
3169
631k
    {
3170
631k
      const int numAlts = alfParam->numAlternativesChroma;
3171
631k
      const uint8_t* ctbAlfAlternative = cs.slice->pic->m_alfCtuAlternative[compIdx].data();
3172
631k
      unsigned numOnes = ctbAlfAlternative[ctuRsAddr];
3173
631k
      assert( ctbAlfAlternative[ctuRsAddr] < numAlts );
3174
1.81M
      for( int i = 0; i < numOnes; ++i )
3175
1.18M
        m_BinEncoder.encodeBin( 1, Ctx::ctbAlfAlternative( compIdx-1 ) );
3176
631k
      if( numOnes < numAlts-1 )
3177
477k
        m_BinEncoder.encodeBin( 0, Ctx::ctbAlfAlternative( compIdx-1 ) );
3178
631k
    }
3179
631k
  }
3180
631k
}
3181
3182
} // namespace vvenc
3183
3184
//! \}
3185