Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/CommonLib/MCTF.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
/** \file     MCTF.h
43
\brief    MCTF class (header)
44
*/
45
46
#pragma once
47
48
#include "CommonLib/Unit.h"
49
#include "EncoderLib/EncStage.h"
50
#include "EncoderLib/SEIFilmGrainAnalyzer.h"
51
#include <sstream>
52
#include <map>
53
#include <deque>
54
#include <algorithm>
55
#include <atomic>
56
#include <cstdint>
57
58
namespace vvenc {
59
60
#if defined(TARGET_SIMD_X86)  && ENABLE_SIMD_OPT_MCTF
61
using namespace x86_simd;
62
#endif
63
#if defined(TARGET_SIMD_ARM)  && ENABLE_SIMD_OPT_MCTF
64
using namespace arm_simd;
65
#endif
66
67
class NoMallocThreadPool;
68
69
//! \ingroup EncoderLib
70
//! \{
71
72
double calcVarCore( const Pel* org, const ptrdiff_t origStride, const int w, const int h );
73
74
75
struct MotionVector
76
{
77
  int x, y;
78
  int error;
79
  uint16_t rmsme;
80
  double overlap;
81
82
0
  MotionVector() : x(0), y(0), error(INT_LEAST32_MAX), rmsme(UINT16_MAX) {}
83
84
0
  void set(int vectorX, int vectorY, int errorValue) { x = vectorX; y = vectorY; error = errorValue; }
85
};
86
87
template <class T>
88
struct Array2D
89
{
90
private:
91
  int m_width, m_height;
92
  std::vector< T > v;
93
public:
94
0
  Array2D() : m_width(0), m_height(0), v() { }
95
  Array2D(int width, int height, const T& value=T()) : m_width(0), m_height(0), v() { allocate(width, height, value); }
96
97
0
  int w() const { return m_width; }
98
0
  int h() const { return m_height; }
99
100
  void allocate(int width, int height, const T& value=T())
101
0
  {
102
0
    m_width=width;
103
0
    m_height=height;
104
0
    v.resize(std::size_t(m_width*m_height), value);
105
0
  }
106
107
  T& get(int x, int y)
108
0
  {
109
0
    assert(x<m_width && y<m_height);
110
0
    return v[y*m_width+x];
111
0
  }
112
113
  const T& get(int x, int y) const
114
0
  {
115
0
    assert(x<m_width && y<m_height);
116
0
    return v[y*m_width+x];
117
0
  }
118
};
119
120
struct TemporalFilterSourcePicInfo
121
{
122
0
  TemporalFilterSourcePicInfo() : picBuffer(), mvs(), index(0) { }
123
  PelStorage            picBuffer;
124
  Array2D<MotionVector> mvs;
125
  int                   index;
126
};
127
// ====================================================================================================================
128
// Class definition
129
// ====================================================================================================================
130
131
struct Picture;
132
133
class MCTF : public EncStage
134
{
135
public:
136
  MCTF( bool enableOpt = true );
137
  virtual ~MCTF();
138
139
  void init( const VVEncCfg& encCfg, bool isFinalPass, NoMallocThreadPool* threadPool );
140
141
protected:
142
  virtual void initPicture    ( Picture* pic );
143
  virtual void processPictures( const PicList& picList, AccessUnitList& auList, PicList& doneList, PicList& freeList );
144
private:
145
  void filter( const std::deque<Picture*>& picFifo, int filterIdx );
146
147
#if defined(TARGET_SIMD_X86) && ENABLE_SIMD_OPT_MCTF
148
  void initMCTF_X86();
149
  template <X86_VEXT vext>
150
  void _initMCTF_X86();
151
#endif
152
153
#if defined(TARGET_SIMD_ARM) && ENABLE_SIMD_OPT_MCTF
154
  void initMCTF_ARM();
155
  template <ARM_VEXT vext>
156
  void _initMCTF_ARM();
157
#endif
158
159
public:
160
  static const int16_t m_interpolationFilter4[16][4];
161
  static const int16_t m_interpolationFilter8[16][8];
162
163
  // The largest block whose squared error cannot overflow 32 bits: 2048 * 1023^2 < 2^31 (samples of at most 10 bits).
164
  static constexpr int MAX_EXACT_INT_AREA = 2048;
165
166
  int ( *m_motionErrorLumaIntX )( const Pel* org, const ptrdiff_t origStride, const Pel* buf, const ptrdiff_t buffStride, const int w, const int h, const int besterror );
167
  int ( *m_motionErrorLumaInt8 )( const Pel* org, const ptrdiff_t origStride, const Pel* buf, const ptrdiff_t buffStride, const int w, const int h, const int besterror );
168
  // m_motionErrorLumaInt8 for the four reference positions refs[0..3] in one call, into errors[0..3]: w is a multiple of
169
  // 16 and w * h at most MAX_EXACT_INT_AREA. The error of position k is exact when it is not above bound k, the
170
  // smallest of besterror and the errors of positions 0 to k - 1; otherwise it is some value above bound k (it may be a
171
  // partial sum, as with the one-position kernels). Comparing the errors in order thus gives the same best vector as
172
  // testing the four positions one after another.
173
  void ( *m_motionErrorLumaInt4 )( const Pel* org, const ptrdiff_t origStride, const Pel* const* refs, const ptrdiff_t buffStride, const int w, const int h, const int besterror, int* errors );
174
  // m_motionErrorLumaInt4 from a one-position kernel: the four positions one after another, each stopping early against
175
  // bound k as the one-position search does. The C code and the SIMD levels without a four-position kernel use it.
176
  template<int ( *motionErrorLumaInt )( const Pel*, const ptrdiff_t, const Pel*, const ptrdiff_t, const int, const int, const int )>
177
  static void motionErrorLumaInt4Loop( const Pel* org, const ptrdiff_t origStride, const Pel* const* refs, const ptrdiff_t buffStride, const int w, const int h, const int besterror, int* errors )
178
0
  {
179
0
    int bound = besterror;
180
0
    for( int k = 0; k < 4; k++ )
181
0
    {
182
0
      errors[k] = motionErrorLumaInt( org, origStride, refs[k], buffStride, w, h, bound );
183
0
      bound     = std::min( bound, errors[k] );
184
0
    }
185
0
  }
186
187
  int ( *m_motionErrorLumaFracX[2] )( const Pel* org, const ptrdiff_t origStride, const Pel* buf, const ptrdiff_t buffStride, const int w, const int h, const int16_t* xFilter, const int16_t* yFilter, const int bitDepth, const int besterror );
188
  int ( *m_motionErrorLumaFrac8[2] )( const Pel* org, const ptrdiff_t origStride, const Pel* buf, const ptrdiff_t buffStride, const int w, const int h, const int16_t* xFilter, const int16_t* yFilter, const int bitDepth, const int besterror );
189
  // The horizontal 4-tap pass of a column of vectors: numRows rows of w samples into filtered (stride w), row r from
190
  // source row r - 1 of buf, rounded and clipped to the sample range; w is a multiple of 16 and at most 32 (MCTFUnitSize),
191
  // numRows at most 36.
192
  void ( *m_filterColumn4 )( const Pel* buf, const ptrdiff_t buffStride, const int w, const int numRows, const int16_t* xFilter, const int bitDepth, Pel* filtered );
193
  // The exact errors (no early exit) of num <= 4 vectors that share their horizontal position, for the 4-tap filters,
194
  // from the rows of m_filterColumn4: vector i uses yFilter[i] and starts rowOffset[i] (0 or 1) rows below filtered; w is
195
  // a multiple of 16, w and h are at most 32 (MCTFUnitSize).
196
  void ( *m_motionErrorLumaFracColumn )( const Pel* org, const ptrdiff_t origStride, const Pel* filtered, const int w, const int h, const int num, const int16_t* const* yFilter, const int* rowOffset, const int bitDepth, int* error );
197
198
  void( *m_applyFrac[MAX_NUM_CH][2] )( const Pel* org, const ptrdiff_t origStride, Pel* dst, const ptrdiff_t dstStride, const int bsx, const int bsy, const int16_t* xFilter, const int16_t* yFilter, const int bitDepth );
199
200
  void( *m_applyPlanarCorrection )( const Pel* refPel, const ptrdiff_t refStride, Pel* dstPel, const ptrdiff_t dstStride, const int32_t w, const int32_t h, const ClpRng& clpRng, const uint16_t motionError );
201
  void( *m_applyBlock )( const CPelBuf& src, PelBuf& dst, const CompArea& blk, const ClpRng& clpRng, const Pel** correctedPics, int numRefs, const int* verror, const double* refStrenghts, double weightScaling, double sigmaSq );
202
  double( *m_calcVar ) ( const Pel* org, const ptrdiff_t origStride, const int w, const int h );
203
204
  // The CU-tree look-ahead reuses the motion search.
205
  void motionEstimationLuma(Array2D<MotionVector> &mvs, const PelStorage &orig, const PelStorage &buffer, const int refMargin, const int bs,
206
    const Array2D<MotionVector> *previous=0, const int factor = 1, const bool doubleRes = false) const;
207
208
private:
209
  static const double   m_chromaFactor;
210
  static const double   m_sigmaMultiplier;
211
  static const int      m_range;
212
  static const int      m_motionVectorFactor;
213
  static const int      m_padding;
214
  static const double   m_refStrengths[2][6];
215
  static const int      m_cuTreeThresh[4];
216
  static const double   m_cuTreeCenter;
217
218
  const VVEncCfg*       m_encCfg;
219
  NoMallocThreadPool*   m_threadPool;
220
  bool                  m_isFinalPass;
221
  int                   m_filterPoc;
222
  Area                  m_area;
223
  int                   m_MCTFSpeedVal;
224
  Picture*              m_lastPicIn;
225
  bool                  m_lowResFltSearch = false;  // TODO: use this to select high/low-res filter (6/4 tap) for motion search
226
  bool                  m_lowResFltApply  = false;  // TODO: use this to select high/low-res filter (6/4 tap) for actual application
227
  int                   m_searchPttrn     = 0;
228
  double                m_filterStrength[VVENC_MAX_MCTF_FRAMES];   // the strength the encoding's filter uses, per MCTF index
229
  int                   m_mctfUnitSize;
230
  FgaRowKernels         m_fgaKernels;       // the temporal residual of the improved film grain analysis (--fga 2)
231
232
  void subsampleLuma    (const PelStorage &input, PelStorage &output, const int factor = 2) const;
233
234
  // The temporal residual of the film grain for the improved analysis (--fga 2) of the picture orig with POC poc, from
235
  // its neighbours POC - 1 and POC + 1 in picFifo, motion compensated with the vectors estimated for the filter (their
236
  // entries in srcFrameInfo).
237
  // Returns the variance of the residual relative to the grain variance: 6 with both neighbours, 2 with one, and 0,
238
  // with no residual made, with none.
239
  int  fgaTemporalResidual( const PelStorage& orig, int poc, const std::deque<Picture*>& picFifo,
240
                            const std::deque<TemporalFilterSourcePicInfo>& srcFrameInfo,
241
                            PelStorage& residual ) const;
242
243
  // refMargin is the width of the replicated border around the reference frame buffer.
244
  int motionErrorLuma   (const PelStorage &orig, const PelStorage &buffer, const int refMargin, const int x, const int y, int dx, int dy, const int bs, const int besterror) const;
245
  // The horizontally filtered columns (m_filterColumn4) of one block's subpel search, kept across its refinement steps:
246
  // a later step's column with the same horizontal position and rows inside a kept one reuses its rows.
247
  class FilteredColumns
248
  {
249
  public:
250
    static constexpr int MAX_WIDTH = 32;   // MCTFUnitSize
251
252
    // The w-wide rows of the column at horizontal position dx (1/16 samples) whose vectors start top to bottom full
253
    // rows below the block (dy >> 4), from a kept column of the same position that covers them, or nullptr.
254
    const Pel* find( const int dx, const int top, const int bottom, const int w )
255
0
    {
256
0
      for( int c = 0; c < m_num; c++ )
257
0
      {
258
0
        if( m_dx[c] == dx && m_top[c] <= top && m_bottom[c] >= bottom )
259
0
        {
260
0
          return rows( c ) + ( top - m_top[c] ) * w;
261
0
        }
262
0
      }
263
0
      return nullptr;
264
0
    }
265
266
    // The buffer for the rows of a new column, a free slot or, with none left, the last one.
267
    Pel* add( const int dx, const int top, const int bottom )
268
0
    {
269
0
      const int c = std::min( m_num, MAX_COLUMNS - 1 );
270
0
      m_num       = c + 1;
271
0
      m_dx[c]     = dx;
272
0
      m_top[c]    = top;
273
0
      m_bottom[c] = bottom;
274
0
      return rows( c );
275
0
    }
276
277
  private:
278
    static constexpr int MAX_COLUMNS = 8;
279
    static constexpr int MAX_ROWS    = MAX_WIDTH + 4;          // h + 3 rows per vector plus the one-row spread of a column
280
    static constexpr int COLUMN_SIZE = MAX_ROWS * MAX_WIDTH;   // a multiple of 16 samples (32 bytes)
281
    static constexpr int ALIGNMENT   = 32;                     // bytes: the 256-bit loads of the vertical pass do not split
282
283
    Pel* rows( const int c )
284
0
    {
285
0
      const uintptr_t start = ( reinterpret_cast<uintptr_t>( m_storage ) + ALIGNMENT - 1 ) & ~uintptr_t( ALIGNMENT - 1 );
286
0
      return reinterpret_cast<Pel*>( start ) + c * COLUMN_SIZE;
287
0
    }
288
289
    int m_dx[MAX_COLUMNS], m_top[MAX_COLUMNS], m_bottom[MAX_COLUMNS];
290
    int m_num = 0;
291
    Pel m_storage[MAX_COLUMNS * COLUMN_SIZE + ALIGNMENT / sizeof( Pel )];
292
  };
293
  void testSubpelLattice( const PelStorage &orig, const PelStorage &buffer, const int refMargin, const int x, const int y, const int bs,
294
                          const MotionVector &center, const int range, const int step, FilteredColumns &columns, MotionVector &best ) const;
295
  void testIntegerLattice( const PelStorage &orig, const PelStorage &buffer, const int refMargin, const int x, const int y, const int bs,
296
                           const int centerX, const int centerY, const int range, const int step, const MotionVector &tested, MotionVector &best ) const;
297
298
  bool estimateLumaLn   ( std::atomic_int& blockX, std::atomic_int* prevLineX, Array2D<MotionVector> &mvs, const PelStorage &orig, const PelStorage &buffer, const int refMargin, const int blockSize,
299
    const Array2D<MotionVector> *previous, const int factor, const bool doubleRes, int blockY, int bitDepth ) const;
300
301
  void bilateralFilter  (const PelStorage &orgPic, std::deque<TemporalFilterSourcePicInfo> &srcFrameInfo, PelStorage &newOrgPic, double overallStrength) const;
302
303
  void xFinalizeBlkLine (const PelStorage &orgPic, std::deque<TemporalFilterSourcePicInfo> &srcFrameInfo, PelStorage &newOrgPic, int yStart, const double sigmaSqCh[MAX_NUM_CH], double overallStrenght) const;
304
305
  // One level of the motion search of one reference: the arguments of motionEstimationLuma.
306
  struct MotionSearchJob
307
  {
308
    Array2D<MotionVector>*       mvs;
309
    const PelStorage*            orig;
310
    const PelStorage*            buffer;
311
    int                          refMargin;
312
    int                          blockSize;
313
    const Array2D<MotionVector>* previous;
314
    int                          factor;
315
    bool                         doubleRes;
316
  };
317
  // Runs the jobs' row tasks together and waits once, so the rows of one job fill the threads the others leave idle.
318
  void motionEstimationLumaJobs( const std::vector<MotionSearchJob>& jobs ) const;
319
320
  // The search pyramid of one reference picture: its subsampled lumas and the vectors of each level.
321
  struct ReferenceSearch
322
  {
323
    TemporalFilterSourcePicInfo* srcPic = nullptr;
324
    PelStorage                   bufferSub2;
325
    PelStorage                   bufferSub4;
326
    PelStorage                   bufferSub8;
327
    Array2D<MotionVector>        mv_m;
328
    Array2D<MotionVector>        mv_0;
329
    Array2D<MotionVector>        mv_1;
330
    Array2D<MotionVector>        mv_2;
331
  };
332
333
  // Builds the reference's subsampled lumas (1/2, 1/4 and, with addLevel, 1/8 resolution).
334
  void subsampleReference( ReferenceSearch& ref, const bool addLevel ) const;
335
  // The same for all references, one pool task each.
336
  void subsampleReferences( std::deque<ReferenceSearch>& refs, const bool addLevel ) const;
337
338
  // Searches the reference pictures refPics level by level, all references of a level at once; appends one
339
  // srcFrameInfo entry per reference and, with calcErr, one mvErr entry, in the order of refPics.
340
  void motionEstimationMCTF(const std::vector<Picture*>& refPics, std::deque<TemporalFilterSourcePicInfo>& srcFrameInfo, const PelStorage& origBuf, PelStorage& origSubsampled2, PelStorage& origSubsampled4, PelStorage& origSubsampled8, std::vector<double>& mvErr, double& minError, bool addLevel, bool calcErr);
341
342
}; // END CLASS DEFINITION MCTF
343
344
//! \}
345
346
} // namespace vvenc
347
348