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.h
Line
Count
Source
1
/* -----------------------------------------------------------------------------
2
The copyright in this software is being made available under the Clear BSD
3
License, included below. No patent rights, trademark rights and/or
4
other Intellectual Property Rights other than the copyrights concerning
5
the Software are granted under this license.
6
7
The Clear BSD License
8
9
Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors.
10
All rights reserved.
11
12
Redistribution and use in source and binary forms, with or without modification,
13
are permitted (subject to the limitations in the disclaimer below) provided that
14
the following conditions are met:
15
16
     * Redistributions of source code must retain the above copyright notice,
17
     this list of conditions and the following disclaimer.
18
19
     * Redistributions in binary form must reproduce the above copyright
20
     notice, this list of conditions and the following disclaimer in the
21
     documentation and/or other materials provided with the distribution.
22
23
     * Neither the name of the copyright holder nor the names of its
24
     contributors may be used to endorse or promote products derived from this
25
     software without specific prior written permission.
26
27
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
28
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
31
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
32
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
36
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38
POSSIBILITY OF SUCH DAMAGE.
39
40
41
------------------------------------------------------------------------------------------- */
42
43
44
/** \file     CuTree.h
45
    \brief    look-ahead stage for CU-tree adaptive quantization
46
*/
47
48
#pragma once
49
50
#include "CommonLib/CommonDef.h"
51
#include "CommonLib/MCTF.h"
52
#include "CommonLib/RdCost.h"
53
#include "EncStage.h"
54
55
#include <functional>
56
#include <map>
57
#include <memory>
58
59
//! \ingroup EncoderLib
60
//! \{
61
62
namespace vvenc {
63
64
class NoMallocThreadPool;
65
66
// Quantizer of the block coder, in the unnormalised N x N Hadamard domain (N times the orthonormal one):
67
// level = ( |c| * scale + round ) >> 16, dequantised |c| = ( level * deqStep + 8 ) >> 4.
68
struct TplQuant
69
{
70
  int32_t scale;      // 2^16 / step
71
  int32_t round;      // dead-zone rounding offset, 2^16 units
72
  int32_t deqStep;    // step, 2^4 units
73
};
74
75
// The analysis works on half-resolution luma in N x N blocks, N = 8 or 16 (16x16 or 32x32 at full resolution, set
76
// by vvenc_config::m_cuTreeBlockSize). The block kernels come in one version per size, indexed by TplBlkSize.
77
enum TplBlkSize { TPL_BLK_8 = 0, TPL_BLK_16 = 1, NUM_TPL_BLK_SIZES = 2 };
78
0
static constexpr int tplBlkSide( int sizeIdx ) { return 8 << sizeIdx; }
Unexecuted instantiation: EncLib.cpp:vvenc::tplBlkSide(int)
Unexecuted instantiation: CuTree.cpp:vvenc::tplBlkSide(int)
79
80
// Codes the N x N residual org - pred: Hadamard transform, quantization, and when recon is given the inverse
81
// transform added to pred. Returns the squared coefficient error in the unnormalised domain (N^2 times the error in
82
// samples) and the estimated bits (Exp-Golomb length of each level plus sign and significance).
83
typedef void ( *TplCodeBlockFn )( const Pel* org, ptrdiff_t orgStride, const Pel* pred, Pel* recon, ptrdiff_t reconStride,
84
                                  const TplQuant& quant, int maxVal, int64_t& dist, int& bits );
85
86
template<int N>
87
void tplCodeBlockCore( const Pel* org, ptrdiff_t orgStride, const Pel* pred, Pel* recon, ptrdiff_t reconStride,
88
                       const TplQuant& quant, int maxVal, int64_t& dist, int& bits );
89
90
// Bilinear prediction of an N x N block from the ( N + 1 )^2 reference samples at src, at the fractional position
91
// ( fx, fy ) in 1/16 sample.
92
typedef void ( *TplPredBlockFn )( const Pel* src, ptrdiff_t srcStride, int fx, int fy, Pel* dst );
93
94
template<int N>
95
void tplPredBlockCore( const Pel* src, ptrdiff_t srcStride, int fx, int fy, Pel* dst );
96
97
// One row of 2x2 averages, ( a + b + c + d + 2 ) >> 2.
98
typedef void ( *TplDownsampleRowFn )( const Pel* src, ptrdiff_t srcStride, Pel* dst, int dstWidth );
99
100
void tplDownsampleRowCore( const Pel* src, ptrdiff_t srcStride, Pel* dst, int dstWidth );
101
102
// ====================================================================================================================
103
// CU-tree adaptive quantization
104
//
105
// CU-tree (the macroblock-tree of x264, J. Garrett-Glaser 2009) lowers the QP of blocks that later pictures predict
106
// from, so the bits spent on them improve every picture that copies them. This stage estimates that dependency
107
// with the temporal dependency model (TPL) of J. Han, P. Wilkins, Y. Xu, J. Bankoski, "A quantitative approach to
108
// the temporal dependency in video coding", arXiv:2108.11586, 2021, which libaom uses. MB-tree measures the
109
// dependency on source samples, which overstates it where quantization removes the detail (film grain, low rates).
110
// TPL codes every block at its picture's QP from both the original and a reconstructed reference; the extra
111
// distortion and rate caused by the reference's coding error is what propagates.
112
//
113
// The analysis runs on half-resolution luma in 8x8 or 16x16 blocks (see TplBlkSize), in coding order. The stage
114
// holds back the pictures of a GOP until the next GOP has arrived, because the GOP's key picture is also
115
// referenced by the next one. The result is a QP offset per CTU, applied where QPA and the frame QP apply the
116
// block importance mapping (BIM) offsets, which CU-tree replaces.
117
// ====================================================================================================================
118
119
class CuTree : public EncStage
120
{
121
public:
122
  CuTree();
123
  virtual ~CuTree();
124
125
  void init( const VVEncCfg& encCfg, NoMallocThreadPool* threadPool );
126
127
  // number of pictures the stage holds in addition to the encoder's own GOP queue
128
  static int getNumLookAheadPics( const VVEncCfg& encCfg );
129
130
  // The reference pictures of a picture as the encoder will build its lists (see CuTree.cpp), public for the unit test.
131
  enum class RefState { AVAILABLE, MISSING, NOT_ARRIVED };
132
  struct PocCodingNum
133
  {
134
    int poc       = -MAX_INT;   // -MAX_INT and -1: none
135
    int codingNum = -1;
136
  };
137
  struct RefContext             // what decides which references a picture can use
138
  {
139
    int          poc;
140
    int          codingNum;
141
    PocCodingNum idr;           // the IDR coded last before the picture
142
    PocCodingNum irap;          // the IRAP coded last before it among those with a lower POC
143
    int          lastPoc;       // the highest POC received
144
    bool         flush;         // no more pictures will arrive
145
  };
146
  static bool     isCodedAsIdr( bool isIrap, int poc, bool cra, bool poc0idr, bool& idrAbove0 );
147
  static RefState refState    ( int refPoc, int refCodingNum, const RefContext& ctx );
148
  static bool     selectRefs  ( const GOPEntry& gopEntry, const RefContext& ctx,
149
                                const std::function<int( int )>& codingNumOf, int refPoc[2] );
150
151
  TplCodeBlockFn     m_codeBlock[NUM_TPL_BLK_SIZES];   // kernels per block size, SIMD where available
152
  TplPredBlockFn     m_predBlock[NUM_TPL_BLK_SIZES];
153
  TplDownsampleRowFn m_downsampleRow;
154
155
#if defined( TARGET_SIMD_X86 ) && ENABLE_SIMD_OPT
156
  void initCuTree_X86();
157
  template <X86_VEXT vext>
158
  void _initCuTree_X86();
159
#endif
160
#if defined( TARGET_SIMD_ARM ) && ENABLE_SIMD_OPT
161
  void initCuTreeARM();
162
  template <ARM_VEXT vext>
163
  void _initCuTreeARM();
164
#endif
165
166
protected:
167
  virtual void initPicture    ( Picture* pic );
168
  virtual void processPictures( const PicList& picList, AccessUnitList& auList, PicList& doneList, PicList& freeList );
169
170
private:
171
  struct Frame;
172
173
  const VVEncCfg*                       m_encCfg;
174
  NoMallocThreadPool*                   m_threadPool;
175
  MCTF                                  m_motionSearch;  // provides the integer motion search of the coarsest level
176
  RdCost                                m_rdCost;        // provides the SIMD Hadamard SATD
177
  FpDistFunc                            m_hadFunc;
178
  int                                   m_lookAheadPics;
179
  int                                   m_blkSizeIdx;    // TplBlkSize of the analysis blocks
180
  int                                   m_blkSize;       // their side at half resolution
181
  int                                   m_blkWidth;      // width and height of the picture in analysis blocks
182
  int                                   m_blkHeight;
183
  int                                   m_qpBDOffset;
184
  double                                m_lambdaLeaf;    // Lagrange multiplier at the QP of unreferenced pictures
185
  std::map<int, std::unique_ptr<Frame>> m_frames;        // analysis data by POC, kept while it can still be referenced
186
  // the IRAP and the IDR picture coded last among the erased ones
187
  PocCodingNum                          m_lastErasedIrap;
188
  PocCodingNum                          m_lastErasedIdr;
189
190
  void   xForEachRow         ( int numRows, const std::function<void( int )>& fn ) const;
191
  void   xDownsample         ( const PelStorage& src, PelStorage& dst ) const;
192
  bool   xIsBatchReady       ( const PicList& picList, int& batchEndPoc ) const;
193
  Frame* xFindFrame          ( int poc ) const;
194
  void   xMarkRandomAccess   ( const PicList& picList );
195
  void   xGetRefContext      ( const Frame& cur, bool flush, RefContext& ctx ) const;
196
  void   xAnalyse            ( Frame& frame, Picture* pic, bool flush );
197
  void   xEstimateMotion     ( const Frame& cur, const Frame& ref, Array2D<MotionVector>& mvs ) const;
198
  void   xSearchInteger      ( const PelStorage& curPic, const PelStorage& refPic, const Array2D<MotionVector>& coarse, Array2D<MotionVector>& mvs ) const;
199
  void   xSearchFractional   ( const Frame& cur, const Frame& ref, const Array2D<MotionVector>& coarse, Array2D<MotionVector>& mvs ) const;
200
  void   xPropagate          ( int firstPoc );
201
  void   xDistribute         ( Frame& ref, int bx, int by, const MotionVector& mv, double dist, double rate ) const;
202
  void   xSetPicQpOffsets    ( const std::vector<Picture*>& codingOrder, int batchEndPoc );
203
  void   xSetQpOffsets       ( const Frame& frame, Picture* pic ) const;
204
};
205
206
} // namespace vvenc
207
208
//! \}
209