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/QuantRDOQ.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
/** \file     QuantRDOQ.cpp
44
    \brief    transform and quantization class
45
*/
46
47
#include "QuantRDOQ.h"
48
#include "UnitTools.h"
49
#include "ContextModelling.h"
50
#include "CodingStructure.h"
51
#include "dtrace_next.h"
52
#include "dtrace_buffer.h"
53
54
#include <stdlib.h>
55
#include <memory.h>
56
57
//! \ingroup CommonLib
58
//! \{
59
60
namespace vvenc {
61
62
struct coeffGroupRDStats
63
{
64
  int    iNNZbeforePos0;
65
  double d64CodedLevelandDist; // distortion and level cost only
66
  double d64UncodedDist;    // all zero coded block distortion
67
  double d64SigCost;
68
  double d64SigCost_0;
69
 int   iNumSbbCtxBins;
70
};
71
72
73
//! \ingroup CommonLib
74
//! \{
75
76
// ====================================================================================================================
77
// Constants
78
// ====================================================================================================================
79
80
81
// ====================================================================================================================
82
// Static functions
83
// ====================================================================================================================
84
85
// ====================================================================================================================
86
// QuantRDOQ class member functions
87
// ====================================================================================================================
88
89
90
5.72k
QuantRDOQ::QuantRDOQ( const Quant* other, bool useScalingLists, bool enableOpt ) : Quant( other, useScalingLists, enableOpt )
91
5.72k
{
92
93
5.72k
  const QuantRDOQ *rdoq = dynamic_cast<const QuantRDOQ*>( other );
94
5.72k
  CHECK( other && !rdoq, "The RDOQ cast must be successfull!" );
95
5.72k
  xInitScalingList( rdoq );
96
5.72k
}
97
98
QuantRDOQ::~QuantRDOQ()
99
5.72k
{
100
5.72k
  xDestroyScalingList();
101
5.72k
}
102
103
104
105
106
/** Get the best level in RD sense
107
 *
108
 * \returns best quantized transform level for given scan position
109
 *
110
 * This method calculates the best quantized transform level for a given scan position.
111
 */
112
inline uint32_t QuantRDOQ::xGetCodedLevel( double&            rd64CodedCost,
113
                                       double&            rd64CodedCost0,
114
                                       double&            rd64CodedCostSig,
115
                                       Intermediate_Int   lLevelDouble,
116
                                       uint32_t               uiMaxAbsLevel,
117
                                       const BinFracBits* fracBitsSig,
118
                                       const BinFracBits& fracBitsPar,
119
                                       const BinFracBits& fracBitsGt1,
120
                                       const BinFracBits& fracBitsGt2,
121
                                       const int          remRegBins,
122
                                       unsigned           goRiceZero,
123
                                       uint16_t             ui16AbsGoRice,
124
                                       int                iQBits,
125
                                       double             errorScale,
126
                                       bool               bLast,
127
                                       const int          maxLog2TrDynamicRange
128
                                     ) const
129
0
{
130
0
  double dCurrCostSig   = 0;
131
0
  uint32_t   uiBestAbsLevel = 0;
132
133
0
  if( !bLast && uiMaxAbsLevel < 3 )
134
0
  {
135
0
    rd64CodedCostSig    = xGetRateSigCoef( *fracBitsSig, 0 );
136
0
    rd64CodedCost       = rd64CodedCost0 + rd64CodedCostSig;
137
0
    if( uiMaxAbsLevel == 0 )
138
0
    {
139
0
      return uiBestAbsLevel;
140
0
    }
141
0
  }
142
0
  else
143
0
  {
144
0
    rd64CodedCost       = MAX_DOUBLE;
145
0
  }
146
147
0
  if( !bLast )
148
0
  {
149
0
    dCurrCostSig        = xGetRateSigCoef( *fracBitsSig, 1 );
150
0
  }
151
152
0
  uint32_t uiMinAbsLevel    = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 );
153
0
  for( int uiAbsLevel  = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- )
154
0
  {
155
0
    double dErr         = double( lLevelDouble  - ( Intermediate_Int(uiAbsLevel) << iQBits ) );
156
157
0
    double dCurrCost    = dErr * dErr * errorScale + xGetICost( xGetICRate( uiAbsLevel, fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, ui16AbsGoRice, maxLog2TrDynamicRange ) );
158
0
    dCurrCost          += dCurrCostSig;
159
160
0
    if( dCurrCost < rd64CodedCost )
161
0
    {
162
0
      uiBestAbsLevel    = uiAbsLevel;
163
0
      rd64CodedCost     = dCurrCost;
164
0
      rd64CodedCostSig  = dCurrCostSig;
165
0
    }
166
0
  }
167
168
0
  return uiBestAbsLevel;
169
0
}
170
171
/** Calculates the cost for specific absolute transform level
172
 * \param uiAbsLevel scaled quantized level
173
 * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
174
 * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
175
 * \param ui16AbsGoRice Rice parameter for coeff_abs_level_minus3
176
 * \param c1Idx
177
 * \param c2Idx
178
 * \param useLimitedPrefixLength
179
 * \param maxLog2TrDynamicRange
180
 * \returns cost of given absolute transform level
181
 */
182
inline int QuantRDOQ::xGetICRate( const uint32_t         uiAbsLevel,
183
                                  const BinFracBits& fracBitsPar,
184
                                  const BinFracBits& fracBitsGt1,
185
                                  const BinFracBits& fracBitsGt2,
186
                                  const int          remRegBins,
187
                                  unsigned           goRiceZero,
188
                                  const uint16_t       ui16AbsGoRice,
189
                                  const int          maxLog2TrDynamicRange  ) const
190
0
{
191
0
  if( remRegBins < 4 )
192
0
  {
193
0
    int       iRate   = int( xGetIEPRate() ); // cost of sign bit
194
0
    uint32_t  symbol  = ( uiAbsLevel == 0 ? goRiceZero : uiAbsLevel <= goRiceZero ? uiAbsLevel-1 : uiAbsLevel );
195
0
    uint32_t  length;
196
0
    const int threshold = COEF_REMAIN_BIN_REDUCTION;
197
0
    if( symbol < ( threshold << ui16AbsGoRice ) )
198
0
    {
199
0
      length = symbol >> ui16AbsGoRice;
200
0
      iRate += ( length + 1 + ui16AbsGoRice ) << SCALE_BITS;
201
0
    }
202
0
    else
203
0
    {
204
0
      length = ui16AbsGoRice;
205
0
      symbol = symbol - ( threshold << ui16AbsGoRice );
206
0
      while( symbol >= ( 1 << length ) )
207
0
      {
208
0
        symbol -= ( 1 << ( length++ ) );
209
0
      }
210
0
      iRate += ( threshold + length + 1 - ui16AbsGoRice + length ) << SCALE_BITS;
211
0
    }
212
0
    return iRate;
213
0
  }
214
215
0
  int iRate = int( xGetIEPRate() ); // cost of sign bit
216
0
  const uint32_t cthres = 4;
217
0
  if( uiAbsLevel >= cthres )
218
0
  {
219
0
    uint32_t symbol = ( uiAbsLevel - cthres ) >> 1;
220
0
    uint32_t length;
221
0
    const int threshold = COEF_REMAIN_BIN_REDUCTION;
222
0
    if( symbol < ( threshold << ui16AbsGoRice ) )
223
0
    {
224
0
      length = symbol >> ui16AbsGoRice;
225
0
      iRate += ( length + 1 + ui16AbsGoRice ) << SCALE_BITS;
226
0
    }
227
0
    else
228
0
    {
229
0
      length = ui16AbsGoRice;
230
0
      symbol = symbol - ( threshold << ui16AbsGoRice );
231
0
      while( symbol >= ( 1 << length ) )
232
0
      {
233
0
        symbol -= ( 1 << ( length++ ) );
234
0
      }
235
0
      iRate += ( threshold + length + 1 - ui16AbsGoRice + length ) << SCALE_BITS;
236
0
    }
237
238
0
    iRate += fracBitsGt1.intBits[1];
239
0
    iRate += fracBitsPar.intBits[( uiAbsLevel - 2 ) & 1];
240
0
    iRate += fracBitsGt2.intBits[1];
241
0
  }
242
0
  else if( uiAbsLevel == 1 )
243
0
  {
244
0
    iRate += fracBitsGt1.intBits[0];
245
0
  }
246
0
  else if( uiAbsLevel == 2 )
247
0
  {
248
0
    iRate += fracBitsGt1.intBits[1];
249
0
    iRate += fracBitsPar.intBits[0];
250
0
    iRate += fracBitsGt2.intBits[0];
251
0
  }
252
0
  else if( uiAbsLevel == 3 )
253
0
  {
254
0
    iRate += fracBitsGt1.intBits[1];
255
0
    iRate += fracBitsPar.intBits[1];
256
0
    iRate += fracBitsGt2.intBits[0];
257
0
  }
258
0
  else
259
0
  {
260
0
    iRate = 0;
261
0
  }
262
0
  return  iRate;
263
0
}
264
265
inline double QuantRDOQ::xGetRateSigCoeffGroup( const BinFracBits& fracBitsSigCG, unsigned uiSignificanceCoeffGroup ) const
266
1.61M
{
267
1.61M
  return xGetICost( fracBitsSigCG.intBits[uiSignificanceCoeffGroup] );
268
1.61M
}
269
270
/** Calculates the cost of signaling the last significant coefficient in the block
271
 * \param uiPosX X coordinate of the last significant coefficient
272
 * \param uiPosY Y coordinate of the last significant coefficient
273
 * \param component colour component ID
274
 * \returns cost of last significant coefficient
275
 */
276
/*
277
 * \param uiWidth width of the transform unit (TU)
278
*/
279
inline double QuantRDOQ::xGetRateLast( const int* lastBitsX, const int* lastBitsY, unsigned PosX, unsigned PosY ) const
280
0
{
281
0
  uint32_t    CtxX  = g_uiGroupIdx[PosX];
282
0
  uint32_t    CtxY  = g_uiGroupIdx[PosY];
283
0
  double  Cost  = lastBitsX[ CtxX ] + lastBitsY[ CtxY ];
284
0
  if( CtxX > 3 )
285
0
  {
286
0
    Cost += xGetIEPRate() * ((CtxX-2)>>1);
287
0
  }
288
0
  if( CtxY > 3 )
289
0
  {
290
0
    Cost += xGetIEPRate() * ((CtxY-2)>>1);
291
0
  }
292
0
  return xGetICost( Cost );
293
0
}
294
295
296
inline double QuantRDOQ::xGetRateSigCoef( const BinFracBits& fracBitsSig, unsigned uiSignificance ) const
297
11.5M
{
298
11.5M
  return xGetICost( fracBitsSig.intBits[uiSignificance] );
299
11.5M
}
300
301
/** Get the cost for a specific rate
302
 * \param dRate rate of a bit
303
 * \returns cost at the specific rate
304
 */
305
inline double QuantRDOQ::xGetICost        ( double                          dRate         ) const
306
16.0M
{
307
16.0M
  return m_dLambda * dRate;
308
16.0M
}
309
310
/** Get the cost of an equal probable bit
311
 * \returns cost of equal probable bit
312
 */
313
inline double QuantRDOQ::xGetIEPRate() const
314
0
{
315
0
  return 32768;
316
0
}
317
318
319
double QuantRDOQ::xGetErrScaleCoeff(const bool needsSqrt2, SizeType width, SizeType height, int qp, const int maxLog2TrDynamicRange, const int channelBitDepth, bool bTransformSkip=false)
320
113k
{
321
113k
  const int iTransformShift = bTransformSkip ? 0 : getTransformShift(channelBitDepth, Size(width, height), maxLog2TrDynamicRange);
322
113k
  double    dErrScale = (double)(1 << SCALE_BITS);                                // Compensate for scaling of bitcount in Lagrange cost function
323
113k
  double    dTransShift = (double)iTransformShift + (needsSqrt2 ? -0.5 : 0.0);
324
113k
  dErrScale = dErrScale * pow(2.0, (-2.0*dTransShift));                     // Compensate for scaling through forward transform
325
113k
  const int  QStep = g_quantScales[needsSqrt2 ? 1 : 0][qp];
326
113k
  double    finalErrScale = dErrScale / QStep / QStep / (1 << (DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth) << 1));
