Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/CommonLib/DepQuant.h
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
#pragma once
43
44
#include "CommonDef.h"
45
#include "Contexts.h"
46
#include "Slice.h"
47
#include "Unit.h"
48
#include "UnitPartitioner.h"
49
#include "QuantRDOQ2.h"
50
51
//! \ingroup CommonLib
52
//! \{
53
54
namespace vvenc {
55
56
namespace DQIntern
57
{
58
  /*================================================================================*/
59
  /*=====                                                                      =====*/
60
  /*=====   R A T E   E S T I M A T O R                                        =====*/
61
  /*=====                                                                      =====*/
62
  /*================================================================================*/
63
64
  struct NbInfoSbb
65
  {
66
    uint8_t   numInv;
67
    uint8_t   invInPos[5];
68
    uint16_t  invInMask;    // the positions of invInPos as bits
69
  };
70
  struct NbInfoOut
71
  {
72
    uint16_t  maxDist;
73
    uint16_t  num;
74
    uint16_t  outPos[5];
75
  };
76
  // For TU shapes with 4x4 SBBs, where the outside neighbours of an SBB's positions (NbInfoOut) lie: in its right,
77
  // below or diagonal SBB. start[] is the start of that SBB in scan order relative to the SBB's own start, or -1 when
78
  // it lies outside the non-zero-out region.
79
  enum NbSbb { NB_SBB_RIGHT = 0, NB_SBB_BELOW = 1, NB_SBB_DIAG = 2, NUM_NB_SBB = 3 };
80
  struct NbSbbStarts
81
  {
82
    int16_t   start[NUM_NB_SBB];
83
  };
84
  // The same for every TU shape with 4x4 SBBs: for neighbour k of the position p of an SBB (k as in the template:
85
  // (x+1,y), (x+2,y), (x+1,y+1), (x,y+1), (x,y+2)), its position inside neighbouring SBB s as idx[k][s][p], or 0x80
86
  // when it does not lie there. Used as pshufb indices.
87
  struct NbOutShuffle16
88
  {
89
    uint8_t   idx[5][NUM_NB_SBB][16];
90
  };
91
  struct CoeffFracBits
92
  {
93
    int32_t   bits[6];
94
  };
95
96
  enum ScanPosType : int8_t { SCAN_ISCSBB = 0, SCAN_SOCSBB = 1, SCAN_EOCSBB = 2 };
97
98
  struct ScanInfo
99
  {
100
25.8M
    ScanInfo() {}
101
    short         numSbb;
102
    short         scanIdx;
103
    short         rasterPos;
104
    short         sbbPos; // byte
105
    short         nextSbbRight;
106
    short         nextSbbBelow;
107
    short         levelsCopySize; // at an SBB's first position: how many levels past the SBB a context copies from its previous one
108
    int8_t        sbbSize;
109
    int8_t        insidePos;
110
    int8_t        nextInsidePos;
111
    ScanPosType   spt;
112
    int8_t        posX;
113
    int8_t        posY;
114
    int8_t        sigCtxOffsetNext;
115
    int8_t        gtxCtxOffsetNext;
116
    NbInfoSbb     currNbInfoSbb;
117
  };
118
119
  class Rom;
120
  struct TUParameters
121
  {
122
    TUParameters ( const Rom& rom, const unsigned width, const unsigned height, const ChannelType chType );
123
    ~TUParameters()
124
131k
    {
125
131k
      delete [] m_scanInfo;
126
131k
    }
127
128
    ChannelType       m_chType;
129
    unsigned          m_width;
130
    unsigned          m_height;
131
    unsigned          m_numCoeff;
132
    unsigned          m_numSbb;
133
    unsigned          m_log2SbbWidth;
134
    unsigned          m_log2SbbHeight;
135
    unsigned          m_log2SbbSize;
136
    unsigned          m_sbbSize;
137
    unsigned          m_sbbMask;
138
    unsigned          m_widthInSbb;
139
    unsigned          m_heightInSbb;
140
    const ScanElement *m_scanSbbId2SbbPos;
141
    const ScanElement *m_scanId2BlkPos;
142
    const NbInfoSbb*  m_scanId2NbInfoSbb;
143
    const NbInfoOut*  m_scanId2NbInfoOut;
144
    const NbSbbStarts* m_scanSbb2NbSbbStarts;   // per SBB in scan order; nullptr unless the SBBs are 4x4
145
    const NbOutShuffle16* m_nbOutShuffle16;
146
    ScanInfo*         m_scanInfo;
147
  private:
148
    void xSetScanInfo( ScanInfo& scanInfo, int scanIdx );
149
  };
150
151
  class Rom
152
  {
153
  public:
154
1.43k
    Rom() : m_scansInitialized(false) {}
155
1.43k
    ~Rom() { xUninitScanArrays(); }
156
1.43k
    void                init        ()                       { xInitScanArrays(); }
157
131k
    const NbInfoSbb*    getNbInfoSbb( int hd, int vd ) const { return m_scanId2NbInfoSbbArray[hd][vd]; }
158
131k
    const NbInfoOut*    getNbInfoOut( int hd, int vd ) const { return m_scanId2NbInfoOutArray[hd][vd]; }
159
131k
    const NbSbbStarts*  getNbSbbStarts( int hd, int vd ) const { return m_scanSbb2NbSbbStartsArray[hd][vd]; }
160
131k
    const NbOutShuffle16& getNbOutShuffle16() const          { return m_nbOutShuffle16; }
161
    const TUParameters* getTUPars   ( const CompArea& area, const ComponentID compID ) const
162
2.25M
    {
163
2.25M
      return m_tuParameters[Log2(area.width)][Log2(area.height)][toChannelType(compID)];
164
2.25M
    }
165
  private:
166
    void  xInitScanArrays   ();
167
    void  xUninitScanArrays ();
168
    void  xSetNbSbb16       ( NbSbbStarts& starts, const int cpos[5], int x, int y, int insidePos, int begSbb );
169
    void  xCheckNbSbb16     ( const NbSbbStarts* starts, const NbInfoOut* nbOut, unsigned numCoeff ) const;
170
  private:
171
    bool          m_scansInitialized;
172
    NbInfoSbb*    m_scanId2NbInfoSbbArray[ MAX_TU_SIZE_IDX ][ MAX_TU_SIZE_IDX ];
173
    NbInfoOut*    m_scanId2NbInfoOutArray[ MAX_TU_SIZE_IDX ][ MAX_TU_SIZE_IDX ];
174
    NbSbbStarts*  m_scanSbb2NbSbbStartsArray[ MAX_TU_SIZE_IDX ][ MAX_TU_SIZE_IDX ];
175
    NbOutShuffle16 m_nbOutShuffle16;
176
    TUParameters* m_tuParameters         [ MAX_TU_SIZE_IDX ][ MAX_TU_SIZE_IDX ][ MAX_NUM_CH ];
177
  };
178
179
  struct RateTablesMemo;
180
181
  // Lower bounds of the chroma rates the all-zero proof (DepQuant::xProvesAllZero) adds up: the minimum over the three sig
182
  // context sets and over the context range a coefficient's diagonal ( x + y ) selects
183
  struct ZeroProofRates
184
  {
185
    int32_t sig0   [2];   // sig_coeff_flag 0 (diagonal < 2: contexts 4..7, else 0..3)
186
    int32_t sig1   [2];   // sig_coeff_flag 1
187
    int32_t level  [2];   // the gtx bits of a nonzero level, bits[1..5] (sign bit included; diagonal 0: contexts 6..10, else 1..5)
188
    int32_t lastLevel;    // the same for the last position, which uses gtx context 0
189
    int32_t sbb0;         // sb_coded_flag 0 and 1, both contexts
190
    int32_t sbb1;
191
  };
192
193
  class RateEstimator
194
  {
195
  public:
196
5.72k
    RateEstimator () {}
197
5.72k
    ~RateEstimator() {}
198
    // returns whether the sig and gtx tables were built (not taken from the memo)
199
    bool initCtx  ( const TUParameters& tuPars, const TransformUnit& tu, const ComponentID compID, const FracBitsAccess& fracBitsAccess,
200
                    RateTablesMemo& memo );
201
202
941k
    inline const BinFracBits *sigSbbFracBits() const { return m_tables->sigSbb; }
203
    inline const BinFracBits *sigFlagBits(unsigned stateId) const
204
3.76M
    {
205
3.76M
      return m_tables->sig[std::max(((int) stateId) - 1, 0)];
206
3.76M
    }
207
1.88M
    inline const CoeffFracBits *gtxFracBits() const { return m_tables->gtx; }
208
    // the bits of coding the last position at this scan position, from the position the trellis already holds
209
    inline int32_t              lastOffset( const ScanInfo& scanInfo ) const
210
8.84M
    {
211
8.84M
      return m_lastBitsX[scanInfo.posX] + m_lastBitsY[scanInfo.posY];
212
8.84M
    }
213
214
  private:
215
    void  xSetLastCoeffOffset ( const FracBitsAccess& fracBitsAccess, const TUParameters& tuPars, const TransformUnit& tu, const ComponentID compID );
216
217
  protected:
218
    void  xSetZeroProofRates  ( ZeroProofRates& rates ) const;   // from the chroma tables held now
219
220
  public:
221
    static const unsigned sm_numCtxSetsSig    = 3;
222
    static const unsigned sm_numCtxSetsGtx    = 2;
223
    static const unsigned sm_maxNumSigSbbCtx  = 2;
224
    static const unsigned sm_maxNumSigCtx     = 12;
225
    static const unsigned sm_maxNumGtxCtx     = 21;
226
    // the coefficient-coding contexts the sig / gtx tables are built from, for both channel types: SigCoeffGroup[2],
227
    // SigFlag[6], ParFlag[2] and GtxFlag[4], defined back to back (checked in RateTablesMemo's constructor)
228
    static const unsigned sm_numCoeffCtx      = 4 + 60 + 32 + 64;
229
    static const unsigned sm_coeffCtxBytes    = sm_numCoeffCtx * sizeof( BinProbModel );
230
231
    // the tables of one channel type
232
    struct RateTables
233
    {
234
      BinFracBits   sigSbb[ sm_maxNumSigSbbCtx ];
235
      BinFracBits   sig   [ sm_numCtxSetsSig ][ sm_maxNumSigCtx ];
236
      CoeffFracBits gtx   [ sm_maxNumGtxCtx ];
237
    };
238
239
  private:
240
    void  xSetSigSbbFracBits  ( const FracBitsAccess& fracBitsAccess, ChannelType chType, RateTables& tables );
241
    void  xSetSigFlagBits     ( const FracBitsAccess& fracBitsAccess, ChannelType chType, RateTables& tables );
242
    void  xSetGtxFlagBits     ( const FracBitsAccess& fracBitsAccess, ChannelType chType, RateTables& tables );
243
244
    int32_t             m_lastBitsX      [ MAX_TB_SIZEY ];
245
    int32_t             m_lastBitsY      [ MAX_TB_SIZEY ];
246
    const RateTables*   m_tables = nullptr;   // the tables of the current block's channel type, held in the memo
247
  };
248
249
  // The memo of RateEstimator::initCtx: per channel type, the sig / gtx tables last built for it and the raw bytes of
250
  // the coefficient-coding contexts they came from (equal bytes give equal tables). DepQuant keeps it after the trellis
251
  // and state arrays, so they keep their place in the object.
252
  struct RateTablesMemo
253
  {
254
    RateTablesMemo();
255
    struct Channel
256
    {
257
      uint8_t                   ctxStates[ RateEstimator::sm_coeffCtxBytes ];
258
      RateEstimator::RateTables tables;
259
    };
260
    Channel channel[ MAX_NUM_CH ];
261
  };
262
263
  /*================================================================================*/
264
  /*=====                                                                      =====*/
265
  /*=====   P R E - Q U A N T I Z E R                                          =====*/
266
  /*=====                                                                      =====*/
267
  /*================================================================================*/
268
269
  struct PQData
270
  {
271
    TCoeff  absLevel;
272
    int64_t deltaDist;
273
  };
274
275
  // What Quantizer::initQuantBlock works out for a block.
276
  struct QuantBlockParams
277
  {
278
    // quantization
279
    int               m_QShift;
280
    int64_t           m_QAdd;
281
    int64_t           m_QScale;
282
    TCoeff            m_maxQIdx;
283
    TCoeff            m_thresLast;
284
    TCoeff            m_thresSSbb;      // the trellis skips a sub-block whose |coeff| * qScale are all below it (xPopulateTrellis)
285
    TCoeff            m_thresDefault;   // the threshold on absolute coefficients without scaling lists
286
    // distortion normalization
287
    int               m_DistShift;
288
    int64_t           m_DistAdd;
289
    int64_t           m_DistStepAdd;
290
    int64_t           m_DistOrgFact;
291
  };
292
293
  // The memo of Quantizer::initQuantBlock with no gValue. With the transform skip path excluded, the result depends
294
  // only on the channel type, the block size, QP and lambda, and on values fixed for the sequence, and those four rarely
295
  // change from one block of a size to the next. Log2( width ) + Log2( height ) is enough for the size: it gives the transform
296
  // shift and whether the sqrt(2) adjustment applies.
297
  struct QuantBlockMemo
298
  {
299
    struct Entry
300
    {
301
      double           lambda = 0;
302
      int              qpDQ   = std::numeric_limits<int>::min();
303
      QuantBlockParams params;
304
    };
305
    Entry entry[ MAX_NUM_CH ][ 2 * 6 + 1 ];
306
  };
307
308
  // Dequantizes the levels qCoeff at scan positions lastScanIdx down to 0 (raster positions scan[i].idx, the block's
309
  // width as stride) into tCoeff, which the caller has zeroed, along the dependent-quantization state chain.
310
  // piDequantCoef: the scaling list's factor per raster position, or nullptr without scaling lists.
311
  void dequantCoeffs( const TCoeffSig* qCoeff, TCoeff* tCoeff, const ScanElement* scan, int lastScanIdx, int width, int height,
312
                      int shift, Intermediate_Int invQScale, const int* piDequantCoef, TCoeff minTCoeff, TCoeff maxTCoeff );
313
  typedef decltype( &dequantCoeffs ) DequantCoeffsFunc;
314
315
  class Quantizer : public QuantBlockParams
316
  {
317
  public:
318
5.72k
    Quantizer() {}
319
5.72k
    void   init            ( int dqThrVal, int sbbSkipThrVal ) { m_DqThrVal = dqThrVal; m_SbbSkipThrVal = sbbSkipThrVal; }
320
    void   initQuantBlock  ( const TransformUnit& tu, const ComponentID compID, const QpParam& cQP, const double lambda, QuantBlockMemo& memo );
321
    void   dequantBlock    ( const TransformUnit& tu, const ComponentID compID, const QpParam& cQP, CoeffBuf& recCoeff, bool enableScalingLists, int* piDequantCoef, DequantCoeffsFunc dequant ) const;
322
    void   initQuantBlock  ( const TransformUnit& tu, const ComponentID compID, const QpParam& cQP, const double lambda, int gValue = -1 );
323
    bool   preQuantCoeff   ( const TCoeff absCoeff, PQData *pqData, int quanCoeff ) const;
324
2.25M
    TCoeff getLastThreshold() const { return m_thresLast; }
325
941k
    TCoeff getSSbbThreshold() const { return m_thresSSbb; }
326
327
2.25M
    int64_t getQScale      () const { return m_QScale; }
328
329
    int               m_DqThrVal;
330
    int               m_SbbSkipThrVal;   // the sub-block skip limit in half quantization steps, 6 fractional bits (0: off)
331
  };
332
333
54.8M
#define RICEMAX 32
334
  extern const int32_t g_goRiceBits[4][RICEMAX];
335
336
  /*================================================================================*/
337
  /*=====                                                                      =====*/
338
  /*=====   T C Q   S T A T E                                                  =====*/
339
  /*=====                                                                      =====*/
340
  /*================================================================================*/
341
342
  struct StateMem;
343
344
  struct SbbCtx
345
  {
346
    uint8_t* sbbFlags;
347
    uint8_t* levels;
348
  };
349
350
  class CommonCtx
351
  {
352
  friend class DepQuant;
353
354
  public:
355
5.72k
    CommonCtx() : m_currSbbCtx( m_allSbbCtx ), m_prevSbbCtx( m_currSbbCtx + 4 ) {}
356
357
34.9k
    inline void swap() { std::swap( m_currSbbCtx, m_prevSbbCtx ); }
358
359
    inline void reset( const TUParameters& tuPars, const RateEstimator& rateEst )
360
941k
    {
361
941k
      m_nbInfo = tuPars.m_scanId2NbInfoOut;
362
941k
      m_nbSbbStarts = tuPars.m_scanSbb2NbSbbStarts;
363
941k
      m_nbOutShuffle16 = tuPars.m_nbOutShuffle16;
364
941k
      ::memcpy( m_sbbFlagBits, rateEst.sigSbbFracBits(), 2 * sizeof( BinFracBits ) );
365
941k
      CHECKD( tuPars.m_numSbb > sm_maxNumSbb, "more sub-blocks than the space for their flags" );
366
941k
      CHECKD( tuPars.m_numCoeff > unsigned( MAX_TB_SIZEY * MAX_TB_SIZEY ), "more coefficients than the space for their levels" );
367
941k
      const int chunkSize = sm_maxNumSbb + tuPars.m_numCoeff + sm_levelsStep;
368
941k
      uint8_t* nextMem = m_memory;
369
8.47M
      for( int k = 0; k < 8; k++, nextMem += chunkSize )
370
7.52M
      {
371
7.52M
        m_allSbbCtx[k].sbbFlags = nextMem;
372
7.52M
        m_allSbbCtx[k].levels = nextMem + sm_maxNumSbb;
373
7.52M
      }
374
941k
    }
375
376
    // At the start of an SBB: takes over the SBB flags and the levels of the SBBs coded so far from the context prevId,
377
    // and sets the template sums (tplAcc, sum1st) of the new SBB's positions from their neighbours in those SBBs.
378
    void update( const ScanInfo& scanInfo, const int prevId, int stateId, StateMem& curr )
379
138k
    {
380
138k
      if( const uint8_t* absLevels = updateSbbFlags( scanInfo, prevId, stateId, curr ) )
381
84.7k
      {
382
84.7k
        updateTemplates( scanInfo, absLevels, stateId, curr );
383
84.7k
      }
384
138k
    }
385
    // The first part of update(). Returns the levels from the new SBB's start when its template sums are needed (a
386
    // neighbouring SBB has significant coefficients), else nullptr: the sums stay 0.
387
    const uint8_t* updateSbbFlags( const ScanInfo& scanInfo, const int prevId, int stateId, StateMem& curr );
388
389
    // For TUs with 4x4 SBBs, else nullptr: where the outside neighbours of the new SBB's positions lie.
390
    const NbSbbStarts* nbSbbStarts( const ScanInfo& scanInfo ) const
391
0
    {
392
0
      return m_nbSbbStarts ? m_nbSbbStarts + ( ( scanInfo.scanIdx - scanInfo.sbbSize ) >> 4 ) : nullptr;
393
0
    }
394
0
    const NbOutShuffle16& nbOutShuffle16() const { return *m_nbOutShuffle16; }
395
396
    void getLevelPtrs( const ScanInfo& scanInfo, uint8_t*& levels0, uint8_t*& levels1, uint8_t*& levels2, uint8_t*& levels3 )
397
138k
    {
398
138k
      levels0 = m_currSbbCtx[0].levels + scanInfo.scanIdx;
399
138k
      levels1 = m_currSbbCtx[1].levels + scanInfo.scanIdx;
400
138k
      levels2 = m_currSbbCtx[2].levels + scanInfo.scanIdx;
401
138k
      levels3 = m_currSbbCtx[3].levels + scanInfo.scanIdx;
402
138k
    }
403
404
  private:
405
    // The second part of update(): the template sums of the new SBB's 16 positions for stateId. Expects them to be 0.
406
    void updateTemplates( const ScanInfo& scanInfo, const uint8_t* absLevels, int stateId, StateMem& curr ) const;
407
408
    const NbInfoOut* m_nbInfo;
409
    const NbSbbStarts* m_nbSbbStarts;
410
    const NbOutShuffle16* m_nbOutShuffle16;
411
    BinFracBits      m_sbbFlagBits[2];
412
    // The flags have room for all the sub-blocks of the largest non-zero area, so clearing them has one size.
413
    static const unsigned sm_maxNumSbb = 64;
414
    // The levels are copied in steps of this size; each context's levels are followed by as much padding.
415
    static const int sm_levelsStep = 16;
416
    // with at most MAX_TB_SIZEY^2 levels (checked in reset), a context's flags, levels and padding fit its share of m_memory
417
    static_assert( sm_maxNumSbb + sm_levelsStep <= unsigned( MLS_GRP_NUM ), "the flags and padding must fit m_memory" );
418
    SbbCtx           m_allSbbCtx[8];
419
    SbbCtx*          m_currSbbCtx;
420
    SbbCtx*          m_prevSbbCtx;
421
    uint8_t          m_memory[8 * ( MAX_TB_SIZEY * MAX_TB_SIZEY + MLS_GRP_NUM )];
422
  };
423
424
  static constexpr int64_t rdCostInit = std::numeric_limits<int64_t>::max() >> 1;
425
426
  struct Decisions
427
  {
428
    int64_t   rdCost[4];
429
    TCoeffSig absLevel[4];
430
    int8_t    prevId[4];
431
  };
432
433
  struct StateMem
434
  {
435
    int64_t  rdCost[4];
436
    int16_t  remRegBins[4];
437
    int32_t  sbbBits0[4];
438
    int32_t  sbbBits1[4];
439
440
    uint8_t tplAcc[16][4];
441
    uint8_t sum1st[16][4];
442
    uint8_t absVal[16][4];
443
444
    struct
445
    {
446
      uint8_t sig[4];
447
      uint8_t cff[4];
448
    } ctx;
449
450
    uint8_t  numSig[4];
451
    int8_t   refSbbCtxId[4];
452
453
    int32_t  cffBits1[RateEstimator::sm_maxNumGtxCtx + 3];
454
455
    int8_t   m_goRicePar[4];
456
    int8_t   m_goRiceZero[4];
457
    const BinFracBits* m_sigFracBitsArray[4];
458
    const CoeffFracBits* m_gtxFracBitsArray;
459
460
    int      cffBitsCtxOffset;
461
    bool     anyRemRegBinsLt4;
462
    int      initRemRegBins;
463
  };
464
465
  static constexpr size_t StateMemSkipCpySize = offsetof( StateMem, sbbBits1 );
466
467
  inline const uint8_t* CommonCtx::updateSbbFlags( const ScanInfo& scanInfo, const int prevId, int stateId, StateMem& curr )
468
138k
  {
469
138k
    uint8_t*    sbbFlags  = m_currSbbCtx[stateId].sbbFlags;
470
138k
    uint8_t*    levels    = m_currSbbCtx[stateId].levels;
471
    // The flags are copied and cleared in full (sm_maxNumSbb bytes, the space each context has for them), the levels in
472
    // steps of sm_levelsStep bytes, into the padding after them: constant sizes let the compiler write both inline. Flags
473
    // past numSbb and levels past levelsCopySize are never read: the templates' reach only shrinks as the scan goes back.
474
138k
    const int   copySize  = scanInfo.levelsCopySize;
475
138k
    uint8_t*    dstLevels = levels + scanInfo.scanIdx + scanInfo.sbbSize;
476
138k
    if( prevId >= 0 )
477
114k
    {
478
114k
      ::memcpy( sbbFlags, m_prevSbbCtx[prevId].sbbFlags, sm_maxNumSbb * sizeof( uint8_t ) );
479
114k
      const uint8_t* srcLevels = m_prevSbbCtx[prevId].levels + scanInfo.scanIdx + scanInfo.sbbSize;
480
646k
      for( int k = 0; k < copySize; k += sm_levelsStep )
481
532k
      {
482
532k
        ::memcpy( dstLevels + k, srcLevels + k, sm_levelsStep );
483
532k
      }
484
114k
    }
485
23.7k
    else
486
23.7k
    {
487
23.7k
      ::memset( sbbFlags, 0, sm_maxNumSbb * sizeof( uint8_t ) );
488
110k
      for( int k = 0; k < copySize; k += sm_levelsStep )
489
86.7k
      {
490
86.7k
        ::memset( dstLevels + k, 0, sm_levelsStep );
491
86.7k
      }
492
23.7k
    }
493
138k
    sbbFlags[scanInfo.sbbPos] = !!curr.numSig[stateId];
494
495
138k
    const int       sigNSbb = ( ( scanInfo.nextSbbRight ? sbbFlags[scanInfo.nextSbbRight] : false ) || ( scanInfo.nextSbbBelow ? sbbFlags[scanInfo.nextSbbBelow] : false ) ? 1 : 0 );
496
138k
    curr.refSbbCtxId[stateId] = stateId;
497
138k
    const BinFracBits sbbBits = m_sbbFlagBits[sigNSbb];
498
499
138k
    curr.sbbBits0[stateId] = sbbBits.intBits[0];
500
138k
    curr.sbbBits1[stateId] = sbbBits.intBits[1];
501
502
138k
    if( sigNSbb || ( ( scanInfo.nextSbbRight && scanInfo.nextSbbBelow ) ? sbbFlags[scanInfo.nextSbbBelow + 1] : false ) )
503
84.7k
    {
504
84.7k
      return levels + scanInfo.scanIdx - scanInfo.sbbSize;
505
84.7k
    }
506
53.6k
    return nullptr;
507
138k
  }
508
}
509
510
class DepQuant : public QuantRDOQ2, DQIntern::RateEstimator
511
{
512
public:
513
  DepQuant( const Quant* other, bool enc, bool useScalingLists, bool enableOpt = true );
514
  virtual ~DepQuant();
515
516
  virtual void quant  (       TransformUnit& tu, const ComponentID compID, const CCoeffBuf& pSrc, TCoeff &uiAbsSum, const QpParam& cQP, const Ctx& ctx );
517
  virtual void dequant( const TransformUnit& tu, CoeffBuf& dstCoeff, const ComponentID compID, const QpParam& cQP );
518
  
519
  virtual void init   ( int rdoq, bool useRDOQTS, int dqThrVal, int sbbSkipThrVal );
520
521
private:
522
  void    xQuantDQ          ( TransformUnit& tu, const CCoeffBuf& srcCoeff, const ComponentID compID, const QpParam& cQP, const double lambda, const Ctx& ctx, TCoeff& absSum, bool enableScalingLists, int* quantCoeff );
523
  bool    xProvesAllZero    ( const DQIntern::TUParameters& tuPars, const TCoeff* tCoeff, const int firstTestPos, const TCoeff quantCoeff );
524
  void    xDequantDQ        ( const TransformUnit& tu, CoeffBuf& recCoeff, const ComponentID compID, const QpParam& cQP, bool enableScalingLists, int* quantCoeff );
525
  // DepQuantDecide.h: templates on the set of per-coefficient kernels (PointerKernels in DepQuant.cpp, one per SIMD translation unit)
526
  template<class Kernels>
527
  void    xDecideAndUpdate  ( const TCoeff absCoeff, const DQIntern::ScanInfo& scanInfo, bool zeroOut, int quantCoeff);
528
  // the states a sub-block's skip path starts from, kept at its last position (SCAN_SOCSBB): by xDecideAndUpdate, and by
529
  // xPopulateTrellis for an all-zero sub-block it decides at its first position only
530
29.1k
  void    xSaveSkipStates   () { ::memcpy( &m_state_skip, &m_state_curr, DQIntern::StateMemSkipCpySize ); }
531
  template<class Kernels>
532
  void    xDecide           ( const DQIntern::ScanInfo &scanInfo, const TCoeff absCoeff, const int lastOffset, DQIntern::Decisions &decisions, bool zeroOut, int quantCoeff );
533
  template<class Kernels>
534
  static void xPopulateTrellis( DepQuant& dq, const DQIntern::TUParameters& tuPars, const int firstTestPos, const TCoeff* tCoeff,
535
                                const bool zeroOut, const int effWidth, const int effHeight, const int quantCoeff );
536
  struct PointerKernels;
537
538
  DQIntern::CommonCtx m_commonCtx;
539
  std::shared_ptr<DQIntern::Rom>
540
                      m_scansRom;
541
  DQIntern::Quantizer m_quant;
542
543
  DQIntern::Decisions m_trellis[MAX_TB_SIZEY * MAX_TB_SIZEY][2];
544
  DQIntern::StateMem  m_state_curr;
545
  DQIntern::StateMem  m_state_skip;
546
  DQIntern::RateTablesMemo m_rateTablesMemo;   // after the trellis and state arrays: see RateTablesMemo
547
  DQIntern::QuantBlockMemo m_quantBlockMemo;
548
  int                 m_firstScanIdx = 0;   // the scan position the current block's trellis starts at
549
  // the rate minima of xProvesAllZero, refreshed by it after the chroma tables were built; after the trellis members, so that they keep their offsets
550
  DQIntern::ZeroProofRates m_zeroProofRates;
551
  bool                     m_zeroProofRatesStale = true;
552
553
#if defined( TARGET_SIMD_X86 ) && ENABLE_SIMD_OPT_QUANT
554
  void initDepQuantX86();
555
  template <X86_VEXT vext>
556
  void _initDepQuantX86();
557
#endif
558
#if defined( TARGET_SIMD_ARM ) && ENABLE_SIMD_OPT_QUANT
559
  void initDepQuantARM();
560
  template <ARM_VEXT vext>
561
  void _initDepQuantARM();
562
#endif
563
564
public:
565
  // has to be called as a first check, assumes no decision has been made yet!!!
566
  void( *m_checkAllRdCosts )( const DQIntern::ScanPosType spt, const DQIntern::PQData* pqData, DQIntern::Decisions& decisions, const DQIntern::StateMem& state );
567
  // as m_checkAllRdCosts, where a level may be 4 or more: its bits then include the Rice code of the state's m_goRicePar
568
  void( *m_checkAllRdCostsGe4 )( const DQIntern::ScanPosType spt, const DQIntern::PQData* pqData, DQIntern::Decisions& decisions, const DQIntern::StateMem& state );
569
  // has to be called as a first check, assumes no decision has been made yet!!!
570
  void( *m_checkAllRdCostsOdd1 )( const DQIntern::ScanPosType spt, const int64_t pq_a_dist, const int64_t pq_b_dist, DQIntern::Decisions& decisions, const DQIntern::StateMem& state );
571
  void( *m_updateStates )( const DQIntern::ScanInfo& scanInfo, const DQIntern::Decisions& decisions, DQIntern::StateMem& curr );
572
  DQIntern::DequantCoeffsFunc m_dequantCoeffs;   // the dequantization kernel of the SIMD level in use (m_quant.dequantBlock)
573
  void( *m_updateStatesEOS )( const DQIntern::ScanInfo& scanInfo, const DQIntern::Decisions& decisions, const DQIntern::StateMem& skip, DQIntern::StateMem& curr, DQIntern::CommonCtx& commonCtx );
574
  // xPopulateTrellis with the kernels of the SIMD level in use; without scaling lists the only indirect call of a block's trellis
575
  void( *m_populateTrellis )( DepQuant& dq, const DQIntern::TUParameters& tuPars, const int firstTestPos, const TCoeff* tCoeff,
576
                              const bool zeroOut, const int effWidth, const int effHeight, const int quantCoeff );
577
};
578
579
} // namespace vvenc
580
581
//! \}
582