Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/EncoderLib/BitAllocation.cpp
Line
Count
Source
1
/* -----------------------------------------------------------------------------
2
The copyright in this software is being made available under the Clear BSD
3
License, included below. No patent rights, trademark rights and/or
4
other Intellectual Property Rights other than the copyrights concerning
5
the Software are granted under this license.
6
7
The Clear BSD License
8
9
Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors.
10
All rights reserved.
11
12
Redistribution and use in source and binary forms, with or without modification,
13
are permitted (subject to the limitations in the disclaimer below) provided that
14
the following conditions are met:
15
16
     * Redistributions of source code must retain the above copyright notice,
17
     this list of conditions and the following disclaimer.
18
19
     * Redistributions in binary form must reproduce the above copyright
20
     notice, this list of conditions and the following disclaimer in the
21
     documentation and/or other materials provided with the distribution.
22
23
     * Neither the name of the copyright holder nor the names of its
24
     contributors may be used to endorse or promote products derived from this
25
     software without specific prior written permission.
26
27
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
28
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
31
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
32
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
36
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38
POSSIBILITY OF SUCH DAMAGE.
39
40
41
------------------------------------------------------------------------------------------- */
42
43
44
/** \file     BitAllocation.cpp
45
\brief    Bit allocation class for QP adaptation and, possibly, rate control
46
*/
47
48
#include "BitAllocation.h"
49
#include "EncStage.h"
50
#include "CommonLib/Picture.h"
51
#include "CommonLib/UnitTools.h"
52
#include <math.h>
53
54
#include "vvenc/vvencCfg.h"
55
56
57
//! \ingroup EncoderLib
58
//! \{
59
60
namespace vvenc {
61
62
// static functions
63
64
static inline int apprI3Log2 (const double d, const bool isSccStrong) // rounded 2*log2(d) or 3*log2(d)
65
13.1k
{
66
13.1k
  const double weight = (isSccStrong ? 2.0 : 3.0);
67
13.1k
  const double dLimit = (isSccStrong ? 5.5e-20 : 1.5e-13);
68
69
13.1k
  return d < dLimit ? -128 : int (floor (weight * log (d) / log (2.0) + 0.5));
70
13.1k
}
71
72
// Activity scale that adds the picture's fractional QP to the rounded QP offsets apprI3Log2 derives from activities, so
73
// that the blocks whose unrounded QP lies within the fraction below the next integer move up to that integer QP.
74
static inline double fractionalQPActivityScale (const double picQPFraction, const bool isSccStrong)
75
4.16k
{
76
4.16k
  return picQPFraction > 0.0 ? pow (2.0, picQPFraction / (isSccStrong ? 2.0 : 3.0)) : 1.0;
77
4.16k
}
78
79
static inline int lumaDQPOffset (const uint32_t avgLumaValue, const uint32_t bitDepth)
80
0
{
81
0
  if (bitDepth > 16 || avgLumaValue >= (1u << bitDepth)) return 0;
82
#if 0
83
  // mapping for peak luminance of ca. 3*400 = 1200 nits
84
  return (2 - int ((9 * uint64_t (avgLumaValue * avgLumaValue)) >> uint64_t (2 * bitDepth)));
85
#else
86
  // mapping for peak luminance of ca. 2*400 =  800 nits
87
0
  return (1 - int ((6 * uint64_t (avgLumaValue * avgLumaValue)) >> uint64_t (2 * bitDepth)));
88
0
#endif
89
0
}
90
91
void calcSpatialVisAct ( const Pel* pSrc,
92
                         const int iSrcStride,
93
                         const int height,
94
                         const int width,
95
                         const uint32_t bitDepth,
96
                         const bool isUHD,
97
                         VisAct& va )
98
13.1k
{
99
13.1k
  CHECK( pSrc == nullptr, "no source buffer given to calculate temporal visual activity" );
100
101
13.1k
  uint64_t saAct;  // spatial absolute activity sum
102
103
  // skip first row as there may be a black border frame
104
13.1k
  pSrc += iSrcStride;
105
106
  // center rows
107
13.1k
  if (isUHD) // high-pass with downsampling
108
0
  {
109
0
    pSrc += iSrcStride;
110
111
0
    saAct = g_pelBufOP.AvgHighPassWithDownsampling (width, height, pSrc, iSrcStride);
112
113
0
    va.hpSpatAct = double (saAct) / double ((width - 4) * (height - 4));
114
0
  }
115
13.1k
  else // HD high-pass without downsampling
116
13.1k
  {
117
13.1k
    saAct = g_pelBufOP.AvgHighPass (width, height, pSrc, iSrcStride);
118
119
13.1k
    va.hpSpatAct = double (saAct) / double ((width - 2) * (height - 2));
120
13.1k
  }
121
122
  // spatial in 12 bit
123
13.1k
  va.spatAct = unsigned (0.5 + va.hpSpatAct * double (bitDepth < 12 ? 1 << (12 - bitDepth) : 1));
124
13.1k
}
125
126
void calcTemporalVisAct ( const Pel* pSrc,
127
                          const int iSrcStride,
128
                          const int height,
129
                          const int width,
130
                          const Pel* pSM1,
131
                          const int iSM1Stride,
132
                          const Pel* pSM2,
133
                          const int iSM2Stride,
134
                          uint32_t frameRate,
135
                          const uint32_t bitDepth,
136
                          const bool isUHD,
137
                          VisAct& va )
138
11.6k
{
139
11.6k
  CHECK( pSrc == nullptr, "no source buffer given to calculate temporal visual activity" );
140
11.6k
  CHECK( pSM1 == nullptr, "no compare buffer given to calculate temporal visual activity" );
141
142
11.6k
  const Pel* pS0 = pSrc;
143
11.6k
  uint64_t taAct;  // temporal absolute activity sum
144
145
  // force 1st-order delta if only prev. frame available
146
11.6k
  if (pSM2 == nullptr || iSM2Stride <= 0) frameRate = 24;
147
148
  // skip first row as there may be a black border frame
149
11.6k
  pSrc += iSrcStride;
150
151
  // center rows
152
11.6k
  if (pS0 == pSM1 && frameRate <= 31)
153
11.6k
  {
154
11.6k
    va.hpTempAct = 0; // bypass high-pass, result will be zero
155
11.6k
  }
156
0
  else if (isUHD)  // downsampled high-pass
157
0
  {
158
0
    const int i2M1Stride = iSM1Stride * 2;
159
160
0
    CHECK (pSM1 == nullptr || iSM1Stride <= 0 || iSM1Stride < width, "Pel buffer pointer pSM1 must not be null!");
161
162
0
    pSrc += iSrcStride;
163
0
    pSM1 += i2M1Stride;
164
0
    if (frameRate <= 31) // 1st-order delta
165
0
    {
166
0
      taAct = g_pelBufOP.AvgHighPassWithDownsamplingDiff1st (width, height, pSrc, pSM1, iSrcStride, iSM1Stride);
167
0
    }
168
0
    else // 2nd-order delta (diff of diffs)
169
0
    {
170
0
      const int i2M2Stride = iSM2Stride * 2;
171
172
0
      CHECK (pSM2 == nullptr || iSM2Stride <= 0 || iSM2Stride < width, "Pel buffer pointer pSM2 must not be null!");
173
174
0
      pSM2 += i2M2Stride;
175
0
      taAct = g_pelBufOP.AvgHighPassWithDownsamplingDiff2nd (width, height, pSrc, pSM1, pSM2, iSrcStride, iSM1Stride, iSM2Stride);
176
0
    }
177
178
0
    va.hpTempAct = double (taAct) / double ((width - 4) * (height - 4));
179
0
  }
180
0
  else // HD high-pass without downsampling
181
0
  {
182
0
    CHECK (pSM1 == nullptr || iSM1Stride <= 0 || iSM1Stride < width, "Pel buffer pointer pSM1 must not be null!");
183
184
0
    pSM1 += iSM1Stride;
185
0
    if (frameRate <= 31) // 1st-order delta
186
0
    {
187
0
      taAct = g_pelBufOP.HDHighPass (width, height, pSrc, pSM1, iSrcStride, iSM1Stride);
188
0
    }
189
0
    else // 2nd-order delta (diff of diffs)
190
0
    {
191
0
      CHECK (pSM2 == nullptr || iSM2Stride <= 0 || iSM2Stride < width, "Pel buffer pointer pSM2 must not be null!");
192
193
0
      pSM2 += iSM2Stride;
194
0
      taAct = g_pelBufOP.HDHighPass2 (width, height, pSrc, pSM1, pSM2, iSrcStride, iSM1Stride, iSM2Stride);
195
0
    }
196
197
0
    va.hpTempAct = double (taAct) / double ((width - 2) * (height - 2));
198
0
  }
199
200
  // temporal in 12 bit
201
11.6k
  va.tempAct = unsigned (0.5 + va.hpTempAct * double (bitDepth < 12 ? 1 << (12 - bitDepth) : 1) * (frameRate <= 31 ? 1.15625 : 1.0));
202
11.6k
}
203
204
void updateVisAct ( VisAct& va, const uint32_t bitDepth )
205
11.6k
{
206
  // minimum part in 12 bit
207
11.6k
  va.minAct = std::min( va.tempAct, va.spatAct );
208
  // lower limit, compensate for high-pass amplification
209
11.6k
  va.hpVisAct = std::max (double (1 << (bitDepth - 6)), va.hpSpatAct + 2.0 * va.hpTempAct);
210
11.6k
  va.visAct   = ClipBD( uint16_t( 0.5 + va.hpVisAct ), bitDepth );
211
11.6k
}
212
213
double filterAndCalculateAverageActivity ( const Pel* pSrc,
214
                                           const int iSrcStride,
215
                                           const int height,
216
                                           const int width,
217
                                           const Pel* pSM1,
218
                                           const int iSM1Stride,
219
                                           const Pel* pSM2,
220
                                           const int iSM2Stride,
221
                                           uint32_t frameRate,
222
                                           const uint32_t bitDepth,
223
                                           const bool isUHD,
224
                                           unsigned* minVisAct = nullptr,
225
                                           unsigned* spVisAct  = nullptr )
226
11.6k
{
227
11.6k
  VisAct va;
228
229
  // spatial activity
230
11.6k
  calcSpatialVisAct( pSrc, iSrcStride, height, width, bitDepth, isUHD, va );
231
232
  // temporal activity
233
11.6k
  calcTemporalVisAct( pSrc, iSrcStride, height, width, pSM1, iSM1Stride, pSM2, iSM2Stride,
234
11.6k
                     frameRate, bitDepth, isUHD, va );
235
236
  // minimum and visual activity
237
11.6k
  updateVisAct( va, bitDepth );
238
239
11.6k
  if( minVisAct )
240
4.65k
  {
241
4.65k
    *minVisAct = va.minAct;
242
4.65k
  }
243
11.6k
  if( spVisAct )
244
4.65k
  {
245
4.65k
    *spVisAct = va.spatAct;
246
4.65k
  }
247
248
11.6k
  return va.hpVisAct;
249
11.6k
}
250
251
static double getAveragePictureActivity (const uint32_t picWidth,  const uint32_t picHeight,
252
                                         const int scaledAverageGopActivity,
253
                                         const bool tempFiltering, const uint32_t bitDepth)
254
5.60k
{
255
5.60k
  if (scaledAverageGopActivity > 0)
256
0
  {
257
0
    return (double (scaledAverageGopActivity) / double (1 << (24 - bitDepth)));
258
0
  }
259
5.60k
  const double hpEnerPic = (tempFiltering ? 32.0 : 16.0) * double (1 << (2 * bitDepth - 10)) * sqrt ((3840.0 * 2160.0) / double (picWidth * picHeight));
260
261
5.60k
  return sqrt (hpEnerPic); // square-root of a_pic value
262
5.60k
}
263
264
static int getGlaringColorQPOffset (Picture* const pic, const int ctuAddr, const int bitDepth, uint32_t &avgLumaValue)
265
6.08k
{
266
6.08k
  const PreCalcValues& pcv  = *pic->cs->pcv;
267
6.08k
  const ChromaFormat chrFmt = pic->chromaFormat;
268
6.08k
  const SizeType chrWidth   = pcv.maxCUSize >> getChannelTypeScaleX (CH_C, chrFmt);
269
6.08k
  const SizeType chrHeight  = pcv.maxCUSize >> getChannelTypeScaleY (CH_C, chrFmt);
270
6.08k
  const unsigned w          = pcv.widthInCtus;
271
6.08k
  const int      midLevel   = 1 << (bitDepth - 1);
272
6.08k
  int chrValue = MAX_INT;
273
274
6.08k
  avgLumaValue = uint32_t ((ctuAddr >= 0) ? pic->ctuAdaptedQP[ctuAddr] : pic->getOrigBuf().Y().getAvg());
275
276
18.2k
  for (uint32_t comp = COMP_Cb; comp < MAX_NUM_COMP; comp++)
277
12.1k
  {
278
12.1k
    const ComponentID compID = (ComponentID) comp;
279
12.1k
    int avgCompValue;
280
281
12.1k
    if (ctuAddr >= 0) // chroma
282
9.30k
    {
283
9.30k
      const CompArea chrArea = clipArea (CompArea (compID, chrFmt, Area ((ctuAddr % w) * chrWidth, (ctuAddr / w) * chrHeight, chrWidth, chrHeight)), pic->block (compID));
284
285
9.30k
      avgCompValue = pic->getOrigBuf (chrArea).getAvg();
286
9.30k
    }
287
2.86k
    else avgCompValue = pic->getOrigBuf (pic->block (compID)).getAvg();
288
289
12.1k
    if (chrValue > avgCompValue) chrValue = avgCompValue; // minimum of the DC offsets
290
12.1k
  }
291
6.08k
  CHECK (chrValue < 0, "mean chroma value cannot be negative!");
292
293
6.08k
  chrValue = (int) avgLumaValue - chrValue;
294
295
6.08k
  if (chrValue > midLevel) return apprI3Log2 (double (chrValue * chrValue) / double (midLevel * midLevel), pic->isSccStrong);
296
297
6.08k
  return 0;
298
6.08k
}
299
300
static int getGlaringColorQPOffsetSubCtu (Picture* const pic, const CompArea& lumaArea, const int bitDepth, uint32_t &avgLumaValue)
301
4.16k
{
302
4.16k
  const ChromaFormat chrFmt = pic->chromaFormat;
303
4.16k
  const SizeType chrWidth   = lumaArea.width  >> getChannelTypeScaleX (CH_C, chrFmt);
304
4.16k
  const SizeType chrHeight  = lumaArea.height >> getChannelTypeScaleY (CH_C, chrFmt);
305
4.16k
  const PosType  chrPosX    = lumaArea.x >> getChannelTypeScaleX (CH_C, chrFmt);
306
4.16k
  const PosType  chrPosY    = lumaArea.y >> getChannelTypeScaleY (CH_C, chrFmt);
307
4.16k
  const int      midLevel   = 1 << (bitDepth - 1);
308
4.16k
  int chrValue = MAX_INT;
309
310
4.16k
  avgLumaValue = pic->getOrigBuf (lumaArea).getAvg();
311
312
12.5k
  for (uint32_t comp = COMP_Cb; comp < MAX_NUM_COMP; comp++)
313
8.33k
  {
314
8.33k
    const ComponentID compID = (ComponentID) comp;
315
8.33k
    const CompArea   chrArea = clipArea (CompArea (compID, chrFmt, Area (chrPosX, chrPosY, chrWidth, chrHeight)), pic->block (compID));
316
317
8.33k
    int avgCompValue = pic->getOrigBuf (chrArea).getAvg();
318
319
8.33k
    if (chrValue > avgCompValue) chrValue = avgCompValue; // minimum of the DC offsets
320
8.33k
  }
321
4.16k
  CHECK (chrValue < 0, "mean chroma value cannot be negative!");
322
323
4.16k
  chrValue = (int) avgLumaValue - chrValue;
324
325
4.16k
  if (chrValue > midLevel) return apprI3Log2 (double (chrValue * chrValue) / double (midLevel * midLevel), pic->isSccStrong);
326
327
4.16k
  return 0;
328
4.16k
}
329
330
static void updateMinNoiseLevelsPic (uint8_t* const minNoiseLevels, const int bitDepth, const unsigned avgValue, const unsigned noise)
331
0
{
332
0
  const unsigned avgIndex = avgValue >> (bitDepth - 3); // one of 8 mean level regions
333
334
0
  CHECK (avgIndex >= QPA_MAX_NOISE_LEVELS, "array index out of bounds");
335
336
0
  if (noise < (unsigned) minNoiseLevels[avgIndex])
337
0
  {
338
0
    minNoiseLevels[avgIndex] = (uint8_t) noise;
339
0
  }
340
0
}
341
342
static void clipQPValToEstimatedMinimStats (const uint8_t* minNoiseLevels, const int bitDepth, const unsigned avgValue,
343
                                            const double resFac, const int extraQPOffset, int& QP) // output QP
344
0
{
345
0
  const unsigned avgIndex = avgValue >> (bitDepth - 3); // one of 8 mean level regions
346
0
  const unsigned x = (1 << 3) - 1;
347
0
  const int32_t dQPOffset = -15;
348
349
0
  CHECK (avgIndex >= QPA_MAX_NOISE_LEVELS, "array index out of bounds");
350
351
0
  int i = minNoiseLevels[avgIndex];
352
353
  // try to "fill in the blanks" in luma range (also results in peak smoothing, as described in PCS 2022 paper)
354
0
  if (avgIndex == 0 && i > minNoiseLevels[0 + 1]) i = minNoiseLevels[0 + 1];
355
0
  if (avgIndex == x && i > minNoiseLevels[x - 1]) i = minNoiseLevels[x - 1];
356
357
0
  if (avgIndex > 0 && avgIndex < x)
358
0
  {
359
0
    const uint8_t maxNeighborNoiseLevel = std::max (minNoiseLevels[avgIndex - 1], minNoiseLevels[avgIndex + 1]);
360
361
0
    if (i > maxNeighborNoiseLevel) i = maxNeighborNoiseLevel;
362
0
  }
363
0
  if (i >= 255)
364
0
  {
365
0
    return;
366
0
  }
367
368
0
  i = std::max (0, apprI3Log2 (std::min (1.0, resFac) * i * i, false) + dQPOffset + extraQPOffset); // = 6*log2
369
0
  if (QP < i)
370
0
  {
371
0
    QP = i;
372
0
  }
373
0
}
374
375
static int applyDeltaQpPeakSmoothing (Picture* const pic, const VVEncCfg* encCfg, const uint32_t startAddr, const uint32_t endAddr)
376
935
{
377
935
  const uint32_t ctuWdt = pic->cs->pcv->widthInCtus;
378
935
  const uint32_t ctuEnd = endAddr - ctuWdt;
379
935
  int deltaQpSum = 0, preSmoothQP = 0;
380
935
  std::vector<int> prevQP;
381
382
935
  if (ctuWdt == 0 || endAddr <= startAddr + 3u * ctuWdt) return 0;
383
384
0
  prevQP.resize (ctuWdt);
385
386
0
  for (uint32_t ctuRsAddr = startAddr; ctuRsAddr < ctuEnd; ctuRsAddr++)
387
0
  {
388
0
    const int32_t idx = ctuRsAddr % ctuWdt;
389
390
0
    if (ctuRsAddr < ctuWdt) prevQP[idx] = pic->ctuAdaptedQP[ctuRsAddr];
391
0
    else if (idx == 0)      preSmoothQP = pic->ctuAdaptedQP[ctuRsAddr];
392
0
    else if (idx == ctuWdt - 1)
393
0
    {
394
0
      prevQP[idx - 1] = preSmoothQP;
395
0
      prevQP[idx] = pic->ctuAdaptedQP[ctuRsAddr];
396
0
    }
397
0
    else // no boundary CTU
398
0
    {
399
0
      const int32_t nextIdx = ctuRsAddr + ctuWdt; // max. and min. in 3x3 neighborhood
400
0
      int qpMax = std::max (preSmoothQP, pic->ctuAdaptedQP[ctuRsAddr + 1]);
401
0
      int qpMin = std::min (preSmoothQP, pic->ctuAdaptedQP[ctuRsAddr + 1]);
402
403
0
      for (int32_t i = -1; i <= 1; i++)
404
0
      {
405
0
        qpMax = std::max (qpMax, std::max (prevQP[idx + i], pic->ctuAdaptedQP[nextIdx + i]));
406
0
        qpMin = std::min (qpMin, std::min (prevQP[idx + i], pic->ctuAdaptedQP[nextIdx + i]));
407
0
      }
408
0
      prevQP[idx - 1] = preSmoothQP;
409
0
      preSmoothQP = pic->ctuAdaptedQP[ctuRsAddr];
410
411
0
      if (preSmoothQP > qpMax)
412
0
      {
413
0
        pic->ctuQpaLambda[ctuRsAddr] *= 0.793701; // peak: decrease adapted lambda, QP
414
0
        pic->ctuAdaptedQP[ctuRsAddr]--;
415
0
        deltaQpSum--;
416
0
      }
417
0
      if (preSmoothQP < qpMin)
418
0
      {
419
0
        pic->ctuQpaLambda[ctuRsAddr] *= 1.259921; // hole: increase adapted lambda, QP
420
0
        pic->ctuAdaptedQP[ctuRsAddr]++;
421
0
        deltaQpSum++;
422
0
      }
423
0
    }
424
0
  }
425
426
0
  prevQP.clear();
427
428
0
  return deltaQpSum;
429
935
}
430
431
static int refineDeltaQpDistribution (Picture* const pic, const VVEncCfg* encCfg,   const int sliceQP,
432
                                      const double sliceLambda, const int rcQpDiff, const int bitDepth,
433
                                      const uint32_t startAddr, const uint32_t endAddr, const int qpSum,
434
                                      const uint32_t tempLayer, const bool isIntra, const bool isEncPass,
435
                                      const uint8_t* minNoiseLevels, std::vector<int>& ctuAvgLuma)
436
0
{
437
0
  const double resRatio = (isEncPass ? sqrt (double (encCfg->m_SourceWidth * encCfg->m_SourceHeight) / (3840.0 * 2160.0)) : 0.0);
438
0
  const int ctusInSlice = int (endAddr - startAddr);
439
0
  const int targetQpSum = (encCfg->m_RCTargetBitrate > 0 ? sliceQP * ctusInSlice : qpSum);
440
0
  int blockQpSum = 0, tempLumaQP;
441
0
  double blockLambda;
442
0
  bool isLimited = false;
443
444
0
  for (uint32_t ctuRsAddr = startAddr; ctuRsAddr < endAddr; ctuRsAddr++)
445
0
  {
446
0
    int clippedLumaQP = std::max (0, pic->ctuAdaptedQP[ctuRsAddr] + rcQpDiff);
447
448
0
    if (isEncPass)
449
0
    {
450
0
      tempLumaQP = clippedLumaQP; // CTU QP before clipping for diff calculation below
451
452
0
      clipQPValToEstimatedMinimStats (minNoiseLevels, bitDepth, ctuAvgLuma[ctuRsAddr - startAddr], resRatio, (isIntra ? encCfg->m_intraQPOffset >> 1 : std::min (4, (int) tempLayer)), clippedLumaQP);
453
0
      if (clippedLumaQP > tempLumaQP)
454
0
      {
455
0
        ctuAvgLuma[ctuRsAddr - startAddr] = -1; // mark CTU as being processed already
456
0
        isLimited = isEncPass;
457
0
      }
458
0
    }
459
460
0
    clippedLumaQP = std::min (MAX_QP, clippedLumaQP);
461
462
0
    blockLambda = sliceLambda * pow (2.0, double (clippedLumaQP - sliceQP) / 3.0);
463
0
    blockQpSum += clippedLumaQP;
464
465
0
    pic->ctuQpaLambda[ctuRsAddr] = blockLambda;  // store modified CTU lambdas and QPs
466
0
    pic->ctuAdaptedQP[ctuRsAddr] = clippedLumaQP;
467
0
  }
468
469
0
  if (blockQpSum > targetQpSum && isLimited) // CTU QPs limited, so distribute saved rate among nonlimited CTUs
470
0
  {
471
0
    int maxCtuQP = 0, minCtuQP = MAX_QP;
472
473
0
    for (uint32_t ctuRsAddr = startAddr; ctuRsAddr < endAddr; ctuRsAddr++) // find max
474
0
    {
475
0
      if (ctuAvgLuma[ctuRsAddr - startAddr] >= 0 && pic->ctuAdaptedQP[ctuRsAddr] > maxCtuQP) // nonlimited CTUs
476
0
      {
477
0
        maxCtuQP = pic->ctuAdaptedQP[ctuRsAddr];
478
0
      }
479
0
      if (pic->ctuAdaptedQP[ctuRsAddr] < minCtuQP)
480
0
      {
481
0
        minCtuQP = pic->ctuAdaptedQP[ctuRsAddr];
482
0
      }
483
0
    }
484
485
0
    minCtuQP = std::max (0, minCtuQP);
486
487
0
    while (maxCtuQP > minCtuQP && blockQpSum > targetQpSum) // spend rate starting at max QPs, then go downward
488
0
    {
489
0
      for (uint32_t ctuRsAddr = startAddr; ctuRsAddr < endAddr; ctuRsAddr++) // reduce
490
0
      {
491
0
        if (ctuAvgLuma[ctuRsAddr - startAddr] >= 0 && pic->ctuAdaptedQP[ctuRsAddr] == maxCtuQP)
492
0
        {
493
0
          tempLumaQP = std::max (0, pic->ctuAdaptedQP[ctuRsAddr] - 1);
494
495
0
          ctuAvgLuma[ctuRsAddr - startAddr] = -1; // mark CTU as being reduced already
496
0
          blockLambda = sliceLambda * pow (2.0, double (tempLumaQP - sliceQP) / 3.0);
497
0
          if (tempLumaQP < pic->ctuAdaptedQP[ctuRsAddr]) blockQpSum--;
498
499
0
          pic->ctuQpaLambda[ctuRsAddr] = blockLambda; // store reduced lambdas and QPs
500
0
          pic->ctuAdaptedQP[ctuRsAddr] = tempLumaQP;
501
0
        }
502
503
0
        if (blockQpSum <= targetQpSum) break;
504
0
      }
505
506
0
      maxCtuQP--;
507
0
    }
508
0
  }
509
510
0
  return (blockQpSum + (ctusInSlice >> 1)) / ctusInSlice;
511
0
}
512
513
// public functions
514
515
// The lowest QP the adaptation may choose: the format's own limit. Dark, low-contrast film needs QPs below 0, as its fine
516
// detail lies below the quantiser step of QP 0 at 10 bits. Rate control stays at 0, as it reads a negative QP as not set;
517
// its first pass runs at a fixed QP with no target bitrate set, so the number of passes tells that one apart.
518
int BitAllocation::getMinAdaptedQP (const Slice* slice, const VVEncCfg* encCfg)
519
5.60k
{
520
5.60k
  return encCfg->m_RCTargetBitrate > 0 || encCfg->m_RCNumPasses == 2 ? 0 : -slice->sps->qpBDOffset[CH_L];
521
5.60k
}
522
523
int BitAllocation::applyQPAdaptationSlice (const Slice* slice, const VVEncCfg* encCfg, const int sliceQP,
524
                                           const double sliceLambda, uint16_t* const picVisActLuma,
525
                                           std::vector<int>& ctuPumpRedQP, std::vector<uint8_t>* ctuRCQPMemory,
526
                                           int* const optChromaQPOffsets, const uint8_t* minNoiseLevels,
527
                                           const uint32_t ctuStartAddr, const uint32_t ctuBoundingAddr)
528
1.43k
{
529
1.43k
  Picture* const pic          = (slice != nullptr ? slice->pic : nullptr);
530
1.43k
  double hpEner[MAX_NUM_COMP] = {0.0, 0.0, 0.0};
531
1.43k
  double averageAdaptedLambda = 0.0;
532
1.43k
  int    averageAdaptedLumaQP = QPA_QP_NOT_SET;
533
1.43k
  uint32_t meanLuma           = MAX_UINT;
534
1.43k
  std::vector<int> ctuAvgLuma;
535
536
1.43k
  if (pic == nullptr || pic->cs == nullptr || encCfg == nullptr || ctuStartAddr >= ctuBoundingAddr)
537
0
  {
538
0
    return QPA_QP_NOT_SET;
539
0
  }
540
541
1.43k
  const bool isEncPass        = (encCfg->m_LookAhead > 0 && !pic->isPreAnalysis);
542
1.43k
  const bool isHDR            = encCfg->m_HdrMode != vvencHDRMode::VVENC_HDR_OFF;
543
1.43k
  const bool isBIM            = (encCfg->hasBlockQpOffsets() && !pic->m_picShared->m_ctuBimQpOffset.empty());
544
1.43k
  const bool isSccStrongRC    = ((encCfg->m_LookAhead > 0 || encCfg->m_RCNumPasses == 2) && pic->isSccStrong);
545
1.43k
  const bool isHighResolution = (std::min (encCfg->m_SourceWidth, encCfg->m_SourceHeight) > 1280);
546
1.43k
  const int  minQP            = getMinAdaptedQP (slice, encCfg);
547
1.43k
  const bool useFrameWiseQPA  = (encCfg->m_QP > MAX_QP_PERCEPT_QPA) && (encCfg->m_framesToBeEncoded != 1) && (slice->TLayer > 0);
548
1.43k
  const uint32_t hpFrameRate  = (pic->force2ndOrder ? 32 : encCfg->m_FrameRate / encCfg->m_FrameScale);
549
1.43k
  const int  bitDepth         = slice->sps->bitDepths[CH_L];
550
1.43k
  double hpEnerPicNorm        = 1.0 / getAveragePictureActivity (encCfg->m_SourceWidth, encCfg->m_SourceHeight, (encCfg->m_RCNumPasses == 2 ? 0 : ctuPumpRedQP.back()),
551
1.43k
                                                                 (encCfg->m_internalUsePerceptQPATempFiltISlice || !slice->isIntra()), bitDepth);
552
1.43k
  if (pic->picQPFraction > 0.0)
553
0
  {
554
0
    hpEnerPicNorm *= fractionalQPActivityScale (pic->picQPFraction, isSccStrongRC);
555
0
  }
556
1.43k
  const PreCalcValues& pcv    = *pic->cs->pcv;
557
558
1.43k
  pic->picInitialQP = sliceQP;  // modified below and used in applyQPAdaptationSubCtu
559
1.43k
  if ((encCfg->m_RCTargetBitrate > 0) && useFrameWiseQPA)
560
0
  {
561
0
    averageAdaptedLumaQP = Clip3 (minQP, MAX_QP, sliceQP - 1); // one will be added again
562
0
  }
563
564
5.72k
  for (uint32_t comp = 0; comp < getNumberValidComponents (pic->chromaFormat); comp++)
565
4.29k
  {
566
4.29k
    const ComponentID compID  = (ComponentID) comp;
567
568
4.29k
    if (isLuma (compID)) // luma: CTU-wise QPA operation
569
1.43k
    {
570
1.43k
      const PosType guardSize = (isHighResolution ? 2 : 1);
571
1.43k
      unsigned zeroMinActCTUs = 0, picSpVisAct = 0;
572
573
6.08k
      for (uint32_t ctuRsAddr = ctuStartAddr; ctuRsAddr < ctuBoundingAddr; ctuRsAddr++)
574
4.65k
      {
575
4.65k
        const Position pos ((ctuRsAddr % pcv.widthInCtus) * pcv.maxCUSize, (ctuRsAddr / pcv.widthInCtus) * pcv.maxCUSize);
576
4.65k
        const CompArea ctuArea   = clipArea (CompArea (COMP_Y, pic->chromaFormat, Area (pos.x, pos.y, pcv.maxCUSize, pcv.maxCUSize)), pic->Y());
577
4.65k
        const SizeType fltWidth  = pcv.maxCUSize + guardSize * (pos.x > 0 ? 2 : 1);
578
4.65k
        const SizeType fltHeight = pcv.maxCUSize + guardSize * (pos.y > 0 ? 2 : 1);
579
4.65k
        const CompArea fltArea   = clipArea (CompArea (COMP_Y, pic->chromaFormat, Area (pos.x > 0 ? pos.x - guardSize : 0, pos.y > 0 ? pos.y - guardSize : 0, fltWidth, fltHeight)), pic->Y());
580
4.65k
        const CPelBuf  picOrig   = pic->getOrigBuf (fltArea);
581
4.65k
        const CPelBuf  picPrv1   = pic->getOrigBufPrev (fltArea, PREV_FRAME_1);
582
4.65k
        const CPelBuf  picPrv2   = pic->getOrigBufPrev (fltArea, PREV_FRAME_2);
583
4.65k
        unsigned minActivityPart = 0, spVisActCTU = 0;
584
585
4.65k
        hpEner[1] = filterAndCalculateAverageActivity (picOrig.buf, picOrig.stride, picOrig.height, picOrig.width,
586
4.65k
                                                       picPrv1.buf, picPrv1.stride, picPrv2.buf, picPrv2.stride, hpFrameRate,
587
4.65k
                                                       bitDepth, isHighResolution, &minActivityPart, &spVisActCTU);
588
589
4.65k
        if (minActivityPart == 0) zeroMinActCTUs++;
590
591
4.65k
        hpEner[comp] += hpEner[1] * double (ctuArea.width * ctuArea.height);
592
4.65k
        pic->ctuQpaLambda[ctuRsAddr] = hpEner[1]; // temporary backup of CTU mean visual activity
593
4.65k
        pic->ctuAdaptedQP[ctuRsAddr] = (int) pic->getOrigBuf (ctuArea).getAvg(); // and mean luma
594
595
4.65k
        if (picOrig.buf == picPrv1.buf) // replace temporal visual activity with min motion error
596
4.65k
        {
597
4.65k
          hpEner[1] = pic->m_picShared->m_minNoiseLevels[pic->ctuAdaptedQP[ctuRsAddr] >> (bitDepth - 3)] * (bitDepth >= 10 ? 1.5 : 0.375);
598
599
4.65k
          if (hpEner[1] < (bitDepth >= 10 ? 382.5 : 95.625)) // levels in first frame
600
0
          {
601
0
            hpEner[comp] += hpEner[1] * double (ctuArea.width * ctuArea.height);
602
0
            pic->ctuQpaLambda[ctuRsAddr] += hpEner[1]; // add noise level to mean visual activity
603
0
          }
604
4.65k
        }
605
0
        else if (!isEncPass && (encCfg->m_RCNumPasses == 2 || pic->gopEntry->m_mctfIndex < 0 || !pic->gopEntry->m_isStartOfGop))
606
0
        {
607
0
          updateMinNoiseLevelsPic (pic->m_picShared->m_minNoiseLevels, bitDepth, pic->ctuAdaptedQP[ctuRsAddr], minActivityPart);
608
0
        }
609
4.65k
        picSpVisAct += spVisActCTU;
610
4.65k
      }
611
612
1.43k
      hpEner[comp] /= double (encCfg->m_SourceWidth * encCfg->m_SourceHeight);
613
1.43k
      if (picVisActLuma != nullptr)
614
1.43k
      {
615
1.43k
        *picVisActLuma = ClipBD (uint16_t (0.5 + hpEner[comp]), bitDepth);
616
1.43k
      }
617
1.43k
      if (ctuBoundingAddr > ctuStartAddr)
618
1.43k
      {
619
1.43k
        const uint32_t nCtu = ctuBoundingAddr - ctuStartAddr;
620
621
1.43k
        pic->picVA.spatAct[ CH_L ] = ClipBD (uint16_t ((picSpVisAct + (nCtu >> 1)) / nCtu), 12);
622
1.43k
      }
623
1.43k
      if (encCfg->m_internalUsePerceptQPATempFiltISlice && slice->isIntra() && pic->getOrigBuf (compID).buf != pic->getOrigBufPrev (compID, PREV_FRAME_1).buf && zeroMinActCTUs * 2 > ctuBoundingAddr - ctuStartAddr)
624
0
      {
625
0
        hpEnerPicNorm *= sqrt (zeroMinActCTUs * 2.0 / float (ctuBoundingAddr - ctuStartAddr)); // frozen-image mode
626
0
      }
627
1.43k
    }
628
2.86k
    else // chroma: only picture-wise operation required
629
2.86k
    {
630
2.86k
      const CPelBuf picOrig = pic->getOrigBuf (compID);
631
2.86k
      const CPelBuf picPrv1 = pic->getOrigBufPrev (compID, PREV_FRAME_1);
632
2.86k
      const CPelBuf picPrv2 = pic->getOrigBufPrev (compID, PREV_FRAME_2);
633
634
2.86k
      hpEner[comp] = filterAndCalculateAverageActivity (picOrig.buf, picOrig.stride, picOrig.height, picOrig.width,
635
2.86k
                                                        picPrv1.buf, picPrv1.stride, picPrv2.buf, picPrv2.stride, hpFrameRate,
636
2.86k
                                                        bitDepth, isHighResolution && (pic->chromaFormat == CHROMA_444));
637
638
2.86k
      const int adaptChromaQPOffset = 1.5 * hpEner[comp] <= hpEner[0] ? 0 : apprI3Log2 (1.5 * hpEner[comp] / hpEner[0], pic->isSccStrong);
639
640
2.86k
      if (averageAdaptedLumaQP == QPA_QP_NOT_SET) // YUV is not 4:0:0!
641
1.43k
      {
642
1.43k
        averageAdaptedLumaQP = Clip3 (minQP, MAX_QP, sliceQP + apprI3Log2 (hpEner[0] * hpEnerPicNorm, isSccStrongRC));
643
644
1.43k
        if (isChromaEnabled (pic->chromaFormat) && (averageAdaptedLumaQP < MAX_QP))
645
1.43k
        {
646
1.43k
          averageAdaptedLumaQP += getGlaringColorQPOffset (pic, -1 /*ctuAddr*/, slice->sps->bitDepths[CH_C], meanLuma);
647
648
1.43k
          if ((averageAdaptedLumaQP > MAX_QP) && !isHDR) averageAdaptedLumaQP = MAX_QP;
649
1.43k
        }
650
        // change mean picture QP index based on picture's average luma value (Sharp)
651
1.43k
        if (isHDR)
652
0
        {
653
0
          if (meanLuma == MAX_UINT) meanLuma = pic->getOrigBuf().Y().getAvg();
654
655
0
          averageAdaptedLumaQP = Clip3 (minQP, MAX_QP, averageAdaptedLumaQP + lumaDQPOffset (meanLuma, bitDepth));
656
0
        }
657
1.43k
      }
658
659
2.86k
      if (optChromaQPOffsets != nullptr) // adapts sliceChromaQpOffsetIntraOrPeriodic
660
2.86k
      {
661
        GCC_WARNING_DISABLE_maybe_uninitialized // probably spurious warning, when building with -fsanitize=undefined: "error: 'encCfg.33' may be used uninitialized in this function"
662
2.86k
        const int lumaChromaMappingDQP = (averageAdaptedLumaQP - slice->sps->chromaQpMappingTable.getMappedChromaQpValue (compID, averageAdaptedLumaQP)) >> (encCfg->m_HdrMode == vvencHDRMode::VVENC_HDR_OFF ? 1 : 2);
663
2.86k
        GCC_WARNING_RESET
664
2.86k
        optChromaQPOffsets[comp - 1] = std::min (3 + lumaChromaMappingDQP, adaptChromaQPOffset + lumaChromaMappingDQP);
665
2.86k
      }
666
2.86k
    } // isLuma or isChroma
667
4.29k
  }
668
669
1.43k
  if (averageAdaptedLumaQP == QPA_QP_NOT_SET) // only if YUV is 4:0:0!
670
0
  {
671
0
    averageAdaptedLumaQP = Clip3 (minQP, MAX_QP, sliceQP + apprI3Log2 (hpEner[0] * hpEnerPicNorm, isSccStrongRC));
672
673
    // change mean picture QP index based on the picture's average luma value (Sharp)
674
0
    if (isHDR)
675
0
    {
676
0
      if (meanLuma == MAX_UINT) meanLuma = pic->getOrigBuf().Y().getAvg();
677
678
0
      averageAdaptedLumaQP = Clip3 (minQP, MAX_QP, averageAdaptedLumaQP + lumaDQPOffset (meanLuma, bitDepth));
679
0
    }
680
0
  }
681
682
1.43k
  if (encCfg->m_RCNumPasses == 2 && (encCfg->m_RCTargetBitrate > 0) && (ctuRCQPMemory != nullptr) && slice->pps->useDQP && (encCfg->m_internalUsePerceptQPATempFiltISlice == 2) && slice->isIntra())
683
0
  {
684
0
    const int nCtu = int (ctuBoundingAddr - ctuStartAddr);
685
0
    const int offs = (slice->poc / encCfg->m_IntraPeriod) * ((nCtu + 1) >> 1);
686
0
    std::vector<uint8_t>& ctuQPMem = *ctuRCQPMemory; // unpack 1st-pass reduction QPs
687
688
0
    if ((ctuPumpRedQP.size() >= nCtu) && (ctuQPMem.size() >= offs + ((nCtu + 1) >> 1)))
689
0
    {
690
0
      for (uint32_t ctuRsAddr = ctuStartAddr; ctuRsAddr < ctuBoundingAddr; ctuRsAddr++)
691
0
      {
692
0
        ctuPumpRedQP[ctuRsAddr] = int ((ctuRsAddr & 1) ? ctuQPMem[offs + (ctuRsAddr >> 1)] >> 4 : ctuQPMem[offs + (ctuRsAddr >> 1)] & 15) - 8;
693
0
      }
694
0
    }
695
0
  }
696
697
1.43k
  if (useFrameWiseQPA || (averageAdaptedLumaQP >= MAX_QP)) // store the CTU-wise QP/lambda values
698
0
  {
699
0
    averageAdaptedLumaQP = std::min (MAX_QP, averageAdaptedLumaQP + 1);
700
0
    averageAdaptedLambda = sliceLambda * pow (2.0, double (averageAdaptedLumaQP - sliceQP) / 3.0);
701
702
0
    for (uint32_t ctuRsAddr = ctuStartAddr; ctuRsAddr < ctuBoundingAddr; ctuRsAddr++)
703
0
    {
704
0
      pic->ctuQpaLambda[ctuRsAddr] = averageAdaptedLambda; // save adapted lambda, QP
705
0
      pic->ctuAdaptedQP[ctuRsAddr] = averageAdaptedLumaQP;
706
0
    }
707
0
  }
708
1.43k
  else // use CTU-level QPA
709
1.43k
  {
710
1.43k
    const int nCtu = int (ctuBoundingAddr - ctuStartAddr);
711
1.43k
    const int dvsr = encCfg->m_IntraPeriod - encCfg->m_GOPSize;
712
1.43k
    const int aaQP = averageAdaptedLumaQP; // backup of initial average QP from above
713
1.43k
    const bool rcIsFirstPassOf2 = ((encCfg->m_RCTargetBitrate == 0) && (ctuRCQPMemory != nullptr) && slice->pps->useDQP && (slice->poc > 0) ? encCfg->m_RCNumPasses == 2 : false);
714
715
1.43k
    if (isEncPass) ctuAvgLuma.resize (nCtu);
716
717
1.43k
    averageAdaptedLumaQP = 0;
718
6.08k
    for (uint32_t ctuRsAddr = ctuStartAddr; ctuRsAddr < ctuBoundingAddr; ctuRsAddr++)
719
4.65k
    {
720
4.65k
      const double hpEnerCTU = pic->ctuQpaLambda[ctuRsAddr];
721
4.65k
      int adaptedLumaQP = Clip3 (minQP, MAX_QP, sliceQP + apprI3Log2 (hpEnerCTU * hpEnerPicNorm, isSccStrongRC));
722
723
4.65k
      if ((encCfg->m_internalUsePerceptQPATempFiltISlice == 2) && slice->isIntra() && (ctuPumpRedQP.size() > ctuRsAddr))
724
0
      {
725
0
        if (rcIsFirstPassOf2) // backup 1st-pass I-frame QP for 2nd rate control pass
726
0
        {
727
0
          if (ctuRsAddr & 1) ctuRCQPMemory->back() |= (Clip3 (-8, 7, ctuPumpRedQP[ctuRsAddr]) + 8) << 4;
728
0
          else /*even addr*/ ctuRCQPMemory->push_back (Clip3 (-8, 7, ctuPumpRedQP[ctuRsAddr]) + 8);
729
0
          if (adaptedLumaQP > 0)
730
0
          {
731
0
            adaptedLumaQP -= (aaQP >> 4); // some first-pass tuning for stabilization
732
0
          }
733
0
        }
734
0
        if (ctuPumpRedQP[ctuRsAddr] < 0) adaptedLumaQP = Clip3 (minQP, MAX_QP, adaptedLumaQP + (ctuPumpRedQP[ctuRsAddr] * encCfg->m_GOPSize - (dvsr >> 1)) / dvsr);
735
0
        else /*ctuPumpRedQP[addr] >= 0*/ adaptedLumaQP = Clip3 (minQP, MAX_QP, adaptedLumaQP + (ctuPumpRedQP[ctuRsAddr] * encCfg->m_GOPSize + (dvsr >> 1)) / dvsr);
736
737
0
        ctuPumpRedQP[ctuRsAddr] = 0; // reset QP memory for temporal pumping analysis
738
0
      }
739
4.65k
      if ((encCfg->m_internalUsePerceptQPATempFiltISlice == 2) && !slice->isIntra() && (slice->TLayer == 0) && rcIsFirstPassOf2 && (adaptedLumaQP < MAX_QP))
740
0
      {
741
0
        adaptedLumaQP++; // this is a first-pass tuning to stabilize the rate control
742
0
      }
743
4.65k
      meanLuma = MAX_UINT;
744
4.65k
      if (isChromaEnabled (pic->chromaFormat) && (adaptedLumaQP < MAX_QP))
745
4.65k
      {
746
4.65k
        adaptedLumaQP += getGlaringColorQPOffset (pic, (int) ctuRsAddr, slice->sps->bitDepths[CH_C], meanLuma);
747
748
4.65k
        if ((adaptedLumaQP > MAX_QP) && !isHDR) adaptedLumaQP = MAX_QP;
749
4.65k
      }
750
      // change the CTU-level QP index based on CTU area's average luma value (Sharp)
751
4.65k
      if (isHDR)
752
0
      {
753
0
        if (meanLuma == MAX_UINT) meanLuma = pic->ctuAdaptedQP[ctuRsAddr];
754
755
0
        adaptedLumaQP = Clip3 (minQP, MAX_QP, adaptedLumaQP + lumaDQPOffset (meanLuma, bitDepth));
756
0
      }
757
      // add further delta-QP of block importance mapping (BIM) detector if available
758
4.65k
      if (isBIM)
759
0
      {
760
0
        adaptedLumaQP = Clip3 (-slice->sps->qpBDOffset[CH_L], MAX_QP, adaptedLumaQP + pic->m_picShared->m_ctuBimQpOffset[ctuRsAddr]);
761
0
      }
762
      // reduce delta-QP variance, avoid wasting precious bit budget at low bit-rates
763
4.65k
      if ((encCfg->m_RCTargetBitrate == 0) && (3 + encCfg->m_QP > MAX_QP_PERCEPT_QPA) && (encCfg->m_framesToBeEncoded != 1))
764
735
      {
765
735
        const int retunedAdLumaQP = adaptedLumaQP + 1;
766
767
735
        adaptedLumaQP = (std::max (0, 1 + MAX_QP_PERCEPT_QPA - encCfg->m_QP) * adaptedLumaQP + std::min (4, 3 + encCfg->m_QP - MAX_QP_PERCEPT_QPA) * aaQP + 2) >> 2;
768
735
        if (adaptedLumaQP > retunedAdLumaQP) adaptedLumaQP = retunedAdLumaQP;
769
735
        if (adaptedLumaQP < MAX_QP && encCfg->m_QP == MAX_QP_PERCEPT_QPA && slice->TLayer > 1) adaptedLumaQP++; // a fine-tuning
770
735
      }
771
4.65k
      if (isEncPass) ctuAvgLuma[ctuRsAddr - ctuStartAddr] = pic->ctuAdaptedQP[ctuRsAddr];
772
773
4.65k
      averageAdaptedLambda = sliceLambda * pow (2.0, double (adaptedLumaQP - sliceQP) / 3.0);
774
4.65k
      averageAdaptedLumaQP += adaptedLumaQP;
775
776
4.65k
      pic->ctuQpaLambda[ctuRsAddr] = averageAdaptedLambda; // save adapted lambda, QP
777
4.65k
      pic->ctuAdaptedQP[ctuRsAddr] = adaptedLumaQP;
778
4.65k
    }
779
780
1.43k
    if (encCfg->m_cuQpDeltaSubdiv == 0 || !slice->isIntra()) averageAdaptedLumaQP += applyDeltaQpPeakSmoothing (pic, encCfg, ctuStartAddr, ctuBoundingAddr);
781
782
1.43k
    const int qpSum = std::max (minQP * nCtu, averageAdaptedLumaQP);
783
1.43k
    averageAdaptedLumaQP = (qpSum + (qpSum < 0 ? -(nCtu >> 1) : nCtu >> 1)) / nCtu;
784
785
1.43k
    if ((encCfg->m_RCTargetBitrate > 0 && averageAdaptedLumaQP != sliceQP) || (isEncPass) || (encCfg->m_LookAhead > 0 && pic->isPreAnalysis) ) // QP/rate control
786
0
    {
787
0
      const int rcQpDiff = (encCfg->m_RCTargetBitrate > 0 || (encCfg->m_LookAhead > 0 && pic->isPreAnalysis) ? sliceQP - averageAdaptedLumaQP : 0);
788
789
0
      averageAdaptedLumaQP = refineDeltaQpDistribution (pic, encCfg, sliceQP, sliceLambda, rcQpDiff, bitDepth, ctuStartAddr, ctuBoundingAddr,
790
0
                                                        qpSum, slice->TLayer, slice->isIntra(), isEncPass, minNoiseLevels, ctuAvgLuma);
791
792
0
      pic->picInitialQP = Clip3 (minQP, MAX_QP, pic->picInitialQP + rcQpDiff); // used in applyQPAdaptationSubCtu
793
0
      pic->isMeanQPLimited = (encCfg->m_RCTargetBitrate > 0) && isEncPass && (averageAdaptedLumaQP > sliceQP);
794
0
    }
795
1.43k
    else if (encCfg->m_rateCap && (pic->gopAdaptedQP > 0) && (averageAdaptedLumaQP < aaQP)) // capped CQF
796
0
    {
797
0
      const int rcQpDiff = aaQP - averageAdaptedLumaQP;
798
799
0
      averageAdaptedLambda = pow (2.0, double (rcQpDiff) / 3.0);
800
0
      for (uint32_t ctuRsAddr = ctuStartAddr; ctuRsAddr < ctuBoundingAddr; ctuRsAddr++)
801
0
      {
802
0
        pic->ctuQpaLambda[ctuRsAddr] *= averageAdaptedLambda; // scale adapted lambda
803
0
        pic->ctuAdaptedQP[ctuRsAddr] = std::min (MAX_QP, pic->ctuAdaptedQP[ctuRsAddr] + rcQpDiff);
804
0
      }
805
806
0
      pic->picInitialQP = Clip3 (minQP, MAX_QP, pic->picInitialQP + rcQpDiff); // used in applyQPAdaptationSubCtu
807
0
      averageAdaptedLumaQP = aaQP;
808
0
    }
809
1.43k
    else if ((encCfg->m_RCTargetBitrate == 0) && (3 + encCfg->m_QP > MAX_QP_PERCEPT_QPA) && (encCfg->m_framesToBeEncoded != 1) && (averageAdaptedLumaQP + 1 < aaQP))
810
0
    {
811
0
      const int lrQpDiff = (aaQP - averageAdaptedLumaQP) >> (encCfg->m_QP <= MAX_QP_PERCEPT_QPA ? 2 : 1); // for monotonous rate change at low rates
812
813
0
      averageAdaptedLambda = pow (2.0, double (lrQpDiff) / 3.0);
814
0
      for (uint32_t ctuRsAddr = ctuStartAddr; ctuRsAddr < ctuBoundingAddr; ctuRsAddr++)
815
0
      {
816
0
        pic->ctuQpaLambda[ctuRsAddr] *= averageAdaptedLambda; // scale adapted lambda
817
0
        pic->ctuAdaptedQP[ctuRsAddr] = std::min (MAX_QP, pic->ctuAdaptedQP[ctuRsAddr] + lrQpDiff);
818
0
      }
819
820
0
      pic->picInitialQP = Clip3 (minQP, MAX_QP, pic->picInitialQP + lrQpDiff); // used in applyQPAdaptationSubCtu
821
0
      averageAdaptedLumaQP = aaQP; // TODO hlm: += lrQpDiff?
822
823
0
      pic->isMeanQPLimited = false;
824
0
    }
825
826
1.43k
    if (isEncPass) ctuAvgLuma.clear();
827
1.43k
  } // CTU-/frame-level QPA
828
829
1.43k
  return averageAdaptedLumaQP;
830
1.43k
}
831
832
int BitAllocation::applyQPAdaptationSubCtu (const Slice* slice, const VVEncCfg* encCfg, const Area& lumaArea, const uint8_t* minNoiseLevels)
833
4.16k
{
834
4.16k
  Picture* const pic          = (slice != nullptr ? slice->pic : nullptr);
835
4.16k
  uint32_t meanLuma           = MAX_UINT;
836
837
4.16k
  if (pic == nullptr || encCfg == nullptr)
838
0
  {
839
0
    return QPA_QP_NOT_SET;
840
0
  }
841
842
4.16k
  const bool isEncPass        = (encCfg->m_LookAhead > 0 && !pic->isPreAnalysis);
843
4.16k
  const bool isHDR            = encCfg->m_HdrMode != vvencHDRMode::VVENC_HDR_OFF;
844
4.16k
  const bool isBIM            = (encCfg->hasBlockQpOffsets() && !pic->m_picShared->m_ctuBimQpOffset.empty());
845
4.16k
  const bool isSccStrongRC    = ((encCfg->m_LookAhead > 0 || encCfg->m_RCNumPasses == 2) && pic->isSccStrong);
846
4.16k
  const bool isHighResolution = (std::min (encCfg->m_SourceWidth, encCfg->m_SourceHeight) > 1280);
847
4.16k
  const int  minQP            = getMinAdaptedQP (slice, encCfg);
848
4.16k
  const uint32_t hpFrameRate  = (pic->force2ndOrder ? 32 : encCfg->m_FrameRate / encCfg->m_FrameScale);
849
4.16k
  const int  bitDepth         = slice->sps->bitDepths[CH_L];
850
4.16k
  const PosType     guardSize = (isHighResolution ? 2 : 1);
851
4.16k
  const Position    pos       = lumaArea.pos();
852
4.16k
  const CompArea    subArea   = clipArea (CompArea (COMP_Y, pic->chromaFormat, Area (pos.x, pos.y, lumaArea.width, lumaArea.height)), pic->Y());
853
4.16k
  const SizeType    fltWidth  = lumaArea.width  + guardSize * (pos.x > 0 ? 2 : 1);
854
4.16k
  const SizeType    fltHeight = lumaArea.height + guardSize * (pos.y > 0 ? 2 : 1);
855
4.16k
  const CompArea    fltArea   = clipArea (CompArea (COMP_Y, pic->chromaFormat, Area (pos.x > 0 ? pos.x - guardSize : 0, pos.y > 0 ? pos.y - guardSize : 0, fltWidth, fltHeight)), pic->Y());
856
4.16k
  const CPelBuf     picOrig   = pic->getOrigBuf (fltArea);
857
4.16k
  const CPelBuf     picPrv1   = pic->getOrigBufPrev (fltArea, PREV_FRAME_1);
858
4.16k
  const CPelBuf     picPrv2   = pic->getOrigBufPrev (fltArea, PREV_FRAME_2);
859
4.16k
  const double hpEnerSubCTU   = filterAndCalculateAverageActivity (picOrig.buf, picOrig.stride, picOrig.height, picOrig.width,
860
4.16k
                                                                   picPrv1.buf, picPrv1.stride, picPrv2.buf, picPrv2.stride, hpFrameRate,
861
4.16k
                                                                   bitDepth, isHighResolution);
862
4.16k
  const double hpEnerPicNorm  = fractionalQPActivityScale (pic->picQPFraction, isSccStrongRC)
863
4.16k
                              / getAveragePictureActivity (encCfg->m_SourceWidth, encCfg->m_SourceHeight, 0,
864
4.16k
                                                           (encCfg->m_internalUsePerceptQPATempFiltISlice || !slice->isIntra()), bitDepth);
865
4.16k
  int adaptedSubCtuQP = Clip3 (minQP, MAX_QP, pic->picInitialQP + apprI3Log2 (hpEnerSubCTU * hpEnerPicNorm, isSccStrongRC));
866
867
4.16k
  if (isChromaEnabled (pic->chromaFormat) && (adaptedSubCtuQP < MAX_QP))
868
4.16k
  {
869
4.16k
    adaptedSubCtuQP += getGlaringColorQPOffsetSubCtu (pic, subArea, slice->sps->bitDepths[CH_C], meanLuma);
870
871
4.16k
    if ((adaptedSubCtuQP > MAX_QP) && !isHDR) adaptedSubCtuQP = MAX_QP;
872
4.16k
  }
873
  // change the sub-CTU-level QP index based on sub-area's average luma value (Sharp)
874
4.16k
  if (isHDR)
875
0
  {
876
0
    if (meanLuma == MAX_UINT) meanLuma = pic->getOrigBuf (subArea).getAvg();
877
878
0
    adaptedSubCtuQP = Clip3 (minQP, MAX_QP, adaptedSubCtuQP + lumaDQPOffset (meanLuma, bitDepth));
879
0
  }
880
  // add additional delta-QP of block importance mapping (BIM) detection if available
881
4.16k
  if (isBIM)
882
0
  {
883
0
    adaptedSubCtuQP = Clip3 (-slice->sps->qpBDOffset[CH_L], MAX_QP, adaptedSubCtuQP + pic->m_picShared->m_ctuBimQpOffset[getCtuAddr (pos, *pic->cs->pcv)]);
884
0
  }
885
  // reduce the delta-QP variance, avoid wasting precious bit budget at low bit-rates
886
4.16k
  if ((encCfg->m_RCTargetBitrate == 0) && (3 + encCfg->m_QP > MAX_QP_PERCEPT_QPA) && (slice->sliceQp >= 0) && (encCfg->m_framesToBeEncoded != 1))
887
0
  {
888
0
    const int retunedAdLumaQP = adaptedSubCtuQP + 1;
889
890
0
    adaptedSubCtuQP = (std::max (0, 1 + MAX_QP_PERCEPT_QPA - encCfg->m_QP) * adaptedSubCtuQP + std::min (4, 3 + encCfg->m_QP - MAX_QP_PERCEPT_QPA) * slice->sliceQp + 2) >> 2;
891
0
    if (adaptedSubCtuQP > retunedAdLumaQP) adaptedSubCtuQP = retunedAdLumaQP;
892
0
    if (adaptedSubCtuQP < MAX_QP && encCfg->m_QP >= MAX_QP_PERCEPT_QPA) adaptedSubCtuQP++; // for monotonous rate change, l. 507
893
0
  }
894
4.16k
  if (isEncPass)
895
0
  {
896
0
    const double resRatio = sqrt (double (encCfg->m_SourceWidth * encCfg->m_SourceHeight) / (3840.0 * 2160.0));
897
898
0
    if (meanLuma == MAX_UINT) meanLuma = pic->getOrigBuf (subArea).getAvg();
899
0
    clipQPValToEstimatedMinimStats (minNoiseLevels, bitDepth, meanLuma, resRatio, (slice->isIntra() ? encCfg->m_intraQPOffset >> 1 : std::min (4, (int) slice->TLayer)), adaptedSubCtuQP);
900
0
  }
901
902
4.16k
  return adaptedSubCtuQP;
903
4.16k
}
904
905
int BitAllocation::getCtuPumpingReducingQP (const Slice* slice, const CPelBuf& origY, const Distortion uiSadBestForQPA,
906
                                            std::vector<int>& ctuPumpRedQP, const uint32_t ctuRsAddr, const int baseQP,
907
                                            const bool isBIM)
908
0
{
909
0
  if (slice == nullptr || !slice->pps->useDQP || ctuPumpRedQP.size() <= ctuRsAddr) return 0;
910
911
0
  const int32_t avgOrig = origY.getAvg();
912
  // sum up the zero-mean absolute values
913
0
  const uint32_t sumAbsZmOrig = g_pelBufOP.sumAbsDeviation (origY.buf, origY.stride, origY.width, origY.height, avgOrig);
914
915
0
  const double sumAbsRatio = double (uiSadBestForQPA * 3 /*TODO: or 4? fine-tune!*/) / double (sumAbsZmOrig == 0 ? 1 : sumAbsZmOrig);
916
0
  const int pumpingReducQP = ((isBIM ? -1 : 0) + int (log (Clip3 (0.25, 4.0, sumAbsRatio)) / log (2.0) + (sumAbsRatio < 1.0 ? -0.5 : 0.5))) >> (baseQP >= 38/*MAX_QP_PERCEPT_QPA*/ ? 1 : 0);
917
918
0
  ctuPumpRedQP[ctuRsAddr] += pumpingReducQP;
919
920
0
  return pumpingReducQP;
921
0
}
922
923
} // namespace vvenc
924
925
//! \}