327
113k
  return    finalErrScale;
328
113k
}
329
330
331
332
/** set error scale coefficients
333
 * \param list                   list ID
334
 * \param size
335
 * \param qp                     quantization parameter
336
 * \param maxLog2TrDynamicRange
337
 * \param bitDepths              reference to bit depth array for all channels
338
 */
339
void QuantRDOQ::xSetErrScaleCoeff( uint32_t list, uint32_t sizeX, uint32_t sizeY, int qp, const int maxLog2TrDynamicRange[MAX_NUM_CH], const BitDepths &bitDepths )
340
10.1M
{
341
10.1M
  const int width = g_scalingListSizeX[sizeX];
342
10.1M
  const int height = g_scalingListSizeX[sizeY];
343
10.1M
  const ChannelType channelType = ( ( list == 0 ) || ( list == MAX_NUM_COMP ) ) ? CH_L : CH_C;
344
10.1M
  const int channelBitDepth = bitDepths[channelType];
345
10.1M
  const int iTransformShift = getTransformShift( channelBitDepth, Size( g_scalingListSizeX[sizeX], g_scalingListSizeX[sizeY] ), maxLog2TrDynamicRange[channelType] );  // Represents scaling through forward transform
346
347
10.1M
  double dErrScale = (double)( 1 << SCALE_BITS );                                // Compensate for scaling of bitcount in Lagrange cost function
348
349
10.1M
  const bool needsSqrt2 = ((Log2(width*height)) & 1) == 1;
350
10.1M
  double dTransShift = (double)iTransformShift + ( needsSqrt2 ? -0.5 : 0.0 );
351
10.1M
  dErrScale = dErrScale*pow( 2.0, ( -2.0*dTransShift ) );                     // Compensate for scaling through forward transform
352
353
10.1M
  if( getScalingListEnabled() )
354
0
  {
355
0
    uint32_t i, uiMaxNumCoeff = width * height;
356
357
0
    int*  piQuantcoeff = getQuantCoeff( list, qp, sizeX, sizeY );
358
0
    double* pdErrScale = xGetErrScaleCoeffSL( list, sizeX, sizeY, qp );
359
360
0
    for( i = 0; i < uiMaxNumCoeff; i++ )
361
0
    {
362
0
      pdErrScale[i] = dErrScale / piQuantcoeff[i] / piQuantcoeff[i] / (1 << (DISTORTION_PRECISION_ADJUSTMENT( bitDepths[channelType] ) << 1));
363
0
    }
364
0
  }
365
366
10.1M
  int QStep = g_quantScales[needsSqrt2][qp];
367
368
10.1M
  xGetErrScaleCoeffNoScalingList(list, sizeX, sizeY, qp) =
369
10.1M
    dErrScale / QStep / QStep / (1 << (DISTORTION_PRECISION_ADJUSTMENT(bitDepths[channelType]) << 1));
370
10.1M
}
371
372
/** set flat matrix value to quantized coefficient
373
 */
374
void QuantRDOQ::setFlatScalingList(const int maxLog2TrDynamicRange[MAX_NUM_CH], const BitDepths &bitDepths)
375
5.72k
{
376
5.72k
  Quant::setFlatScalingList( maxLog2TrDynamicRange, bitDepths );
377
378
5.72k
  const int minimumQp = 0;
379
5.72k
  const int maximumQp = SCALING_LIST_REM_NUM;
380
381
45.8k
  for(uint32_t sizeX = 0; sizeX < SCALING_LIST_SIZE_NUM; sizeX++)
382
40.0k
  {
383
320k
    for(uint32_t sizeY = 0; sizeY < SCALING_LIST_SIZE_NUM; sizeY++)
384
280k
    {
385
1.96M
      for(uint32_t list = 0; list < SCALING_LIST_NUM; list++)
386
1.68M
      {
387
11.7M
        for(int qp = minimumQp; qp < maximumQp; qp++)
388
10.1M
        {
389
10.1M
          xSetErrScaleCoeff( list, sizeX, sizeY, qp, maxLog2TrDynamicRange, bitDepths );
390
10.1M
        }
391
1.68M
      }
392
280k
    }
393
40.0k
  }
394
5.72k
}
395
396
/** initialization process of scaling list array
397
 */
