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/EncLib.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     EncLib.cpp
45
    \brief    encoder class
46
*/
47
48
#include "EncLib.h"
49
#include "CommonLib/Picture.h"
50
#include "CommonLib/CommonDef.h"
51
#include "CommonLib/TimeProfiler.h"
52
#include "CommonLib/Rom.h"
53
#include "CommonLib/MCTF.h"
54
#include "Utilities/NoMallocThreadPool.h"
55
#include "Utilities/MsgLog.h"
56
#include "EncStage.h"
57
#include "PreProcess.h"
58
#include "CuTree.h"
59
#include "EncGOP.h"
60
#include "CommonLib/x86/CommonDefX86.h"
61
62
//! \ingroup EncoderLib
63
//! \{
64
65
namespace vvenc {
66
67
68
// ====================================================================================================================
69
// Constructor / destructor / create / destroy
70
// ====================================================================================================================
71
72
EncLib::EncLib( MsgLog& logger )
73
1.43k
  : msg             ( logger )
74
1.43k
  , m_recYuvBufFunc  ( nullptr )
75
1.43k
  , m_recYuvBufCtx   ( nullptr )
76
1.43k
  , m_encCfg         ()
77
1.43k
  , m_orgCfg         ()
78
1.43k
  , m_firstPassCfg   ()
79
1.43k
  , m_rateCtrl       ( nullptr )
80
1.43k
  , m_preProcess     ( nullptr )
81
1.43k
  , m_MCTF           ( nullptr )
82
1.43k
  , m_cuTree         ( nullptr )
83
1.43k
  , m_preEncoder     ( nullptr )
84
1.43k
  , m_gopEncoder     ( nullptr )
85
1.43k
  , m_threadPool     ( nullptr )
86
1.43k
  , m_picsRcvd       ( 0 )
87
1.43k
  , m_passInitialized( -1 )
88
1.43k
  , m_maxNumPicShared( MAX_INT )
89
1.43k
  , m_accessUnitOutputStarted( false )
90
1.43k
{
91
1.43k
}
92
93
EncLib::~EncLib()
94
1.43k
{
95
1.43k
  delete m_rateCtrl;
96
1.43k
  m_rateCtrl = nullptr;
97
1.43k
}
98
99
void EncLib::setRecYUVBufferCallback( void* ctx, vvencRecYUVBufferCallback func )
100
0
{
101
0
  m_recYuvBufCtx  = ctx;
102
0
  m_recYuvBufFunc = func;
103
0
  if( m_rateCtrl && m_rateCtrl->rcIsFinalPass && m_gopEncoder )
104
0
  {
105
0
    m_gopEncoder->setRecYUVBufferCallback( m_recYuvBufCtx, m_recYuvBufFunc );
106
0
  }
107
0
}
108
109
void EncLib::initEncoderLib( const vvenc_config& encCfg )
110
1.43k
{
111
  // copy config parameter
112
1.43k
  const_cast<VVEncCfg&>(m_encCfg) = encCfg;
113
114
#if defined( REAL_TARGET_X86 ) && defined( _MSC_VER ) && _MSC_VER >= 1938 && _MSC_VER < 1939
115
  if( read_x86_extension_flags() >= x86_simd::AVX2 )
116
  {
117
    msg.log( VVENC_WARNING, "WARNING: MSVC version 17.8 produces invalid AVX2 code, partially disabling AVX2!\n" );
118
  }
119
120
#endif
121
  // setup modified configs for rate control
122
1.43k
  if( m_encCfg.m_RCNumPasses > 1 || m_encCfg.m_LookAhead )
123
0
  {
124
0
    xInitRCCfg();
125
0
  }
126
127
  // initialize pass
128
1.43k
  initPass( 0, nullptr );
129
130
#if ENABLE_TRACING
131
  g_trace_ctx = tracing_init( m_encCfg.m_traceFile, m_encCfg.m_traceRule, msg );
132
  if( g_trace_ctx && m_encCfg.m_listTracingChannels )
133
  {
134
    std::string sChannelsList;
135
    g_trace_ctx->getChannelsList( sChannelsList );
136
    msg.log( VVENC_INFO, "\n Using tracing channels:\n\n%s\n", sChannelsList.c_str() );
137
  }
138
#endif
139
140
#if ENABLE_TIME_PROFILING
141
  if( g_timeProfiler )
142
  {
143
    delete g_timeProfiler;
144
  }
145
  g_timeProfiler = timeProfilerCreate( encCfg );
146
#endif
147
1.43k
}
148
149
void EncLib::uninitEncoderLib()
150
1.43k
{
151
#if ENABLE_TRACING
152
  if( g_trace_ctx )
153
  {
154
    tracing_uninit( g_trace_ctx );
155
  }
156
#endif
157
158
#if ENABLE_CU_MODE_COUNTERS
159
  std::cout << std::endl;
160
  std::cout << "CU Modes statistic across picture types and temporal levels (0:Intra, >0:Inter, luma only)" << std::endl;
161
  for( size_t j = 0; j < g_cuCounters1D.getNumCntTypes(); j++ )
162
  {
163
    for( size_t i = 0; i < g_cuCounters1D.getDimHor() - 1; i++ )
164
    {
165
      g_cuCounters1D[j][0][g_cuCounters1D.getDimHor() - 1] += g_cuCounters1D[j][0][i];
166
    }
167
  }
168
  StatCounters::report2D( std::cout, g_cuCounters1D, false, true, false, true, true, CU_MODES_TESTED );
169
170
  std::cout << std::endl;
171
  std::cout << "CU Modes statistic across block-shapes (Non-I-Slices, luma only)" << std::endl;
172
  StatCounters::report2D( std::cout, g_cuCounters2D, true, true, false, true, true, CU_MODES_TESTED );
173
#endif
174
175
#if ENABLE_TIME_PROFILING
176
#if ENABLE_TIME_PROFILING_MT_MODE
177
  if( m_threadPool )
178
  {
179
    for(auto& p : m_threadPool->getProfilers())
180
    {
181
      *g_timeProfiler += *p;
182
    }
183
  }
184
#endif
185
  timeProfilerResults( g_timeProfiler );
186
  delete g_timeProfiler;
187
  g_timeProfiler = nullptr;
188
#endif
189
1.43k
  xUninitLib();
190
1.43k
}
191
192
void EncLib::initPass( int pass, const char* statsFName )
193
1.43k
{
194
1.43k
  CHECK( m_passInitialized != pass && m_passInitialized + 1 != pass, "initialization of passes only in successive order possible" );
195
196
1.43k
  if( m_rateCtrl == nullptr )
197
1.43k
  {
198
1.43k
    m_rateCtrl = new RateCtrl(msg);
199
1.43k
  }
200
201
1.43k
  m_rateCtrl->setRCPass( m_encCfg, pass, statsFName );
202
203
1.43k
  if( m_passInitialized + 1 != pass )
204
0
  {
205
0
    return;
206
0
  }
207
208
  // reset
209
1.43k
  xUninitLib();
210
211
  // enable encoder config based on rate control pass
212
1.43k
  if( m_encCfg.m_RCNumPasses > 1 || ( m_encCfg.m_LookAhead && m_orgCfg.m_RCTargetBitrate > 0 ) )
213
0
  {
214
0
    if( !m_rateCtrl->rcIsFinalPass )
215
0
    {
216
      // set encoder config for 1st rate control pass
217
0
      const_cast<VVEncCfg&>(m_encCfg) = m_firstPassCfg;
218
0
    }
219
0
    else
220
0
    {
221
      // restore encoder config for final 2nd RC pass
222
0
      const_cast<VVEncCfg&>(m_encCfg) = m_orgCfg;
223
0
      m_rateCtrl->init( m_encCfg );
224
0
      const_cast<VVEncCfg&>(m_encCfg).m_QP = m_rateCtrl->getBaseQP();
225
0
    }
226
0
    if( m_encCfg.m_RCTargetBitrate > 0 && !m_encCfg.m_LookAhead )
227
0
    {
228
0
      m_rateCtrl->processFirstPassData( false );
229
0
    }
230
0
  }
231
1.43k
  else if( m_encCfg.m_usePerceptQPA && m_encCfg.m_LookAhead )
232
0
  {
233
0
    m_rateCtrl->init( m_encCfg );
234
0
  }
235
236
  // thread pool
237
1.43k
  if( m_encCfg.m_numThreads > 0 )
238
1.43k
  {
239
1.43k
    m_threadPool = new NoMallocThreadPool( m_encCfg.m_numThreads, "EncSliceThreadPool", &m_encCfg );
240
1.43k
  }
241
1.43k
  m_maxNumPicShared = 0;
242
243
  // pre processing
244
1.43k
  m_preProcess = new PreProcess( msg );
245
1.43k
  m_preProcess->initStage( m_encCfg, 1, -m_encCfg.m_leadFrames, true, true, false );
246
1.43k
  m_preProcess->init( m_encCfg, m_rateCtrl->rcIsFinalPass );
247
1.43k
  m_encStages.push_back( m_preProcess );
248
1.43k
  m_maxNumPicShared += 1;
249
250
  // MCTF
251
1.43k
  if( m_encCfg.m_vvencMCTF.MCTF || m_encCfg.m_usePerceptQPA )
252
1.43k
  {
253
1.43k
    m_MCTF = new MCTF();
254
1.43k
    const int leadFrames   = std::min( VVENC_MCTF_RANGE, m_encCfg.m_leadFrames );
255
1.43k
    const int minQueueSize = m_encCfg.m_vvencMCTF.MCTFFutureReference ? ( leadFrames + 1 + VVENC_MCTF_RANGE ) : ( leadFrames + 1 );
256
1.43k
    m_MCTF->initStage( m_encCfg, minQueueSize, -leadFrames, true, true, false );
257
1.43k
    m_MCTF->init( m_encCfg, m_rateCtrl->rcIsFinalPass, m_threadPool );
258
1.43k
    m_encStages.push_back( m_MCTF );
259
1.43k
    m_maxNumPicShared += minQueueSize - leadFrames;
260
1.43k
  }
261
262
  // CU-tree look-ahead, holds the pictures of a GOP until the next GOP has arrived
263
1.43k
  if( m_encCfg.useCuTree() )
264
0
  {
265
0
    m_cuTree = new CuTree();
266
0
    m_cuTree->initStage( m_encCfg, 1, 0, false, true, false );
267
0
    m_cuTree->init( m_encCfg, m_threadPool );
268
0
    m_encStages.push_back( m_cuTree );
269
    // a GOP and its look-ahead wait here, while the GOP encoder holds the previous GOP
270
0
    m_maxNumPicShared += m_encCfg.m_GOPSize + CuTree::getNumLookAheadPics( m_encCfg );
271
0
  }
272
273
  // pre analysis encoder
274
1.43k
  if( m_encCfg.m_LookAhead )
275
0
  {
276
0
    m_preEncoder = new EncGOP( msg );
277
0
    const int minQueueSize = m_firstPassCfg.m_GOPSize + 1;
278
0
    m_preEncoder->initStage( m_firstPassCfg, minQueueSize, 0, false, false, false );
279
0
    m_preEncoder->init( m_firstPassCfg, m_preProcess->getGOPCfg(), *m_rateCtrl, m_threadPool, true );
280
0
    m_encStages.push_back( m_preEncoder );
281
0
    m_maxNumPicShared += minQueueSize;
282
0
  }
283
284
  // gop encoder
285
1.43k
  m_gopEncoder = new EncGOP( msg );
286
1.43k
  const int minQueueSize = m_encCfg.m_GOPSize + 1;
287
1.43k
  m_gopEncoder->initStage( m_encCfg, minQueueSize, 0, false, false, m_encCfg.m_stageParallelProc );
288
1.43k
  m_gopEncoder->init( m_encCfg, m_preProcess->getGOPCfg(), *m_rateCtrl, m_threadPool, false );
289
1.43k
  m_encStages.push_back( m_gopEncoder );
290
1.43k
  m_maxNumPicShared += minQueueSize;
291
  // the stages that wait for their own pool tasks start the GOP encoder's ready pictures meanwhile
292
1.43k
  if( m_encCfg.m_stageParallelProc )
293
1.43k
  {
294
1.43k
    if( m_MCTF )   m_MCTF  ->setStartStage( m_gopEncoder );
295
1.43k
    if( m_cuTree ) m_cuTree->setStartStage( m_gopEncoder );
296
1.43k
  }
297
298
  // additional pictures due to structural delay
299
1.43k
  m_maxNumPicShared += m_preProcess->getGOPCfg()->getNumReorderPics()[ m_encCfg.m_maxTLayer ];
300
1.43k
  m_maxNumPicShared += 3;
301
  // increase number of picture buffers for GOP parallel processing (with IFP), or read GOPs ahead
302
  // so that frame parallel encoding can start pictures of later GOPs early (without IFP)
303
1.43k
  m_maxNumPicShared += m_encCfg.m_numParallelGOPs ? (m_encCfg.m_GOPSize + 1) * m_encCfg.m_numParallelGOPs: 0;
304
305
1.43k
  if( m_rateCtrl->rcIsFinalPass )
306
1.43k
  {
307
1.43k
    m_gopEncoder->setRecYUVBufferCallback( m_recYuvBufCtx, m_recYuvBufFunc );
308
1.43k
  }
309
310
  // link encoder stages
311
4.29k
  for( int i = 0; i < (int)m_encStages.size() - 1; i++ )
312
2.86k
  {
313
2.86k
    m_encStages[ i ]->linkNextStage( m_encStages[ i + 1 ] );
314
2.86k
  }
315
316
1.43k
  m_picsRcvd                = -m_encCfg.m_leadFrames;
317
1.43k
  m_accessUnitOutputStarted = false;
318
1.43k
  m_passInitialized         = pass;
319
1.43k
}
320
321
void EncLib::xUninitLib()
322
2.86k
{
323
  // make sure all processing threads are stopped before releasing data
324
2.86k
  if( m_threadPool )
325
1.43k
  {
326
1.43k
    m_threadPool->shutdown( true );
327
    // A task that makes other tasks ready mid-run without signalProgress() shows up here instead of only as a slowdown.
328
    // Not always an error: a wake-up delayed past the safety interval by preemption of the producer counts as well.
329
1.43k
    if( m_threadPool->numWakeUpsMissed() != 0 )
330
0
    {
331
0
      msg.log( VVENC_INFO, "Thread pool: %u wake-ups caught by the safety interval\n", m_threadPool->numWakeUpsMissed() );
332
0
    }
333
1.43k
  }
334
335
  // sub modules
336
2.86k
  if( m_rateCtrl != nullptr )
337
2.86k
  {
338
2.86k
    m_rateCtrl->destroy();
339
2.86k
  }
340
2.86k
  if( m_preProcess )
341
1.43k
  {
342
1.43k
    delete m_preProcess;
343
1.43k
    m_preProcess = nullptr;
344
1.43k
  }
345
2.86k
  if( m_MCTF )
346
1.43k
  {
347
1.43k
    delete m_MCTF;
348
1.43k
    m_MCTF = nullptr;
349
1.43k
  }
350
2.86k
  if( m_cuTree )
351
0
  {
352
0
    delete m_cuTree;
353
0
    m_cuTree = nullptr;
354
0
  }
355
2.86k
  if( m_preEncoder )
356
0
  {
357
0
    delete m_preEncoder;
358
0
    m_preEncoder = nullptr;
359
0
  }
360
2.86k
  if( m_gopEncoder )
361
1.43k
  {
362
1.43k
    delete m_gopEncoder;
363
1.43k
    m_gopEncoder = nullptr;
364
1.43k
  }
365
2.86k
  m_encStages.clear();
366
367
2.86k
  for( auto picShared : m_picSharedList )
368
1.43k
  {
369
1.43k
    delete picShared;
370
1.43k
  }
371
2.86k
  m_picSharedList.clear();
372
373
  // thread pool
374
2.86k
  if( m_threadPool )
375
1.43k
  {
376
1.43k
    delete m_threadPool;
377
1.43k
    m_threadPool = nullptr;
378
1.43k
  }
379
2.86k
}
380
381
void EncLib::xInitRCCfg()
382
0
{
383
  // backup original configuration
384
0
  const_cast<VVEncCfg&>(m_orgCfg) = m_encCfg;
385
386
  // initialize first pass configuration
387
0
  m_firstPassCfg = m_encCfg;
388
0
  vvenc_init_preset( &m_firstPassCfg, vvencPresetMode::VVENC_FIRSTPASS );
389
390
  // fixed-QP encoding in first rate control pass
391
0
  m_firstPassCfg.m_RCTargetBitrate = 0;
392
0
  if( m_firstPassCfg.m_FirstPassMode > 2 )
393
0
  {
394
0
    m_firstPassCfg.m_SourceWidth  = ( m_encCfg.m_SourceWidth  >> 1 ) & ( ~7 );
395
0
    m_firstPassCfg.m_SourceHeight = ( m_encCfg.m_SourceHeight >> 1 ) & ( ~7 );
396
0
    m_firstPassCfg.m_PadSourceWidth  = m_firstPassCfg.m_SourceWidth;
397
0
    m_firstPassCfg.m_PadSourceHeight = m_firstPassCfg.m_SourceHeight;
398
0
#if TILES_IFP_2PRC_HOTFIX
399
0
    if( m_firstPassCfg.m_ifp && (m_firstPassCfg.m_numTileCols > 1 || m_firstPassCfg.m_numTileRows > 1) )
400
0
    {
401
      // due to sub-sampling, expected different tile configuration in cfg (m_tileRowHeight[], m_tileColumnWidth[])
402
      // currently, disable auto tiles for the first pass
403
0
      m_firstPassCfg.m_numTileCols = 1;
404
0
      m_firstPassCfg.m_numTileRows = 1;
405
0
      m_firstPassCfg.m_picPartitionFlag = false;
406
0
    }
407
0
#endif
408
0
  }
409
410
  // preserve some settings
411
0
  m_firstPassCfg.m_intraQPOffset   = m_encCfg.m_intraQPOffset;
412
0
  m_firstPassCfg.m_GOPQPA          = m_encCfg.m_GOPQPA;
413
0
  if( m_firstPassCfg.m_usePerceptQPA && ( m_firstPassCfg.m_QP <= MAX_QP_PERCEPT_QPA || m_firstPassCfg.m_framesToBeEncoded == 1 ) )
414
0
  {
415
0
    m_firstPassCfg.m_CTUSize       = m_encCfg.m_CTUSize;
416
0
  }
417
0
  m_firstPassCfg.m_vvencMCTF.MCTF  = m_encCfg.m_vvencMCTF.MCTF;
418
  // the first pass measures the rates with the final pass's block importance mapping; the firstpass preset also
419
  // leaves the CU-tree block size of the final pass
420
0
  m_firstPassCfg.m_blockImportanceMapping = m_encCfg.m_blockImportanceMapping;
421
0
  m_firstPassCfg.m_IBCMode         = m_encCfg.m_IBCMode;
422
0
  m_firstPassCfg.m_bimCtuSize      = m_encCfg.m_CTUSize;
423
0
  m_firstPassCfg.m_log2MinCodingBlockSize = m_encCfg.m_log2MinCodingBlockSize;
424
425
  // set Inter block size
426
0
  if( m_firstPassCfg.m_FirstPassMode > 0 )
427
0
  {
428
0
    m_firstPassCfg.m_MinQT[ 1 ] = m_firstPassCfg.m_MaxQT[ 1 ] = ( std::min( m_firstPassCfg.m_SourceWidth, m_firstPassCfg.m_SourceHeight ) < 720 ? 32 : 64 );
429
0
  }
430
431
  // clear MaxCuDQPSubdiv
432
0
  if( m_firstPassCfg.m_CTUSize < 128 && std::min( m_firstPassCfg.m_SourceWidth, m_firstPassCfg.m_SourceHeight ) >= 720 )
433
0
  {
434
0
    m_firstPassCfg.m_cuQpDeltaSubdiv = 0;
435
0
  }
436
0
}
437
438
// ====================================================================================================================
439
// Public member functions
440
// ====================================================================================================================
441
442
// The current I/O work flow consists of three main parts:
443
//   1. At the beginning, the encoder can consume input YUV buffers without an output.
444
//   2. After the first encoded picture/access unit is output, on each next call: one yuv-buffer IN / one encoded access unit (AU) OUT.
445
//      Hence, in stage-parallel mode, we must wait until next encoded picture (AU) is going to be output,
446
//      unless nothing can progress without more input (then the call returns a buffered AU; none only when the buffer has run dry)
447
//   3. When no more input is available, the top level goes into flushing mode: nullptr IN / one encoded access unit (AU) OUT. 
448
//      The encoder flushes the encoded AUs until the queues are empty.
449
450
void EncLib::encodePicture( bool flush, const vvencYUVBuffer* yuvInBuf, AccessUnitList& au, bool& isQueueEmpty )
451
2.86k
{
452
2.86k
  PROFILER_ACCUM_AND_START_NEW_SET( 1, g_timeProfiler, P_TOP_LEVEL );
453
454
2.86k
  CHECK( yuvInBuf == nullptr && ! flush, "no input picture given" );
455
456
  // clear output access unit
457
2.86k
  au.clearAu();
458
459
  // NOTE regarding the stage parallel processing
460
  // The next input yuv-buffer must be passed to the encoding process (1.Stage).
461
  // The following should be considered:
462
  //   1. The final stage is non-blocking, so it doesn't wait until picture is reconstructed.
463
  //   2. Generally, the stages have different throughput; last stage is the slowest.
464
  //   3. The number of picture-units required for the input yuv-buffers is limited.
465
  //   4. Due to chunk-mode and non-blockiness, it's possible that we can run out of picture-units.
466
  //   5. Then we have to wait for the next available picture-unit, so the input frame can be passed to the 1.stage.
467
468
  // CU-tree passes its pictures on a GOP at a time, and the GOP encoder only starts with a GOP and one picture queued.
469
  // When the intra period cuts a GOP short, the GOP encoder waits for CU-tree's next batch, at most a GOP of input.
470
  // A buffer of that many access units covers the wait, so that every call, once the output has started, takes its
471
  // input picture and returns one access unit: with CU-tree the output starts once more than GOP + 1 access units
472
  // (and never fewer than the usual 4) are queued, in both modes. Without stage parallel processing the loop also
473
  // refills the buffer before it returns; with it the loop only waits while no access unit is buffered, so the stages
474
  // keep running in parallel with the input.
475
2.86k
  const size_t cuTreeBuffer = m_encCfg.useCuTree() ? m_encCfg.m_GOPSize + 1 : 0;
476
2.86k
  const size_t outputDelay  = m_encCfg.useCuTree() ? std::max<size_t>( cuTreeBuffer, 4 ) : ( m_encCfg.m_stageParallelProc ? 4 : 0 );
477
2.86k
  const size_t auBuffer     = m_encCfg.m_stageParallelProc ? 0 : cuTreeBuffer;
478
479
2.86k
  PicShared* picShared = nullptr;
480
2.86k
  bool inputPending    = ( yuvInBuf != nullptr );
481
2.86k
  bool stalledBefore   = false;
482
5.70k
  while( true )
483
5.70k
  {
484
    // send new YUV input buffer to first encoder stage
485
5.70k
    if( inputPending )
486
1.43k
    {
487
1.43k
      picShared = xGetFreePicShared();
488
1.43k
      if( picShared )
489
1.43k
      {
490
1.43k
        picShared->reuse( m_picsRcvd, yuvInBuf );
491
1.43k
        m_encStages[ 0 ]->addPicSorted( picShared, flush );
492
1.43k
        m_picsRcvd  += 1;
493
1.43k
        inputPending = false;
494
1.43k
      }
495
1.43k
    }
496
497
5.70k
    PROFILER_EXT_UPDATE( g_timeProfiler, P_TOP_LEVEL, 0 );
498
499
    // trigger stages
500
5.70k
    isQueueEmpty = m_picsRcvd > 0 || ( m_picsRcvd <= 0 && flush );
501
5.70k
    bool progress = false;
502
5.70k
    for( auto encStage : m_encStages )
503
17.1k
    {
504
17.1k
      progress     |= encStage->runStage( flush, au );
505
17.1k
      isQueueEmpty &= encStage->isStageDone();
506
17.1k
    }
507
508
5.70k
    if( !au.empty() )
509
1.43k
    {
510
1.43k
      m_AuList.push_back( au );
511
512
1.43k
      au.detachNalUnitList();
513
1.43k
      au.clearAu();
514
      // NOTE: delay AU output in stage parallel mode, and by the CU-tree buffer
515
1.43k
      if( !m_accessUnitOutputStarted )
516
1.43k
        m_accessUnitOutputStarted = m_AuList.size() > outputDelay || flush;
517
1.43k
    }
518
519
    // wait if input picture hasn't been stored yet or if encoding is running and no new output access unit has been encoded
520
    // (or, with the CU-tree buffer, until the buffer is full again)
521
5.70k
    bool waitAndStay = inputPending || ( m_rateCtrl->rcIsFinalPass && m_AuList.size() <= auBuffer && ! isQueueEmpty && ( m_accessUnitOutputStarted || flush ) );
522
5.70k
    if( ! waitAndStay )
523
2.86k
    {
524
2.86k
      break;
525
2.86k
    }
526
    // With the CU-tree buffer (no stage parallel processing), nothing changes until a stage passes a picture on:
527
    // return for more input rather than wait for an access unit that cannot come.
528
2.84k
    if( auBuffer && ! inputPending && ! progress )
529
0
    {
530
0
      break;
531
0
    }
532
533
2.84k
    if( m_encCfg.m_stageParallelProc )
534
2.84k
    {
535
2.84k
      bool picInCoding = false;
536
2.84k
      for( auto encStage : m_encStages )
537
8.52k
      {
538
8.52k
        if( encStage->isNonBlocking() )
539
2.84k
          picInCoding |= encStage->waitForFreeEncoders();
540
8.52k
      }
541
      // With no picture in coding, no stage passing a picture on and the input taken, nothing changes until more
542
      // input arrives: the GOP encoder waits for a GOP and one picture, which CU-tree passes on only with its
543
      // look-ahead. Return for more input rather than wait for an access unit that cannot come: a buffered one if
544
      // there is one (the CU-tree buffer above), none only as the fallback when the buffer has run dry. The second
545
      // such pass in a row decides, so that a picture finished after the GOP encoder looked at it is collected first.
546
2.84k
      const bool stalled = ! picInCoding && ! progress && ! inputPending && ! flush;
547
2.84k
      if( stalled && stalledBefore )
548
0
      {
549
0
        break;
550
0
      }
551
2.84k
      stalledBefore = stalled;
552
2.84k
    }
553
2.84k
  }
554
555
  // check if we have an AU to output
556
2.86k
  if( !m_AuList.empty() && m_accessUnitOutputStarted )
557
1.43k
  {
558
1.43k
    au = m_AuList.front();
559
1.43k
    m_AuList.front().detachNalUnitList();
560
1.43k
    m_AuList.pop_front();
561
1.43k
  }
562
563
  // reset output access unit, if not final pass
564
2.86k
  if( ! m_rateCtrl->rcIsFinalPass )
565
0
  {
566
0
    au.clearAu();
567
0
  }
568
569
  // finally, ensure that the whole queue is empty
570
2.86k
  isQueueEmpty &= m_AuList.empty();
571
2.86k
}
572
573
void EncLib::printSummary()
574
0
{
575
0
  if( m_gopEncoder )
576
0
  {
577
0
    m_gopEncoder->printOutSummary( m_encCfg.m_printMSEBasedSequencePSNR, m_encCfg.m_printSequenceMSE, m_encCfg.m_printHexPsnr );
578
0
  }
579
0
}
580
581
void EncLib::getParameterSets( AccessUnitList& au )
582
0
{
583
0
  if( m_gopEncoder )
584
0
  {
585
0
    m_gopEncoder->getParameterSets( au );
586
0
  }
587
0
}
588
589
int EncLib::getCurPass() const
590
0
{
591
0
  return m_passInitialized;
592
0
}
593
594
// ====================================================================================================================
595
// Protected member functions
596
// ====================================================================================================================
597
598
// The stage-parallel limit counts source buffers, not PicShared objects: a picture the GOP encoder has reconstructed
599
// lends its source buffer to new input (PicShared::canLendSource), so that the next GOP's pictures can enter MCTF while
600
// the current GOP's pictures wait for their output (they keep their metadata, which later pictures and the output read).
601
// Each reconstructed picture that cannot lend yet (a later picture's QPA or its film grain analysis still reads the
602
// source) raises the limit by one: when no picture can lend, new input gets a new source buffer.
603
PicShared* EncLib::xGetFreePicShared()
604
1.43k
{
605
1.43k
  PicShared* unusedWithoutSource = nullptr;
606
1.43k
  PicShared* lender              = nullptr;
607
1.43k
  size_t     numSources          = 0;
608
1.43k
  for( auto itr : m_picSharedList )
609
0
  {
610
0
    if( ! itr->isUsed() )
611
0
    {
612
0
      if( itr->hasSource() )
613
0
      {
614
0
        return itr;
615
0
      }
616
0
      if( ! unusedWithoutSource )
617
0
      {
618
0
        unusedWithoutSource = itr;
619
0
      }
620
0
    }
621
0
    else if( ! lender && itr->canLendSource() )
622
0
    {
623
0
      lender = itr;
624
0
    }
625
0
    numSources += itr->hasSource() ? 1 : 0;
626
0
  }
627
628
1.43k
  const bool atLimit = m_encCfg.m_stageParallelProc && numSources >= (size_t)m_maxNumPicShared;
629
1.43k
  const bool lend    = atLimit && lender;
630
1.43k
  const bool noRoom  = atLimit && ! lender
631
0
                       && numSources >= (size_t)m_maxNumPicShared + (size_t)m_gopEncoder->numEncodedWithSource();
632
1.43k
  if( noRoom )
633
0
  {
634
0
    return nullptr;
635
0
  }
636
637
1.43k
  PicShared* picShared = unusedWithoutSource;
638
1.43k
  if( ! picShared )
639
1.43k
  {
640
1.43k
    picShared = new PicShared();
641
1.43k
    picShared->create( m_encCfg.m_framesToBeEncoded, m_encCfg.m_internChromaFormat, Size( m_encCfg.m_PadSourceWidth, m_encCfg.m_PadSourceHeight ), m_encCfg.m_vvencMCTF.MCTF || m_encCfg.m_usePerceptQPA, ! lend );
642
1.43k
    m_picSharedList.push_back( picShared );
643
1.43k
  }
644
0
  else if( ! lend )
645
0
  {
646
0
    picShared->createSource();
647
0
  }
648
1.43k
  if( lend )
649
0
  {
650
0
    picShared->takeSourceFrom( *lender );
651
0
  }
652
1.43k
  CHECK( ! picShared->hasSource(), "out of memory" );
653
654
1.43k
  return picShared;
655
1.43k
}
656
657
} // namespace vvenc
658
659
//! \}