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/CuTree.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     CuTree.cpp
45
    \brief    look-ahead stage for CU-tree adaptive quantization
46
47
    Implements the temporal dependency model (TPL) of
48
    J. Han, P. Wilkins, Y. Xu, J. Bankoski, "A quantitative approach to the temporal dependency in video coding",
49
    arXiv:2108.11586, 2021 (https://arxiv.org/abs/2108.11586). The equation numbers in the comments refer to it.
50
*/
51
52
#include "CuTree.h"
53
#include "EncSlice.h"
54
#include "CommonLib/Picture.h"
55
#include "Utilities/NoMallocThreadPool.h"
56
57
#include <algorithm>
58
#include <atomic>
59
#include <cmath>
60
#include <condition_variable>
61
#include <memory>
62
#include <mutex>
63
#include <vector>
64
65
//! \ingroup EncoderLib
66
//! \{
67
68
namespace vvenc {
69
70
static constexpr int MAX_BLK_SIZE = tplBlkSide( NUM_TPL_BLK_SIZES - 1 );   // largest analysis block, half resolution
71
static constexpr int MV_PREC      = 16;                    // motion vectors are in 1/16 sample, as in MCTF
72
static constexpr int NUM_LEVELS   = 3;                     // half, quarter and eighth resolution
73
static constexpr int NO_REF       = MAX_INT;
74
// Border of the half-resolution pictures. Motion search and prediction clamp reads that go beyond it.
75
static constexpr int LOWRES_PAD   = 32;
76
77
enum CuTreePred : uint8_t
78
{
79
  CTP_INTRA = 0,
80
  CTP_L0    = 1,
81
  CTP_L1    = 2,
82
  CTP_BI    = 3
83
};
84
85
// Analysis data of one picture. Distortions are squared errors of full-resolution samples.
86
struct CuTree::Frame
87
{
88
  int                   poc       = 0;
89
  int                   codingNum = 0;
90
  int                   qp        = 0;       // the picture's QP from the temporal-layer cascade
91
  bool                  isIntra   = false;
92
  bool                  isIrap    = false;   // an IRAP picture (CRA or IDR), see xMarkRandomAccess
93
  bool                  isIdr     = false;   // an IDR picture, which removes every picture coded before it
94
  bool                  analysed  = false;
95
  bool                  hasImages = true;    // lowRes and recon are kept while other pictures can reference them
96
  int                   refPoc[2] = { NO_REF, NO_REF };
97
  int                   picQpOffset = 0;     // BIM 2's picture-level QP offset, see xSetPicQpOffsets
98
  PelStorage            lowRes[NUM_LEVELS];
99
  PelStorage            recon;               // half-resolution reconstruction at the picture's QP
100
  Array2D<MotionVector> mvs[2];              // half-resolution motion towards refPoc[0] and refPoc[1]
101
  std::vector<uint8_t>  predMode;
102
  std::vector<float>    distRec;             // distortion of the coded block, predicted from reconstructed references
103
  std::vector<float>    distSrc[2];          // the same with reference l replaced by its original
104
  std::vector<float>    deltaDist[2];        // extra distortion and rate caused by the coding error of reference l
105
  std::vector<float>    deltaRate[2];
106
  std::vector<double>   propDist;            // distortion and rate that later pictures owe to each block
107
  std::vector<double>   propRate;
108
};
109
110
// ====================================================================================================================
111
// Block helpers
112
// ====================================================================================================================
113
114
// The encoder's own (SIMD) Hadamard SATD of the difference between two analysis blocks.
115
struct BlockSatd
116
{
117
  FpDistFunc func;
118
  int        bitDepth;
119
  int        size;
120
121
  int operator()( const Pel* org, ptrdiff_t orgStride, const Pel* pred, ptrdiff_t predStride ) const
122
0
  {
123
0
    const DistParam dp( org, ( int ) orgStride, pred, ( int ) predStride, size, size, func, bitDepth, 0, COMP_Y );
124
0
    return ( int ) func( dp );
125
0
  }
126
};
127
128
template<int N>
129
void tplPredBlockCore( const Pel* src, ptrdiff_t srcStride, int fx, int fy, Pel* dst )
130
0
{
131
0
  for( int j = 0; j < N; j++ )
132
0
  {
133
0
    const Pel* row0 = src + j * srcStride;
134
0
    const Pel* row1 = row0 + srcStride;
135
0
    for( int i = 0; i < N; i++ )
136
0
    {
137
0
      const int top    = row0[i] * ( MV_PREC - fx ) + row0[i + 1] * fx;
138
0
      const int bottom = row1[i] * ( MV_PREC - fx ) + row1[i + 1] * fx;
139
0
      dst[j * N + i] = Pel( ( top * ( MV_PREC - fy ) + bottom * fy + 128 ) >> 8 );
140
0
    }
141
0
  }
142
0
}
Unexecuted instantiation: void vvenc::tplPredBlockCore<8>(short const*, long, int, int, short*)
Unexecuted instantiation: void vvenc::tplPredBlockCore<16>(short const*, long, int, int, short*)
143
144
template void tplPredBlockCore<8> ( const Pel* src, ptrdiff_t srcStride, int fx, int fy, Pel* dst );
145
template void tplPredBlockCore<16>( const Pel* src, ptrdiff_t srcStride, int fx, int fy, Pel* dst );
146
147
void tplDownsampleRowCore( const Pel* src, ptrdiff_t srcStride, Pel* dst, int dstWidth )
148
0
{
149
0
  const Pel* below = src + srcStride;
150
0
  for( int x = 0; x < dstWidth; x++ )
151
0
  {
152
0
    dst[x] = Pel( ( src[2 * x] + src[2 * x + 1] + below[2 * x] + below[2 * x + 1] + 2 ) >> 2 );
153
0
  }
154
0
}
155
156
// Bilinear prediction of the n x n block at (x, y) displaced by mv (1/16 sample). Positions outside the padded
157
// reference repeat its edge, as the motion search does.
158
static void predictBlock( TplPredBlockFn predBlock, int n, const CPelBuf& ref, int x, int y, const MotionVector& mv, Pel* dst )
159
0
{
160
0
  const int fx = mv.x & ( MV_PREC - 1 );
161
0
  const int fy = mv.y & ( MV_PREC - 1 );
162
0
  const int x0 = x + ( mv.x >> 4 );
163
0
  const int y0 = y + ( mv.y >> 4 );
164
0
  const int minX = -LOWRES_PAD, maxX = ( int ) ref.width  + LOWRES_PAD - 1;
165
0
  const int minY = -LOWRES_PAD, maxY = ( int ) ref.height + LOWRES_PAD - 1;
166
167
0
  if( x0 >= minX && x0 + n <= maxX && y0 >= minY && y0 + n <= maxY )
168
0
  {
169
0
    predBlock( ref.buf + y0 * ref.stride + x0, ref.stride, fx, fy, dst );
170
0
    return;
171
0
  }
172
173
0
  for( int j = 0; j < n; j++ )
174
0
  {
175
0
    const Pel* row0 = ref.buf + Clip3( minY, maxY, y0 + j     ) * ref.stride;
176
0
    const Pel* row1 = ref.buf + Clip3( minY, maxY, y0 + j + 1 ) * ref.stride;
177
0
    for( int i = 0; i < n; i++ )
178
0
    {
179
0
      const int c0 = Clip3( minX, maxX, x0 + i );
180
0
      const int c1 = Clip3( minX, maxX, x0 + i + 1 );
181
0
      const int top    = row0[c0] * ( MV_PREC - fx ) + row0[c1] * fx;
182
0
      const int bottom = row1[c0] * ( MV_PREC - fx ) + row1[c1] * fx;
183
0
      dst[j * n + i] = Pel( ( top * ( MV_PREC - fy ) + bottom * fy + 128 ) >> 8 );
184
0
    }
185
0
  }
186
0
}
187
188
// The best of DC, vertical, horizontal and planar prediction of an N x N block from the neighbouring source samples,
189
// by SATD. The size is a template parameter so that the loops over the block keep a constant trip count.
190
template<int N>
191
static void predictIntra( const CPelBuf& pic, int x, int y, int bitDepth, const BlockSatd& satd, Pel* bestPred )
192
0
{
193
0
  static constexpr int n = N, log2n = N == 16 ? 4 : 3;
194
0
  const Pel* org     = pic.buf + y * pic.stride + x;
195
0
  const bool hasTop  = y > 0;
196
0
  const bool hasLeft = x > 0;
197
0
  Pel top[n], left[n];
198
0
  Pel pred[n * n];
199
200
0
  int sum = 0;
201
0
  for( int i = 0; i < n; i++ )
202
0
  {
203
0
    top[i]  = hasTop  ? org[i - pic.stride]     : 0;
204
0
    left[i] = hasLeft ? org[i * pic.stride - 1] : 0;
205
0
    sum    += ( hasTop ? top[i] : 0 ) + ( hasLeft ? left[i] : 0 );
206
0
  }
207
0
  const int num = ( hasTop ? n : 0 ) + ( hasLeft ? n : 0 );
208
209
0
  int best = MAX_INT;
210
0
  auto keepBest = [&]()
211
0
  {
212
0
    const int cost = satd( org, pic.stride, pred, n );
213
0
    if( cost < best )
214
0
    {
215
0
      best = cost;
216
0
      std::copy_n( pred, n * n, bestPred );
217
0
    }
218
0
  };
Unexecuted instantiation: CuTree.cpp:vvenc::predictIntra<16>(vvenc::AreaBuf<short const> const&, int, int, int, vvenc::BlockSatd const&, short*)::{lambda()#1}::operator()() const
Unexecuted instantiation: CuTree.cpp:vvenc::predictIntra<8>(vvenc::AreaBuf<short const> const&, int, int, int, vvenc::BlockSatd const&, short*)::{lambda()#1}::operator()() const
219
220
0
  const Pel dc = num ? Pel( ( sum + ( num >> 1 ) ) / num ) : Pel( 1 << ( bitDepth - 1 ) );
221
0
  std::fill_n( pred, n * n, dc );
222
0
  keepBest();
223
224
0
  if( hasTop )
225
0
  {
226
0
    for( int j = 0; j < n; j++ ) std::copy_n( top, n, pred + j * n );
227
0
    keepBest();
228
0
  }
229
0
  if( hasLeft )
230
0
  {
231
0
    for( int j = 0; j < n; j++ ) std::fill_n( pred + j * n, n, left[j] );
232
0
    keepBest();
233
0
  }
234
0
  if( hasTop && hasLeft )
235
0
  {
236
0
    for( int j = 0; j < n; j++ )
237
0
    {
238
0
      for( int i = 0; i < n; i++ )
239
0
      {
240
0
        const int hor = ( n - 1 - i ) * left[j] + ( i + 1 ) * top[n - 1];
241
0
        const int ver = ( n - 1 - j ) * top[i]  + ( j + 1 ) * left[n - 1];
242
0
        pred[j * n + i] = Pel( ( hor + ver + n ) >> ( log2n + 1 ) );
243
0
      }
244
0
    }
245
0
    keepBest();
246
0
  }
247
0
}
Unexecuted instantiation: CuTree.cpp:void vvenc::predictIntra<16>(vvenc::AreaBuf<short const> const&, int, int, int, vvenc::BlockSatd const&, short*)
Unexecuted instantiation: CuTree.cpp:void vvenc::predictIntra<8>(vvenc::AreaBuf<short const> const&, int, int, int, vvenc::BlockSatd const&, short*)
248
249
// 8-point Hadamard butterflies on v[0], v[s], ..., v[7 s].
250
static void hadamard8( int32_t* v, int s )
251
0
{
252
0
  const int32_t a0 = v[0] + v[4 * s], a1 = v[s] + v[5 * s], a2 = v[2 * s] + v[6 * s], a3 = v[3 * s] + v[7 * s];
253
0
  const int32_t a4 = v[0] - v[4 * s], a5 = v[s] - v[5 * s], a6 = v[2 * s] - v[6 * s], a7 = v[3 * s] - v[7 * s];
254
0
  const int32_t b0 = a0 + a2, b1 = a1 + a3, b2 = a0 - a2, b3 = a1 - a3;
255
0
  const int32_t b4 = a4 + a6, b5 = a5 + a7, b6 = a4 - a6, b7 = a5 - a7;
256
0
  v[0] = b0 + b1; v[s] = b0 - b1; v[2 * s] = b2 + b3; v[3 * s] = b2 - b3;
257
0
  v[4 * s] = b4 + b5; v[5 * s] = b4 - b5; v[6 * s] = b6 + b7; v[7 * s] = b6 - b7;
258
0
}
259
260
// 16-point Hadamard butterflies: one stage across the two halves, then the 8-point transform of each half.
261
static void hadamard16( int32_t* v, int s )
262
0
{
263
0
  for( int i = 0; i < 8; i++ )
264
0
  {
265
0
    const int32_t a = v[i * s], b = v[( i + 8 ) * s];
266
0
    v[i * s]       = a + b;
267
0
    v[( i + 8 ) * s] = a - b;
268
0
  }
269
0
  hadamard8( v, s );
270
0
  hadamard8( v + 8 * s, s );
271
0
}
272
273
// The Hadamard butterflies of one row or column of an N x N analysis block.
274
template<int N>
275
static void hadamardBlk( int32_t* v, int s )
276
0
{
277
0
  if( N == 16 ) hadamard16( v, s );
278
0
  else          hadamard8 ( v, s );
279
0
}
Unexecuted instantiation: CuTree.cpp:void vvenc::hadamardBlk<8>(int*, int)
Unexecuted instantiation: CuTree.cpp:void vvenc::hadamardBlk<16>(int*, int)
280
281
// The scalar block coder. Integer Hadamard butterflies are exact in any order, so the SIMD versions give the
282
// same numbers.
283
template<int N>
284
void tplCodeBlockCore( const Pel* org, ptrdiff_t orgStride, const Pel* pred, Pel* recon, ptrdiff_t reconStride,
285
                       const TplQuant& quant, int maxVal, int64_t& dist, int& bits )
286
0
{
287
0
  static constexpr int LOG2N = N == 16 ? 4 : 3;
288
0
  int32_t c[N * N];
289
0
  for( int y = 0; y < N; y++ )
290
0
  {
291
0
    for( int x = 0; x < N; x++ )
292
0
    {
293
0
      c[y * N + x] = org[y * orgStride + x] - pred[y * N + x];
294
0
    }
295
0
  }
296
0
  for( int y = 0; y < N; y++ ) hadamardBlk<N>( c + y * N, 1 );
297
0
  for( int x = 0; x < N; x++ ) hadamardBlk<N>( c + x, N );
298
299
0
  dist = 0;
300
0
  bits = 0;
301
0
  for( int i = 0; i < N * N; i++ )
302
0
  {
303
0
    const int32_t absCoeff = abs( c[i] );
304
0
    const int32_t level    = ( absCoeff * quant.scale + quant.round ) >> 16;
305
0
    const int32_t absDeq   = ( level * quant.deqStep + 8 ) >> 4;
306
0
    const int64_t err      = absCoeff - absDeq;
307
0
    dist += err * err;
308
0
    bits += level > 0 ? 2 * floorLog2( level ) + 3 : 0;
309
0
    c[i]  = c[i] < 0 ? -absDeq : absDeq;
310
0
  }
311
312
0
  if( recon )
313
0
  {
314
    // the unnormalised transform applied twice scales by N^2
315
0
    for( int y = 0; y < N; y++ ) hadamardBlk<N>( c + y * N, 1 );
316
0
    for( int x = 0; x < N; x++ ) hadamardBlk<N>( c + x, N );
317
0
    for( int y = 0; y < N; y++ )
318
0
    {
319
0
      for( int x = 0; x < N; x++ )
320
0
      {
321
0
        const int32_t res = ( c[y * N + x] + ( 1 << ( 2 * LOG2N - 1 ) ) ) >> ( 2 * LOG2N );
322
0
        recon[y * reconStride + x] = Pel( Clip3( 0, maxVal, pred[y * N + x] + res ) );
323
0
      }
324
0
    }
325
0
  }
326
0
}
Unexecuted instantiation: void vvenc::tplCodeBlockCore<8>(short const*, long, short const*, short*, long, vvenc::TplQuant const&, int, long&, int&)
Unexecuted instantiation: void vvenc::tplCodeBlockCore<16>(short const*, long, short const*, short*, long, vvenc::TplQuant const&, int, long&, int&)
327
328
template void tplCodeBlockCore<8> ( const Pel* org, ptrdiff_t orgStride, const Pel* pred, Pel* recon, ptrdiff_t reconStride,
329
                                    const TplQuant& quant, int maxVal, int64_t& dist, int& bits );
330
template void tplCodeBlockCore<16>( const Pel* org, ptrdiff_t orgStride, const Pel* pred, Pel* recon, ptrdiff_t reconStride,
331
                                    const TplQuant& quant, int maxVal, int64_t& dist, int& bits );
332
333
// Codes a half-resolution residual block the way TPL does with a Walsh-Hadamard transform. Distortion and rate are
334
// scaled to the full-resolution block it stands for, twice as wide and high: its low frequencies have twice the
335
// coefficient amplitude, so the step is halved and the squared error counts four times.
336
struct BlockCoder
337
{
338
  TplCodeBlockFn codeBlock;
339
  int            size;
340
  TplQuant       quant;
341
342
  // step of the orthonormal half-resolution coefficients, dead-zone rounding offset below one half
343
0
  BlockCoder( TplCodeBlockFn fn, int n, double step, double deadZone ) : codeBlock( fn ), size( n )
344
0
  {
345
0
    const double unnormStep = step * n;
346
0
    quant.scale   = int32_t( std::lround( 65536.0 / unnormStep ) );
347
0
    quant.round   = int32_t( std::lround( 65536.0 * deadZone ) );
348
0
    quant.deqStep = int32_t( std::lround( 16.0 * unnormStep ) );
349
0
  }
350
351
  struct Result
352
  {
353
    double dist;      // squared error, full-resolution scale
354
    double rate;      // estimated bits
355
  };
356
357
  Result code( const Pel* org, ptrdiff_t orgStride, const Pel* pred, Pel* recon, ptrdiff_t reconStride, int maxVal ) const
358
0
  {
359
0
    int64_t dist = 0;
360
0
    int     bits = 0;
361
0
    codeBlock( org, orgStride, pred, recon, reconStride, quant, maxVal, dist, bits );
362
    // unnormalised domain: size^2 times the sample error; full resolution: 4 times the half-resolution error
363
0
    return { double( dist ) / ( size * size / 4 ), double( bits ) };
364
0
  }
365
};
366
367
// Quantization step and Lagrange multiplier of a QP, in sample units of the internal bit depth.
368
static double qpToStep( int qp, int bitDepth )
369
0
{
370
0
  return std::pow( 2.0, ( qp - 4 ) / 6.0 ) * double( 1 << ( bitDepth - 8 ) );
371
0
}
372
373
static double qpToLambda( int qp, int bitDepth )
374
0
{
375
0
  return 0.57 * std::pow( 2.0, ( qp - 12 ) / 3.0 ) * double( 1 << ( 2 * ( bitDepth - 8 ) ) );
376
0
}
377
378
// The rate a block passes on for its own propagated rate R_prop: log2( 2^(2 R_prop) / ( r * 2^(2 R_prop) + 1 - r ) ),
379
// r = D_src / D_rec in [0, 1]. From R_prop = 512 bits on, 2^(2 R_prop) overflows to infinity and the expression
380
// becomes NaN (inf / inf, or 0 * inf for r = 0). The same value is -log2( r + ( 1 - r ) * 2^(-2 R_prop) ), in which
381
// 2^(-2 R_prop) <= 2^-1024 is far below double precision (a positive r is at least 1/64 / D_rec), so it is
382
// -log2( r ), or 2 R_prop for r = 0.
383
static double propagatedRate( double propRate, double growth, double srcRatio )
384
0
{
385
0
  if( std::isfinite( growth ) )
386
0
  {
387
0
    return std::log2( growth / ( srcRatio * growth + 1.0 - srcRatio ) );
388
0
  }
389
0
  return srcRatio > 0.0 ? -std::log2( srcRatio ) : 2.0 * propRate;
390
0
}
391
392
// ====================================================================================================================
393
// Stage
394
// ====================================================================================================================
395
396
CuTree::CuTree()
397
0
  : m_codeBlock    { tplCodeBlockCore<8>, tplCodeBlockCore<16> }
398
0
  , m_predBlock    { tplPredBlockCore<8>, tplPredBlockCore<16> }
399
0
  , m_downsampleRow( tplDownsampleRowCore )
400
0
  , m_encCfg       ( nullptr )
401
0
  , m_threadPool   ( nullptr )
402
0
  , m_motionSearch ( true )
403
0
  , m_hadFunc      ( nullptr )
404
0
  , m_lookAheadPics( 0 )
405
0
  , m_blkSizeIdx   ( TPL_BLK_8 )
406
0
  , m_blkSize      ( 8 )
407
0
  , m_blkWidth     ( 0 )
408
0
  , m_blkHeight    ( 0 )
409
0
  , m_qpBDOffset   ( 0 )
410
0
  , m_lambdaLeaf   ( 0.0 )
411
0
{
412
0
}
413
414
CuTree::~CuTree()
415
0
{
416
0
}
417
418
int CuTree::getNumLookAheadPics( const VVEncCfg& encCfg )
419
0
{
420
  // the key picture of a GOP is referenced by the whole next GOP
421
0
  return encCfg.m_GOPSize;
422
0
}
423
424
void CuTree::init( const VVEncCfg& encCfg, NoMallocThreadPool* threadPool )
425
0
{
426
0
  m_encCfg        = &encCfg;
427
0
  m_threadPool    = threadPool;
428
0
  m_lookAheadPics = getNumLookAheadPics( encCfg );
429
  // the configured size is that of the full-resolution block, 16 or 32
430
0
  m_blkSizeIdx    = encCfg.m_cuTreeBlockSize == 32 ? TPL_BLK_16 : TPL_BLK_8;
431
0
  m_blkSize       = tplBlkSide( m_blkSizeIdx );
432
0
  m_blkWidth      = ( encCfg.m_PadSourceWidth  / 2 ) / m_blkSize;
433
0
  m_blkHeight     = ( encCfg.m_PadSourceHeight / 2 ) / m_blkSize;
434
0
  m_qpBDOffset    = 6 * ( encCfg.m_internalBitDepth[CH_L] - 8 );
435
0
  m_motionSearch.init( encCfg, true, threadPool );
436
#if defined( TARGET_SIMD_X86 ) && ENABLE_SIMD_OPT
437
  initCuTree_X86();
438
#endif
439
#if defined( TARGET_SIMD_ARM ) && ENABLE_SIMD_OPT
440
  initCuTreeARM();
441
#endif
442
0
  m_rdCost.create();
443
  // the Hadamard SATD of the block size; setDistParam picks it by the block width
444
0
  const CPelBuf blk( nullptr, m_blkSize, m_blkSize );
445
0
  m_hadFunc       = m_rdCost.setDistParam( blk, blk, encCfg.m_internalBitDepth[CH_L], DF_HAD ).distFunc;
446
447
  // TPL weighs rate with the Lagrange multiplier of the unreferenced pictures, the top temporal layer.
448
0
  GOPEntry topEntry;
449
0
  topEntry.setDefaultGOPEntry();
450
0
  topEntry.copyFromGopCfg( encCfg.m_GOPList[0] );
451
0
  for( int i = 1; i < encCfg.m_GOPSize && i < VVENC_MAX_GOP; i++ )
452
0
  {
453
0
    if( encCfg.m_GOPList[i].m_temporalId > topEntry.m_temporalId ) topEntry.copyFromGopCfg( encCfg.m_GOPList[i] );
454
0
  }
455
0
  topEntry.m_vtl = std::min( 5, encCfg.m_maxTLayer );
456
0
  const int leafQp = Clip3( -m_qpBDOffset, MAX_QP, EncSlice::getCascadeQP( encCfg, topEntry, false, encCfg.m_QP, m_qpBDOffset ) );
457
0
  m_lambdaLeaf    = qpToLambda( leafQp, encCfg.m_internalBitDepth[CH_L] );
458
0
}
459
460
// The rows of one xForEachRow call, shared by the stage thread and the helper tasks. A helper that starts after
461
// the call has returned still holds them and finds no row left.
462
struct CuTreeRows
463
{
464
  std::atomic<int>                  next{ 0 };
465
  int                               done    = 0;   // rows finished, guarded by mutex
466
  int                               numRows = 0;
467
  const std::function<void( int )>* fn      = nullptr;
468
  std::mutex                        mutex;
469
  std::condition_variable           allDone;
470
471
  void work()
472
0
  {
473
0
    for( int row = next++; row < numRows; row = next++ )
474
0
    {
475
0
      ( *fn )( row );
476
0
      std::lock_guard<std::mutex> lock( mutex );
477
0
      if( ++done == numRows )
478
0
      {
479
0
        allDone.notify_one();
480
0
      }
481
0
    }
482
0
  }
483
484
  void waitAllDone()
485
0
  {
486
0
    std::unique_lock<std::mutex> lock( mutex );
487
0
    allDone.wait( lock, [this] { return done == numRows; } );
488
0
  }
489
};
490
491
// Runs fn( row ) for rows 0 .. numRows - 1. The stage thread works through the rows itself and workers of the
492
// thread pool join in when they are free. Waiting for row tasks instead stalled the stage thread, and with it the
493
// stages before the encoder, behind the encoder's queued CTU tasks. Rows write disjoint data, so the result does
494
// not depend on which thread runs which row.
495
void CuTree::xForEachRow( int numRows, const std::function<void( int )>& fn ) const
496
0
{
497
0
  auto rows     = std::make_shared<CuTreeRows>();
498
0
  rows->numRows = numRows;
499
0
  rows->fn      = &fn;
500
501
0
  const int numHelpers = m_threadPool ? std::min( m_threadPool->numThreads(), numRows - 1 ) : 0;
502
0
  for( int i = 0; i < numHelpers; i++ )
503
0
  {
504
0
    m_threadPool->addBarrierTask( []( int, void* param )
505
0
    {
506
0
      std::unique_ptr<std::shared_ptr<CuTreeRows>> held( static_cast<std::shared_ptr<CuTreeRows>*>( param ) );
507
0
      ( *held )->work();
508
0
      return true;
509
0
    }, new std::shared_ptr<CuTreeRows>( rows ) );
510
0
  }
511
0
  rows->work();
512
0
  pollStartStage();
513
0
  rows->waitAllDone(); // for the rows helpers took and still run
514
0
}
515
516
// Halves the luma resolution with 2x2 averages and pads the result.
517
void CuTree::xDownsample( const PelStorage& src, PelStorage& dst ) const
518
0
{
519
0
  const CPelBuf in      = src.Y();
520
0
  const int width       = in.width / 2;
521
0
  const int height      = in.height / 2;
522
0
  const int rowsPerTask = 16;
523
0
  dst.create( CHROMA_400, Area( 0, 0, width, height ), 0, LOWRES_PAD );
524
0
  const PelBuf out      = dst.Y();
525
526
0
  xForEachRow( ( height + rowsPerTask - 1 ) / rowsPerTask, [&]( int task )
527
0
  {
528
0
    for( int y = task * rowsPerTask; y < std::min( height, ( task + 1 ) * rowsPerTask ); y++ )
529
0
    {
530
0
      m_downsampleRow( in.buf + 2 * y * in.stride, in.stride, out.buf + y * out.stride, width );
531
0
    }
532
0
  } );
533
0
  dst.extendBorderPel( LOWRES_PAD, LOWRES_PAD );
534
0
}
535
536
void CuTree::initPicture( Picture* pic )
537
0
{
538
0
  std::unique_ptr<Frame> frame( new Frame );
539
0
  frame->poc       = pic->poc;
540
0
  frame->codingNum = pic->gopEntry->m_codingNum;
541
542
0
  xDownsample( pic->getOrigBuffer(), frame->lowRes[0] );
543
0
  for( int level = 1; level < NUM_LEVELS; level++ )
544
0
  {
545
0
    xDownsample( frame->lowRes[level - 1], frame->lowRes[level] );
546
0
  }
547
548
0
  m_frames[pic->poc] = std::move( frame );
549
0
}
550
551
void CuTree::processPictures( const PicList& picList, AccessUnitList& auList, PicList& doneList, PicList& freeList )
552
0
{
553
0
  int batchEndPoc = 0;
554
0
  if( picList.empty() || ! xIsBatchReady( picList, batchEndPoc ) )
555
0
  {
556
0
    return;
557
0
  }
558
559
0
  xMarkRandomAccess( picList );
560
561
  // Every picture is coded from reconstructed references, so the references go first: analyse in coding order.
562
0
  const bool flush = picList.back()->isFlush;
563
0
  std::vector<Picture*> codingOrder( picList.begin(), picList.end() );
564
0
  std::sort( codingOrder.begin(), codingOrder.end(), []( const Picture* a, const Picture* b ) { return a->gopEntry->m_codingNum < b->gopEntry->m_codingNum; } );
565
0
  for( auto pic : codingOrder )
566
0
  {
567
0
    Frame* frame = xFindFrame( pic->poc );
568
0
    if( frame->analysed )
569
0
    {
570
0
      continue;
571
0
    }
572
0
    pollStartStage();
573
0
    xAnalyse( *frame, pic, flush );
574
575
    // In a hierarchical GOP the top temporal layer is never referenced, its pictures are not needed any more.
576
0
    if( frame->analysed && m_encCfg->m_maxTLayer > 0 && pic->gopEntry->m_temporalId >= m_encCfg->m_maxTLayer )
577
0
    {
578
0
      for( auto& level : frame->lowRes ) level.destroy();
579
0
      frame->recon.destroy();
580
0
      frame->hasImages = false;
581
0
    }
582
0
  }
583
584
0
  xPropagate( picList.front()->poc );
585
0
  xSetPicQpOffsets( codingOrder, batchEndPoc );
586
587
0
  for( auto pic : picList )
588
0
  {
589
0
    if( pic->poc > batchEndPoc )
590
0
    {
591
0
      break;
592
0
    }
593
0
    xSetQpOffsets( *xFindFrame( pic->poc ), pic );
594
0
    doneList.push_back( pic );
595
0
    freeList.push_back( pic );
596
0
  }
597
598
  // Keep the pictures from the batch's last one on, which the next GOP references, and every picture a cached
599
  // later picture references. Pictures not analysed yet take their first usable reference from the batch's last
600
  // picture on (an IDR or IRAP that removes a list entry removes the deeper, older entries too, and after an IDR
601
  // dropped as coded later, the next entries lie within the GOP).
602
0
  int oldestPocNeeded = batchEndPoc;
603
0
  for( auto itr = m_frames.upper_bound( batchEndPoc ); itr != m_frames.end(); itr++ )
604
0
  {
605
0
    for( int refPoc : itr->second->refPoc )
606
0
    {
607
0
      if( refPoc != NO_REF ) oldestPocNeeded = std::min( oldestPocNeeded, refPoc );
608
0
    }
609
0
  }
610
0
  const auto eraseEnd = m_frames.lower_bound( oldestPocNeeded );
611
0
  for( auto itr = m_frames.begin(); itr != eraseEnd; itr++ )
612
0
  {
613
    // the random access points coded last stay known after their analysis data is gone (xGetRefContext); IRAP
614
    // pictures are coded in POC order
615
0
    const Frame& frame = *itr->second;
616
0
    if( frame.isIrap ) m_lastErasedIrap = { frame.poc, frame.codingNum };
617
0
    if( frame.isIdr  ) m_lastErasedIdr  = { frame.poc, frame.codingNum };
618
0
  }
619
0
  m_frames.erase( m_frames.begin(), eraseEnd );
620
0
}
621
622
// Marks the IRAP and IDR pictures as EncGOP::xGetNalUnitType will code them (see isCodedAsIdr). A start-of-intra
623
// picture is an IRAP. Re-read on every call: at the end of the sequence fixStartOfLastGop can make a picture the start
624
// of an intra period.
625
void CuTree::xMarkRandomAccess( const PicList& picList )
626
0
{
627
0
  const bool cra = m_encCfg->m_DecodingRefreshType == VVENC_DRT_CRA
628
0
                || m_encCfg->m_DecodingRefreshType == VVENC_DRT_CRA_CRE;
629
0
  for( auto pic : picList )
630
0
  {
631
0
    Frame& frame = *xFindFrame( pic->poc );
632
0
    frame.isIrap = pic->gopEntry->m_isStartOfIntra || ( m_encCfg->m_poc0idr && pic->poc == 0 );
633
0
  }
634
0
  bool idrAbove0 = m_lastErasedIdr.poc > 0;
635
0
  for( auto& entry : m_frames )
636
0
  {
637
0
    Frame& frame = *entry.second;
638
0
    frame.isIdr  = isCodedAsIdr( frame.isIrap, frame.poc, cra, m_encCfg->m_poc0idr, idrAbove0 );
639
0
  }
640
0
}
641
642
// Whether EncGOP::xGetNalUnitType codes a picture as an IDR. POC 0 with POC0IDR is one. Every other IRAP is one,
643
// except under the refresh types CRA and CRA_CRE: there with POC0IDR none is, and without it only the first ones are
644
// (the first intra picture is coded as an IDR, and the IRAPs after it until an IDR with a POC above 0 has been coded).
645
// Call it in POC order (IRAP pictures are coded in POC order); idrAbove0 carries that state from one call to the next.
646
bool CuTree::isCodedAsIdr( bool isIrap, int poc, bool cra, bool poc0idr, bool& idrAbove0 )
647
0
{
648
0
  bool idr = false;
649
0
  if( poc0idr && poc == 0 )
650
0
  {
651
0
    idr = true;
652
0
  }
653
0
  else if( isIrap )
654
0
  {
655
0
    idr = cra ? ! poc0idr && ! idrAbove0 : true;
656
0
  }
657
0
  idrAbove0 = idrAbove0 || ( idr && poc > 0 );
658
0
  return idr;
659
0
}
660
661
// The IDR and IRAP pictures that decide which references the picture can use (see refState).
662
void CuTree::xGetRefContext( const Frame& cur, bool flush, RefContext& ctx ) const
663
0
{
664
0
  ctx.poc       = cur.poc;
665
0
  ctx.codingNum = cur.codingNum;
666
0
  ctx.lastPoc   = m_frames.rbegin()->first;
667
0
  ctx.flush     = flush;
668
  // the erased pictures have lower POCs than every cached one and were coded before every picture still to analyse
669
0
  ctx.idr       = m_lastErasedIdr;
670
0
  ctx.irap      = m_lastErasedIrap;
671
0
  for( auto& entry : m_frames )
672
0
  {
673
0
    const Frame& f = *entry.second;
674
0
    if( f.codingNum >= cur.codingNum )
675
0
    {
676
0
      continue;
677
0
    }
678
0
    if( f.isIdr && f.codingNum > ctx.idr.codingNum )
679
0
    {
680
0
      ctx.idr = { f.poc, f.codingNum };
681
0
    }
682
0
    if( f.isIrap && f.poc < cur.poc && f.codingNum > ctx.irap.codingNum )
683
0
    {
684
0
      ctx.irap = { f.poc, f.codingNum };
685
0
    }
686
0
  }
687
0
}
688
689
// Whether a reference picture can be used by a picture, following how the encoder builds its reference lists
690
// (Slice::createExplicitReferencePictureSetFromReference after the reference marking of
691
// Slice::setDecodingRefreshMarking): a picture that does not exist (POC below 0, or past the end of the sequence) or is
692
// coded after the picture is missing; an IDR removes every picture coded before it; and once a picture follows an IRAP
693
// (CRA or IDR) in POC order, the pictures before that IRAP are removed too. refCodingNum is -1 for a picture no longer
694
// cached. The encoder's quirk that after the first IDR the first CRA's leading pictures cannot use that IDR is not
695
// followed. Long-term references and DRAP, which vvenc does not use, are not considered.
696
CuTree::RefState CuTree::refState( int refPoc, int refCodingNum, const RefContext& ctx )
697
0
{
698
0
  if( refPoc < 0 )
699
0
  {
700
0
    return RefState::MISSING;
701
0
  }
702
0
  if( refPoc > ctx.lastPoc )
703
0
  {
704
0
    return ctx.flush ? RefState::MISSING : RefState::NOT_ARRIVED;
705
0
  }
706
0
  if( refCodingNum >= 0 )
707
0
  {
708
0
    if( refCodingNum > ctx.codingNum || refCodingNum < ctx.idr.codingNum )
709
0
    {
710
0
      return RefState::MISSING;
711
0
    }
712
0
  }
713
0
  else if( refPoc < ctx.idr.poc )
714
0
  {
715
    // no longer cached: below the IDR it was coded before it (the RADL pictures of an IDR are all analysed in the
716
    // IDR's batch, before any of them can be erased)
717
0
    return RefState::MISSING;
718
0
  }
719
0
  if( refPoc < ctx.irap.poc )
720
0
  {
721
0
    return RefState::MISSING;
722
0
  }
723
0
  return RefState::AVAILABLE;
724
0
}
725
726
// The first entry of each reference list as the encoder builds it from the GOP entry: the first usable entry of the
727
// list, an empty L0 taking the first usable L1 entry and an empty L1 the first usable L0 entry; L1 only for B slices.
728
// codingNumOf gives a picture's coding number, -1 if it is no longer cached. Returns false if an entry has not arrived
729
// yet, so the picture has to be analysed later. refPoc[1] is NO_REF where L1 would only repeat L0 (uni-prediction).
730
bool CuTree::selectRefs( const GOPEntry& gopEntry, const RefContext& ctx, const std::function<int( int )>& codingNumOf,
731
                         int refPoc[2] )
732
0
{
733
0
  const bool usesL1 = gopEntry.m_sliceType == 'B' && gopEntry.m_numRefPicsActive[1] > 0;
734
0
  int first[2] = { NO_REF, NO_REF };
735
0
  for( int l = 0; l < 2; l++ )
736
0
  {
737
0
    if( l == 1 && ! usesL1 && first[0] != NO_REF )
738
0
    {
739
0
      break; // L1 is needed only by B slices, or to fill an empty L0
740
0
    }
741
0
    for( int k = 0; k < gopEntry.m_numRefPics[l]; k++ )
742
0
    {
743
0
      const int poc = ctx.poc - gopEntry.m_deltaRefPics[l][k];
744
0
      const RefState state = refState( poc, codingNumOf( poc ), ctx );
745
0
      if( state == RefState::NOT_ARRIVED )
746
0
      {
747
0
        return false;
748
0
      }
749
0
      if( state == RefState::AVAILABLE )
750
0
      {
751
0
        first[l] = poc;
752
0
        break;
753
0
      }
754
0
    }
755
0
  }
756
0
  refPoc[0] = first[0] != NO_REF ? first[0] : first[1];
757
0
  refPoc[1] = ! usesL1 ? NO_REF : first[1] != NO_REF ? first[1] : first[0];
758
0
  if( refPoc[1] == refPoc[0] )
759
0
  {
760
0
    refPoc[1] = NO_REF;
761
0
  }
762
0
  return true;
763
0
}
764
765
// A batch is the pictures of the GOP that comes next. It is ready when that GOP and the look-ahead after it
766
// have arrived, or when the encoder is flushed.
767
bool CuTree::xIsBatchReady( const PicList& picList, int& batchEndPoc ) const
768
0
{
769
0
  const int  gopNum = picList.front()->gopEntry->m_gopNum;
770
0
  const bool flush  = picList.back()->isFlush;
771
0
  bool gopComplete  = false;
772
773
0
  batchEndPoc = picList.front()->poc;
774
0
  for( auto pic : picList )
775
0
  {
776
0
    if( pic->gopEntry->m_gopNum != gopNum )
777
0
    {
778
0
      gopComplete = true;
779
0
      break;
780
0
    }
781
0
    batchEndPoc = pic->poc;
782
0
  }
783
784
0
  return flush || ( gopComplete && picList.back()->poc >= batchEndPoc + m_lookAheadPics );
785
0
}
786
787
CuTree::Frame* CuTree::xFindFrame( int poc ) const
788
0
{
789
0
  auto itr = m_frames.find( poc );
790
0
  return itr == m_frames.end() ? nullptr : itr->second.get();
791
0
}
792
793
// Codes every block of the picture as TPL does: picks intra, L0, L1 or bi-prediction by rate-distortion cost with
794
// the original references, then codes the chosen mode with the reconstructed references and keeps the
795
// reconstruction for the pictures that reference this one (Han et al., Eqs. 6 to 11).
796
void CuTree::xAnalyse( Frame& frame, Picture* pic, bool flush )
797
0
{
798
0
  const GOPEntry& gopEntry = *pic->gopEntry;
799
0
  const int bitDepth       = m_encCfg->m_internalBitDepth[CH_L];
800
0
  const int maxVal         = ( 1 << bitDepth ) - 1;
801
0
  const int numBlocks      = m_blkWidth * m_blkHeight;
802
803
0
  frame.isIntra   = gopEntry.m_sliceType == 'I';
804
0
  frame.qp        = Clip3( -m_qpBDOffset, MAX_QP, EncSlice::getCascadeQP( *m_encCfg, gopEntry, frame.isIntra, m_encCfg->m_QP, m_qpBDOffset ) );
805
806
  // the first reference picture of each list as the encoder will use it, which must be reconstructed already
807
0
  Frame* refs[2] = { nullptr, nullptr };
808
0
  if( ! frame.isIntra )
809
0
  {
810
0
    RefContext ctx;
811
0
    xGetRefContext( frame, flush, ctx );
812
0
    auto codingNumOf = [this]( int poc ) { const Frame* f = xFindFrame( poc ); return f ? f->codingNum : -1; };
813
0
    int refPoc[2];
814
0
    if( ! selectRefs( gopEntry, ctx, codingNumOf, refPoc ) )
815
0
    {
816
0
      return; // a reference has not arrived yet, analyse the picture later
817
0
    }
818
0
    for( int l = 0; l < 2; l++ )
819
0
    {
820
0
      if( refPoc[l] == NO_REF )
821
0
      {
822
0
        continue;
823
0
      }
824
0
      refs[l] = xFindFrame( refPoc[l] );
825
0
      CHECK( ! refs[l], "CU tree: the analysis data of a usable reference picture is gone" );
826
0
      if( ! refs[l]->hasImages )
827
0
      {
828
0
        refs[l] = nullptr; // not expected: only unreferenced pictures drop their images
829
0
      }
830
0
      else if( ! refs[l]->analysed )
831
0
      {
832
0
        return; // the reference is not reconstructed yet
833
0
      }
834
0
    }
835
0
    for( int l = 0; l < 2; l++ )
836
0
    {
837
0
      frame.refPoc[l] = refs[l] ? refPoc[l] : NO_REF;
838
0
    }
839
0
  }
840
0
  for( int l = 0; l < 2; l++ )
841
0
  {
842
0
    if( refs[l] )
843
0
    {
844
0
      xEstimateMotion( frame, *refs[l], frame.mvs[l] );
845
0
    }
846
0
  }
847
848
  // samples outside the block grid keep their source values
849
0
  const CPelBuf org = frame.lowRes[0].Y();
850
0
  frame.recon.create( CHROMA_400, Area( 0, 0, org.width, org.height ), 0, LOWRES_PAD );
851
0
  frame.recon.Y().copyFrom( org );
852
0
  frame.predMode.assign( numBlocks, CTP_INTRA );
853
0
  frame.distRec.assign( numBlocks, 0.f );
854
0
  for( int l = 0; l < 2; l++ )
855
0
  {
856
0
    frame.distSrc  [l].assign( numBlocks, 0.f );
857
0
    frame.deltaDist[l].assign( numBlocks, 0.f );
858
0
    frame.deltaRate[l].assign( numBlocks, 0.f );
859
0
  }
860
861
0
  const int            n         = m_blkSize;
862
0
  const TplPredBlockFn predBlock = m_predBlock[m_blkSizeIdx];
863
0
  const BlockSatd      satd      = { m_hadFunc, bitDepth, n };
864
0
  const double         step      = qpToStep( frame.qp, bitDepth ) / 2;
865
0
  const double         lambda    = qpToLambda( frame.qp, bitDepth );
866
  // rounding offsets of HM's quantizer without RDOQ
867
0
  const BlockCoder     intraCoder( m_codeBlock[m_blkSizeIdx], n, step, 1.0 / 3 );
868
0
  const BlockCoder     interCoder( m_codeBlock[m_blkSizeIdx], n, step, 1.0 / 6 );
869
0
  const PelBuf         recon     = frame.recon.Y();
870
871
0
  xForEachRow( m_blkHeight, [&]( int by )
872
0
  {
873
0
    Pel predSrc[2][MAX_BLK_SIZE * MAX_BLK_SIZE], predRec[2][MAX_BLK_SIZE * MAX_BLK_SIZE];
874
0
    Pel pred[MAX_BLK_SIZE * MAX_BLK_SIZE], predIntra[MAX_BLK_SIZE * MAX_BLK_SIZE];
875
876
0
    for( int bx = 0; bx < m_blkWidth; bx++ )
877
0
    {
878
0
      const int  idx    = by * m_blkWidth + bx;
879
0
      const int  x      = bx * n, y = by * n;
880
0
      const Pel* orgBlk = org.buf + y * org.stride + x;
881
0
      Pel*       recBlk = recon.buf + y * recon.stride + x;
882
0
      auto cost = [&]( const BlockCoder::Result& r ) { return r.dist + lambda * r.rate; };
883
884
0
      if( n == 16 ) predictIntra<16>( org, x, y, bitDepth, satd, predIntra );
885
0
      else          predictIntra<8> ( org, x, y, bitDepth, satd, predIntra );
886
0
      const BlockCoder::Result intra = intraCoder.code( orgBlk, org.stride, predIntra, nullptr, 0, maxVal );
887
888
      // mode decision with the original references
889
0
      int    bestMode = CTP_INTRA;
890
0
      double bestCost = cost( intra );
891
0
      BlockCoder::Result src[2] = {};
892
0
      for( int l = 0; l < 2; l++ )
893
0
      {
894
0
        if( ! refs[l] ) continue;
895
0
        predictBlock( predBlock, n, refs[l]->lowRes[0].Y(), x, y, frame.mvs[l].get( bx, by ), predSrc[l] );
896
0
        src[l] = interCoder.code( orgBlk, org.stride, predSrc[l], nullptr, 0, maxVal );
897
0
        if( cost( src[l] ) < bestCost )
898
0
        {
899
0
          bestCost = cost( src[l] );
900
0
          bestMode = l == 0 ? CTP_L0 : CTP_L1;
901
0
        }
902
0
      }
903
0
      if( refs[0] && refs[1] )
904
0
      {
905
0
        for( int i = 0; i < n * n; i++ ) pred[i] = Pel( ( predSrc[0][i] + predSrc[1][i] + 1 ) >> 1 );
906
0
        const BlockCoder::Result srcBi = interCoder.code( orgBlk, org.stride, pred, nullptr, 0, maxVal );
907
0
        if( cost( srcBi ) < bestCost )
908
0
        {
909
0
          bestCost = cost( srcBi );
910
0
          bestMode = CTP_BI;
911
0
        }
912
0
      }
913
0
      frame.predMode[idx] = uint8_t( bestMode );
914
915
0
      if( bestMode == CTP_INTRA )
916
0
      {
917
        // intra cuts the dependency
918
0
        frame.distRec[idx] = float( intraCoder.code( orgBlk, org.stride, predIntra, recBlk, recon.stride, maxVal ).dist );
919
0
        continue;
920
0
      }
921
922
      // code the chosen mode from the reconstructed references
923
0
      for( int l = 0; l < 2; l++ )
924
0
      {
925
0
        if( refs[l] ) predictBlock( predBlock, n, refs[l]->recon.Y(), x, y, frame.mvs[l].get( bx, by ), predRec[l] );
926
0
      }
927
0
      if( bestMode != CTP_BI )
928
0
      {
929
0
        const int l = bestMode == CTP_L0 ? 0 : 1;
930
0
        const BlockCoder::Result rec = interCoder.code( orgBlk, org.stride, predRec[l], recBlk, recon.stride, maxVal );
931
0
        frame.distRec  [idx]    = float( rec.dist );
932
0
        frame.distSrc  [l][idx] = float( std::min( src[l].dist, rec.dist ) );
933
0
        frame.deltaDist[l][idx] = float( std::max( 0.0, rec.dist - src[l].dist ) );
934
0
        frame.deltaRate[l][idx] = float( std::max( 0.0, rec.rate - src[l].rate ) );
935
0
        continue;
936
0
      }
937
938
      // bi-prediction: the dependency on each reference is measured by keeping the other one reconstructed
939
0
      for( int i = 0; i < n * n; i++ ) pred[i] = Pel( ( predRec[0][i] + predRec[1][i] + 1 ) >> 1 );
940
0
      const BlockCoder::Result rec = interCoder.code( orgBlk, org.stride, pred, recBlk, recon.stride, maxVal );
941
0
      frame.distRec[idx] = float( rec.dist );
942
0
      for( int l = 0; l < 2; l++ )
943
0
      {
944
0
        const Pel* other = predRec[1 - l];
945
0
        for( int i = 0; i < n * n; i++ ) pred[i] = Pel( ( predSrc[l][i] + other[i] + 1 ) >> 1 );
946
0
        const BlockCoder::Result mixed = interCoder.code( orgBlk, org.stride, pred, nullptr, 0, maxVal );
947
0
        frame.distSrc  [l][idx] = float( std::min( mixed.dist, rec.dist ) );
948
0
        frame.deltaDist[l][idx] = float( std::max( 0.0, rec.dist - mixed.dist ) );
949
0
        frame.deltaRate[l][idx] = float( std::max( 0.0, rec.rate - mixed.rate ) );
950
0
      }
951
0
    }
952
0
  } );
953
954
0
  frame.recon.extendBorderPel( LOWRES_PAD, LOWRES_PAD );
955
0
  frame.propDist.assign( numBlocks, 0.0 );
956
0
  frame.propRate.assign( numBlocks, 0.0 );
957
0
  frame.analysed = true;
958
0
}
959
960
// Hierarchical motion search: MCTF's integer search of 2N x 2N blocks at eighth resolution, refined by xSearchInteger
961
// at quarter and half resolution, then the N x N analysis blocks to quarter sample by xSearchFractional.
962
void CuTree::xEstimateMotion( const Frame& cur, const Frame& ref, Array2D<MotionVector>& mvs ) const
963
0
{
964
0
  const int searchSize = 2 * m_blkSize;
965
0
  Array2D<MotionVector> integerMvs[NUM_LEVELS];
966
967
0
  for( int level = NUM_LEVELS - 1; level >= 0; level-- )
968
0
  {
969
0
    const CPelBuf picLevel = cur.lowRes[level].Y();
970
0
    integerMvs[level].allocate( picLevel.width / searchSize + 1, picLevel.height / searchSize + 1 );
971
0
    if( level == NUM_LEVELS - 1 )
972
0
    {
973
0
      m_motionSearch.motionEstimationLuma( integerMvs[level], cur.lowRes[level], ref.lowRes[level], LOWRES_PAD, searchSize, nullptr, 2 );
974
0
    }
975
0
    else
976
0
    {
977
0
      xSearchInteger( cur.lowRes[level], ref.lowRes[level], integerMvs[level + 1], integerMvs[level] );
978
0
    }
979
0
  }
980
981
0
  const CPelBuf pic = cur.lowRes[0].Y();
982
0
  mvs.allocate( pic.width / m_blkSize + 1, pic.height / m_blkSize + 1 );
983
0
  xSearchFractional( cur, ref, integerMvs[0], mvs );
984
0
}
985
986
// The positions one block's motion search has checked. Checking a position again cannot change the result: its error
987
// is the same, and only a smaller error replaces the best. Neighbouring blocks often share a vector, and the
988
// refinement steps come back to positions checked before, so the searches skip them.
989
class CheckedPositions
990
{
991
public:
992
  // Records the position; false when it was checked before.
993
  bool add( int x, int y )
994
0
  {
995
0
    for( int i = 0; i < m_num; i++ )
996
0
    {
997
0
      if( m_x[i] == x && m_y[i] == y )
998
0
      {
999
0
        return false;
1000
0
      }
1001
0
    }
1002
0
    if( m_num < CAPACITY ) // more positions than any search checks, see xSearchInteger
1003
0
    {
1004
0
      m_x[m_num]   = x;
1005
0
      m_y[m_num++] = y;
1006
0
    }
1007
0
    return true;
1008
0
  }
1009
1010
private:
1011
  static constexpr int CAPACITY = 48;
1012
  int m_x[CAPACITY], m_y[CAPACITY];
1013
  int m_num = 0;
1014
};
1015
1016
// Integer motion of the 2N x 2N blocks of a level from the coarser level: the best of the parent's and its
1017
// neighbours' vectors (doubled) and zero, refined by a small diamond search; at most 1 + 9 + 8 * 4 positions.
1018
void CuTree::xSearchInteger( const PelStorage& curPic, const PelStorage& refPic, const Array2D<MotionVector>& coarse, Array2D<MotionVector>& mvs ) const
1019
0
{
1020
0
  const int     bs     = 2 * m_blkSize;
1021
0
  const CPelBuf org    = curPic.Y();
1022
0
  const CPelBuf refBuf = refPic.Y();
1023
0
  if( org.height < m_blkSize || org.width < m_blkSize )
1024
0
  {
1025
0
    return;
1026
0
  }
1027
0
  const int     rows   = ( org.height - m_blkSize ) / bs + 1;
1028
0
  const int     cols   = ( org.width  - m_blkSize ) / bs + 1;
1029
1030
0
  xForEachRow( rows, [&]( int by )
1031
0
  {
1032
0
    for( int bx = 0; bx < cols; bx++ )
1033
0
    {
1034
0
      const int  x  = bx * bs, y = by * bs;
1035
0
      const int  bw = std::min<int>( bs, org.width  - x ) & ~7;
1036
0
      const int  bh = std::min<int>( bs, org.height - y ) & ~7;
1037
0
      const Pel* orgBlk = org.buf + y * org.stride + x;
1038
      // keep the displaced block inside the padded reference
1039
0
      const int  minX = -LOWRES_PAD - x, maxX = int( refBuf.width )  + LOWRES_PAD - bw - x;
1040
0
      const int  minY = -LOWRES_PAD - y, maxY = int( refBuf.height ) + LOWRES_PAD - bh - y;
1041
0
      MotionVector     best;
1042
0
      CheckedPositions checked;
1043
0
      auto check = [&]( int dx, int dy )
1044
0
      {
1045
0
        dx = Clip3( minX, maxX, dx );
1046
0
        dy = Clip3( minY, maxY, dy );
1047
0
        if( ! checked.add( dx, dy ) )
1048
0
        {
1049
0
          return;
1050
0
        }
1051
0
        const Pel* refBlk = refBuf.buf + ( y + dy ) * refBuf.stride + x + dx;
1052
0
        const int  error  = m_motionSearch.m_motionErrorLumaInt8( orgBlk, org.stride, refBlk, refBuf.stride, bw, bh, best.error );
1053
0
        if( error < best.error )
1054
0
        {
1055
0
          best.set( dx * MV_PREC, dy * MV_PREC, error );
1056
0
        }
1057
0
      };
1058
1059
0
      check( 0, 0 );
1060
0
      for( int py = by / 2 - 1; py <= by / 2 + 1; py++ )
1061
0
      {
1062
0
        for( int px = bx / 2 - 1; px <= bx / 2 + 1; px++ )
1063
0
        {
1064
0
          if( px >= 0 && py >= 0 && px < coarse.w() && py < coarse.h() && coarse.get( px, py ).error != INT_LEAST32_MAX )
1065
0
          {
1066
0
            const MotionVector& c = coarse.get( px, py );
1067
0
            check( 2 * c.x / MV_PREC, 2 * c.y / MV_PREC );
1068
0
          }
1069
0
        }
1070
0
      }
1071
0
      for( int iter = 0; iter < 8; iter++ )
1072
0
      {
1073
0
        const MotionVector center = best;
1074
0
        check( center.x / MV_PREC - 1, center.y / MV_PREC );
1075
0
        check( center.x / MV_PREC + 1, center.y / MV_PREC );
1076
0
        check( center.x / MV_PREC, center.y / MV_PREC - 1 );
1077
0
        check( center.x / MV_PREC, center.y / MV_PREC + 1 );
1078
0
        if( best.x == center.x && best.y == center.y )
1079
0
        {
1080
0
          break;
1081
0
        }
1082
0
      }
1083
0
      mvs.get( bx, by ) = best;
1084
0
    }
1085
0
  } );
1086
0
}
1087
1088
// Motion of the N x N analysis blocks from the integer motion of the 2N x 2N blocks: the best of the parent's and
1089
// its neighbours' vectors and zero, refined to half and then quarter sample with the bilinear predictor.
1090
void CuTree::xSearchFractional( const Frame& cur, const Frame& ref, const Array2D<MotionVector>& coarse, Array2D<MotionVector>& mvs ) const
1091
0
{
1092
0
  const CPelBuf org    = cur.lowRes[0].Y();
1093
0
  const CPelBuf refBuf = ref.lowRes[0].Y();
1094
0
  const int            n         = m_blkSize;
1095
0
  const TplPredBlockFn predBlock = m_predBlock[m_blkSizeIdx];
1096
0
  const int            rows      = org.height / n;
1097
0
  const int            cols      = org.width  / n;
1098
1099
0
  xForEachRow( rows, [&]( int by )
1100
0
  {
1101
0
    Pel pred[MAX_BLK_SIZE * MAX_BLK_SIZE];
1102
0
    for( int bx = 0; bx < cols; bx++ )
1103
0
    {
1104
0
      const int  x      = bx * n, y = by * n;
1105
0
      const Pel* orgBlk = org.buf + y * org.stride + x;
1106
0
      MotionVector     best;
1107
0
      CheckedPositions checked;
1108
0
      auto check = [&]( int mvx, int mvy )
1109
0
      {
1110
0
        if( ! checked.add( mvx, mvy ) )
1111
0
        {
1112
0
          return;
1113
0
        }
1114
0
        MotionVector mv;
1115
0
        mv.set( mvx, mvy, 0 );
1116
0
        predictBlock( predBlock, n, refBuf, x, y, mv, pred );
1117
0
        const int error = m_motionSearch.m_motionErrorLumaInt8( orgBlk, org.stride, pred, n, n, n, best.error );
1118
0
        if( error < best.error )
1119
0
        {
1120
0
          best.set( mvx, mvy, error );
1121
0
        }
1122
0
      };
1123
1124
0
      check( 0, 0 );
1125
0
      for( int py = by / 2 - 1; py <= by / 2 + 1; py++ )
1126
0
      {
1127
0
        for( int px = bx / 2 - 1; px <= bx / 2 + 1; px++ )
1128
0
        {
1129
0
          if( px >= 0 && py >= 0 && px < coarse.w() && py < coarse.h() )
1130
0
          {
1131
0
            const MotionVector& c = coarse.get( px, py );
1132
0
            check( c.x, c.y );
1133
0
          }
1134
0
        }
1135
0
      }
1136
0
      for( int step = MV_PREC / 2; step >= MV_PREC / 4; step /= 2 )
1137
0
      {
1138
0
        const MotionVector center = best;
1139
0
        for( int dy = -step; dy <= step; dy += step )
1140
0
        {
1141
0
          for( int dx = -step; dx <= step; dx += step )
1142
0
          {
1143
0
            if( dx || dy )
1144
0
            {
1145
0
              check( center.x + dx, center.y + dy );
1146
0
            }
1147
0
          }
1148
0
        }
1149
0
      }
1150
0
      mvs.get( bx, by ) = best;
1151
0
    }
1152
0
  } );
1153
0
}
1154
1155
// Walks the analysed pictures from firstPoc on in reverse coding order and passes each block's dependency to the
1156
// reference blocks it predicts from (Han et al., Eqs. 12, 16 and 17):
1157
//   dD_ref += dD + dD / D_rec * D_prop
1158
//   dR_ref += dR + log2( 2^(2 R_prop) / ( D_src / D_rec * 2^(2 R_prop) + 1 - D_src / D_rec ) )
1159
void CuTree::xPropagate( int firstPoc )
1160
0
{
1161
0
  std::vector<Frame*> order;
1162
0
  for( auto& entry : m_frames )
1163
0
  {
1164
0
    Frame& frame = *entry.second;
1165
0
    std::fill( frame.propDist.begin(), frame.propDist.end(), 0.0 );
1166
0
    std::fill( frame.propRate.begin(), frame.propRate.end(), 0.0 );
1167
0
    if( frame.poc >= firstPoc && frame.analysed && ! frame.isIntra )
1168
0
    {
1169
0
      order.push_back( &frame );
1170
0
    }
1171
0
  }
1172
0
  std::sort( order.begin(), order.end(), []( const Frame* a, const Frame* b ) { return a->codingNum > b->codingNum; } );
1173
1174
0
  for( Frame* frame : order )
1175
0
  {
1176
0
    Frame* refs[2] = { xFindFrame( frame->refPoc[0] ), xFindFrame( frame->refPoc[1] ) };
1177
1178
0
    for( int by = 0; by < m_blkHeight; by++ )
1179
0
    {
1180
0
      for( int bx = 0; bx < m_blkWidth; bx++ )
1181
0
      {
1182
0
        const int idx  = by * m_blkWidth + bx;
1183
0
        const int mode = frame->predMode[idx];
1184
0
        if( mode == CTP_INTRA || frame->distRec[idx] <= 0.f )
1185
0
        {
1186
0
          continue;
1187
0
        }
1188
0
        const double distRec  = frame->distRec[idx];
1189
0
        const double propRate = frame->propRate[idx];
1190
0
        const double growth   = propRate > 0.0 ? std::pow( 2.0, 2.0 * propRate ) : 1.0;
1191
1192
0
        for( int l = 0; l < 2; l++ )
1193
0
        {
1194
0
          const bool usesRef = mode == CTP_BI || mode == ( l == 0 ? CTP_L0 : CTP_L1 );
1195
0
          if( ! usesRef || ! refs[l] )
1196
0
          {
1197
0
            continue;
1198
0
          }
1199
0
          const double deltaDist = frame->deltaDist[l][idx];
1200
0
          const double srcRatio  = frame->distSrc[l][idx] / distRec;
1201
0
          const double dist      = deltaDist + deltaDist / distRec * frame->propDist[idx];
1202
0
          const double rate      = frame->deltaRate[l][idx] + ( propRate > 0.0 ? propagatedRate( propRate, growth, srcRatio ) : 0.0 );
1203
0
          if( dist > 0.0 || rate > 0.0 )
1204
0
          {
1205
0
            xDistribute( *refs[l], bx, by, frame->mvs[l].get( bx, by ), dist, rate );
1206
0
          }
1207
0
        }
1208
0
      }
1209
0
    }
1210
0
  }
1211
0
}
1212
1213
// Adds the dependency to the up to four reference blocks that the displaced block overlaps, in proportion to the
1214
// overlapping area. Parts outside the picture are dropped.
1215
void CuTree::xDistribute( Frame& ref, int bx, int by, const MotionVector& mv, double dist, double rate ) const
1216
0
{
1217
0
  const int log2Units = floorLog2( m_blkSize * MV_PREC );   // log2 of one block in motion vector units
1218
0
  const int units     = 1 << log2Units;
1219
0
  const int posX = bx * units + mv.x;
1220
0
  const int posY = by * units + mv.y;
1221
  // floor division and remainder; positions can be negative, and >> rounds those down
1222
0
  const int x0 = posX >> log2Units;
1223
0
  const int y0 = posY >> log2Units;
1224
0
  const int fx = posX & ( units - 1 );
1225
0
  const int fy = posY & ( units - 1 );
1226
0
  const double distScale = dist / double( units * units );
1227
0
  const double rateScale = rate / double( units * units );
1228
1229
0
  const int xs[2] = { x0, x0 + 1 };
1230
0
  const int ys[2] = { y0, y0 + 1 };
1231
0
  const int ws[2] = { units - fx, fx };
1232
0
  const int hs[2] = { units - fy, fy };
1233
1234
0
  for( int j = 0; j < 2; j++ )
1235
0
  {
1236
0
    if( ys[j] < 0 || ys[j] >= m_blkHeight || hs[j] == 0 )
1237
0
    {
1238
0
      continue;
1239
0
    }
1240
0
    for( int i = 0; i < 2; i++ )
1241
0
    {
1242
0
      if( xs[i] < 0 || xs[i] >= m_blkWidth || ws[i] == 0 )
1243
0
      {
1244
0
        continue;
1245
0
      }
1246
0
      const int    idx  = ys[j] * m_blkWidth + xs[i];
1247
0
      const double area = double( ws[i] * hs[j] );
1248
0
      ref.propDist[idx] += distScale * area;
1249
0
      ref.propRate[idx] += rateScale * area;
1250
0
    }
1251
0
  }
1252
0
}
1253
1254
// The picture-level QP offsets of BIM 2 (MCTF): MCTF's offset for the pictures it analysed, and for the others 3/4 of
1255
// the mean of their two references' offsets, as EncGOP's initPicAuxQPOffsets derives them for BIM 2. They lower the QP
1256
// of whole pictures in static content, which CU-tree's CTU offsets, relative to the picture's own mean dependency,
1257
// cannot do. Runs in coding order, so the references come first; MCTF has to have run, its offsets are read before
1258
// xSetQpOffsets replaces them.
1259
void CuTree::xSetPicQpOffsets( const std::vector<Picture*>& codingOrder, int batchEndPoc )
1260
0
{
1261
0
  for( auto pic : codingOrder )
1262
0
  {
1263
0
    Frame* frame = xFindFrame( pic->poc );
1264
0
    if( pic->poc > batchEndPoc || ! frame )
1265
0
    {
1266
0
      continue;
1267
0
    }
1268
0
    if( ! pic->m_picShared->m_ctuBimQpOffset.empty() )
1269
0
    {
1270
0
      frame->picQpOffset = pic->m_picShared->m_picAuxQpOffset;
1271
0
      continue;
1272
0
    }
1273
0
    const Frame* ref0 = xFindFrame( frame->refPoc[0] );
1274
0
    const Frame* ref1 = xFindFrame( frame->refPoc[1] );
1275
0
    if( ref0 && ref1 )
1276
0
    {
1277
0
      const int sum      = ref0->picQpOffset + ref1->picQpOffset;
1278
0
      frame->picQpOffset = ( 3 * sum + ( sum < 0 ? 3 : 4 ) ) >> 3;   // rounding as in initPicAuxQPOffsets
1279
0
    }
1280
0
  }
1281
0
}
1282
1283
// The QP offset of each CTU (Han et al., Eqs. 19 to 21): with the dependency factor
1284
//   alpha = ( distortion + lambda * rate owed by later pictures ) / own distortion
1285
// of the CTU and of the picture, lambda_ctu = lambda * ( 1 + alpha_pic ) / ( 1 + alpha_ctu ). As lambda goes with
1286
// 2^(QP / 3), the QP offset is a multiple of -log2( beta ), beta = ( 1 + alpha_ctu ) / ( 1 + alpha_pic ). Like
1287
// libaom's superblock QP, the change is damped to the square root of beta for intra pictures and for CTUs below
1288
// the picture's average, and to the fourth root for CTUs above it in inter pictures. The offsets go where QPA
1289
// and the non-QPA path pick up the BIM offsets. The picture QP gets BIM 2's picture offset (xSetPicQpOffsets) and,
1290
// rounded, the mean of the CTU offsets, which the CTUs lose again: as with BIM 2, the CTU offsets average 0, so rate
1291
// control, which sets the picture QP itself, still gets the QP it chose.
1292
void CuTree::xSetQpOffsets( const Frame& frame, Picture* pic ) const
1293
0
{
1294
0
  const int ctuSize      = m_encCfg->m_bimCtuSize;
1295
0
  const int widthInCtus  = ( m_encCfg->m_PadSourceWidth  + ctuSize - 1 ) / ctuSize;
1296
0
  const int heightInCtus = ( m_encCfg->m_PadSourceHeight + ctuSize - 1 ) / ctuSize;
1297
0
  const int blksPerCtu   = ctuSize / ( 2 * m_blkSize );
1298
1299
0
  PicShared* picShared = pic->m_picShared;
1300
0
  picShared->m_ctuBimQpOffset.assign( widthInCtus * heightInCtus, 0 );
1301
0
  picShared->m_picAuxQpOffset = frame.picQpOffset;
1302
0
  if( m_blkWidth == 0 || m_blkHeight == 0 || ! frame.analysed )
1303
0
  {
1304
0
    return; // picture smaller than one analysis block, or not analysed
1305
0
  }
1306
1307
0
  auto blockDep = [&]( int idx ) { return frame.propDist[idx] + m_lambdaLeaf * frame.propRate[idx]; };
1308
1309
0
  double picDep = 0.0, picDist = 0.0;
1310
0
  for( int idx = 0; idx < m_blkWidth * m_blkHeight; idx++ )
1311
0
  {
1312
0
    picDep  += blockDep( idx );
1313
0
    picDist += frame.distRec[idx];
1314
0
  }
1315
0
  const double alphaPic = picDep / std::max( picDist, 1.0 );
1316
1317
0
  for( int cy = 0; cy < heightInCtus; cy++ )
1318
0
  {
1319
    // CTUs at the right and bottom edge may lie beyond the last full analysis block
1320
0
    const int by0 = std::min( cy * blksPerCtu, m_blkHeight - 1 );
1321
0
    const int by1 = std::max( by0 + 1, std::min( ( cy + 1 ) * blksPerCtu, m_blkHeight ) );
1322
0
    for( int cx = 0; cx < widthInCtus; cx++ )
1323
0
    {
1324
0
      const int bx0 = std::min( cx * blksPerCtu, m_blkWidth - 1 );
1325
0
      const int bx1 = std::max( bx0 + 1, std::min( ( cx + 1 ) * blksPerCtu, m_blkWidth ) );
1326
1327
0
      double dep = 0.0, dist = 0.0;
1328
0
      for( int by = by0; by < by1; by++ )
1329
0
      {
1330
0
        for( int bx = bx0; bx < bx1; bx++ )
1331
0
        {
1332
0
          dep  += blockDep( by * m_blkWidth + bx );
1333
0
          dist += frame.distRec[by * m_blkWidth + bx];
1334
0
        }
1335
0
      }
1336
0
      const double alphaCtu = dep / std::max( dist, 1.0 );
1337
0
      const double beta     = ( 1.0 + alphaCtu ) / ( 1.0 + alphaPic );
1338
0
      const double damping  = beta < 1.0 || frame.isIntra ? 0.5 : 0.25;
1339
0
      picShared->m_ctuBimQpOffset[cy * widthInCtus + cx] = int( std::lround( -m_encCfg->m_cuTreeScale * damping * std::log2( beta ) ) );
1340
0
    }
1341
0
  }
1342
1343
  // move the mean into the picture QP, rounded as MCTF does for BIM 2
1344
0
  const int numCtu = widthInCtus * heightInCtus;
1345
0
  int       sum    = 0;
1346
0
  for( int offset : picShared->m_ctuBimQpOffset ) sum += offset;
1347
0
  const int mean = ( sum + ( sum < 0 ? -( numCtu >> 1 ) : numCtu >> 1 ) ) / numCtu;
1348
0
  for( int& offset : picShared->m_ctuBimQpOffset ) offset -= mean;
1349
0
  picShared->m_picAuxQpOffset += mean;
1350
0
}
1351
1352
} // namespace vvenc
1353
1354
//! \}