398
void QuantRDOQ::xInitScalingList( const QuantRDOQ* other )
399
5.72k
{
400
5.72k
  m_isErrScaleListOwner = other == nullptr;
401
402
5.72k
  bool useScalingLists = getScalingListEnabled();
403
404
45.8k
  for(uint32_t sizeIdX = 0; sizeIdX < SCALING_LIST_SIZE_NUM; sizeIdX++)
405
40.0k
  {
406
320k
    for(uint32_t sizeIdY = 0; sizeIdY < SCALING_LIST_SIZE_NUM; sizeIdY++)
407
280k
    {
408
1.96M
      for(uint32_t qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
409
1.68M
      {
410
11.7M
        for(uint32_t listId = 0; listId < SCALING_LIST_NUM; listId++)
411
10.1M
        {
412
10.1M
          if( m_isErrScaleListOwner )
413
2.52M
          {
414
2.52M
            m_errScale[sizeIdX][sizeIdY][listId][qp] = useScalingLists ? new double[g_scalingListSizeX[sizeIdX] * g_scalingListSizeX[sizeIdY]] : nullptr;
415
2.52M
          }
416
7.57M
          else
417
7.57M
          {
418
7.57M
            m_errScale[sizeIdX][sizeIdY][listId][qp] = other->m_errScale[sizeIdX][sizeIdY][listId][qp];
419
7.57M
          }
420
10.1M
        } // listID loop
421
1.68M
      }
422
280k
    }
423
40.0k
  }
424
5.72k
}
425
426
/** destroy quantization matrix array
427
 */
428
void QuantRDOQ::xDestroyScalingList()
429
5.72k
{
430
5.72k
  if( !m_isErrScaleListOwner ) return;
431
432
11.4k
  for(uint32_t sizeIdX = 0; sizeIdX < SCALING_LIST_SIZE_NUM; sizeIdX++)
433
10.0k
  {
434
80.1k
    for(uint32_t sizeIdY = 0; sizeIdY < SCALING_LIST_SIZE_NUM; sizeIdY++)
435
70.1k
    {
436
491k
      for(uint32_t listId = 0; listId < SCALING_LIST_NUM; listId++)
437
421k
      {
438
2.94M
        for(uint32_t qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
439
2.52M
        {
440
2.52M
          if(m_errScale[sizeIdX][sizeIdY][listId][qp])
441
0
          {
442
0
            delete [] m_errScale[sizeIdX][sizeIdY][listId][qp];
443
0
          }
444
2.52M
        }
445
421k
      }
446
70.1k
    }
447
10.0k
  }
448
//   Quant::destroyScalingList();
449
1.43k
}
450
451
452
void QuantRDOQ::quant(TransformUnit& tu, const ComponentID compID, const CCoeffBuf& pSrc, TCoeff &uiAbsSum, const QpParam& cQP, const Ctx& ctx)
453
120k
{
454
120k
  const CompArea& rect       = tu.blocks[compID];
455
120k
  const uint32_t uiWidth     = rect.width;
456
120k
  const uint32_t uiHeight    = rect.height;
457
458
120k
  const CCoeffBuf&  piCoef   = pSrc;
459
120k
        CoeffSigBuf piQCoef  = tu.getCoeffs(compID);
460
461
120k
  const bool useTransformSkip      = tu.mtsIdx[compID]==MTS_SKIP;
462
463
120k
  bool useRDOQ = useTransformSkip ? m_useRDOQTS : m_RDOQ > 0;
464
465
120k
  if( !tu.cu->ispMode || !isLuma(compID) )
466
120k
  {
467
120k
    useRDOQ &= uiWidth > 2;
468
120k
    useRDOQ &= uiHeight > 2;
469
120k
  }
470
471
120k
  if( useRDOQ )
472
113k
  {
473
113k
    if (!tu.cs->picture->useSelectiveRdoq || xNeedRDOQ(tu, compID, piCoef, cQP))
474
113k
    {
475
113k
      if( useTransformSkip )
476
113k
      {
477
113k
        if(tu.cu->bdpcmM[toChannelType(compID)])
478
110k
        {
479
110k
          forwardRDPCM( tu, compID, pSrc, uiAbsSum, cQP, ctx );
480
110k
        }
481
3.32k
        else
482
3.32k
        {
483
3.32k
          rateDistOptQuantTS( tu, compID, pSrc, uiAbsSum, cQP, ctx );
484
3.32k
        }
485
113k
      }
486
0
      else
487
0
      {
488
0
        xRateDistOptQuant( tu, compID, pSrc, uiAbsSum, cQP, ctx );
489
0
      }
490
113k
    }
491
0
    else
492
0
    {
493
0
      piQCoef.fill(0);
494
0
      uiAbsSum = 0;
495
0
      tu.lastPos[compID] = -1;
496
0
    }
497
113k
  }
498
6.51k
  else
499
6.51k
  {
500
6.51k
    Quant::quant( tu, compID, pSrc, uiAbsSum, cQP, ctx );
501
6.51k
  }
502
120k
}
503
504
505
506
void QuantRDOQ::xRateDistOptQuant(TransformUnit& tu, const ComponentID compID, const CCoeffBuf& pSrc, TCoeff &uiAbsSum, const QpParam& cQP, const Ctx &ctx)
507
0
{
508
0
  const FracBitsAccess& fracBits = ctx.getFracBitsAcess();
509
510
0
  const SPS &sps            = *tu.cs->sps;
511
0
  const CompArea& rect      = tu.blocks[compID];
512
0
  const uint32_t uiWidth    = rect.width;
513
0
  const uint32_t uiHeight   = rect.height;
514
0
  const ChannelType chType  = toChannelType(compID);
515
0
  const int channelBitDepth = sps.bitDepths[ chType ];
516
517
0
  const int  maxLog2TrDynamicRange = sps.getMaxLog2TrDynamicRange();
518
519
0
  const bool useIntraSubPartitions = tu.cu->ispMode && isLuma(compID);
520
  /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
521
  * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
522
  * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
523
  * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
524
  */
525
526
  // Represents scaling through forward transform
527
0
  const int iTransformShift = getTransformShift(channelBitDepth, rect.size(), maxLog2TrDynamicRange);
528
529
0
  double     d64BlockUncodedCost               = 0;
530
0
  const uint32_t uiLog2BlockWidth                  = Log2(uiWidth);
531
0
  const uint32_t uiLog2BlockHeight                 = Log2(uiHeight);
532
0
  const uint32_t uiMaxNumCoeff                     = rect.area();
533
534
0
  CHECK(compID >= MAX_NUM_TBLOCKS, "Invalid component ID");
535
536
0
  int scalingListType = getScalingListType(tu.cu->predMode, compID);
537
538
0
  CHECK(scalingListType >= SCALING_LIST_NUM, "Invalid scaling list");
539
540
0
  const TCoeff    *plSrcCoeff = pSrc.buf;
541
0
        TCoeffSig *piDstCoeff = tu.getCoeffs(compID).buf;
542
543
0
  double *pdCostCoeff  = m_pdCostCoeff;
544
0
  double *pdCostSig    = m_pdCostSig;
545
0
  double *pdCostCoeff0 = m_pdCostCoeff0;
546
0
  int    *rateIncUp    = m_rateIncUp;
547
0
  int    *rateIncDown  = m_rateIncDown;
548
0
  int    *sigRateDelta = m_sigRateDelta;
549
0
  TCoeff *deltaU       = m_deltaU;
550
551
0
  memset( piDstCoeff,     0, sizeof( TCoeffSig ) * uiMaxNumCoeff );
552
0
  memset( m_pdCostCoeff,  0, sizeof( double ) *  uiMaxNumCoeff );
553
0
  memset( m_pdCostSig,    0, sizeof( double ) *  uiMaxNumCoeff );
554
0
  memset( m_rateIncUp,    0, sizeof( int    ) *  uiMaxNumCoeff );
555
0
  memset( m_rateIncDown,  0, sizeof( int    ) *  uiMaxNumCoeff );
556
0
  memset( m_sigRateDelta, 0, sizeof( int    ) *  uiMaxNumCoeff );
557
0
  memset( m_deltaU,       0, sizeof( TCoeff ) *  uiMaxNumCoeff );
558
559
560
0
  const bool   needSqrtAdjustment = TU::needsSqrt2Scale( tu, compID );
561
0
  const bool   isTransformSkip    = tu.mtsIdx[compID]==MTS_SKIP;
562
0
  const double *const pdErrScale  = xGetErrScaleCoeffSL(scalingListType, uiLog2BlockWidth, uiLog2BlockHeight, cQP.rem(isTransformSkip));
563
0
  const int    *const piQCoef     = getQuantCoeff(scalingListType, cQP.rem(isTransformSkip), uiLog2BlockWidth, uiLog2BlockHeight);
564
0
  const bool isLfnstApplied       = tu.cu->lfnstIdx > 0 && (CU::isSepTree(*tu.cu) ? true : isLuma(compID));
565
0
  const bool enableScalingLists   = getUseScalingList(uiWidth, uiHeight, isTransformSkip, isLfnstApplied);
566
0
  const int    defaultQuantisationCoefficient = g_quantScales[ needSqrtAdjustment ?1:0][cQP.rem(isTransformSkip)];
567
0
  const double defaultErrorScale              = xGetErrScaleCoeffNoScalingList(scalingListType, uiLog2BlockWidth, uiLog2BlockHeight, cQP.rem(isTransformSkip));
568
0
  const int iQBits = QUANT_SHIFT + cQP.per(isTransformSkip) + iTransformShift + (needSqrtAdjustment?-1:0);                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
569
570
571
0
  const TCoeff entropyCodingMinimum = -(1 << maxLog2TrDynamicRange);
572
0
  const TCoeff entropyCodingMaximum =  (1 << maxLog2TrDynamicRange) - 1;
573
574
0
  CoeffCodingContext cctx(tu, compID, tu.cs->slice->signDataHidingEnabled);
575
0
  const int    iCGSizeM1      = (1 << cctx.log2CGSize()) - 1;
576
577
0
  int     iCGLastScanPos      = -1;
578
0
  double  d64BaseCost         = 0;
579
0
  int     iLastScanPos        = -1;
580
581
0
  int ctxBinSampleRatio   = MAX_TU_LEVEL_CTX_CODED_BIN_CONSTRAINT;
582
0
  int remRegBins          = (tu.getTbAreaAfterCoefZeroOut( compID ) * ctxBinSampleRatio) >> 4;
583
0
  uint32_t  goRiceParam   = 0;
584
585
0
  double *pdCostCoeffGroupSig = m_pdCostCoeffGroupSig;
586
0
  memset( pdCostCoeffGroupSig, 0, ( uiMaxNumCoeff >> cctx.log2CGSize() ) * sizeof( double ) );
587
0
  int iScanPos;
588
0
  coeffGroupRDStats rdStats;
589
590
#if ENABLE_TRACING
591
  DTRACE( g_trace_ctx, D_RDOQ, "%d: %3d, %3d, %dx%d, comp=%d\n", DTRACE_GET_COUNTER( g_trace_ctx, D_RDOQ ), rect.x, rect.y, rect.width, rect.height, compID );
592
#endif
593
594
0
  const uint32_t lfnstIdx = tu.cu->lfnstIdx;
595
596
0
  const int iCGNum = lfnstIdx > 0 ? 1 : std::min<int>(JVET_C0024_ZERO_OUT_TH, uiWidth) * std::min<int>(JVET_C0024_ZERO_OUT_TH, uiHeight) >> cctx.log2CGSize();
597
598
0
  for (int subSetId = iCGNum - 1; subSetId >= 0; subSetId--)
599
0
  {
600
0
    cctx.initSubblock( subSetId );
601
602
0
    int remRegBinsStartCG = remRegBins;
603
604
0
    uint32_t maxNonZeroPosInCG = iCGSizeM1;
605
0
    if( lfnstIdx > 0 && ( ( uiWidth == 4 && uiHeight == 4 ) || ( uiWidth == 8 && uiHeight == 8 && cctx.cgPosX() == 0 && cctx.cgPosY() == 0 ) ) )
606
0
    {
607
0
      maxNonZeroPosInCG = 7;
608
0
    }
609
610
0
    memset( &rdStats, 0, sizeof (coeffGroupRDStats));
611
612
0
    for( int iScanPosinCG = iCGSizeM1; iScanPosinCG > maxNonZeroPosInCG; iScanPosinCG-- )
613
0
    {
614
0
      iScanPos = cctx.minSubPos() + iScanPosinCG;
615
0
      uint32_t    blkPos = cctx.blockPos( iScanPos );
616
0
      piDstCoeff[ blkPos ] = 0;
617
0
    }
618
0
    for( int iScanPosinCG = maxNonZeroPosInCG; iScanPosinCG >= 0; iScanPosinCG-- )
619
0
    {
620
0
      iScanPos = cctx.minSubPos() + iScanPosinCG;
621
      //===== quantization =====
622
0
      uint32_t    uiBlkPos          = cctx.blockPos(iScanPos);
623
624
      // set coeff
625
0
      const int    quantisationCoefficient = (enableScalingLists) ? piQCoef   [uiBlkPos]               : defaultQuantisationCoefficient;
626
0
      const double errorScale              = (enableScalingLists) ? pdErrScale[uiBlkPos]               : defaultErrorScale;
627
0
      const int64_t  tmpLevel                = int64_t(abs(plSrcCoeff[ uiBlkPos ])) * quantisationCoefficient;
628
629
0
      const Intermediate_Int lLevelDouble  = (Intermediate_Int)std::min<int64_t>(tmpLevel, std::numeric_limits<Intermediate_Int>::max() - (Intermediate_Int(1) << (iQBits - 1)));
630
631
0
      uint32_t uiMaxAbsLevel        = std::min<uint32_t>(uint32_t(entropyCodingMaximum), uint32_t((lLevelDouble + (Intermediate_Int(1) << (iQBits - 1))) >> iQBits));
632
633
0
      const double dErr         = double( lLevelDouble );
634
0
      pdCostCoeff0[ iScanPos ]  = dErr * dErr * errorScale;
635
0
      d64BlockUncodedCost      += pdCostCoeff0[ iScanPos ];
636
0
      piDstCoeff[ uiBlkPos ]    = uiMaxAbsLevel;
637
638
0
      if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 )
639
0
      {
640
0
        iLastScanPos            = iScanPos;
641
0
        iCGLastScanPos          = cctx.subSetId();
642
0
      }
643
644
0
      if ( iLastScanPos >= 0 )
645
0
      {
646
647
#if ENABLE_TRACING
648
        uint32_t uiCGPosY = cctx.cgPosY();
649
        uint32_t uiCGPosX = cctx.cgPosX();
650
        uint32_t uiPosY = cctx.posY( iScanPos );
651
        uint32_t uiPosX = cctx.posX( iScanPos );
652
        DTRACE( g_trace_ctx, D_RDOQ, "%d [%d][%d][%2d:%2d][%2d:%2d]", DTRACE_GET_COUNTER( g_trace_ctx, D_RDOQ ), iScanPos, uiBlkPos, uiCGPosX, uiCGPosY, uiPosX, uiPosY );
653
#endif
654
        //===== coefficient level estimation =====
655
0
        unsigned ctxIdSig = 0;
656
0
        if( iScanPos != iLastScanPos )
657
0
        {
658
0
          ctxIdSig = cctx.sigCtxIdAbs( iScanPos, piDstCoeff, 0 );
659
0
        }
660
0
        uint32_t    uiLevel;
661
0
        uint8_t ctxOffset     = cctx.ctxOffsetAbs     ();
662
0
        uint32_t    uiParCtx      = cctx.parityCtxIdAbs   ( ctxOffset );
663
0
        uint32_t    uiGt1Ctx      = cctx.greater1CtxIdAbs ( ctxOffset );
664
0
        uint32_t    uiGt2Ctx      = cctx.greater2CtxIdAbs ( ctxOffset );
665
0
        uint32_t    goRiceZero    = 0;
666
0
        if( remRegBins < 4 )
667
0
        {
668
0
          unsigned  sumAbs = cctx.templateAbsSum( iScanPos, piDstCoeff, 0 );
669
0
          goRiceParam             = g_auiGoRiceParsCoeff   [ sumAbs ];
670
0
          goRiceZero              = g_auiGoRicePosCoeff0(0, goRiceParam);
671
0
        }
672
673
0
        const BinFracBits fracBitsPar = fracBits.getFracBitsArray( uiParCtx );
674
0
        const BinFracBits fracBitsGt1 = fracBits.getFracBitsArray( uiGt1Ctx );
675
0
        const BinFracBits fracBitsGt2 = fracBits.getFracBitsArray( uiGt2Ctx );
676
677
0
        if( iScanPos == iLastScanPos )
678
0
        {
679
0
          uiLevel = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
680
0
                                    lLevelDouble, uiMaxAbsLevel, nullptr, fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, iQBits, errorScale, 1, maxLog2TrDynamicRange );
681
0
        }
682
0
        else
683
0
        {
684
0
          DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ_MORE, " uiCtxSig=%d", ctxIdSig );
685
686
0
          const BinFracBits fracBitsSig = fracBits.getFracBitsArray( ctxIdSig );
687
0
          uiLevel = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
688
0
                                    lLevelDouble, uiMaxAbsLevel, &fracBitsSig, fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, iQBits, errorScale, 0, maxLog2TrDynamicRange );
689
0
          sigRateDelta[ uiBlkPos ] = ( remRegBins < 4 ? 0 : fracBitsSig.intBits[1] - fracBitsSig.intBits[0] );
690
0
        }
691
692
0
        DTRACE( g_trace_ctx, D_RDOQ, " Lev=%d \n", uiLevel );
693
0
        DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ, " CostC0=%d\n", (int64_t)( pdCostCoeff0[iScanPos] ) );
694
0
        DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ, " CostC =%d\n", (int64_t)( pdCostCoeff[iScanPos] ) );
695
696
0
        deltaU[ uiBlkPos ]        = TCoeff((lLevelDouble - (Intermediate_Int(uiLevel) << iQBits)) >> (iQBits-8));
697
698
0
        if( uiLevel > 0 )
699
0
        {
700
0
          int rateNow              = xGetICRate( uiLevel,   fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, maxLog2TrDynamicRange );
701
0
          rateIncUp   [ uiBlkPos ] = xGetICRate( uiLevel+1, fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, maxLog2TrDynamicRange ) - rateNow;
702
0
          rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, maxLog2TrDynamicRange ) - rateNow;
703
0
        }
704
0
        else // uiLevel == 0
705
0
        {
706
0
          if( remRegBins < 4 )
707
0
          {
708
0
            int rateNow            = xGetICRate( uiLevel,   fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, maxLog2TrDynamicRange );
709
0
            rateIncUp [ uiBlkPos ] = xGetICRate( uiLevel+1, fracBitsPar, fracBitsGt1, fracBitsGt2, remRegBins, goRiceZero, goRiceParam, maxLog2TrDynamicRange ) - rateNow;
710
0
          }
711
0
          else
712
0
          {
713
0
            rateIncUp [ uiBlkPos ] = fracBitsGt1.intBits[ 0 ];
714
0
          }
715
0
        }
716
0
        piDstCoeff[ uiBlkPos ] = uiLevel;
717
0
        d64BaseCost           += pdCostCoeff [ iScanPos ];
718
719
0
        if( ( (iScanPos & iCGSizeM1) == 0 ) && ( iScanPos > 0 ) )
720
0
        {
721
0
          goRiceParam   = 0;
722
0
        }
723
0
        else if( remRegBins >= 4 )
724
0
        {
725
0
          int  sumAll = cctx.templateAbsSum(iScanPos, piDstCoeff, 4);
726
0
          goRiceParam = g_auiGoRiceParsCoeff[sumAll];
727
0
          remRegBins -= (uiLevel < 2 ? uiLevel : 3) + (iScanPos != iLastScanPos);
728
0
        }
729
0
      }
730
0
      else
731
0
      {
732
0
        d64BaseCost    += pdCostCoeff0[ iScanPos ];
733
0
      }
734
0
      rdStats.d64SigCost += pdCostSig[ iScanPos ];
