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/EncModeCtrl.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     EncModeCtrl.h
43
    \brief    Encoder controller for trying out specific modes
44
*/
45
46
#pragma once
47
48
#include "InterSearch.h"
49
#include "CommonLib/CommonDef.h"
50
#include "CommonLib/CodingStructure.h"
51
52
#include <memory>
53
#include <typeinfo>
54
#include <vector>
55
56
//! \ingroup EncoderLib
57
//! \{
58
59
namespace vvenc {
60
61
//////////////////////////////////////////////////////////////////////////
62
// Encoder modes to try out
63
//////////////////////////////////////////////////////////////////////////
64
65
66
enum EncTestModeType
67
{
68
  ETM_MERGE_SKIP,
69
  ETM_INTER_ME,
70
  ETM_INTER_IMV,
71
  ETM_INTRA,
72
  ETM_SPLIT_QT,
73
  ETM_SPLIT_BT_H,
74
  ETM_SPLIT_BT_V,
75
  ETM_SPLIT_TT_H,
76
  ETM_SPLIT_TT_V,
77
  ETM_RECO_CACHED,
78
  ETM_IBC,
79
  ETM_IBC_MERGE,
80
  ETM_INVALID
81
};
82
83
enum EncTestModeOpts
84
{
85
  ETO_STANDARD    =  0,                   // empty      (standard option)
86
  ETO_FORCE_MERGE =  1<<0,                // bit   0    (indicates forced merge)
87
  ETO_IMV_SHIFT   =  1,                   // bits  1-3  (imv parameter starts at bit 1)
88
  ETO_IMV         =  7<<ETO_IMV_SHIFT,    // bits  1-3  (imv parameter uses 3 bits)
89
  ETO_DUMMY       =  1<<5,                // bit   5    (dummy)
90
  ETO_INVALID     = 0xffffffff            // bits 0-31  (invalid option)
91
};
92
93
static inline void getAreaIdxNew(const Area& area, const PreCalcValues &pcv, unsigned& idx1, unsigned& idx2, unsigned& idx3, unsigned& idx4)
94
413k
{
95
413k
  idx1 = Log2( area.width  )-2;
96
413k
  idx2 = Log2( area.height )-2;
97
413k
  idx3 = (area.x & pcv.maxCUSizeMask) >> MIN_CU_LOG2;
98
413k
  idx4 = (area.y & pcv.maxCUSizeMask) >> MIN_CU_LOG2;
99
413k
}
Unexecuted instantiation: vvencimpl.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: EncLib.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: CuTree.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: EncGOP.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: EncPicture.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: EncSlice.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: InterSearch.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Unexecuted instantiation: EncCu.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
EncModeCtrl.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
Line
Count
Source
94
413k
{
95
413k
  idx1 = Log2( area.width  )-2;
96
413k
  idx2 = Log2( area.height )-2;
97
413k
  idx3 = (area.x & pcv.maxCUSizeMask) >> MIN_CU_LOG2;
98
413k
  idx4 = (area.y & pcv.maxCUSizeMask) >> MIN_CU_LOG2;
99
413k
}
Unexecuted instantiation: IntraSearch.cpp:vvenc::getAreaIdxNew(vvenc::Area const&, vvenc::PreCalcValues const&, unsigned int&, unsigned int&, unsigned int&, unsigned int&)
100
101
struct EncTestMode
102
{
103
  EncTestMode()
104
921k
    : type( ETM_INVALID ), opts( ETO_INVALID  ), qp( -1  ), lossless( false ) {}
105
  EncTestMode( EncTestModeType _type )
106
0
    : type( _type       ), opts( ETO_STANDARD ), qp( -1  ), lossless( false ) {}
107
  EncTestMode( EncTestModeType _type, int _qp, bool _lossless )
108
0
    : type( _type       ), opts( ETO_STANDARD ), qp( _qp ), lossless( _lossless ) {}
109
  EncTestMode( EncTestModeType _type, EncTestModeOpts _opts, int _qp, bool _lossless )
110
536k
    : type( _type       ), opts( _opts        ), qp( _qp ), lossless( _lossless ) {}
111
112
  EncTestModeType type;
113
  EncTestModeOpts opts;
114
  int             qp;
115
  bool            lossless;
116
  double          maxCostAllowed;
117
};
118
119
120
inline bool isModeSplit( const EncTestMode& encTestmode )
121
587k
{
122
587k
  switch( encTestmode.type )
123
587k
  {
124
119k
  case ETM_SPLIT_QT     :
125
183k
  case ETM_SPLIT_BT_H   :
126
242k
  case ETM_SPLIT_BT_V   :
127
277k
  case ETM_SPLIT_TT_H   :
128
304k
  case ETM_SPLIT_TT_V   :
129
304k
    return true;
130
283k
  default:
131
283k
    return false;
132
587k
  }
133
587k
}
134
135
inline bool isModeNoSplit( const EncTestMode& encTestmode )
136
0
{
137
0
  return !isModeSplit( encTestmode );
138
0
}
139
140
inline bool isModeInter( const EncTestMode& encTestmode ) // perhaps remove
141
185k
{
142
185k
  return (   encTestmode.type == ETM_INTER_ME
143
185k
          || encTestmode.type == ETM_INTER_IMV
144
185k
          || encTestmode.type == ETM_MERGE_SKIP
145
185k
         );
146
185k
}
147
148
inline PartSplit getPartSplit( const EncTestMode& encTestmode )
149
746k
{
150
746k
  switch( encTestmode.type )
151
746k
  {
152
195k
  case ETM_SPLIT_QT     : return CU_QUAD_SPLIT;
153
248k
  case ETM_SPLIT_BT_H   : return CU_HORZ_SPLIT;
154
235k
  case ETM_SPLIT_BT_V   : return CU_VERT_SPLIT;
155
37.3k
  case ETM_SPLIT_TT_H   : return CU_TRIH_SPLIT;
156
29.1k
  case ETM_SPLIT_TT_V   : return CU_TRIV_SPLIT;
157
0
  default:                return CU_DONT_SPLIT;
158
746k
  }
159
746k
}
160
161
//////////////////////////////////////////////////////////////////////////
162
// EncModeCtrl controls if specific modes should be tested
163
//////////////////////////////////////////////////////////////////////////
164
165
struct ComprCUCtx
166
{
167
  ComprCUCtx()
168
160k
  {
169
160k
  }
170
171
  ComprCUCtx( const CodingStructure& cs, const uint32_t _minDepth, const uint32_t _maxDepth )
172
156k
    : minDepth      ( _minDepth  )
173
156k
    , maxDepth      ( _maxDepth  )
174
156k
    , bestCS        ( nullptr    )
175
156k
    , bestCU        ( nullptr    )
176
156k
    , bestTU        ( nullptr    )
177
156k
    , bestMode      ()
178
156k
    , bestCostBeforeSplit   (MAX_DOUBLE)
179
156k
    , bestCostVertSplit     (MAX_DOUBLE)
180
156k
    , bestCostHorzSplit     (MAX_DOUBLE)
181
156k
    , bestCostNoImv         (MAX_DOUBLE *.5)
182
156k
    , grad_horVal           (0)
183
156k
    , grad_verVal           (0)
184
156k
    , grad_dupVal           (0)
185
156k
    , grad_dowVal           (0)
186
156k
    , interHad              (MAX_DISTORTION)
187
156k
    , maxQtSubDepth         (0)
188
156k
    , isReusingCu           (false)
189
156k
    , qtBeforeBt            (false)
190
156k
    , doTriHorzSplit        (false)
191
156k
    , doTriVertSplit        (false)
192
156k
    , didQuadSplit          (false)
193
156k
    , didHorzSplit          (false)
194
156k
    , didVertSplit          (false)
195
156k
    , doHorChromaSplit      (false)
196
156k
    , doVerChromaSplit      (false)
197
156k
    , doQtChromaSplit       (false)
198
156k
    , isBestNoSplitSkip     (false)
199
156k
    , intraWasTested        (false)
200
156k
    , relatedCuIsValid      (false)
201
156k
    , isIntra               (false)
202
156k
    , nonSkipWasTested      (false)
203
156k
    , bestNsPredMode        (EncTestMode())
204
156k
    , meCost                (MAX_DOUBLE)
205
156k
    , meLargestMvd          (-1)
206
156k
  {
207
156k
  }
208
209
  unsigned          minDepth;
210
  unsigned          maxDepth;
211
  CodingStructure*  bestCS;
212
  CodingUnit*       bestCU;
213
  TransformUnit*    bestTU;
214
  EncTestMode       bestMode;
215
  double            bestCostBeforeSplit;
216
  double            bestCostVertSplit;
217
  double            bestCostHorzSplit;
218
  double            bestCostNoImv;
219
  double            grad_horVal;
220
  double            grad_verVal;
221
  double            grad_dupVal;
222
  double            grad_dowVal;
223
  Distortion        interHad;
224
  int               maxQtSubDepth;
225
  bool              isReusingCu;
226
  bool              qtBeforeBt;
227
  bool              doTriHorzSplit;
228
  bool              doTriVertSplit;
229
  int               doMoreSplits;
230
  bool              didQuadSplit;
231
  bool              didHorzSplit;
232
  bool              didVertSplit;
233
  bool              doHorChromaSplit;
234
  bool              doVerChromaSplit;
235
  bool              doQtChromaSplit;
236
  bool              isBestNoSplitSkip;
237
  bool              intraWasTested;
238
  bool              relatedCuIsValid;
239
  bool              isIntra;
240
  bool              nonSkipWasTested;
241
  EncTestMode       bestNsPredMode;
242
  // FastAMVR: the motion search with quarter-sample MVDs and equal bi-prediction weights
243
  double            meCost;            // its best RD cost, MAX_DOUBLE where it has none
244
  int               meLargestMvd;      // the largest MVD component of its result in quarter samples, -1 where it has none
245
};
246
247
//////////////////////////////////////////////////////////////////////////
248
// some utility interfaces that expose some functionality that can be used without concerning about which particular controller is used
249
//////////////////////////////////////////////////////////////////////////
250
251
static const int MAX_STORED_CU_INFO_REFS = 4;
252
253
struct CodedCUInfo
254
{
255
  bool      relatedCuIsValid;
256
  bool      isInter;
257
  bool      isIntra;
258
  bool      isSkip;
259
  bool      isMMVDSkip;
260
  bool      isIBC;
261
  uint8_t   BcwIdx;
262
  uint8_t   numPuInfoStored;
263
  int       poc, ctuRsAddr;
264
  bool      validMv[NUM_REF_PIC_LIST_01][MAX_STORED_CU_INFO_REFS];
265
  Mv        saveMv [NUM_REF_PIC_LIST_01][MAX_STORED_CU_INFO_REFS];
266
  uint32_t  puSse  [SBT_NUM_SL];
267
  uint8_t   puSbt  [SBT_NUM_SL];
268
  double    bestCost;
269
270
  bool getMv  ( const RefPicList refPicList, const int iRefIdx,       Mv& rMv ) const;
271
  void setMv  ( const RefPicList refPicList, const int iRefIdx, const Mv& rMv );
272
};
273
274
class CacheBlkInfoCtrl
275
{
276
protected:
277
  // x in CTU, y in CTU, width, height
278
  CodedCUInfo*         m_codedCUInfo[6][6][MAX_CU_SIZE >> MIN_CU_LOG2][MAX_CU_SIZE >> MIN_CU_LOG2];
279
  CodedCUInfo*         m_codedCUInfoBuf;
280
  const PreCalcValues* m_pcv;
281
282
protected:
283
284
  void create   ( int ctuSize );
285
  void destroy  ();
286
  void init     ( const Slice &slice );
287
288
public:
289
5.72k
  CacheBlkInfoCtrl() : m_codedCUInfoBuf( nullptr ) {}
290
5.72k
  ~CacheBlkInfoCtrl () {}
291
292
  CodedCUInfo& getBlkInfo   ( const UnitArea& area );
293
  void         initBlk      ( const UnitArea& area, int poc );
294
295
  uint8_t      findBestSbt  ( const UnitArea& area, const uint32_t curPuSse );
296
  bool         saveBestSbt  ( const UnitArea& area, const uint32_t curPuSse, const uint8_t curPuSbt );
297
};
298
299
struct BestEncodingInfo
300
{ 
301
  CodingUnit      cu;
302
  TransformUnit   tu;
303
  EncTestMode     testMode;
304
  int             poc;
305
  Distortion      dist;
306
  double          costEDO;
307
};
308
309
// Hands out runs of T from chunks that are kept for reuse. Runs never move, so pointers into them
310
// stay valid until reset() makes all chunks available again.
311
template<typename T, size_t ChunkSize>
312
class ReusableChunkArena
313
{
314
public:
315
  T* take( const size_t n )
316
0
  {
317
0
    CHECK( n > ChunkSize, "Run larger than an arena chunk" );
318
0
    if( m_current < 0 || m_used + n > ChunkSize )
319
0
    {
320
0
      m_current++;
321
0
      if( m_current == ( int ) m_chunks.size() )
322
0
      {
323
0
        m_chunks.emplace_back( new T[ChunkSize] );
324
0
      }
325
0
      m_used = 0;
326
0
    }
327
0
    T* run  = m_chunks[m_current].get() + m_used;
328
0
    m_used += n;
329
0
    return run;
330
0
  }
Unexecuted instantiation: vvenc::ReusableChunkArena<vvenc::BestEncodingInfo, 256ul>::take(unsigned long)
Unexecuted instantiation: vvenc::ReusableChunkArena<vvenc::Mv, 4096ul>::take(unsigned long)
Unexecuted instantiation: vvenc::ReusableChunkArena<short, 131072ul>::take(unsigned long)
331
332
0
  void reset()   { m_current = -1; m_used = 0; }
Unexecuted instantiation: vvenc::ReusableChunkArena<vvenc::BestEncodingInfo, 256ul>::reset()
Unexecuted instantiation: vvenc::ReusableChunkArena<short, 131072ul>::reset()
Unexecuted instantiation: vvenc::ReusableChunkArena<vvenc::Mv, 4096ul>::reset()
333
0
  void release() { m_chunks.clear(); reset(); }
Unexecuted instantiation: vvenc::ReusableChunkArena<vvenc::BestEncodingInfo, 256ul>::release()
Unexecuted instantiation: vvenc::ReusableChunkArena<short, 131072ul>::release()
Unexecuted instantiation: vvenc::ReusableChunkArena<vvenc::Mv, 4096ul>::release()
334
335
private:
336
  std::vector<std::unique_ptr<T[]>> m_chunks;
337
  int    m_current = -1;
338
  size_t m_used    = 0;
339
};
340
341
class BestEncInfoCache
342
{
343
private:
344
  const PreCalcValues* m_pcv;
345
  // The stored result of every CU size and position inside the CTU being encoded, or null. A result
346
  // only matches a CU of the same picture and position, so none outlives the CTU it was stored for,
347
  // and init() empties the slots of the previous CTU and reuses their storage.
348
  BestEncodingInfo*    m_bestEncInfo[6][6][MAX_CU_SIZE >> MIN_CU_LOG2][MAX_CU_SIZE >> MIN_CU_LOG2];
349
  std::vector<BestEncodingInfo**>           m_filledSlots;
350
  ReusableChunkArena<BestEncodingInfo, 256> m_entryArena;
351
  ReusableChunkArena<TCoeffSig, 131072>     m_coeffArena;
352
  ReusableChunkArena<Mv, 4096>              m_dmvrMvArena;
353
  ChromaFormat         m_chFmt;
354
  CodingStructure      m_dummyCS;
355
  XUCache              m_dummyCache;
356
357
  BestEncodingInfo*    xNewEntry( const int wIdx, const int hIdx );
358
359
protected:
360
  bool                 m_reuseCuResults;
361
  void create   ( const bool reuseCuResults, const ChromaFormat chFmt, int ctuSize );
362
  void destroy  ();
363
364
public:
365
5.72k
  BestEncInfoCache() : m_pcv( nullptr ), m_chFmt( CHROMA_420 ), m_dummyCS( m_dummyCache, nullptr ) {}
366
5.72k
  ~BestEncInfoCache() {}
367
368
  void init             ( const Slice &slice );
369
  bool setCsFrom        (       CodingStructure& cs,       EncTestMode& testMode, const Partitioner& partitioner ) const;
370
  bool setFromCs        ( const CodingStructure& cs, const EncTestMode& testMode, const Partitioner& partitioner );
371
  bool isReusingCuValid ( const CodingStructure &cs, const Partitioner &partitioner, int qp );
372
};
373
374
//////////////////////////////////////////////////////////////////////////
375
// EncModeCtrl - allows and controls modes introduced by QTBT (inkl. multi-type-tree)
376
//                    - only 2Nx2N, no RQT, additional binary/triary CU splits
377
//////////////////////////////////////////////////////////////////////////
378
379
class EncModeCtrl: public CacheBlkInfoCtrl, public BestEncInfoCache
380
{
381
protected:
382
383
  const VVEncCfg*       m_pcEncCfg;
384
        RdCost*         m_pcRdCost;
385
  static_vector<ComprCUCtx, ( MAX_CU_DEPTH << 2 )> m_ComprCUCtxList;
386
  unsigned              m_skipThresholdE0023FastEnc;
387
388
  void     xNoteMotionSearchCost  ( const EncTestMode& encTestmode, const CodingStructure& tempCS );
389
390
public:
391
  ComprCUCtx*           comprCUCtx;
392
393
5.72k
  ~EncModeCtrl    () { destroy(); }
394
395
  void init               ( const VVEncCfg& encCfg, RdCost *pRdCost );
396
  void destroy            ();
397
  void initCTUEncoding    ( const Slice &slice );
398
  // cuLeft / cuAbove: the restricted left and above neighbours of the CU (DeriveCtx::determineNeighborCus)
399
  void initCULevel        ( Partitioner &partitioner, const CodingStructure& cs, int  MergeSimpleFlag, const CodingUnit* cuLeft, const CodingUnit* cuAbove );
400
  void finishCULevel      ( Partitioner &partitioner );
401
402
  bool tryMode            ( const EncTestMode& encTestmode, const CodingStructure &cs, Partitioner& partitioner );
403
  bool trySplit           ( const EncTestMode& encTestmode, const CodingStructure &cs, Partitioner& partitioner, const EncTestMode& lastTestmode );
404
  bool useModeResult      ( const EncTestMode& encTestmode, CodingStructure*& tempCS,  Partitioner& partitioner, const bool useEDO );
405
406
  void beforeSplit        ( Partitioner& partitioner );
407
408
  // FastAMVR: noteMotionSearchMvd keeps the largest MVD of the current node's motion search with equal bi-prediction weights;
409
  // skipsAmvrSearch and skips4PelAmvr say where the AMVR search, or its 4-sample MVDs, cannot pay
410
  void     noteMotionSearchMvd  ( const CodingUnit& cu );
411
  bool     skipsAmvrSearch      ( const CodingStructure& bestCS ) const;
412
  bool     skips4PelAmvr        () const;
413
};
414
415
} // namespace vvenc
416
417
//! \}
418