735
0
      if (iScanPosinCG == 0 )
736
0
      {
737
0
        rdStats.d64SigCost_0 = pdCostSig[ iScanPos ];
738
0
      }
739
0
      if (piDstCoeff[ uiBlkPos ] )
740
0
      {
741
0
        cctx.setSigGroup();
742
0
        rdStats.d64CodedLevelandDist += pdCostCoeff[ iScanPos ] - pdCostSig[ iScanPos ];
743
0
        rdStats.d64UncodedDist += pdCostCoeff0[ iScanPos ];
744
0
        if ( iScanPosinCG != 0 )
745
0
        {
746
0
          rdStats.iNNZbeforePos0++;
747
0
        }
748
0
      }
749
0
    } //end for (iScanPosinCG)
750
751
0
    if (iCGLastScanPos >= 0)
752
0
    {
753
0
      if( cctx.subSetId() )
754
0
      {
755
0
        if( !cctx.isSigGroup() )
756
0
        {
757
0
          const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray( cctx.sigGroupCtxId() );
758
0
          d64BaseCost += xGetRateSigCoeffGroup(fracBitsSigGroup, 0) - rdStats.d64SigCost;
759
0
          pdCostCoeffGroupSig[ cctx.subSetId() ] = xGetRateSigCoeffGroup(fracBitsSigGroup, 0);
760
0
        }
761
0
        else
762
0
        {
763
0
          if (cctx.subSetId() < iCGLastScanPos) //skip the last coefficient group, which will be handled together with last position below.
764
0
          {
765
0
            if ( rdStats.iNNZbeforePos0 == 0 )
766
0
            {
767
0
              d64BaseCost -= rdStats.d64SigCost_0;
768
0
              rdStats.d64SigCost -= rdStats.d64SigCost_0;
769
0
            }
770
            // rd-cost if SigCoeffGroupFlag = 0, initialization
771
0
            double d64CostZeroCG = d64BaseCost;
772
773
0
            const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray( cctx.sigGroupCtxId() );
774
775
0
            if (cctx.subSetId() < iCGLastScanPos)
776
0
            {
777
0
              d64BaseCost  += xGetRateSigCoeffGroup(fracBitsSigGroup,1);
778
0
              d64CostZeroCG += xGetRateSigCoeffGroup(fracBitsSigGroup,0);
779
0
              pdCostCoeffGroupSig[ cctx.subSetId() ] = xGetRateSigCoeffGroup(fracBitsSigGroup,1);
780
0
            }
781
782
            // try to convert the current coeff group from non-zero to all-zero
783
0
            d64CostZeroCG += rdStats.d64UncodedDist;  // distortion for resetting non-zero levels to zero levels
784
0
            d64CostZeroCG -= rdStats.d64CodedLevelandDist;   // distortion and level cost for keeping all non-zero levels
785
0
            d64CostZeroCG -= rdStats.d64SigCost;     // sig cost for all coeffs, including zero levels and non-zerl levels
786
787
                                                     // if we can save cost, change this block to all-zero block
788
0
            if ( d64CostZeroCG < d64BaseCost )
789
0
            {
790
0
              cctx.resetSigGroup();
791
0
              d64BaseCost = d64CostZeroCG;
792
0
              remRegBins = remRegBinsStartCG;
793
0
              if (cctx.subSetId() < iCGLastScanPos)
794
0
              {
795
0
                pdCostCoeffGroupSig[ cctx.subSetId() ] = xGetRateSigCoeffGroup(fracBitsSigGroup,0);
796
0
              }
797
              // reset coeffs to 0 in this block
798
0
              for( int iScanPosinCG = maxNonZeroPosInCG; iScanPosinCG >= 0; iScanPosinCG-- )
799
0
              {
800
0
                iScanPos      = cctx.minSubPos() + iScanPosinCG;
801
0
                uint32_t uiBlkPos = cctx.blockPos( iScanPos );
802
803
0
                if (piDstCoeff[ uiBlkPos ])
804
0
                {
805
0
                  piDstCoeff [ uiBlkPos ] = 0;
806
0
                  pdCostCoeff[ iScanPos ] = pdCostCoeff0[ iScanPos ];
807
0
                  pdCostSig  [ iScanPos ] = 0;
808
0
                }
809
0
              }
810
0
            } // end if ( d64CostAllZeros < d64BaseCost )
811
0
          }
812
0
        } // end if if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
813
0
      }
814
0
      else
815
0
      {
816
0
        cctx.setSigGroup();
817
0
      }
818
0
    }
819
0
  } //end for (cctx.subSetId)
820
821
822
  //===== estimate last position =====
823
0
  if ( iLastScanPos < 0 )
824
0
  {
825
0
    return;
826
0
  }
827
828
0
  double  d64BestCost         = 0;
829
0
  int     iBestLastIdxP1      = 0;
830
831
832
0
  if( !CU::isIntra( *tu.cu ) && isLuma( compID ) && tu.depth == 0 )
833
0
  {
834
0
    const BinFracBits fracBitsQtRootCbf = fracBits.getFracBitsArray( Ctx::QtRootCbf() );
835
0
    d64BestCost  = d64BlockUncodedCost + xGetICost( fracBitsQtRootCbf.intBits[ 0 ] );
836
0
    d64BaseCost += xGetICost( fracBitsQtRootCbf.intBits[ 1 ] );
837
0
  }
838
0
  else
839
0
  {
840
0
    bool previousCbf       = tu.cbf[COMP_Cb];
841
0
    bool lastCbfIsInferred = false;
842
0
    if( useIntraSubPartitions )
843
0
    {
844
0
      bool rootCbfSoFar       = false;
845
0
      bool isLastSubPartition = CU::isISPLast(*tu.cu, tu.Y(), compID);
846
0
      uint32_t nTus = tu.cu->ispMode == HOR_INTRA_SUBPARTITIONS ? tu.cu->lheight() >> Log2(tu.lheight()) : tu.cu->lwidth() >> Log2(tu.lwidth());
847
0
      if( isLastSubPartition )
848
0
      {
849
0
        TransformUnit* tuPointer = tu.cu->firstTU;
850
0
        for( int tuIdx = 0; tuIdx < nTus - 1; tuIdx++ )
851
0
        {
852
0
          rootCbfSoFar |= TU::getCbfAtDepth(*tuPointer, COMP_Y, tu.depth);
853
0
          tuPointer     = tuPointer->next;
854
0
        }
855
0
        if( !rootCbfSoFar )
856
0
        {
857
0
          lastCbfIsInferred = true;
858
0
        }
859
0
      }
860
0
      if( !lastCbfIsInferred )
861
0
      {
862
0
        previousCbf = TU::getPrevTuCbfAtDepth(tu, compID, tu.depth);
863
0
      }
864
0
    }
865
0
    BinFracBits fracBitsQtCbf = fracBits.getFracBitsArray( Ctx::QtCbf[compID]( DeriveCtx::CtxQtCbf( rect.compID, previousCbf, useIntraSubPartitions ) ) );
866
867
0
    if( !lastCbfIsInferred )
868
0
    {
869
0
      d64BestCost  = d64BlockUncodedCost + xGetICost(fracBitsQtCbf.intBits[0]);
870
0
      d64BaseCost += xGetICost(fracBitsQtCbf.intBits[1]);
871
0
    }
872
0
    else
873
0
    {
874
0
      d64BestCost  = d64BlockUncodedCost;
875
0
    }
876
0
  }
877
878
0
  int lastBitsX[LAST_SIGNIFICANT_GROUPS] = { 0 };
879
0
  int lastBitsY[LAST_SIGNIFICANT_GROUPS] = { 0 };
880
0
  {
881
0
    int dim1 = std::min<int>(JVET_C0024_ZERO_OUT_TH, uiWidth);
882
0
    int dim2 = std::min<int>(JVET_C0024_ZERO_OUT_TH, uiHeight);
883
0
    int bitsX = 0;
884
0
    int bitsY = 0;
885
0
    int ctxId;
886
    //X-coordinate
887
0
    for ( ctxId = 0; ctxId < g_uiGroupIdx[dim1-1]; ctxId++)
888
0
    {
889
0
      const BinFracBits fB = fracBits.getFracBitsArray( cctx.lastXCtxId(ctxId) );
890
0
      lastBitsX[ ctxId ]   = bitsX + fB.intBits[ 0 ];
891
0
      bitsX               +=         fB.intBits[ 1 ];
892
0
    }
893
0
    lastBitsX[ctxId] = bitsX;
894
    //Y-coordinate
895
0
    for ( ctxId = 0; ctxId < g_uiGroupIdx[dim2-1]; ctxId++)
896
0
    {
897
0
      const BinFracBits fB = fracBits.getFracBitsArray( cctx.lastYCtxId(ctxId) );
898
0
      lastBitsY[ ctxId ]   = bitsY + fB.intBits[ 0 ];
899
0
      bitsY               +=         fB.intBits[ 1 ];
900
0
    }
901
0
    lastBitsY[ctxId] = bitsY;
902
0
  }
903
904
905
0
  bool bFoundLast = false;
906
0
  for (int iCGScanPos = iCGLastScanPos; iCGScanPos >= 0; iCGScanPos--)
907
0
  {
908
0
    d64BaseCost -= pdCostCoeffGroupSig [ iCGScanPos ];
909
0
    if (cctx.isSigGroup( iCGScanPos ) )
910
0
    {
911
0
      uint32_t maxNonZeroPosInCG = iCGSizeM1;
912
0
      if( lfnstIdx > 0 && ( ( uiWidth == 4 && uiHeight == 4 ) || ( uiWidth == 8 && uiHeight == 8 && cctx.cgPosX() == 0 && cctx.cgPosY() == 0 ) ) )
913
0
      {
914
0
        maxNonZeroPosInCG = 7;
915
0
      }
916
0
      for( int iScanPosinCG = maxNonZeroPosInCG; iScanPosinCG >= 0; iScanPosinCG-- )
917
0
      {
918
0
        iScanPos = iCGScanPos * (iCGSizeM1 + 1) + iScanPosinCG;
919
920
0
        if (iScanPos > iLastScanPos)
921
0
        {
922
0
          continue;
923
0
        }
924
0
        uint32_t   uiBlkPos     = cctx.blockPos( iScanPos );
925
926
0
        if( piDstCoeff[ uiBlkPos ] )
927
0
        {
928
0
          uint32_t   uiPosY = uiBlkPos >> uiLog2BlockWidth;
929
0
          uint32_t   uiPosX = uiBlkPos - ( uiPosY << uiLog2BlockWidth );
930
0
          double d64CostLast  = xGetRateLast( lastBitsX, lastBitsY, uiPosX, uiPosY );
931
932
0
          double totalCost = d64BaseCost + d64CostLast - pdCostSig[ iScanPos ];
933
934
0
          if( totalCost < d64BestCost )
935
0
          {
936
0
            iBestLastIdxP1  = iScanPos + 1;
937
0
            d64BestCost     = totalCost;
938
0
          }
939
0
          if( piDstCoeff[ uiBlkPos ] > 1 )
940
0
          {
941
0
            bFoundLast = true;
942
0
            break;
943
0
          }
944
0
          d64BaseCost      -= pdCostCoeff[ iScanPos ];
945
0
          d64BaseCost      += pdCostCoeff0[ iScanPos ];
946
0
        }
947
0
        else
948
0
        {
949
0
          d64BaseCost      -= pdCostSig[ iScanPos ];
950
0
        }
951
0
      } //end for
952
0
      if (bFoundLast)
953
0
      {
954
0
        break;
955
0
      }
956
0
    } // end if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
957
0
    DTRACE( g_trace_ctx, D_RDOQ_COST, "%d: %3d, %3d, %dx%d, comp=%d\n", DTRACE_GET_COUNTER( g_trace_ctx, D_RDOQ_COST ), rect.x, rect.y, rect.width, rect.height, compID );
958
0
    DTRACE( g_trace_ctx, D_RDOQ_COST, "Uncoded=%d\n", (int64_t)( d64BlockUncodedCost ) );
959
0
    DTRACE( g_trace_ctx, D_RDOQ_COST, "Coded  =%d\n", (int64_t)( d64BaseCost ) );
960
961
0
  } // end for
962
963
964
0
  for ( int scanPos = 0; scanPos < iBestLastIdxP1; scanPos++ )
965
0
  {
966
0
    int blkPos = cctx.blockPos( scanPos );
967
0
    TCoeff level = piDstCoeff[ blkPos ];
968
0
    uiAbsSum += level;
969
0
    piDstCoeff[ blkPos ] = ( plSrcCoeff[ blkPos ] < 0 ) ? -level : level;
970
0
  }
971
972
  //===== clean uncoded coefficients =====
973
0
  for ( int scanPos = iBestLastIdxP1; scanPos <= iLastScanPos; scanPos++ )
974
0
  {
975
0
    piDstCoeff[ cctx.blockPos( scanPos ) ] = 0;
976
0
  }
977
0
  iLastScanPos = iBestLastIdxP1 - 1;
978
979
0
  if( cctx.signHiding() && uiAbsSum>=2)
980
0
  {
981
0
    const double inverseQuantScale = double(g_invQuantScales[0][cQP.rem(isTransformSkip)]);
982
0
    int64_t rdFactor = (int64_t)(inverseQuantScale * inverseQuantScale * (1 << (2 * cQP.per(isTransformSkip))) / m_dLambda / 16
983
0
                                  / (1 << (2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth)))
984
0
                             + 0.5);
985
986
0
    int lastCG = -1;
987
0
    int absSum = 0 ;
988
0
    int n ;
989
0
    for (int subSet = iCGNum - 1; subSet >= 0; subSet--)
990
0
    {
991
0
      int  subPos         = subSet << cctx.log2CGSize();
992
0
      int  firstNZPosInCG = iCGSizeM1 + 1, lastNZPosInCG = -1;
993
0
      absSum = 0 ;
994
995
0
      for( n = iCGSizeM1; n >= 0; --n )
996
0
      {
997
0
        if( piDstCoeff[ cctx.blockPos( n + subPos )] )
998
0
        {
999
0
          lastNZPosInCG = n;
1000
0
          break;
1001
0
        }
1002
0
      }
1003
1004
0
      for( n = 0; n <= iCGSizeM1; n++ )
1005
0
      {
1006
0
        if( piDstCoeff[ cctx.blockPos( n + subPos )] )
1007
0
        {
1008
0
          firstNZPosInCG = n;
1009
0
          break;
1010
0
        }
1011
0
      }
1012
1013
0
      for( n = firstNZPosInCG; n <= lastNZPosInCG; n++ )
1014
0
      {
1015
0
        absSum += int(piDstCoeff[ cctx.blockPos( n + subPos )]);
1016
0
      }
1017
1018
0
      if(lastNZPosInCG>=0 && lastCG==-1)
1019
0
      {
1020
0
        lastCG = 1;
1021
0
      }
1022
1023
0
      if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
1024
0
      {
1025
0
        uint32_t signbit = (piDstCoeff[cctx.blockPos(subPos+firstNZPosInCG)]>0?0:1);
1026
0
        if( signbit!=(absSum&0x1) )  // hide but need tune
1027
0
        {
1028
          // calculate the cost
1029
0
          int64_t minCostInc = std::numeric_limits<int64_t>::max(), curCost = std::numeric_limits<int64_t>::max();
1030
0
          int minPos = -1, finalChange = 0, curChange = 0;
1031
1032
0
          for( n = (lastCG == 1 ? lastNZPosInCG : iCGSizeM1); n >= 0; --n )
1033
0
          {
1034
0
            uint32_t uiBlkPos   = cctx.blockPos( n + subPos );
1035
0
            if(piDstCoeff[ uiBlkPos ] != 0 )
1036
0
            {
1037
0
              int64_t costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos];
1038
0
              int64_t costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos]
1039
0
                -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
1040
1041
0
              if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
1042
0
              {
1043
0
                costDown -= (4<<SCALE_BITS);
1044
0
              }
1045
1046
0
              if(costUp<costDown)
1047
0
              {
1048
0
                curCost = costUp;
1049
0
                curChange =  1;
1050
0
              }
1051
0
              else
1052
0
              {
1053
0
                curChange = -1;
1054
0
                if(n==firstNZPosInCG && abs(piDstCoeff[uiBlkPos])==1)
1055
0
                {
1056
0
                  curCost = std::numeric_limits<int64_t>::max();
1057
0
                }
1058
0
                else
1059
0
                {
1060
0
                  curCost = costDown;
1061
0
                }
1062
0
              }
1063
0
            }
1064
0
            else
1065
0
            {
1066
0
              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<SCALE_BITS) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ;
1067
0
              curChange = 1 ;
1068
1069
0
              if(n<firstNZPosInCG)
1070
0
              {
1071
0
                uint32_t thissignbit = (plSrcCoeff[uiBlkPos]>=0?0:1);
1072
0
                if(thissignbit != signbit )
1073
0
                {
1074
0
                  curCost = std::numeric_limits<int64_t>::max();
1075
0
                }
1076
0
              }
1077
0
            }
1078
1079
0
            if( curCost<minCostInc)
1080
0
            {
1081
0
              minCostInc = curCost;
1082
0
              finalChange = curChange;
1083
0
              minPos = uiBlkPos;
1084
0
            }
1085
0
          }
1086
1087
0
          if(piDstCoeff[minPos] == entropyCodingMaximum || piDstCoeff[minPos] == entropyCodingMinimum)
1088
0
          {
1089
0
            finalChange = -1;
1090
0
          }
1091
1092
0
          if(plSrcCoeff[minPos]>=0)
1093
0
          {
1094
0
            piDstCoeff[minPos] += finalChange ;
1095
0
          }
1096
0
          else
1097
0
          {
1098
0
            piDstCoeff[minPos] -= finalChange ;
1099
0
          }
1100
0
        }
1101
0
      }
1102
1103
0
      if(lastCG==1)
1104
0
      {
1105
0
        lastCG=0 ;
1106
0
      }
1107
0
    }
1108
1109
    // Check due to saving of last pos. Sign data hiding can change the position of last coef.
1110
0
    if( piDstCoeff[cctx.blockPos( iLastScanPos )] == 0 )
1111
0
    {
1112
0
      int scanPos = iLastScanPos - 1;
1113
0
      for( ; scanPos >= 0; scanPos-- )
1114
0
      {
1115
0
        if( piDstCoeff[cctx.blockPos( scanPos )] )
1116
0
          break;
1117
0
      }
1118
0
      iLastScanPos = scanPos;
1119
0
    }
1120
0
  }
1121
0
  tu.lastPos[compID] = iLastScanPos;
1122
0
}
1123
1124
void QuantRDOQ::rateDistOptQuantTS( TransformUnit& tu, const ComponentID compID, const CCoeffBuf& coeffs, TCoeff &absSum, const QpParam& qp, const Ctx &ctx )
1125
3.32k
{
1126
3.32k
  const FracBitsAccess& fracBits = ctx.getFracBitsAcess();
1127
1128
3.32k
  const SPS &sps            = *tu.cs->sps;
1129
3.32k
  const CompArea& rect      = tu.blocks[compID];
1130
3.32k
  const uint32_t width      = rect.width;
1131
3.32k
  const uint32_t height     = rect.height;
1132
3.32k
  const ChannelType chType  = toChannelType(compID);
1133
3.32k
  const int channelBitDepth = sps.bitDepths[ chType ];
1134
1135
3.32k
  const int  maxLog2TrDynamicRange = sps.getMaxLog2TrDynamicRange();
1136
1137
3.32k
  const int transformShift = getTransformShift( channelBitDepth, rect.size(), maxLog2TrDynamicRange );
1138
1139
3.32k
  const uint32_t maxNumCoeff                        = rect.area();
1140
1141
3.32k
  CHECK( compID >= MAX_NUM_TBLOCKS, "Invalid component ID" );
1142
1143
3.32k
  int scalingListType = getScalingListType( tu.cu->predMode, compID );
1144
3.32k
  CHECK( scalingListType >= SCALING_LIST_NUM, "Invalid scaling list" );
1145
1146
3.32k
  const TCoeff    *srcCoeff = coeffs.buf;
1147
3.32k
        TCoeffSig *dstCoeff = tu.getCoeffs( compID ).buf;
1148
1149
  // costCoeff and costSig need no clearing: the sub-block loop writes them at every scan position before reading them
1150
  // (costSig is set on every path of xGetCodedLevelTSPred: its first level candidate always has a finite cost)
1151
3.32k
  double *costCoeff  = m_pdCostCoeff;
1152
3.32k
  double *costSig    = m_pdCostSig;
1153
3.32k
  double *costCoeff0 = m_pdCostCoeff0;
1154
1155
3.32k
  m_bdpcm = 0;
1156
1157
3.32k
  const bool   needsSqrt2Scale = TU::needsSqrt2Scale( tu, compID );  // should always be false - transform-skipped blocks don't require sqrt(2) compensation.
1158
3.32k
  const bool   isTransformSkip = tu.mtsIdx[compID]==MTS_SKIP;
1159
3.32k
  const int    qBits = QUANT_SHIFT + qp.per(isTransformSkip) + (isTransformSkip ? 0 : transformShift) + (needsSqrt2Scale ? -1 : 0);  // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
1160
3.32k
  const int    quantisationCoefficient = g_quantScales[needsSqrt2Scale?1:0][qp.rem(isTransformSkip)];
1161
3.32k
  const double errorScale              = xGetErrScaleCoeff( TU::needsSqrt2Scale(tu, compID), width, height, qp.rem(isTransformSkip), maxLog2TrDynamicRange, channelBitDepth, isTransformSkip);
1162
1163
3.32k
  const TCoeff entropyCodingMaximum = ( 1 << maxLog2TrDynamicRange ) - 1;
1164
1165
3.32k
  uint32_t coeffLevels[3];
1166
3.32k
  double   coeffLevelError[4];
1167
1168
3.32k
  CoeffCodingContext cctx( tu, compID, tu.cs->slice->signDataHidingEnabled );
1169
3.32k
  const int sbSizeM1    = ( 1 << cctx.log2CGSize() ) - 1;
1170
3.32k
  double    baseCost    = 0;
1171
3.32k
  uint32_t  goRiceParam = 0;
1172
1173
3.32k
  double *costSigSubBlock = m_pdCostCoeffGroupSig;
1174
3.32k
  memset( costSigSubBlock, 0, ( maxNumCoeff >> cctx.log2CGSize() ) * sizeof( double ) );
1175
1176
3.32k
  const int sbNum = width * height >> cctx.log2CGSize();
1177
3.32k
  int scanPos;
1178
3.32k
  coeffGroupRDStats rdStats;
1179
1180
3.32k
  bool anySigCG = false;
1181
1182
3.32k
  int maxCtxBins = (cctx.maxNumCoeff() * 7) >> 2;
1183
3.32k
  cctx.remRegBins = maxCtxBins;
1184
1185
37.2k
  for( int sbId = 0; sbId < sbNum; sbId++ )
1186
33.8k
  {
1187
33.8k
    cctx.initSubblock( sbId );
1188
1189
33.8k
    int noCoeffCoded = 0;
1190
33.8k
    baseCost = 0.0;
1191
33.8k
    memset( &rdStats, 0, sizeof (coeffGroupRDStats));
1192
1193
33.8k
    rdStats.iNumSbbCtxBins = 0;
1194
1195
576k
    for( int scanPosInSB = 0; scanPosInSB <= sbSizeM1; scanPosInSB++ )
1196
542k
    {
1197
542k
      int lastPosCoded = sbSizeM1;
1198
542k
      scanPos = cctx.minSubPos() + scanPosInSB;
1199
      //===== quantization =====
1200
542k
      uint32_t blkPos = cctx.blockPos( scanPos );
1201
1202
      // set coeff
1203
542k
      const int64_t          tmpLevel    = int64_t( abs( srcCoeff[blkPos] ) ) * quantisationCoefficient;
1204
542k
      const Intermediate_Int levelDouble = (Intermediate_Int)std::min<int64_t>( tmpLevel, std::numeric_limits<Intermediate_Int>::max() - ( Intermediate_Int( 1 ) << ( qBits - 1 ) ) );
1205
1206
542k
      uint32_t roundAbsLevel = std::min<uint32_t>(uint32_t(entropyCodingMaximum), uint32_t((levelDouble + (Intermediate_Int(1) << (qBits - 1))) >> qBits));
1207
1208
542k
      double dErr = double(levelDouble);
1209
542k
      coeffLevelError[0] = dErr * dErr * errorScale;
1210
1211
542k
      costCoeff0[scanPos] = coeffLevelError[0];
1212
542k
      dstCoeff[blkPos]    = roundAbsLevel;
1213
1214
      //===== coefficient level estimation =====
1215
542k
            unsigned    ctxIdSig = cctx.sigCtxIdAbsTS( scanPos, dstCoeff );
1216
542k
            uint32_t    cLevel;
1217
542k
      const BinFracBits fracBitsSig = fracBits.getFracBitsArray( ctxIdSig );
1218
1219
542k
      DTRACE_COND( ( roundAbsLevel != 0 ), g_trace_ctx, D_RDOQ_MORE, " uiCtxSig=%d", ctxIdSig );
1220
1221
      // the sub-block's last position is coded significant when no other coefficient of the sub-block is
1222
542k
      const bool lastCoeff = scanPosInSB == lastPosCoded && noCoeffCoded == 0;
1223
542k
      int numUsedCtxBins = 0;
1224
1225
542k
      if( roundAbsLevel == 0 && !lastCoeff )
1226
508k
      {
1227
        // Exact shortcut of xGetCodedLevelTSPred for a coefficient that rounds to zero (most coefficients, even at high rates):
1228
        // it codes the zero level with only the significance flag, so the level candidates and the parity, greater-1
1229
        // and sign contexts it would not read are skipped.
1230
508k
        const bool ctxCoded = cctx.remRegBins >= 4;
1231
508k
        costSig  [scanPos]  = ctxCoded ? xGetRateSigCoef( fracBitsSig, 0 ) : xGetICost( 1 << SCALE_BITS );
1232
508k
        costCoeff[scanPos]  = costCoeff0[scanPos] + costSig[scanPos];
1233
508k
        numUsedCtxBins      = ctxCoded ? 1 : 0;
1234
508k
        cLevel              = 0;
1235
508k
      }
1236
33.8k
      else
1237
33.8k
      {
1238
33.8k
        uint32_t minAbsLevel = (roundAbsLevel > 1 ? roundAbsLevel - 1 : 1);
1239
1240
33.8k
        uint32_t downAbsLevel = std::min<uint32_t>(uint32_t(entropyCodingMaximum), uint32_t(levelDouble >> qBits));
1241
33.8k
        uint32_t upAbsLevel = std::min<uint32_t>(uint32_t(entropyCodingMaximum), downAbsLevel + 1);
1242
1243
33.8k
        m_testedLevels = 0;
1244
33.8k
        coeffLevels[m_testedLevels++] = roundAbsLevel;
1245
1246
33.8k
        if (minAbsLevel != roundAbsLevel)
1247
33.8k
          coeffLevels[m_testedLevels++] = minAbsLevel;
1248
1249
33.8k
        int rightPixel, belowPixel, predPixel;
1250
1251
33.8k
        cctx.neighTS(rightPixel, belowPixel, scanPos, dstCoeff);
1252
33.8k
        predPixel = cctx.deriveModCoeff(rightPixel, belowPixel, upAbsLevel, 0);
1253
1254
33.8k
        if (upAbsLevel != roundAbsLevel && upAbsLevel != minAbsLevel && predPixel == 1)
1255
0
          coeffLevels[m_testedLevels++] = upAbsLevel;
1256
1257
33.8k
        const BinFracBits fracBitsPar = fracBits.getFracBitsArray( cctx.parityCtxIdAbsTS() );
1258
1259
        //goRiceParam = cctx.templateAbsSumTS( scanPos, dstCoeff );
1260
33.8k
        goRiceParam = 1;
1261
33.8k
        unsigned ctxIdSign = cctx.signCtxIdAbsTS(scanPos, dstCoeff, 0);
1262
33.8k
        const BinFracBits fracBitsSign = fracBits.getFracBitsArray(ctxIdSign);
1263
33.8k
        const uint8_t     sign         = srcCoeff[ blkPos ] < 0 ? 1 : 0;
1264
1265
33.8k
        unsigned gt1CtxId = cctx.lrg1CtxIdAbsTS(scanPos, dstCoeff, 0);
1266
33.8k
        const BinFracBits fracBitsGr1 = fracBits.getFracBitsArray(gt1CtxId);
1267
1268
33.8k
        cLevel = xGetCodedLevelTSPred(costCoeff[scanPos], costCoeff0[scanPos], costSig[scanPos], levelDouble, qBits, errorScale, coeffLevels, coeffLevelError,
1269
33.8k
                                      &fracBitsSig, fracBitsPar, cctx, fracBits, fracBitsSign, fracBitsGr1, sign, rightPixel, belowPixel, goRiceParam, lastCoeff, maxLog2TrDynamicRange, numUsedCtxBins);
1270
33.8k
      }
1271
1272
542k
      cctx.remRegBins -= numUsedCtxBins;
1273
542k
      rdStats.iNumSbbCtxBins += numUsedCtxBins;
1274
1275
542k
      if (cLevel > 0)
1276
0
      {
1277
0
        noCoeffCoded++;
1278
0
      }
1279
1280
542k
      TCoeff level = cLevel;
1281
542k
      dstCoeff[blkPos] = (level != 0 && srcCoeff[blkPos] < 0) ? -level : level;
1282
542k
      baseCost           += costCoeff[ scanPos ];
1283
542k
      rdStats.d64SigCost += costSig[ scanPos ];
1284
1285
542k
      if( dstCoeff[ blkPos ] )
1286
0
      {
1287
0
        cctx.setSigGroup();
1288
0
        rdStats.d64CodedLevelandDist += costCoeff [ scanPos ] - costSig[ scanPos ];
1289
0
        rdStats.d64UncodedDist       += costCoeff0[ scanPos ];
1290
0
      }
1291
542k
    } //end for (iScanPosinCG)
1292
1293
33.8k
    if( !cctx.isSigGroup() )
1294
33.8k
    {
1295
33.8k
      const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray( cctx.sigGroupCtxId( true ) );
1296
33.8k
      baseCost += xGetRateSigCoeffGroup( fracBitsSigGroup, 0 ) - rdStats.d64SigCost;
1297
33.8k
      costSigSubBlock[cctx.subSetId()] = xGetRateSigCoeffGroup( fracBitsSigGroup, 0 );
1298
33.8k
      cctx.remRegBins += rdStats.iNumSbbCtxBins; // skip sub-block
1299
33.8k
    }
1300
0
    else if( sbId != sbNum - 1 || anySigCG )
1301
0
    {
1302
      // rd-cost if SigCoeffGroupFlag = 0, initialization
1303
0
      double costZeroSB = baseCost;
1304
1305
0
      const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray( cctx.sigGroupCtxId( true ) );
1306
1307
0
      baseCost   += xGetRateSigCoeffGroup( fracBitsSigGroup, 1 );
1308
0
      costZeroSB += xGetRateSigCoeffGroup( fracBitsSigGroup, 0 );
1309
0
      costSigSubBlock[ cctx.subSetId() ] = xGetRateSigCoeffGroup( fracBitsSigGroup, 1 );
1310
1311
0
      costZeroSB += rdStats.d64UncodedDist;         // distortion for resetting non-zero levels to zero levels
1312
0
      costZeroSB -= rdStats.d64CodedLevelandDist;   // distortion and level cost for keeping all non-zero levels
1313
0
      costZeroSB -= rdStats.d64SigCost;             // sig cost for all coeffs, including zero levels and non-zerl levels
1314
1315
0
      if( costZeroSB < baseCost )
1316
0
      {
1317
0
        cctx.resetSigGroup();
1318
0
        baseCost = costZeroSB;
1319
0
        costSigSubBlock[ cctx.subSetId() ] = xGetRateSigCoeffGroup( fracBitsSigGroup, 0 );
1320
0
        cctx.remRegBins += rdStats.iNumSbbCtxBins; // skip sub-block
1321
1322
0
        for( int scanPosInSB = 0; scanPosInSB <= sbSizeM1; scanPosInSB++ )
1323
0
        {
1324
0
          scanPos = cctx.minSubPos() + scanPosInSB;
1325
0
          uint32_t blkPos = cctx.blockPos( scanPos );
1326
1327
0
          if( dstCoeff[ blkPos ] )
1328
0
          {
1329
0
            dstCoeff[ blkPos ] = 0;
1330
0
            costCoeff[ scanPos ] = costCoeff0[ scanPos ];
1331
0
            costSig[ scanPos] = 0;
1332
0
          }
1333
0
        }
1334
0
      }
1335
0
      else
1336
0
      {
1337
0
        anySigCG = true;
1338
0
      }
1339
0
    }
1340
33.8k
  }
1341
1342
  // the sum of the absolute levels: the block's coefficients are contiguous (stride == width), any order gives the sum
1343
3.32k
  CHECKD( tu.getCoeffs( compID ).stride != (int) width,"transform-skip RDOQ expects a compact coefficient buffer" );
1344
545k
  for( uint32_t i = 0; i < maxNumCoeff; i++ )
1345
542k
  {
1346
542k
    absSum += abs( dstCoeff[i] );
1347
542k
  }
1348
3.32k
}
1349
1350
void QuantRDOQ::forwardRDPCM( TransformUnit& tu, const ComponentID compID, const CCoeffBuf& coeffs, TCoeff &absSum, const QpParam& qp, const Ctx &ctx )
1351
110k
{
1352
110k
  const FracBitsAccess& fracBits = ctx.getFracBitsAcess();
1353
1354
110k
  const SPS &sps = *tu.cs->sps;
1355
110k
  const CompArea& rect = tu.blocks[compID];
1356
110k
  const uint32_t width = rect.width;
1357
110k
  const uint32_t height = rect.height;
1358
110k
  const ChannelType chType = toChannelType(compID);
1359
110k
  const int channelBitDepth = sps.bitDepths[chType];
1360
1361
110k
  const int  maxLog2TrDynamicRange = sps.getMaxLog2TrDynamicRange();
1362
110k
  const int  dirMode = tu.cu->bdpcmM[toChannelType(compID)];
1363
1364
110k
  const int transformShift = getTransformShift(channelBitDepth, rect.size(), maxLog2TrDynamicRange);
1365
1366
110k
  const uint32_t maxNumCoeff = rect.area();
1367
1368
110k
  CHECK(compID >= MAX_NUM_TBLOCKS, "Invalid component ID");
1369
1370
110k
  int scalingListType = getScalingListType(tu.cu->predMode, compID);
1371
110k
  CHECK(scalingListType >= SCALING_LIST_NUM, "Invalid scaling list");
1372
1373
110k
  const TCoeff    *srcCoeff = coeffs.buf;
1374
110k
        TCoeffSig *dstCoeff = tu.getCoeffs(compID).buf;
1375
1376
110k
  double *costCoeff = m_pdCostCoeff;
1377
110k
  double *costSig = m_pdCostSig;
1378
110k
  double *costCoeff0 = m_pdCostCoeff0;
1379
1380
110k
  memset(m_pdCostCoeff, 0, sizeof(double) *  maxNumCoeff);
1381
110k
  memset(m_pdCostSig, 0, sizeof(double) *  maxNumCoeff);
1382
110k
  memset(m_fullCoeff, 0, sizeof(TCoeff) * maxNumCoeff);
1383
1384
110k
  m_bdpcm = dirMode;
1385
1386
110k
  const bool   needsSqrt2Scale = TU::needsSqrt2Scale(tu, compID);  // should always be false - transform-skipped blocks don't require sqrt(2) compensation.
1387
110k
  const bool   isTransformSkip = tu.mtsIdx[compID]==MTS_SKIP;
1388
110k
  const int    qBits = QUANT_SHIFT + qp.per(isTransformSkip) + (isTransformSkip? 0 : transformShift) + ( needsSqrt2Scale ? -1 : 0);  // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
1389
110k
  const int    quantisationCoefficient = g_quantScales[needsSqrt2Scale ? 1 : 0][qp.rem(isTransformSkip)];
1390
110k
  const double errorScale = xGetErrScaleCoeff(TU::needsSqrt2Scale(tu, compID), width, height, qp.rem(isTransformSkip), maxLog2TrDynamicRange, channelBitDepth, isTransformSkip);
1391
1392
110k
  TrQuantParams trQuantParams;
1393
110k
  trQuantParams.rightShift = (IQUANT_SHIFT - ((isTransformSkip ? 0 : transformShift) + qp.per(isTransformSkip)));
1394
110k
  trQuantParams.qScale = g_invQuantScales[needsSqrt2Scale ? 1 : 0][qp.rem(isTransformSkip)];
1395
1396
110k
  const TCoeff entropyCodingMaximum = (1 << maxLog2TrDynamicRange) - 1;
1397
1398
110k
  uint32_t coeffLevels[3];
1399
110k
  double   coeffLevelError[4];
1400
1401
110k
  CoeffCodingContext cctx(tu, compID, tu.cs->slice->signDataHidingEnabled);
1402
110k
  const int sbSizeM1 = (1 << cctx.log2CGSize()) - 1;
1403
110k
  double    baseCost = 0;
1404
110k
  uint32_t  goRiceParam = 0;
1405
1406
110k
  double *costSigSubBlock = m_pdCostCoeffGroupSig;
1407
110k
  memset(costSigSubBlock, 0, (maxNumCoeff >> cctx.log2CGSize()) * sizeof(double));
1408
1409
110k
  const int sbNum = width * height >> cctx.log2CGSize();
1410
110k
  int scanPos;
1411
110k
  coeffGroupRDStats rdStats;
1412
1413
110k
  bool anySigCG = false;
1414
1415
110k
  int maxCtxBins = (cctx.maxNumCoeff() * 7) >> 2;
1416
110k
  cctx.remRegBins = maxCtxBins;
1417
1418
818k
  for (int sbId = 0; sbId < sbNum; sbId++)
1419
707k
  {
1420
707k
    cctx.initSubblock(sbId);
1421
1422
707k
    int noCoeffCoded = 0;
1423
707k
    baseCost = 0.0;
1424
707k
    memset(&rdStats, 0, sizeof(coeffGroupRDStats));
1425
707k
    rdStats.iNumSbbCtxBins = 0;
1426
1427
12.0M
    for (int scanPosInSB = 0; scanPosInSB <= sbSizeM1; scanPosInSB++)
1428
11.3M
    {
1429
11.3M
      int lastPosCoded = sbSizeM1;
1430
11.3M
      scanPos = cctx.minSubPos() + scanPosInSB;
1431
      //===== quantization =====
1432
11.3M
      uint32_t blkPos = cctx.blockPos(scanPos);
1433
1434
11.3M
      const int posX = cctx.posX(scanPos);
1435
11.3M
      const int posY = cctx.posY(scanPos);
1436
11.3M
      const int posS = (1 == dirMode) ? posX : posY;
1437
11.3M
      const int posNb = (1 == dirMode) ? (posX - 1) + posY * coeffs.stride : posX + (posY - 1) * coeffs.stride;
1438
11.3M
      TCoeff predCoeff = (0 != posS) ? m_fullCoeff[posNb] : 0;
1439
1440
      // set coeff
1441
11.3M
      const int64_t          tmpLevel = int64_t(abs(srcCoeff[blkPos] - predCoeff)) * quantisationCoefficient;
1442
11.3M
      const Intermediate_Int levelDouble = (Intermediate_Int)std::min<int64_t>(tmpLevel, std::numeric_limits<Intermediate_Int>::max() - (Intermediate_Int(1) << (qBits - 1)));
1443
11.3M
      uint32_t roundAbsLevel = std::min<uint32_t>(uint32_t(entropyCodingMaximum), uint32_t((levelDouble + (Intermediate_Int(1) << (qBits - 1))) >> qBits));
1444
11.3M
      uint32_t minAbsLevel = (roundAbsLevel > 1 ? roundAbsLevel - 1 : 1);
1445
1446
11.3M
      m_testedLevels = 0;
1447
11.3M
      coeffLevels[m_testedLevels++] = roundAbsLevel;
1448
1449
11.3M
      if (minAbsLevel != roundAbsLevel)
1450
10.8M
        coeffLevels[m_testedLevels++] = minAbsLevel;
1451
1452
11.3M
      double dErr = double(levelDouble);
1453
11.3M
      coeffLevelError[0]  = dErr * dErr * errorScale;
1454
1455
11.3M
      costCoeff0[scanPos] = coeffLevelError[0];
1456
11.3M
      dstCoeff[blkPos]    = coeffLevels[0];
1457
1458
      //===== coefficient level estimation =====
1459
11.3M
      unsigned    ctxIdSig = cctx.sigCtxIdAbsTS(scanPos, dstCoeff);
1460
11.3M
      uint32_t    cLevel;
1461
11.3M
      const BinFracBits fracBitsPar = fracBits.getFracBitsArray(cctx.parityCtxIdAbsTS());
1462
1463
      //goRiceParam = cctx.templateAbsSumTS(scanPos, dstCoeff);
1464
11.3M
      goRiceParam = 1;
1465
11.3M
      unsigned ctxIdSign = cctx.signCtxIdAbsTS(scanPos, dstCoeff, dirMode);
1466
11.3M
      const BinFracBits fracBitsSign = fracBits.getFracBitsArray(ctxIdSign);
1467
11.3M
      const uint8_t     sign = srcCoeff[blkPos] - predCoeff < 0 ? 1 : 0;
1468
11.3M
      unsigned gt1CtxId = cctx.lrg1CtxIdAbsTS(scanPos, dstCoeff, dirMode);
1469
11.3M
      const BinFracBits fracBitsGr1 = fracBits.getFracBitsArray(gt1CtxId);
1470
1471
11.3M
      DTRACE_COND((dstCoeff[blkPos] != 0), g_trace_ctx, D_RDOQ_MORE, " uiCtxSig=%d", ctxIdSig);
1472
1473
11.3M
      const BinFracBits fracBitsSig = fracBits.getFracBitsArray(ctxIdSig);
1474
11.3M
      bool lastCoeff = false; //
1475
11.3M
      if (scanPosInSB == lastPosCoded && noCoeffCoded == 0)
1476
579k
      {
1477
579k
        lastCoeff = true;
1478
579k
      }
1479
11.3M
      int rightPixel, belowPixel;
1480
11.3M
      cctx.neighTS(rightPixel, belowPixel, scanPos, dstCoeff);
1481
11.3M
      int numUsedCtxBins = 0;
1482
11.3M
      cLevel = xGetCodedLevelTSPred(costCoeff[scanPos], costCoeff0[scanPos], costSig[scanPos], levelDouble, qBits, errorScale, coeffLevels, coeffLevelError,
1483
11.3M
        &fracBitsSig, fracBitsPar, cctx, fracBits, fracBitsSign, fracBitsGr1, sign, rightPixel, belowPixel, goRiceParam, lastCoeff, maxLog2TrDynamicRange, numUsedCtxBins);
1484
11.3M
      cctx.remRegBins -= numUsedCtxBins;
1485
11.3M
      rdStats.iNumSbbCtxBins += numUsedCtxBins;
1486
1487
11.3M
      if (cLevel > 0)
1488
537k
      {
1489
537k
        noCoeffCoded++;
1490
537k
      }
1491
11.3M
      dstCoeff[blkPos] = cLevel;
1492
1493
11.3M
      if (sign)
1494
3.85M
      {
1495
3.85M
        dstCoeff[blkPos] = -dstCoeff[blkPos];
1496
3.85M
      }
1497
1498
11.3M
      xDequantSample( m_fullCoeff[blkPos], dstCoeff[blkPos], trQuantParams );
1499
11.3M
      m_fullCoeff[blkPos] += predCoeff;
1500
1501
11.3M
      baseCost += costCoeff[scanPos];
1502
11.3M
      rdStats.d64SigCost += costSig[scanPos];
1503
1504
11.3M
      if (dstCoeff[blkPos])
1505
537k
      {
1506
537k
        cctx.setSigGroup();
1507
537k
        rdStats.d64CodedLevelandDist += costCoeff[scanPos] - costSig[scanPos];
1508
537k
        rdStats.d64UncodedDist += costCoeff0[scanPos];
1509
537k
      }
1510
11.3M
    } //end for (iScanPosinCG)
1511
1512
707k
    if (!cctx.isSigGroup())
1513
566k
    {
1514
566k
      const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray(cctx.sigGroupCtxId(true));
1515
566k
      baseCost += xGetRateSigCoeffGroup(fracBitsSigGroup, 0) - rdStats.d64SigCost;
1516
566k
      costSigSubBlock[cctx.subSetId()] = xGetRateSigCoeffGroup(fracBitsSigGroup, 0);
1517
566k
      cctx.remRegBins += rdStats.iNumSbbCtxBins; // skip sub-block
1518
566k
    }
1519
140k
    else if (sbId != sbNum - 1 || anySigCG)
1520
135k
    {
1521
      // rd-cost if SigCoeffGroupFlag = 0, initialization
1522
135k
      double costZeroSB = baseCost;
1523
1524
135k
      const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray(cctx.sigGroupCtxId(true));
1525
1526
135k
      baseCost += xGetRateSigCoeffGroup(fracBitsSigGroup, 1);
1527
135k
      costZeroSB += xGetRateSigCoeffGroup(fracBitsSigGroup, 0);
1528
135k
      costSigSubBlock[cctx.subSetId()] = xGetRateSigCoeffGroup(fracBitsSigGroup, 1);
1529
1530
135k
      costZeroSB += rdStats.d64UncodedDist;         // distortion for resetting non-zero levels to zero levels
1531
135k
      costZeroSB -= rdStats.d64CodedLevelandDist;   // distortion and level cost for keeping all non-zero levels
1532
135k
      costZeroSB -= rdStats.d64SigCost;             // sig cost for all coeffs, including zero levels and non-zerl levels
1533
1534
135k
      if (costZeroSB < baseCost)
1535
12.5k
      {
1536
12.5k
        cctx.resetSigGroup();
1537
12.5k
        baseCost = costZeroSB;
1538
12.5k
        costSigSubBlock[cctx.subSetId()] = xGetRateSigCoeffGroup(fracBitsSigGroup, 0);
1539
12.5k
        cctx.remRegBins += rdStats.iNumSbbCtxBins; // skip sub-block
1540
1541
212k
        for (int scanPosInSB = 0; scanPosInSB <= sbSizeM1; scanPosInSB++)
1542
200k
        {
1543
200k
          scanPos = cctx.minSubPos() + scanPosInSB;
1544
200k
          uint32_t blkPos = cctx.blockPos(scanPos);
1545
1546
200k
          const int posX = cctx.posX(scanPos);
1547
200k
          const int posY = cctx.posY(scanPos);
1548
200k
          const int posS = (1 == dirMode) ? posX : posY;
1549
200k
          const int posNb = (1 == dirMode) ? (posX - 1) + posY * coeffs.stride : posX + (posY - 1) * coeffs.stride;
1550
200k
          m_fullCoeff[scanPos] = (0 != posS) ? m_fullCoeff[posNb] : 0;
1551
1552
200k
          if (dstCoeff[blkPos])
1553
12.8k
          {
1554
12.8k
            dstCoeff[blkPos] = 0;
1555
12.8k
            costCoeff[scanPos] = costCoeff0[scanPos];
1556
12.8k
            costSig[scanPos] = 0;
1557
12.8k
          }
1558
200k
        }
1559
12.5k
      }
1560
122k
      else
1561
122k
      {
1562
122k
        anySigCG = true;
1563
122k
      }
1564
135k
    }
1565
707k
  }
1566
1567
  //===== estimate last position =====
1568
11.4M
  for (int scanPos = 0; scanPos < maxNumCoeff; scanPos++)
1569
11.3M
  {
1570
11.3M
    int blkPos = cctx.blockPos(scanPos);
1571
11.3M
    TCoeff level = dstCoeff[blkPos];
1572
11.3M
    absSum += abs(level);
1573
11.3M
  }
1574
110k
}
1575
1576
void QuantRDOQ::xDequantSample(TCoeff& pRes, TCoeffSig& coeff, const TrQuantParams& trQuantParams)
1577
11.3M
{
1578
  // xDequant
1579
11.3M
  if (trQuantParams.rightShift > 0)
1580
8.57M
  {
1581
8.57M
    const Intermediate_Int qAdd = Intermediate_Int(1) << (trQuantParams.rightShift - 1);
1582
8.57M
    pRes = TCoeff((Intermediate_Int(coeff) * trQuantParams.qScale + qAdd) >> trQuantParams.rightShift);
1583
8.57M
  }
1584
2.74M
  else
1585
2.74M
  {
1586
2.74M
    pRes = TCoeff((Intermediate_Int(coeff) * trQuantParams.qScale) *(1<< -trQuantParams.rightShift));
1587
2.74M
  }
1588
11.3M
}
1589
1590
inline uint32_t QuantRDOQ::xGetCodedLevelTSPred(double&            rd64CodedCost,
1591
  double&            rd64CodedCost0,
1592
  double&            rd64CodedCostSig,
1593
  Intermediate_Int    levelDouble,
1594
  int                 qBits,
1595
  double              errorScale,
1596
  uint32_t coeffLevels[],
1597
  double coeffLevelError[],
1598
  const BinFracBits* fracBitsSig,
1599
  const BinFracBits& fracBitsPar,
1600
  CoeffCodingContext& cctx,
1601
  const FracBitsAccess& fracBitsAccess,
1602
  const BinFracBits& fracBitsSign,
1603
  const BinFracBits& fracBitsGt1,
1604
  const uint8_t      sign,
1605
  int                rightPixel,
1606
  int                belowPixel,
1607
  uint16_t           ricePar,
1608
  bool               isLast,
1609
  const int          maxLog2TrDynamicRange,
1610
  int&               numUsedCtxBins
1611
) const
1612
11.3M
{
1613
11.3M
  double currCostSig = 0;
1614
11.3M
  uint32_t   bestAbsLevel = 0;
1615
11.3M
  numUsedCtxBins = 0;
1616
11.3M
  int numBestCtxBin = 0;
1617
11.3M
  if (!isLast && coeffLevels[0] < 3)
1618
10.2M
  {
1619
10.2M
    if (cctx.remRegBins >= 4)
1620
10.0M
    rd64CodedCostSig = xGetRateSigCoef(*fracBitsSig, 0);
1621
189k
    else
1622
189k
      rd64CodedCostSig = xGetICost(1 << SCALE_BITS);
1623
10.2M
    rd64CodedCost = rd64CodedCost0 + rd64CodedCostSig;
1624
10.2M
    if (cctx.remRegBins >= 4)
1625
10.0M
      numUsedCtxBins++;
1626
10.2M
    if (coeffLevels[0] == 0)
1627
9.76M
    {
1628
9.76M
      return bestAbsLevel;
1629
9.76M
    }
1630
10.2M
  }
1631
1.07M
  else
1632
1.07M
  {
1633
1.07M
    rd64CodedCost = MAX_DOUBLE;
1634
1.07M
  }
1635
1636
1.58M
  if (!isLast)
1637
973k
  {
1638
973k
    if (cctx.remRegBins >= 4)
1639
930k
      currCostSig = xGetRateSigCoef(*fracBitsSig, 1);
1640
43.4k
    else
1641
43.4k
      currCostSig = xGetICost(1 << SCALE_BITS);
1642
973k
    if (coeffLevels[0] >= 3 && cctx.remRegBins >= 4)
1643
429k
      numUsedCtxBins++;
1644
973k
  }
1645
1646
4.28M
  for (int errorInd = 1; errorInd <= m_testedLevels; errorInd++)
1647
2.70M
  {
1648
2.70M
    int absLevel = coeffLevels[errorInd - 1];
1649
2.70M
    double dErr = 0.0;
1650
2.70M
    dErr = double(levelDouble - (Intermediate_Int(absLevel) << qBits));
1651
2.70M
    coeffLevelError[errorInd] = dErr * dErr * errorScale;
1652
2.70M
    int modAbsLevel = absLevel;
1653
2.70M
    if (cctx.remRegBins >= 4) 
1654
2.61M
    {
1655
2.61M
      modAbsLevel = cctx.deriveModCoeff(rightPixel, belowPixel, absLevel, m_bdpcm);
1656
2.61M
    }
1657
2.70M
    int numCtxBins = 0;
1658
2.70M
    double dCurrCost = coeffLevelError[errorInd] + xGetICost(xGetICRateTS(modAbsLevel, fracBitsPar, cctx, fracBitsAccess, fracBitsSign, fracBitsGt1, numCtxBins, sign, ricePar, maxLog2TrDynamicRange));
1659
1660
2.70M
    if (cctx.remRegBins >= 4)
1661
2.61M
      dCurrCost += currCostSig; // if cctx.numCtxBins < 4, xGetICRateTS return rate including sign cost. dont need to add any more
1662
1663
2.70M
    if (dCurrCost < rd64CodedCost)
1664
1.18M
    {
1665
1.18M
      bestAbsLevel = absLevel;
1666
1.18M
      rd64CodedCost = dCurrCost;
1667
1.18M
      rd64CodedCostSig = currCostSig;
1668
1.18M
      numBestCtxBin = numCtxBins;
1669
1.18M
    }
1670
2.70M
  }
1671
1.58M
  numUsedCtxBins += numBestCtxBin;
1672
1.58M
  return bestAbsLevel;
1673
11.3M
}
1674
1675
inline int QuantRDOQ::xGetICRateTS( const uint32_t            absLevel,
1676
                                    const BinFracBits&        fracBitsPar,
1677
                                    const CoeffCodingContext& cctx,
1678
                                    const FracBitsAccess&     fracBitsAccess,
1679
                                    const BinFracBits&        fracBitsSign,
1680
                                    const BinFracBits&        fracBitsGt1,
1681
                                    int&                      numCtxBins,
1682
                                    const uint8_t             sign,
1683
                                    const uint16_t            ricePar,
1684
                                    const int                 maxLog2TrDynamicRange  ) const
1685
2.70M
{
1686
 
1687
2.70M
  if (cctx.remRegBins < 4) // Full by-pass coding 
1688
83.1k
  {
1689
83.1k
    int rate = absLevel ? (1 << SCALE_BITS) : 0; // 1 bit to signal sign of non-zero 
1690
1691
83.1k
    uint32_t symbol = absLevel;
1692
1693
83.1k
    uint32_t length;
1694
83.1k
    const int threshold = COEF_REMAIN_BIN_REDUCTION;
1695
83.1k
    if (symbol < (threshold << ricePar))
1696
39.2k
    {
1697
39.2k
      length = symbol >> ricePar;
1698
39.2k
      rate += (length + 1 + ricePar) << SCALE_BITS;
1699
39.2k
    }
1700
43.9k
    else
1701
43.9k
    {
1702
43.9k
      length = ricePar;
1703
43.9k
      symbol = symbol - (threshold << ricePar);
1704
195k
      while (symbol >= (1 << length))
1705
151k
      {
1706
151k
        symbol -= (1 << (length++));
1707
151k
      }
1708
43.9k
      rate += (threshold + length + 1 - ricePar + length) << SCALE_BITS;
1709
43.9k
    }
1710
1711
83.1k
    return rate;
1712
83.1k
  }
1713
1714
2.61M
  else if (cctx.remRegBins >= 4 && cctx.remRegBins < 8) // First pass context coding and all by-pass coding ( Sign flag is not counted here)
1715
13.9k
  {
1716
13.9k
    int rate = fracBitsSign.intBits[sign]; // sign bits
1717
13.9k
    if (absLevel)
1718
13.3k
      numCtxBins++;
1719
1720
13.9k
    if (absLevel > 1)
1721
10.0k
    {
1722
10.0k
      rate += fracBitsGt1.intBits[1];
1723
10.0k
      rate += fracBitsPar.intBits[(absLevel - 2) & 1];
1724
1725
10.0k
      numCtxBins += 2;
1726
1727
10.0k
      int cutoffVal = 2;
1728
1729
10.0k
      if (absLevel >= cutoffVal)
1730
10.0k
      {
1731
10.0k
        uint32_t symbol = (absLevel - cutoffVal) >> 1;
1732
10.0k
        uint32_t length;
1733
10.0k
        const int threshold = COEF_REMAIN_BIN_REDUCTION;
1734
10.0k
        if (symbol < (threshold << ricePar))
1735
6.84k
        {
1736
6.84k
          length = symbol >> ricePar;
1737
6.84k
          rate += (length + 1 + ricePar) << SCALE_BITS;
1738
6.84k
        }
1739
3.22k
        else
1740
3.22k
        {
1741
3.22k
          length = ricePar;
1742
3.22k
          symbol = symbol - (threshold << ricePar);
1743
12.9k
          while (symbol >= (1 << length))
1744
9.74k
          {
1745
9.74k
            symbol -= (1 << (length++));
1746
9.74k
          }
1747
3.22k
          rate += (threshold + length + 1 - ricePar + length) << SCALE_BITS;
1748
3.22k
        }
1749
10.0k
      }
1750
10.0k
    }
1751
3.85k
    else if (absLevel == 1)
1752
3.26k
    {
1753
3.26k
      rate += fracBitsGt1.intBits[0];
1754
3.26k
      numCtxBins++;
1755
3.26k
    }
1756
597
    else
1757
597
    {
1758
597
      rate = 0;
1759
597
    }
1760
13.9k
    return rate;
1761
13.9k
  }
1762
    
1763
2.60M
  int rate = fracBitsSign.intBits[sign];
1764
1765
2.60M
  if (absLevel)
1766
2.00M
    numCtxBins++;
1767
1768
2.60M
  if( absLevel > 1 )
1769
899k
  {
1770
899k
    rate += fracBitsGt1.intBits[1];
1771
899k
    rate += fracBitsPar.intBits[( absLevel - 2 ) & 1];
1772
899k
    numCtxBins += 2;
1773
1774
899k
          int cutoffVal = 2;
1775
899k
    const int numGtBins = 4;
1776
4.49M
    for( int i = 0; i < numGtBins; i++ )
1777
3.59M
    {
1778
3.59M
      if( absLevel >= cutoffVal )
1779
2.65M
      {
1780
2.65M
        const uint16_t ctxGtX = cctx.greaterXCtxIdAbsTS( cutoffVal>>1 );
1781
2.65M
        const BinFracBits &fracBitsGtX = fracBitsAccess.getFracBitsArray( ctxGtX );
1782
2.65M
        unsigned gtX = ( absLevel >= ( cutoffVal + 2 ) );
1783
2.65M
        rate += fracBitsGtX.intBits[gtX];
1784
2.65M
        numCtxBins++;
1785
2.65M
      }
1786
3.59M
      cutoffVal += 2;
1787
3.59M
    }
1788
1789
899k
    if( absLevel >= cutoffVal )
1790
460k
    {
1791
460k
      uint32_t symbol = ( absLevel - cutoffVal ) >> 1;
1792
460k
      uint32_t length;
1793
460k
      const int threshold = COEF_REMAIN_BIN_REDUCTION;
1794
460k
      if( symbol < ( threshold << ricePar ) )
1795
189k
      {
1796
189k
        length = symbol >> ricePar;
1797
189k
        rate  += ( length + 1 + ricePar ) << SCALE_BITS;
1798
189k
      }
1799
270k
      else
1800
270k
      {
1801
270k
        length = ricePar;
1802
270k
        symbol = symbol - ( threshold << ricePar );
1803
1.12M
        while( symbol >= ( 1 << length ) )
1804
859k
        {
1805
859k
          symbol -= ( 1 << ( length++ ) );
1806
859k
        }
1807
270k
        rate += ( threshold + length + 1 - ricePar + length ) << SCALE_BITS;
1808
270k
      }
1809
460k
    }
1810
899k
  }
1811
1.70M
  else if( absLevel == 1 )
1812
1.10M
  {
1813
1.10M
    rate += fracBitsGt1.intBits[0];
1814
1.10M
    numCtxBins++;
1815
1.10M
  }
1816
596k
  else
1817
596k
  {
1818
596k
    rate = 0;
1819
596k
  }
1820
2.60M
  return rate;
1821
2.70M
}
1822
1823
} // namespace vvenc
1824
1825
//! \}
1826