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/EncGOP.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     EncGOP.cpp
45
    \brief    GOP encoder class
46
*/
47
48
#include "EncGOP.h"
49
#include "CommonLib/SEI.h"
50
#include "CommonLib/UnitTools.h"
51
#include "CommonLib/dtrace_codingstruct.h"
52
#include "CommonLib/dtrace_buffer.h"
53
#include "CommonLib/TimeProfiler.h"
54
#include "CommonLib/MD5.h"
55
#include "NALwrite.h"
56
#include "BitAllocation.h"
57
#include "EncHRD.h"
58
#include "GOPCfg.h"
59
60
#include <algorithm>
61
#include <limits>
62
#include <list>
63
64
//! \ingroup EncoderLib
65
//! \{
66
67
namespace vvenc {
68
69
#ifdef TRACE_ENABLE_ITT
70
static __itt_string_handle* itt_handle_start = __itt_string_handle_create( "Start" );
71
static __itt_domain* itt_domain_gopEncoder   = __itt_domain_create( "GOPEncoder" );
72
#endif
73
74
// ====================================================================================================================
75
// fast forward decoder in encoder
76
// ====================================================================================================================
77
78
void initPicAuxQPOffsets( const Slice* slice, const bool isBIM ) // get m_picShared->m_picAuxQpOffset and m_picShared->m_ctuBimQpOffset if unavailable
79
1.43k
{
80
1.43k
  const Picture* slicePic = slice->pic;
81
82
1.43k
  if (isBIM && slicePic && slicePic->m_picShared->m_ctuBimQpOffset.empty())
83
1.43k
  {
84
1.43k
    const Picture* refPicL0 = slice->getRefPic (REF_PIC_LIST_0, 0);
85
1.43k
    const Picture* refPicL1 = slice->getRefPic (REF_PIC_LIST_1, 0);
86
87
1.43k
    if (refPicL0 && !refPicL0->m_picShared->m_ctuBimQpOffset.empty() &&
88
0
        refPicL1 && !refPicL1->m_picShared->m_ctuBimQpOffset.empty() &&
89
0
        refPicL0->m_picShared->m_ctuBimQpOffset.size() == refPicL1->m_picShared->m_ctuBimQpOffset.size())
90
0
    {
91
0
      const PicShared* pic0 = refPicL0->m_picShared;
92
0
      const PicShared* pic1 = refPicL1->m_picShared;
93
0
      PicShared* const picC = slicePic->m_picShared;
94
0
      const int32_t  numCtu = (int32_t) pic0->m_ctuBimQpOffset.size();
95
0
      int i, sumCtuQpOffset = 0;
96
97
0
      picC->m_ctuBimQpOffset.resize (numCtu);
98
99
0
      for (i = 0; i < numCtu; i++) // scale and merge QPs
100
0
      {
101
0
        const int qpOffset0 = pic0->m_ctuBimQpOffset[i] + pic0->m_picAuxQpOffset; // CTU delta-QP #1
102
0
        const int qpOffset1 = pic1->m_ctuBimQpOffset[i] + pic1->m_picAuxQpOffset; // CTU delta-QP #2
103
0
        const int qpOffsetC = (3 * qpOffset0 + 3 * qpOffset1 + (qpOffset0 + qpOffset1 < 0 ? 3 : 4)) >> 3; // 3 instead of 4 for correct rounding to -2
104
105
0
        picC->m_ctuBimQpOffset[i] = qpOffsetC;
106
0
        sumCtuQpOffset += qpOffsetC;
107
0
      }
108
109
0
      picC->m_picAuxQpOffset = (sumCtuQpOffset + (sumCtuQpOffset < 0 ? -(numCtu >> 1) : numCtu >> 1)) / numCtu; // pic average; delta-QP scaling: 0.75
110
0
      for (i = 0; i < numCtu; i++) // excl. average again
111
0
      {
112
0
        picC->m_ctuBimQpOffset[i] -= picC->m_picAuxQpOffset; // delta-QP relative to the aux average
113
0
      }
114
0
    }
115
1.43k
  }
116
1.43k
}
117
118
119
// ====================================================================================================================
120
// Constructor / destructor / initialization / destroy
121
// ====================================================================================================================
122
123
EncGOP::EncGOP( MsgLog& logger )
124
1.43k
  : msg                  ( logger )
125
1.43k
  , m_recYuvBufFunc      ( nullptr )
126
1.43k
  , m_recYuvBufCtx       ( nullptr )
127
1.43k
  , m_threadPool         ( nullptr )
128
1.43k
  , m_pcEncCfg           ( nullptr )
129
1.43k
  , m_gopCfg             ( nullptr )
130
1.43k
  , m_pcRateCtrl         ( nullptr )
131
1.43k
  , m_spsMap             ( MAX_NUM_SPS )
132
1.43k
  , m_ppsMap             ( MAX_NUM_PPS )
133
1.43k
  , m_isPreAnalysis      ( false )
134
1.43k
  , m_bFirstWrite        ( true )
135
1.43k
  , m_bRefreshPending    ( false )
136
1.43k
  , m_lastCodingNum      ( -1 )
137
1.43k
  , m_numPicsCoded       ( 0 )
138
1.43k
  , m_numPicsInMissing   ( 0 )
139
1.43k
  , m_numPicsOutOffset   ( 0 )
140
1.43k
  , m_lastCts            ( 0 )
141
1.43k
  , m_pocRecOut          ( 0 )
142
1.43k
  , m_ticksPerFrameMul4  ( 0 )
143
1.43k
  , m_lastIDR            ( 0 )
144
1.43k
  , m_lastRasPoc         ( MAX_INT )
145
1.43k
  , m_pocCRA             ( 0 )
146
1.43k
  , m_associatedIRAPPOC  ( 0 )
147
1.43k
  , m_associatedIRAPType ( VVENC_NAL_UNIT_CODED_SLICE_IDR_N_LP )
148
1.43k
  , m_picSetupTasks      ( false )
149
1.43k
  , m_numSetupsQueued    ( 0 )
150
1.43k
  , m_numSetupsDone      ( 0 )
151
1.43k
  , m_numPicsStarted     ( 0 )
152
1.43k
{
153
1.43k
}
154
155
EncGOP::~EncGOP()
156
1.43k
{
157
1.43k
  xWaitFgaTasks();
158
1.43k
  freePicList();
159
160
1.43k
  for( auto& picEncoder : m_freePicEncoderList )
161
5.72k
  {
162
5.72k
    if( picEncoder )
163
5.72k
    {
164
5.72k
      delete picEncoder;
165
5.72k
    }
166
5.72k
  }
167
1.43k
  m_freePicEncoderList.clear();
168
1.43k
  m_threadPool = nullptr;
169
170
  // cleanup parameter sets
171
1.43k
  m_spsMap.clearMap();
172
1.43k
  m_ppsMap.clearMap();
173
174
1.43k
  for( auto& p : m_globalApsList ) delete p;
175
1.43k
  m_globalApsList.clear();
176
1.43k
}
177
178
void EncGOP::init( const VVEncCfg& encCfg, const GOPCfg* gopCfg, RateCtrl& rateCtrl, NoMallocThreadPool* threadPool, bool isPreAnalysis )
179
1.43k
{
180
1.43k
  m_pcEncCfg      = &encCfg;
181
1.43k
  m_gopCfg        = gopCfg;
182
1.43k
  m_pcRateCtrl    = &rateCtrl;
183
1.43k
  m_threadPool    = threadPool;
184
1.43k
  m_isPreAnalysis = isPreAnalysis;
185
186
  // setup parameter sets
187
1.43k
  const int dciId = m_pcEncCfg->m_decodingParameterSetEnabled ? 1 : 0;
188
1.43k
  SPS& sps0       = *( m_spsMap.allocatePS( 0 ) ); // NOTE: implementations that use more than 1 SPS need to be aware of activation issues.
189
1.43k
  PPS& pps0       = *( m_ppsMap.allocatePS( 0 ) );
190
191
1.43k
  xInitSPS( sps0 );
192
1.43k
  sps0.dciId = m_DCI.dciId;
193
1.43k
  xInitVPS( m_VPS );
194
1.43k
  xInitDCI( m_DCI, sps0, dciId );
195
1.43k
  xInitPPS( pps0, sps0 );
196
1.43k
  xInitRPL( sps0 );
197
1.43k
  xInitHrdParameters( sps0 );
198
199
1.43k
  if ( encCfg.m_fga )
200
0
  {
201
    // --fga 1: VTM's analysis with its bugs fixed; --fga 2: with the improvements beyond VTM; --fga 3: --fga 2 with the
202
    // auto-regressive grain model
203
0
    m_fgAnalyzer.init( m_pcEncCfg->m_PadSourceWidth, m_pcEncCfg->m_PadSourceHeight, m_pcEncCfg->m_internChromaFormat,
204
0
                         m_pcEncCfg->m_internalBitDepth, m_pcEncCfg->m_fg.m_fgcSEICompModelPresent, encCfg.m_fga == 2, encCfg.m_fga == 3 );
205
0
    m_fgcByStartPoc[ std::numeric_limits<int>::min() ] = FilmGrainParam( m_fgAnalyzer, m_pcEncCfg->m_fgaStrength );   // no grain, until the first analysis measures it
206
0
  }
207
208
1.43k
  if( !m_pcEncCfg->m_poc0idr )
209
1.43k
  {
210
1.43k
    m_associatedIRAPType = VVENC_NAL_UNIT_CODED_SLICE_IDR_W_RADL;
211
1.43k
  }
212
1.43k
  m_seiEncoder.init( encCfg, gopCfg, m_EncHRD );
213
214
  // One CU encoder per worker thread is enough: a worker encodes one CTU at a time, whichever
215
  // of the parallel pictures it belongs to.
216
1.43k
  const int numThreadRsrc = ( encCfg.m_numThreads > 0 && threadPool ) ? threadPool->numThreads() : 1;
217
1.43k
  m_threadRsrc.init( encCfg, sps0, pps0, &m_globalCtuQpVector, rateCtrl, numThreadRsrc );
218
219
  // IFP: a picture's ALF APSs reach the global list at its ALF derivation; from then on the pictures predicting their
220
  // APSs from it may start (see the start condition in xProcessPictures)
221
1.43k
  auto apsReady = [this]( Picture& pic )
222
1.43k
  {
223
0
    std::lock_guard<std::mutex> lock( m_gopEncMutex );
224
0
    pic.picApsGlobal->initalized = true;
225
0
    m_gopEncCond.notify_one();
226
0
  };
227
228
1.43k
  const int maxPicEncoder = ( encCfg.m_maxParallelFrames ) ? encCfg.m_maxParallelFrames : 1;
229
7.16k
  for ( int i = 0; i < maxPicEncoder; i++ )
230
5.72k
  {
231
5.72k
    EncPicture* picEncoder = new EncPicture;
232
5.72k
    picEncoder->init( encCfg, &m_globalCtuQpVector, sps0, pps0, rateCtrl, threadPool, m_threadRsrc, apsReady );
233
5.72k
    m_freePicEncoderList.push_back( picEncoder );
234
5.72k
  }
235
236
1.43k
  if (encCfg.m_usePerceptQPA)
237
1.43k
  {
238
1.43k
    m_globalCtuQpVector.resize( pps0.useDQP && (encCfg.m_internalUsePerceptQPATempFiltISlice == 2) && encCfg.m_salienceBasedOpt ? pps0.picWidthInCtu * pps0.picHeightInCtu + 1 : 1 );
239
1.43k
  }
240
241
  // With pictures coded in parallel, a picture's setup (EncPicture::compressPicture up to its CTU tasks) runs as a
242
  // thread pool task instead of on the calling thread, which also runs the pre-processing stages (MCTF). Its results
243
  // are read only by the picture's own tasks, except with rate control and look-ahead (lock-step, the rate cap, two
244
  // passes and the pre-analysis encoder read them on the calling thread) and with the pumping reduction of the QPA,
245
  // whose CTU QP vector is shared by all pictures; those keep the setup on the calling thread. MaxParallelFrames > 0 is
246
  // needed because only then do the pictures share their unit cache under a mutex.
247
1.43k
  m_picSetupTasks = encCfg.m_numThreads > 0 && encCfg.m_maxParallelFrames > 0 && ! isPreAnalysis
248
1.43k
                    && encCfg.m_RCTargetBitrate == 0 && encCfg.m_RCNumPasses != 2 && ! encCfg.m_rateCap
249
1.43k
                    && encCfg.m_LookAhead <= 0 && m_globalCtuQpVector.size() <= 1;
250
251
1.43k
  if( m_pcEncCfg->m_FrameRate && m_pcEncCfg->m_TicksPerSecond > 0 )
252
1.43k
  {
253
1.43k
    m_ticksPerFrameMul4 = (int)((int64_t)4 *(int64_t)m_pcEncCfg->m_TicksPerSecond * (int64_t)m_pcEncCfg->m_FrameScale/(int64_t)m_pcEncCfg->m_FrameRate);
254
1.43k
  }
255
1.43k
  m_forceSCC = false;
256
1.43k
  m_rcap.reset();
257
1.43k
}
258
259
260
// ====================================================================================================================
261
// Class interface
262
// ====================================================================================================================
263
264
265
void EncGOP::setRecYUVBufferCallback( void* ctx, std::function<void( void*, vvencYUVBuffer* )> func )
266
1.43k
{
267
1.43k
  m_recYuvBufCtx  = ctx;
268
1.43k
  m_recYuvBufFunc = func;
269
1.43k
}
270
271
void EncGOP::initPicture( Picture* pic )
272
1.43k
{
273
1.43k
  pic->encTime.startTimer();
274
275
1.43k
  pic->TLayer = pic->gopEntry->m_temporalId;
276
1.43k
  if( pic->ctsValid )
277
1.43k
  {
278
1.43k
    if( m_lastCts )
279
0
    {
280
0
      int64_t ticksPerFrame = m_ticksPerFrameMul4/4;
281
0
      int64_t expectedCtsDiff = (m_pcEncCfg->m_TicksPerSecond > 0 ) ? ticksPerFrame : 1;
282
0
      int64_t ctsDiff = pic->cts - m_lastCts;
283
284
0
      if( ctsDiff >= (expectedCtsDiff<<1) || ctsDiff < 0 )
285
0
      {
286
        // signalize that frames are missing at that particular picture
287
0
        pic->picOutOffset = (m_pcEncCfg->m_TicksPerSecond > 0 ) ? (ctsDiff - ticksPerFrame)/ticksPerFrame : ctsDiff-1;
288
0
        m_numPicsInMissing += pic->picOutOffset;
289
0
      }
290
0
    }
291
1.43k
    m_lastCts = pic->cts;
292
1.43k
  }
293
1.43k
  if( m_numPicsInMissing )
294
0
  {
295
0
    pic->picsInMissing = m_numPicsInMissing;
296
0
  }
297
298
1.43k
  pic->setSccFlags( m_pcEncCfg );
299
300
1.43k
  CHECK( m_ppsMap.getFirstPS() == nullptr || m_spsMap.getPS( m_ppsMap.getFirstPS()->spsId ) == nullptr, "picture set not initialised" );
301
302
1.43k
  const PPS& pps = *( m_ppsMap.getFirstPS() );
303
1.43k
  const SPS& sps = *( m_spsMap.getPS( pps.spsId ) );
304
305
1.43k
  if( pic->cs && pic->cs->picHeader )
306
0
  {
307
0
    delete pic->cs->picHeader;
308
0
    pic->cs->picHeader = nullptr;
309
0
  }
310
311
1.43k
  std::mutex* mutex = ( m_pcEncCfg->m_maxParallelFrames ) ? &m_unitCacheMutex : nullptr;
312
1.43k
  pic->finalInit( m_VPS, sps, pps, nullptr, m_shrdUnitCache, mutex, nullptr );
313
314
1.43k
  pic->vps = &m_VPS;
315
1.43k
  pic->dci = &m_DCI;
316
317
  // filter data initialization
318
1.43k
  const uint32_t numberOfCtusInFrame = pic->cs->pcv->sizeInCtus;
319
320
1.43k
  if( m_pcEncCfg->m_usePerceptQPA )
321
1.43k
  {
322
1.43k
    pic->ctuQpaLambda.resize (numberOfCtusInFrame);
323
1.43k
    pic->ctuAdaptedQP.resize (numberOfCtusInFrame);
324
1.43k
  }
325
326
1.43k
  if( pic->cs->sps->saoEnabled )
327
1.43k
  {
328
1.43k
    pic->resizeSAO( numberOfCtusInFrame, 0 );
329
1.43k
    pic->resizeSAO( numberOfCtusInFrame, 1 );
330
1.43k
  }
331
332
1.43k
  if( pic->cs->sps->alfEnabled )
333
1.43k
  {
334
1.43k
    pic->resizeAlfCtuBuffers( numberOfCtusInFrame );
335
1.43k
  }
336
337
1.43k
  pic->encTime.stopTimer();
338
1.43k
}
339
340
bool EncGOP::waitForFreeEncoders()
341
2.84k
{
342
2.84k
  std::unique_lock<std::mutex> lock( m_gopEncMutex );
343
2.84k
  if( xEncodersFinished() )
344
3
  {
345
3
    return false;
346
3
  }
347
2.84k
  CHECK( m_pcEncCfg->m_numThreads <= 0, "run into MT code, but no threading enabled" );
348
  // Return as soon as a picture finished since the last return. A finish after the GOP pass released the lock and
349
  // before this wait notifies nobody; without the predicate the main thread would sleep until the next finish while
350
  // the freed encoder and the pictures waiting for that one stay idle.
351
5.68k
  m_gopEncCond.wait( lock, [this] { return m_numPicsFinished != m_numPicsFinishedWaited; } );
352
2.84k
  m_numPicsFinishedWaited = m_numPicsFinished;
353
2.84k
  return true;
354
2.84k
}
355
356
bool EncGOP::hasEnoughPictures( const PicList& picList ) const
357
5.70k
{
358
5.70k
  if( EncStage::hasEnoughPictures( picList ) )
359
0
  {
360
0
    return true;
361
0
  }
362
363
  // GOPSize + 1 pictures ensure that the GOP of the next picture to initialize is complete (the GOP QP cascade reads all
364
  // of it). Pictures arrive in POC order and a GOP covers consecutive POCs, so that GOP is also complete once any picture
365
  // of a later GOP has arrived; the list is in coding order, so its last picture has the highest GOP number. A GOP shorter
366
  // than GOPSize (the first one, when the intra period is not a multiple of the GOP size) then need not wait for
367
  // GOPSize + 1 pictures. With look-ahead, the GOP encoder gets its pictures in coding order from the pre-analysis
368
  // encoder, so the size test alone decides. It also decides in blocking mode (no frame parallel coding): there, once
369
  // the output has started, every call must give an access unit, which only GOPSize + 1 queued pictures guarantee
370
  // (after a short first GOP, the next GOP's first picture in coding order is still up to GOPSize pictures away).
371
5.70k
  if( m_isPreAnalysis || m_pcEncCfg->m_LookAhead || ! isNonBlocking() )
372
0
  {
373
0
    return false;
374
0
  }
375
5.70k
  const auto nextPic = std::find_if( picList.begin(), picList.end(), []( const Picture* pic ) { return ! pic->isInitDone; } );
376
5.70k
  return nextPic != picList.end() && picList.back()->gopEntry->m_gopNum > ( *nextPic )->gopEntry->m_gopNum;
377
5.70k
}
378
379
void EncGOP::processPictures( const PicList& picList, AccessUnitList& auList, PicList& doneList, PicList& freeList )
380
4.27k
{
381
4.27k
  CHECK( picList.empty(), "empty input picture list given" );
382
383
  // create list of pictures ordered in coding order and ready to be encoded
384
4.27k
  xInitPicsInCodingOrder( picList );
385
386
  // encode pictures
387
4.27k
  xProcessPictures( auList, doneList );
388
389
  // output reconstructed YUV
390
4.27k
  xOutputRecYuv( picList );
391
392
  // release pictures not needed anymore
393
4.27k
  xReleasePictures( picList, freeList );
394
395
  // clear output access unit
396
4.27k
  if( m_isPreAnalysis )
397
0
  {
398
0
    auList.clearAu();
399
0
  }
400
4.27k
}
401
402
// Whether a reference picture of pic has not started yet (it is still in the processing list).
403
static bool hasUnstartedRef( const Picture& pic, const std::list<Picture*>& procList )
404
0
{
405
0
  const Slice& slice = *pic.slices[ 0 ];
406
0
  for( int refList = 0; refList < NUM_REF_PIC_LIST_01; refList++ )
407
0
  {
408
0
    for( int i = 0; i < slice.numRefIdx[ refList ]; i++ )
409
0
    {
410
0
      if( std::find( procList.begin(), procList.end(), slice.refPicList[ refList ][ i ] ) != procList.end() )
411
0
      {
412
0
        return true;
413
0
      }
414
0
    }
415
0
  }
416
0
  return false;
417
0
}
418
419
// The ready picture to start next: the key pictures (temporal layer 0 or 1) of the list front's GOP and the next one
420
// first, the lower layer first, then the others in list order. The key pictures are the long ones every later picture
421
// depends on; started early, they overlap the previous GOP's upper layers instead of running nearly alone after them.
422
// Only one GOP ahead: ranking further ahead would keep overtaking the next picture to output (the output would stall).
423
// With IFP a picture may start before its references are reconstructed, but only after they have started (else every
424
// picture encoder could wait on rows nobody codes), and after any picture whose references are reconstructed: a chain
425
// of row-locked pictures must not hold every picture encoder while independent work waits.
426
template<typename IsReady>
427
static std::list<Picture*>::iterator findNextPicToStart( std::list<Picture*>& procList, bool ifp, IsReady isReady )
428
1.43k
{
429
  // ranks: 0 and 1 the key pictures' layers, NON_KEY the others; ROW_LOCKED is added for a row-locked start
430
1.43k
  const int NON_KEY = 2, ROW_LOCKED = 3;
431
1.43k
  if( procList.empty() )
432
0
  {
433
0
    return procList.end();
434
0
  }
435
1.43k
  const int maxRankedGop = procList.front()->gopEntry->m_gopNum + 1;   // the last GOP whose key pictures go first
436
1.43k
  auto best     = procList.end();
437
1.43k
  int  bestRank = std::numeric_limits<int>::max();
438
1.43k
  for( auto it = procList.begin(); it != procList.end(); ++it )
439
1.43k
  {
440
1.43k
    const Picture* pic     = *it;
441
1.43k
    const int      tlRank  = pic->gopEntry->m_gopNum <= maxRankedGop ? std::min<int>( pic->TLayer, NON_KEY ) : NON_KEY;
442
    // the rank is at least tlRank; equal ranks keep the first in list order
443
1.43k
    if( tlRank >= bestRank || ! isReady( pic ) )
444
0
    {
445
0
      continue;
446
0
    }
447
1.43k
    const bool rowLocked = ifp && ! pic->slices[ 0 ]->checkAllRefPicsReconstructed();
448
1.43k
    if( rowLocked && hasUnstartedRef( *pic, procList ) )
449
0
    {
450
0
      continue;
451
0
    }
452
1.43k
    const int rank = ( rowLocked ? ROW_LOCKED : 0 ) + tlRank;
453
1.43k
    if( rank < bestRank )
454
1.43k
    {
455
1.43k
      best     = it;
456
1.43k
      bestRank = rank;
457
1.43k
      if( rank == 0 )
458
1.43k
      {
459
1.43k
        break;
460
1.43k
      }
461
1.43k
    }
462
1.43k
  }
463
1.43k
  CHECKD( best != procList.end() && ifp && ! ( *best )->slices[ 0 ]->checkAllRefPicsReconstructed()
464
1.43k
            && hasUnstartedRef( **best, procList ), "a row-locked picture must not start before its references" );
465
1.43k
  return best;
466
1.43k
}
467
468
// In lock-step mode (rate control with frame-parallel coding) pictures are coded in chunks, each after the previous
469
// chunk's rate-control update.
470
bool EncGOP::xIsLockStep() const
471
4.27k
{
472
4.27k
  return ( m_pcEncCfg->m_RCTargetBitrate > 0 || ( m_pcEncCfg->m_LookAhead > 0 && ! m_isPreAnalysis ) ) && m_pcEncCfg->m_maxParallelFrames > 0;
473
4.27k
}
474
475
// Whether new pictures join the processing list on every pass and start by temporal layer (findNextPicToStart), so that
476
// the long key pictures of the next GOP overlap the current GOP. Otherwise the list is refilled when empty and pictures
477
// start in list order: with one picture encoder (its start order is the coding order, which AMaxBT follows), lock-step
478
// RC, rate cap, and the I pictures' temporal pumping reduction, whose CTU QP memory (sized only then) the key pictures
479
// fill and the next I picture reads. With IFP and NumParallelGOPs 0 the list still takes one GOP at a time
480
// (xGetProcessingLists), so the next GOP's key pictures start early only from the pictures already held.
481
bool EncGOP::xFetchOnEveryPass( bool lockStepMode ) const
482
4.27k
{
483
4.27k
  const bool ctuQpMemory = m_globalCtuQpVector.size() > 1;
484
4.27k
  return m_pcEncCfg->m_maxParallelFrames > 0 && ! lockStepMode && ! m_pcEncCfg->m_rateCap && ! ctuQpMemory;
485
4.27k
}
486
487
// Starts ready pictures of the processing list while picture encoders are free, at most maxStarts of them (0: no limit).
488
// In blocking mode it waits for a picture encoder or a reference as needed.
489
void EncGOP::xStartPictures( bool lockStepMode, bool fetchOnEveryPass, int maxStarts )
490
1.43k
{
491
1.43k
  int numStarted = 0;
492
2.86k
  while( true )
493
2.86k
  {
494
2.86k
    Picture* pic           = nullptr;
495
2.86k
    EncPicture* picEncoder = nullptr;
496
497
    // fetch next picture to be encoded and next free picture encoder
498
2.86k
    {
499
2.86k
      std::unique_lock<std::mutex> lock( m_gopEncMutex, std::defer_lock );
500
2.86k
      if( m_pcEncCfg->m_numThreads > 0) lock.lock();
501
502
      // leave the loop when nothing to do (when all encoders are finished or in non-blocking mode)
503
2.86k
      if( m_procList.empty() && ( isNonBlocking() || xEncodersFinished() ) )
504
1.43k
      {
505
1.43k
        break;
506
1.43k
      }
507
508
      // get next picture ready to be encoded
509
      // if ALF enabled and ALFTempPred is used, ensure that refAps is initialized
510
      // rate capping and MT frame parallel: in the first GOP after scene cut, ensure that the two first frames of 
511
      //                                     this GOP are finished. Their data will be used to adjust the QP of
512
      //                                     remaining frames of this scene-cut-GOP.
513
1.43k
      const std::list<Picture *>* rcUpdateList = &m_rcUpdateList;
514
1.43k
      const VVEncCfg* encCfg = m_pcEncCfg;
515
1.43k
      auto isReady = [encCfg, rcUpdateList]( const Picture* cand ) {
516
1.43k
        return ( encCfg->m_ifp || cand->slices[ 0 ]->checkAllRefPicsReconstructed() )
517
1.43k
          && ( !encCfg->m_alf || ( !cand->refApsGlobal || cand->refApsGlobal->initalized ) )
518
1.43k
          && ( !encCfg->m_rateCap || !encCfg->m_maxParallelFrames || !cand->isSceneCutGOP || (!rcUpdateList->front()->isSceneCutCheckAdjQP && !rcUpdateList->front()->gopEntry->m_isStartOfGop ) )
519
1.43k
          ; };
520
1.43k
      auto picItr = fetchOnEveryPass ? findNextPicToStart( m_procList, m_pcEncCfg->m_ifp, isReady )
521
1.43k
                                     : find_if( m_procList.begin(), m_procList.end(), isReady );
522
523
1.43k
      const bool nextPicReady = picItr != m_procList.end();
524
525
      // check at least one picture and one pic encoder ready
526
1.43k
      if( m_freePicEncoderList.empty() || ! nextPicReady )
527
0
      {
528
        // non-blocking stage: wait on top level, let other stages do their jobs
529
        // in non-lockstep mode, check if next picture can be output
530
0
        if( isNonBlocking() || ( ! lockStepMode && m_gopEncListOutput.front()->isEncoded ) )
531
0
        {
532
0
          break;
533
0
        }
534
0
        CHECK( m_pcEncCfg->m_numThreads <= 0, "run into MT code, but no threading enabled" );
535
0
        CHECK( xEncodersFinished(), "wait for picture to be finished, but no pic encoder running" );
536
0
        m_gopEncCond.wait( lock );
537
0
        continue;
538
0
      }
539
540
1.43k
      pic = *picItr;
541
1.43k
      picEncoder = m_freePicEncoderList.front();
542
543
      // rate-control with look-ahead: init next chunk
544
1.43k
      if( m_pcEncCfg->m_RCTargetBitrate > 0 && m_pcEncCfg->m_LookAhead )
545
0
      {
546
0
        CHECK( m_isPreAnalysis, "rate control enabled for pre analysis" );
547
548
0
        if( pic->isFlush )
549
0
        {
550
0
          m_pcRateCtrl->setRCRateSavingState(0); // tell budget estimation that end of video is near
551
0
        }
552
0
        if( pic->gopEntry->m_isStartOfGop )
553
0
        {
554
          // check the RC final pass requirement for availability of preprocessed pictures (GOP + 1)
555
0
          if( m_pcRateCtrl->lastPOCInCache() <= pic->poc && ! pic->isFlush )
556
0
          {
557
0
            break;
558
0
          }
559
0
          m_pcRateCtrl->processFirstPassData( pic->isFlush, pic->poc );
560
0
        }
561
0
      }
562
563
1.43k
      m_freePicEncoderList.pop_front();
564
1.43k
    }
565
566
1.43k
    CHECK( picEncoder == nullptr, "no free picture encoder available" );
567
1.43k
    CHECK( pic        == nullptr, "no picture to be encoded, ready for encoding" );
568
1.43k
    m_procList.remove( pic );
569
570
1.43k
    xEncodePicture( pic, picEncoder );
571
1.43k
    if( ++numStarted == maxStarts )
572
0
    {
573
0
      break;
574
0
    }
575
1.43k
  }
576
1.43k
}
577
578
// The poll of the earlier stages (EncStage::pollStartStage) while the main thread waits in them: starts up to two
579
// ready pictures (so the stage's wait is not delayed much), never outputs or updates rate control. Not with rate
580
// control or look-ahead (a picture's RC init reads the updates made at output) or the rate cap, whose starts wait for
581
// those updates.
582
void EncGOP::startReadyPictures()
583
0
{
584
0
  CHECKD( m_isPreAnalysis, "the pre-analysis encoder is not polled" );
585
0
  if( ! isNonBlocking() || m_pcEncCfg->m_RCTargetBitrate > 0 || m_pcEncCfg->m_LookAhead > 0 || m_pcEncCfg->m_rateCap || m_procList.empty() )
586
0
  {
587
0
    return;
588
0
  }
589
0
  xStartPictures( false, xFetchOnEveryPass( false ), 2 );
590
0
}
591
592
void EncGOP::xProcessPictures( AccessUnitList& auList, PicList& doneList )
593
4.27k
{
594
  // in lockstep mode, process all pictures in processing list
595
4.27k
  const bool lockStepMode = xIsLockStep();
596
597
  // get list of pictures to be encoded and used for RC update
598
4.27k
  CHECK( m_pcEncCfg->m_rateCap && lockStepMode, "Rate capping should not be used in lockstep mode" );
599
  // rate cap and MT: finish the previous GOP before processing the next one
600
4.27k
  const bool rateCapPrevGopConstr = m_pcEncCfg->m_rateCap && !m_rcUpdateList.empty();
601
602
4.27k
  const bool fetchOnEveryPass = xFetchOnEveryPass( lockStepMode );
603
4.27k
  if( ( m_procList.empty() || fetchOnEveryPass ) && (!m_gopEncListInput.empty() || !m_rcInputReorderList.empty()) && !rateCapPrevGopConstr )
604
1.43k
  {
605
1.43k
    xGetProcessingLists( m_procList, m_rcUpdateList, lockStepMode );
606
1.43k
  }
607
608
4.27k
  if( ! m_procList.empty() )
609
1.43k
  {
610
    // encode one picture in serial mode / multiple pictures in FPP mode
611
1.43k
    PROFILER_ACCUM_AND_START_NEW_SET( 1, g_timeProfiler, P_IGNORE );
612
1.43k
    xStartPictures( lockStepMode, fetchOnEveryPass, 0 );
613
1.43k
  }
614
615
4.27k
  if( lockStepMode && m_pcEncCfg->m_ifpLines && !m_rcUpdateList.empty() )
616
0
  {
617
0
    xUpdateRcIfp();
618
0
  }
619
620
4.27k
  if( m_pcEncCfg->m_rateCap )
621
0
  {
622
0
    xUpdateRateCap();
623
0
  }
624
625
  // picture/AU output
626
  // 
627
  // in lock-step mode:
628
  // the output of a picture is connected to evaluation of the lock-step-chunk
629
  // if the next picture to output belongs to the current chunk, do output (evaluation) when all pictures of the chunk are finished
630
631
4.27k
  if( m_gopEncListOutput.empty() || !m_gopEncListOutput.front()->isEncoded ||
632
1.43k
    ( lockStepMode && !m_pcEncCfg->m_ifpLines && !m_rcUpdateList.empty() && m_gopEncListOutput.front() == m_rcUpdateList.front() && !xLockStepPicsFinished() ) )
633
2.84k
  {
634
2.84k
    return;
635
2.84k
  }
636
1.43k
  PROFILER_ACCUM_AND_START_NEW_SET( 1, g_timeProfiler, P_TOP_LEVEL );
637
638
  // AU output
639
1.43k
  Picture* outPic = m_gopEncListOutput.front();
640
1.43k
  m_gopEncListOutput.pop_front();
641
642
1.43k
  xWritePicture( *outPic, auList, false );
643
644
  // update pending RC
645
  // first pic has been written to bitstream
646
  // therefore we have at least for this picture a valid total bit and head bit count
647
1.43k
  if( !m_rcUpdateList.empty() && m_rcUpdateList.front() == outPic && (!lockStepMode || !m_pcEncCfg->m_ifpLines)  )
648
0
  {
649
0
    if( m_pcEncCfg->m_RCTargetBitrate > 0 )
650
0
    {
651
0
      for( auto pic : m_rcUpdateList )
652
0
      {
653
0
        if( pic != outPic )
654
0
        {
655
0
          pic->actualHeadBits  = outPic->actualHeadBits;
656
0
          pic->actualTotalBits = pic->sliceDataStreams[0].getNumberOfWrittenBits();
657
0
        }
658
0
        m_pcRateCtrl->updateAfterPicEncRC( pic );
659
0
      }
660
0
    }
661
662
0
    if( lockStepMode )
663
0
      m_rcUpdateList.clear();
664
0
    else
665
0
      m_rcUpdateList.pop_front();
666
0
  }
667
668
1.43k
  const bool skipFirstPass = ( ! m_pcRateCtrl->rcIsFinalPass || m_isPreAnalysis ) && outPic->gopEntry->m_skipFirstPass;
669
1.43k
  if( m_pcEncCfg->m_useAMaxBT && ! skipFirstPass )
670
0
  {
671
0
    m_BlkStat.updateMaxBT( *outPic->slices[0], outPic->picBlkStat );
672
0
  }
673
674
1.43k
  outPic->slices[ 0 ]->updateRefPicCounter( -1 );
675
1.43k
  outPic->isFinished = true;
676
677
1.43k
  if( ! m_isPreAnalysis )
678
1.43k
  {
679
    // a film grain analysis may still read the filtered picture
680
1.43k
    for( auto& task : m_fgaTasks )
681
0
    {
682
0
      if( task->pic == outPic )
683
0
      {
684
0
        task->counter.wait();
685
0
      }
686
0
    }
687
1.43k
    outPic->getFilteredOrigBuffer().destroy();
688
1.43k
  }
689
690
1.43k
  doneList.push_back( outPic );
691
692
1.43k
  m_numPicsCoded += 1;
693
1.43k
}
694
695
void EncGOP::xSyncAlfAps( Picture& pic )
696
1.43k
{
697
1.43k
  Slice& slice = *pic.cs->slice;
698
1.43k
  const bool mtPicParallel = m_pcEncCfg->m_numThreads > 0;
699
700
1.43k
  if( mtPicParallel && slice.isIntra() )
701
1.43k
  {
702
    // reset APS propagation on Intra-Slice in MT-mode
703
1.43k
    return;
704
1.43k
  }
705
706
0
  const PicApsGlobal* refAps = pic.refApsGlobal;
707
0
  if( !refAps )
708
0
    return;
709
0
  CHECK( !refAps->initalized, "Attempt referencing from an uninitialized APS" );
710
0
  pic.refApsGlobal->refCnt--;
711
0
  CHECK( pic.refApsGlobal->refCnt < 0, "Not expected APS ref. counter\n" );
712
713
  // copy ref APSs to current picture
714
0
  const ParameterSetMap<APS>& src = refAps->apsMap;
715
0
  ParameterSetMap<APS>&       dst = pic.picApsMap;
716
0
  if( mtPicParallel && pic.TLayer == 0 )
717
0
  {
718
    // in pic.parallel case, due to limited number of APS IDs, limit propagation of TID-0 APS
719
0
    CHECK( slice.sps->maxTLayers > ALF_CTB_MAX_NUM_APS, "Not enough space for ALF APSs in MT mode: not supported"  )
720
0
    int numApsTID0 = ALF_CTB_MAX_NUM_APS - (int)slice.sps->maxTLayers;
721
0
    int lastTakenApsPOC = pic.poc;
722
0
    while( numApsTID0 > 0 )
723
0
    {
724
0
      const APS* candAPS = nullptr;
725
0
      int candMapIdx = 0;
726
0
      for( int i = 0; i < ALF_CTB_MAX_NUM_APS; i++ )
727
0
      {
728
0
        const int mapIdx = ( i << NUM_APS_TYPE_LEN ) + ALF_APS;
729
0
        const APS* srcAPS = src.getPS( mapIdx );
730
0
        if( srcAPS && srcAPS->apsId != MAX_UINT && srcAPS->poc < lastTakenApsPOC && ( !candAPS || srcAPS->poc > candAPS->poc ) )
731
0
        {
732
0
          candAPS = srcAPS;
733
0
          candMapIdx = mapIdx;
734
0
        }
735
0
      }
736
0
      if( !candAPS )
737
0
        break;
738
739
0
      APS* dstAPS = dst.allocatePS( candMapIdx );
740
0
      *dstAPS = *candAPS;
741
0
      dst.clearChangedFlag( candMapIdx );
742
0
      lastTakenApsPOC = candAPS->poc;
743
0
      numApsTID0--;
744
0
    }
745
0
  }
746
0
  else
747
0
  {
748
0
    for( int i = 0; i < ALF_CTB_MAX_NUM_APS; i++ )
749
0
    {
750
0
      const int apsMapIdx = ( i << NUM_APS_TYPE_LEN ) + ALF_APS;
751
0
      const APS* srcAPS = src.getPS( apsMapIdx );
752
0
      if( srcAPS )
753
0
      {
754
0
        APS* dstAPS = dst.allocatePS( apsMapIdx );
755
0
        *dstAPS = *srcAPS;
756
0
        dst.clearChangedFlag( apsMapIdx );
757
0
      }
758
0
    }
759
0
  }
760
0
  dst.setApsIdStart( src.getApsIdStart() );
761
0
}
762
763
void EncGOP::xEncodePicture( Picture* pic, EncPicture* picEncoder )
764
1.43k
{
765
  // first pass temporal down-sampling
766
1.43k
  if( ( ! m_pcRateCtrl->rcIsFinalPass || m_isPreAnalysis ) && pic->gopEntry->m_skipFirstPass )
767
0
  {
768
0
    pic->isReconstructed = true;
769
0
    pic->isEncoded       = true;
770
0
    m_freePicEncoderList.push_back( picEncoder );
771
0
    return;
772
0
  }
773
774
  // decoder in encoder
775
1.43k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "finalpass", m_pcRateCtrl->rcIsFinalPass ? 1: 0 ) );
776
777
1.43k
  if( m_pcEncCfg->m_alf && m_pcEncCfg->m_alfTempPred )
778
1.43k
  {
779
    // Establish reference APS for current picture
780
1.43k
    xSyncAlfAps( *pic );
781
1.43k
  }
782
783
  // initialize next picture
784
1.43k
  pic->isPreAnalysis = m_isPreAnalysis;
785
  // before any task of the picture is queued: its tasks' priority (EncSlice::xProcessCtus)
786
1.43k
  pic->encStartOrder = ++m_numPicsStarted;
787
788
1.43k
  if( pic->slices[0]->TLayer + 1 < m_pcEncCfg->m_maxTLayer ) // skip for highest two temporal levels
789
1.43k
  {
790
1.43k
    initPicAuxQPOffsets( pic->slices[0], m_pcEncCfg->hasBlockQpOffsets() );
791
1.43k
  }
792
793
1.43k
  if( m_pcEncCfg->m_RCTargetBitrate > 0 )
794
0
  {
795
0
    pic->picInitialQP     = -1;
796
0
    pic->picInitialLambda = -1.0;
797
798
0
    m_pcRateCtrl->initRateControlPic( *pic, pic->slices[0], pic->picInitialQP, pic->picInitialLambda );
799
0
  }
800
801
1.43k
  if( pic->isSceneCutGOP && !pic->isSceneCutCheckAdjQP && !pic->gopEntry->m_isStartOfGop && m_rcap.gopAdaptedQPAdj )
802
0
  {
803
0
    pic->gopAdaptedQP += m_rcap.gopAdaptedQPAdj;
804
0
  }
805
806
  // finish picture encoding and cleanup, once all CTU tasks of the picture are done
807
1.43k
  static auto finishTask = []( int, void* task_param )
808
1.43k
  {
809
1.43k
    FinishTaskParam* param = static_cast<FinishTaskParam*>( task_param );
810
    // The pictures that reference this one may start as soon as what they read is final: the reconstruction and
811
    // motion (done by the CTU tasks) and the ALF APSs. Writing the slice data, the distortion and the cleanup run on
812
    // this one thread after that and do not change the reconstruction, motion or APSs.
813
1.43k
    param->picEncoder->finalizeReference( *param->pic );
814
1.43k
    {
815
1.43k
      std::lock_guard<std::mutex> lock( param->gopEncoder->m_gopEncMutex );
816
1.43k
      param->pic->isReconstructed = true;
817
1.43k
      if( param->pic->picApsGlobal )
818
1.43k
        param->pic->picApsGlobal->initalized = true;
819
      // counted like a finish, so that waitForFreeEncoders returns for it: the pictures referencing this one may start
820
1.43k
      param->gopEncoder->m_numPicsFinished++;
821
1.43k
      param->gopEncoder->m_gopEncCond.notify_one();
822
1.43k
    }
823
1.43k
    param->picEncoder->finalizePicture( *param->pic );
824
1.43k
    param->gopEncoder->xStoreLostGrainSpectra( *param->pic );
825
1.43k
    {
826
1.43k
      std::lock_guard<std::mutex> lock( param->gopEncoder->m_gopEncMutex );
827
1.43k
      param->pic->isEncoded = true;
828
1.43k
      param->gopEncoder->m_freePicEncoderList.push_back( param->picEncoder );
829
1.43k
      param->gopEncoder->m_numPicsFinished++;
830
1.43k
      param->gopEncoder->m_gopEncCond.notify_one();
831
1.43k
    }
832
1.43k
    delete param;
833
1.43k
    return true;
834
1.43k
  };
835
836
1.43k
  if( m_picSetupTasks )
837
1.43k
  {
838
    // compress next picture in a thread pool task, see init(). The setups run one at a time in start order, as they did on
839
    // the calling thread: with inter-frame parallelism, a picture's CTU tasks wait for CTU lines of its references, which
840
    // only exist once the references' setups have run.
841
1.43k
    static auto setupTask = []( int, void* task_param )
842
1.43k
    {
843
1.43k
      FinishTaskParam* param = static_cast<FinishTaskParam*>( task_param );
844
1.43k
      EncGOP* gopEncoder     = param->gopEncoder;
845
1.43k
      param->picEncoder->compressPicture( *param->pic, *gopEncoder );
846
1.43k
      gopEncoder->m_numSetupsDone++;
847
      // The finish task is added only now: until compressPicture added the CTU tasks, the done barrier of the picture
848
      // encoder's CTU task counter is still open from its previous picture. Once it is added, the finish task may run,
849
      // delete param and let the encoder finish, so nothing is touched after it. It has the same priority as the
850
      // picture's CTU tasks (EncSlice::xProcessCtus).
851
1.43k
      gopEncoder->m_threadPool->addBarrierTask( finishTask, param, nullptr, nullptr, { &param->picEncoder->m_ctuTasksDoneCounter.done }, nullptr,
852
1.43k
                                                1 + param->pic->encStartOrder );
853
1.43k
      return true;
854
1.43k
    };
855
1.43k
    static auto setupReady = []( int, void* task_param )
856
1.43k
    {
857
1.43k
      const FinishTaskParam* param = static_cast<const FinishTaskParam*>( task_param );
858
1.43k
      return param->gopEncoder->m_numSetupsDone == param->setupNum;
859
1.43k
    };
860
1.43k
    FinishTaskParam* param = new FinishTaskParam( this, picEncoder, pic );
861
1.43k
    param->setupNum        = m_numSetupsQueued++;
862
    // the most urgent priority (0), as the pre-analysis rows: a setup is short and holds back all of its picture's tasks
863
1.43k
    m_threadPool->addBarrierTask( setupTask, param, nullptr, nullptr, {}, setupReady, 0 );
864
1.43k
    return;
865
1.43k
  }
866
867
  // compress next picture
868
0
  picEncoder->compressPicture( *pic, *this );
869
870
  // finish picture encoding and cleanup
871
0
  if( m_pcEncCfg->m_numThreads > 0 )
872
0
  {
873
0
    FinishTaskParam* param = new FinishTaskParam( this, picEncoder, pic );
874
    // the priority of the picture's CTU tasks (EncSlice::xProcessCtus): it frees the picture encoder, so it ranks with them
875
0
    m_threadPool->addBarrierTask( finishTask, param, nullptr, nullptr, { &picEncoder->m_ctuTasksDoneCounter.done }, nullptr,
876
0
                                  1 + pic->encStartOrder );
877
0
  }
878
0
  else
879
0
  {
880
0
    picEncoder->finalizeReference( *pic );
881
0
    picEncoder->finalizePicture( *pic );
882
0
    xStoreLostGrainSpectra( *pic );
883
0
    pic->isReconstructed = true;
884
0
    pic->isEncoded       = true;
885
0
    if( pic->picApsGlobal ) pic->picApsGlobal->initalized = true;
886
0
    m_freePicEncoderList.push_back( picEncoder );
887
0
  }
888
0
}
889
890
void EncGOP::xOutputRecYuv( const PicList& picList )
891
4.27k
{
892
4.27k
  if( m_pcRateCtrl->rcIsFinalPass && m_recYuvBufFunc )
893
0
  {
894
0
    CHECK( m_isPreAnalysis, "yuv output enabled for pre analysis" );
895
    // ordered YUV output
896
0
    bool bRun = true;
897
0
    while( bRun )
898
0
    {
899
0
      bRun = false;
900
0
      for( auto pic : picList )
901
0
      {
902
0
        if( pic->poc != m_pocRecOut )
903
0
          continue;
904
0
        if( ! pic->isEncoded )
905
0
          return;
906
907
0
        const PPS& pps = *(pic->cs->pps);
908
0
        vvencYUVBuffer yuvBuffer;
909
0
        vvenc_YUVBuffer_default( &yuvBuffer );
910
0
        setupYuvBuffer( pic->getRecoBuf(), yuvBuffer, &pps.conformanceWindow );
911
0
        yuvBuffer.sequenceNumber = pic->poc;
912
0
        m_recYuvBufFunc( m_recYuvBufCtx, &yuvBuffer );
913
914
0
        m_pocRecOut += 1;
915
0
        pic->isNeededForOutput = false;
916
0
        bRun = true;
917
0
        break;
918
0
      }
919
0
    }
920
0
  }
921
4.27k
  else
922
4.27k
  {
923
    // no output needed, simply unmark pictures
924
4.27k
    for( auto pic : picList )
925
4.27k
    {
926
4.27k
      if( pic->isEncoded && pic->isNeededForOutput )
927
1.43k
        pic->isNeededForOutput = false;
928
4.27k
    }
929
4.27k
  }
930
4.27k
}
931
932
void EncGOP::xReleasePictures( const PicList& picList, PicList& freeList )
933
4.27k
{
934
4.27k
  const bool allPicsDone = m_numPicsCoded >= m_picCount && ( picList.empty() || picList.back()->isFlush );
935
  // Writing a picture reads its reconstruction only for the decoded picture hash SEI. Without it, a
936
  // picture that no other picture references and that is not waiting for reconstruction output needs
937
  // neither its reconstruction nor its motion field once it is reconstructed.
938
4.27k
  const bool writeReadsReco = m_pcEncCfg->m_decodedPictureHashSEIType != VVENC_HASHTYPE_NONE;
939
  // Once encoded, a picture of the final encoder (the last stage; never the pre-analysis encoder, whose pictures the
940
  // final pass reads again) no longer reads its source: finalizePicture computes PSNR before isEncoded is set (while
941
  // isReconstructed is set before it, see xEncodePicture). It may then lend the source buffer
942
  // to new input (EncLib::xGetFreePicShared). Its temporally filtered copy and its links to the two previous source
943
  // pictures (QPA, read only while it is coded) are released here instead of at output, so those pictures can lend their
944
  // source buffers sooner. Not with rate control or rate cap, whose updates after reconstruction are kept as they are,
945
  // and not before the picture's film grain analysis has read its source.
946
4.27k
  const bool lendSources = ! m_isPreAnalysis && m_pcEncCfg->m_RCTargetBitrate == 0 && ! m_pcEncCfg->m_rateCap;
947
4.27k
  for( auto pic : picList )
948
4.27k
  {
949
4.27k
    if( lendSources && pic->isEncoded && pic->m_picShared && ! pic->m_picShared->isSourceDone()
950
1.43k
        && ! ( m_pcEncCfg->m_fga && xFgaReadsSource( *pic ) ) )
951
1.43k
    {
952
1.43k
      pic->m_picShared->setSourceDone();
953
1.43k
      pic->getFilteredOrigBuffer().destroy();
954
1.43k
      pic->m_picShared->releasePrevBuffers( pic );
955
1.43k
    }
956
4.27k
    const bool isUnused = ! pic->isNeededForOutput && ! pic->isReferenced && pic->refCounter <= 0;
957
4.27k
    if( ( pic->isFinished && isUnused ) || allPicsDone )
958
1.43k
    {
959
      // Nothing reads a released picture any more. Its buffers are allocated again when the
960
      // picture object is reused and its next picture starts encoding.
961
1.43k
      pic->releaseEncodingBuffers();
962
1.43k
      if( pic->m_picShared )
963
1.43k
      {
964
        // a later picture's QPA reference may still hold the source: it must not be lent any more
965
1.43k
        pic->m_picShared->clearSourceDone();
966
1.43k
      }
967
1.43k
      freeList.push_back( pic );
968
1.43k
    }
969
2.84k
    else if( pic->isEncoded && isUnused && ! writeReadsReco )
970
0
    {
971
0
      pic->releaseEncodingBuffers();
972
0
    }
973
4.27k
  }
974
4.27k
}
975
976
void EncGOP::printOutSummary( const bool printMSEBasedSNR, const bool printSequenceMSE, const bool printHexPsnr )
977
0
{
978
  //--CFG_KDY
979
  //const int rateMultiplier = 1;
980
0
  double fps = m_pcEncCfg->m_FrameRate/(double)m_pcEncCfg->m_FrameScale;
981
0
  m_AnalyzeAll.setFrmRate( fps );
982
0
  m_AnalyzeI.setFrmRate( fps );
983
0
  m_AnalyzeP.setFrmRate( fps );
984
0
  m_AnalyzeB.setFrmRate( fps );
985
986
0
  const ChromaFormat chFmt = m_pcEncCfg->m_internChromaFormat;
987
988
0
  const BitDepths& bitDepths = m_spsMap.getFirstPS()->bitDepths;
989
  //-- all
990
0
  std::string summary( "\n" );
991
0
  if( m_pcEncCfg->m_verbosity >= VVENC_DETAILS )
992
0
    summary.append("\nvvenc [info]: SUMMARY --------------------------------------------------------\n");
993
994
0
  summary.append( m_AnalyzeAll.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, printHexPsnr, bitDepths));
995
996
0
  if( m_pcEncCfg->m_verbosity < VVENC_DETAILS )
997
0
  {
998
0
    msg.log( VVENC_INFO,summary.c_str() );
999
0
  }
1000
0
  else
1001
0
  {
1002
0
    summary.append( "\n\nvvenc [info]: I Slices--------------------------------------------------------\n" );
1003
0
    summary.append( m_AnalyzeI.printOut('i', chFmt, printMSEBasedSNR, printSequenceMSE, printHexPsnr, bitDepths));
1004
1005
0
    summary.append( "\n\nvvenc [info]: P Slices--------------------------------------------------------\n" );
1006
0
    summary.append( m_AnalyzeP.printOut('p', chFmt, printMSEBasedSNR, printSequenceMSE, printHexPsnr, bitDepths));
1007
1008
0
    summary.append( "\n\nvvenc [info]: B Slices--------------------------------------------------------\n" );
1009
0
    summary.append( m_AnalyzeB.printOut('b', chFmt, printMSEBasedSNR, printSequenceMSE, printHexPsnr, bitDepths));
1010
0
    msg.log( VVENC_DETAILS,summary.c_str() );
1011
0
  }
1012
1013
0
  if (m_pcEncCfg->m_summaryOutFilename[0] != '\0' )
1014
0
  {
1015
0
    std::string summaryOutFilename(m_pcEncCfg->m_summaryOutFilename);
1016
0
    m_AnalyzeAll.printSummary(chFmt, printSequenceMSE, printHexPsnr, bitDepths, summaryOutFilename);
1017
0
  }
1018
1019
0
  if (m_pcEncCfg->m_summaryPicFilenameBase[0] != '\0' )
1020
0
  {
1021
0
    std::string summaryPicFilenameBase(m_pcEncCfg->m_summaryPicFilenameBase);
1022
1023
0
    m_AnalyzeI.printSummary(chFmt, printSequenceMSE, printHexPsnr, bitDepths, summaryPicFilenameBase+"I.txt");
1024
0
    m_AnalyzeP.printSummary(chFmt, printSequenceMSE, printHexPsnr, bitDepths, summaryPicFilenameBase+"P.txt");
1025
0
    m_AnalyzeB.printSummary(chFmt, printSequenceMSE, printHexPsnr, bitDepths, summaryPicFilenameBase+"B.txt");
1026
0
  }
1027
0
}
1028
1029
void EncGOP::getParameterSets( AccessUnitList& accessUnit )
1030
0
{
1031
0
  CHECK( m_ppsMap.getFirstPS() == nullptr || m_spsMap.getPS( m_ppsMap.getFirstPS()->spsId ) == nullptr, "sps/pps not initialised" );
1032
1033
0
  const PPS& pps = *( m_ppsMap.getFirstPS() );
1034
0
  const SPS& sps = *( m_spsMap.getPS( pps.spsId ) );
1035
1036
0
  if (sps.vpsId != 0)
1037
0
  {
1038
0
    xWriteVPS( accessUnit, &m_VPS, m_HLSWriter );
1039
0
  }
1040
0
  xWriteDCI( accessUnit, &m_DCI, m_HLSWriter );
1041
0
  xWriteSPS( accessUnit, &sps, m_HLSWriter );
1042
0
  xWritePPS( accessUnit, &pps, &sps, m_HLSWriter );
1043
0
}
1044
1045
void EncGOP::xUpdateRasInit( Slice* slice )
1046
1.43k
{
1047
1.43k
  slice->pendingRasInit = false;
1048
1.43k
  if ( slice->poc > m_lastRasPoc )
1049
0
  {
1050
0
    m_lastRasPoc = MAX_INT;
1051
0
    slice->pendingRasInit = true;
1052
0
  }
1053
1.43k
  if ( slice->isIRAP() )
1054
1.43k
  {
1055
1.43k
    m_lastRasPoc = slice->poc;
1056
1.43k
  }
1057
1.43k
}
1058
1059
void EncGOP::xInitVPS(VPS &vps) const
1060
1.43k
{
1061
  // The SPS must have already been set up.
1062
  // set the VPS profile information.
1063
1.43k
  vps.maxLayers                   = 1;
1064
1.43k
  vps.maxSubLayers                = 1;
1065
1.43k
  vps.vpsId                       = 0;
1066
1.43k
  vps.allLayersSameNumSubLayers   = true;
1067
1.43k
  vps.allIndependentLayers        = true;
1068
1.43k
  vps.eachLayerIsAnOls            = true;
1069
1.43k
  vps.olsModeIdc                  = 0;
1070
1.43k
  vps.numOutputLayerSets          = 1;
1071
1.43k
  vps.numPtls                     = 1;
1072
1.43k
  vps.extension                   = false;
1073
1.43k
  vps.totalNumOLSs                = 0;
1074
1.43k
  vps.numDpbParams                = 0;
1075
1.43k
  vps.sublayerDpbParamsPresent    = false;
1076
1.43k
  vps.targetOlsIdx                = -1;
1077
1078
93.0k
  for (int i = 0; i < MAX_VPS_LAYERS; i++)
1079
91.6k
  {
1080
91.6k
    vps.layerId[i]                = 0;
1081
91.6k
    vps.independentLayer[i]       = true;
1082
5.95M
    for (int j = 0; j < MAX_VPS_LAYERS; j++)
1083
5.86M
    {
1084
5.86M
      vps.directRefLayer[i][j]    = 0;
1085
5.86M
      vps.directRefLayerIdx[i][j] = MAX_VPS_LAYERS;
1086
5.86M
      vps.interLayerRefIdx[i][i]  = NOT_VALID;
1087
5.86M
    }
1088
91.6k
  }
1089
1090
368k
  for (int i = 0; i < MAX_NUM_OLSS; i++)
1091
366k
  {
1092
23.8M
    for (int j = 0; j < MAX_VPS_LAYERS; j++)
1093
23.4M
    {
1094
23.4M
      vps.olsOutputLayer[i][j]    = 0;
1095
23.4M
    }
1096
366k
    vps.ptPresent[i]              = (i == 0) ? 1 : 0;
1097
366k
    vps.ptlMaxTemporalId[i]       = vps.maxSubLayers - 1;
1098
366k
    vps.olsPtlIdx[i]              = 0;
1099
366k
  }
1100
1101
1.43k
  vps.profileTierLevel.resize( 1 );
1102
1.43k
}
1103
1104
void EncGOP::xInitDCI(DCI &dci, const SPS &sps, const int dciId) const
1105
1.43k
{
1106
  // The SPS must have already been set up.
1107
  // set the DPS profile information.
1108
1.43k
  dci.dciId                 = dciId;
1109
1110
1.43k
  dci.profileTierLevel.resize(1);
1111
  // copy profile level tier info
1112
1.43k
  dci.profileTierLevel[0]   = sps.profileTierLevel;
1113
1.43k
}
1114
1115
void EncGOP::xInitConstraintInfo(ConstraintInfo &ci) const
1116
1.43k
{
1117
1.43k
  ci.intraOnlyConstraintFlag                      = m_pcEncCfg->m_intraOnlyConstraintFlag;
1118
1.43k
  ci.maxBitDepthConstraintIdc                     = m_pcEncCfg->m_bitDepthConstraintValue - 8;
1119
1.43k
  ci.maxChromaFormatConstraintIdc                 = m_pcEncCfg->m_internChromaFormat;
1120
1.43k
  ci.onePictureOnlyConstraintFlag                 = false;
1121
1.43k
  ci.lowerBitRateConstraintFlag                   = false;
1122
1.43k
  ci.allLayersIndependentConstraintFlag           = false;
1123
1.43k
  ci.noQtbttDualTreeIntraConstraintFlag           = ! m_pcEncCfg->m_dualITree;
1124
1.43k
  ci.noPartitionConstraintsOverrideConstraintFlag = false;
1125
1.43k
  ci.noSaoConstraintFlag                          = ! m_pcEncCfg->m_bUseSAO;
1126
1.43k
  ci.noAlfConstraintFlag                          = ! m_pcEncCfg->m_alf;
1127
1.43k
  ci.noCCAlfConstraintFlag                        = ! m_pcEncCfg->m_ccalf;
1128
1.43k
  ci.noRefWraparoundConstraintFlag                = false;
1129
1.43k
  ci.noTemporalMvpConstraintFlag                  = m_pcEncCfg->m_TMVPModeId == 0;
1130
1.43k
  ci.noSbtmvpConstraintFlag                       = !m_pcEncCfg->m_SbTMVP;
1131
1.43k
  ci.noAmvrConstraintFlag                         = false;
1132
1.43k
  ci.noBdofConstraintFlag                         = ! m_pcEncCfg->m_BDOF;
1133
1.43k
  ci.noDmvrConstraintFlag                         = ! m_pcEncCfg->m_DMVR;
1134
1.43k
  ci.noCclmConstraintFlag                         = ! m_pcEncCfg->m_LMChroma;
1135
1.43k
  ci.noMtsConstraintFlag                          = !(m_pcEncCfg->m_MTSImplicit || m_pcEncCfg->m_MTS);
1136
1.43k
  ci.noSbtConstraintFlag                          = m_pcEncCfg->m_SBT == 0;
1137
1.43k
  ci.noAffineMotionConstraintFlag                 = ! m_pcEncCfg->m_Affine;
1138
1.43k
  ci.noBcwConstraintFlag                          = m_pcEncCfg->m_BCW == 0;
1139
1.43k
  ci.noIbcConstraintFlag                          = m_pcEncCfg->m_IBCMode == 0;
1140
1.43k
  ci.noCiipConstraintFlag                         = m_pcEncCfg->m_CIIP == 0;
1141
1.43k
  ci.noGeoConstraintFlag                          = m_pcEncCfg->m_Geo == 0;
1142
1.43k
  ci.noLadfConstraintFlag                         = true;
1143
1.43k
  ci.noTransformSkipConstraintFlag                = m_pcEncCfg->m_TS == 0;
1144
1.43k
  ci.noBDPCMConstraintFlag                        = m_pcEncCfg->m_useBDPCM==0;
1145
1.43k
  ci.noJointCbCrConstraintFlag                    = ! m_pcEncCfg->m_JointCbCrMode;
1146
1.43k
  ci.noMrlConstraintFlag                          = ! m_pcEncCfg->m_MRL;
1147
1.43k
  ci.noIspConstraintFlag                          = m_pcEncCfg->m_ISP == 0;
1148
1.43k
  ci.noMipConstraintFlag                          = ! m_pcEncCfg->m_MIP;
1149
1.43k
  ci.noQpDeltaConstraintFlag                      = false;
1150
1.43k
  ci.noDepQuantConstraintFlag                     = ! m_pcEncCfg->m_DepQuantEnabled;
1151
1.43k
  ci.noMixedNaluTypesInPicConstraintFlag          = false;
1152
1.43k
  ci.noSignDataHidingConstraintFlag               = ! m_pcEncCfg->m_SignDataHidingEnabled;
1153
1.43k
  ci.noLfnstConstraintFlag                        = ! m_pcEncCfg->m_LFNST;
1154
1.43k
  ci.noMmvdConstraintFlag                         = ! m_pcEncCfg->m_MMVD;
1155
1.43k
  ci.noSmvdConstraintFlag                         = ! m_pcEncCfg->m_SMVD;
1156
1.43k
  ci.noProfConstraintFlag                         = ! m_pcEncCfg->m_PROF;
1157
1.43k
  ci.noPaletteConstraintFlag                      = true;
1158
1.43k
  ci.noActConstraintFlag                          = true;
1159
1.43k
  ci.noLmcsConstraintFlag                         = true;
1160
1.43k
  ci.noTrailConstraintFlag                        = m_pcEncCfg->m_IntraPeriod == 1;
1161
1.43k
  ci.noStsaConstraintFlag                         = m_pcEncCfg->m_IntraPeriod == 1 || ! m_gopCfg->hasNonZeroTemporalId();
1162
1.43k
  ci.noRaslConstraintFlag                         = m_pcEncCfg->m_IntraPeriod == 1 || ! m_gopCfg->hasLeadingPictures();
1163
1.43k
  ci.noRadlConstraintFlag                         = m_pcEncCfg->m_IntraPeriod == 1 || ! m_gopCfg->hasLeadingPictures();
1164
1.43k
  ci.noIdrConstraintFlag                          = false;
1165
1.43k
  ci.noCraConstraintFlag                          = (m_pcEncCfg->m_DecodingRefreshType != VVENC_DRT_CRA && m_pcEncCfg->m_DecodingRefreshType != VVENC_DRT_CRA_CRE);
1166
1.43k
  ci.noGdrConstraintFlag                          = false;
1167
1.43k
  ci.noApsConstraintFlag                          = !m_pcEncCfg->m_alf;
1168
1.43k
}
1169
1170
void EncGOP::xInitSPS(SPS &sps) const
1171
1.43k
{
1172
1.43k
  ProfileTierLevel* profileTierLevel = &sps.profileTierLevel;
1173
1174
1.43k
  xInitConstraintInfo( profileTierLevel->constraintInfo );
1175
1176
1.43k
  profileTierLevel->levelIdc      = m_pcEncCfg->m_level;
1177
1.43k
  profileTierLevel->tierFlag      = m_pcEncCfg->m_levelTier;
1178
1.43k
  profileTierLevel->profileIdc    = m_pcEncCfg->m_profile;
1179
1.43k
  profileTierLevel->subProfileIdc.clear();
1180
1.43k
  profileTierLevel->subProfileIdc.push_back( m_pcEncCfg->m_subProfile );
1181
1182
1.43k
  if( m_pcEncCfg->m_maxPicWidth != 0 && m_pcEncCfg->m_maxPicHeight != 0 )
1183
0
  {
1184
0
    const int minCuSize = std::max( 1 << ( vvenc::MIN_CU_LOG2 + 1 ), 1 << m_pcEncCfg->m_log2MinCodingBlockSize );
1185
0
    int padRight = 0, padBottom = 0;
1186
0
    if( m_pcEncCfg->m_maxPicWidth % minCuSize )
1187
0
    {
1188
0
      padRight = ( ( m_pcEncCfg->m_maxPicWidth / minCuSize) + 1 ) * minCuSize - m_pcEncCfg->m_maxPicWidth;
1189
0
    }
1190
0
    if( m_pcEncCfg->m_maxPicHeight % minCuSize )
1191
0
    {
1192
0
      padBottom = ( ( m_pcEncCfg->m_maxPicHeight / minCuSize) + 1 ) * minCuSize - m_pcEncCfg->m_maxPicHeight;
1193
0
    }
1194
0
    sps.maxPicWidthInLumaSamples      = m_pcEncCfg->m_maxPicWidth + padRight;
1195
0
    sps.maxPicHeightInLumaSamples     = m_pcEncCfg->m_maxPicHeight + padBottom;
1196
    
1197
0
    sps.conformanceWindow.setWindow( 0, padRight, 0, padBottom );
1198
0
  }
1199
1.43k
  else
1200
1.43k
  {
1201
1.43k
    sps.maxPicWidthInLumaSamples      = m_pcEncCfg->m_PadSourceWidth;
1202
1.43k
    sps.maxPicHeightInLumaSamples     = m_pcEncCfg->m_PadSourceHeight;
1203
1.43k
    sps.conformanceWindow.setWindow( m_pcEncCfg->m_confWinLeft, m_pcEncCfg->m_confWinRight, m_pcEncCfg->m_confWinTop, m_pcEncCfg->m_confWinBottom );
1204
1.43k
  }
1205
1.43k
  sps.chromaFormatIdc               = m_pcEncCfg->m_internChromaFormat;
1206
1.43k
  sps.CTUSize                       = m_pcEncCfg->m_CTUSize;
1207
1.43k
  sps.maxMTTDepth[0]                = m_pcEncCfg->m_maxMTTDepthI;
1208
1.43k
  int maxMTTDepthVal = m_pcEncCfg->m_maxMTTDepth;
1209
1.43k
  int minMaxMttD = maxMTTDepthVal % 10;
1210
2.86k
  while( maxMTTDepthVal )
1211
1.43k
  {
1212
1.43k
    minMaxMttD      = std::min( minMaxMttD, maxMTTDepthVal % 10 );
1213
1.43k
    maxMTTDepthVal /= 10;
1214
1.43k
  }
1215
1.43k
  sps.maxMTTDepth[1]                = minMaxMttD;
1216
1.43k
  sps.maxMTTDepth[2]                = m_pcEncCfg->m_maxMTTDepthIChroma;
1217
5.72k
  for( int i = 0; i < 3; i++)
1218
4.29k
  {
1219
4.29k
    sps.minQTSize[i]                = m_pcEncCfg->m_MinQT[i];
1220
4.29k
    sps.maxBTSize[i]                = m_pcEncCfg->m_maxBT[i];
1221
4.29k
    sps.maxTTSize[i]                = m_pcEncCfg->m_maxTT[i];
1222
4.29k
  }
1223
1.43k
  sps.minQTSize[2]                <<= getChannelTypeScaleX(CH_C, m_pcEncCfg->m_internChromaFormat);
1224
1225
1.43k
  sps.maxNumMergeCand               = m_pcEncCfg->m_maxNumMergeCand;
1226
1.43k
  sps.maxNumAffineMergeCand         = !!m_pcEncCfg->m_Affine ? m_pcEncCfg->m_maxNumAffineMergeCand : 0;
1227
1.43k
  sps.maxNumGeoCand                 = !!m_pcEncCfg->m_Geo    ? m_pcEncCfg->m_maxNumGeoCand : 0;
1228
1.43k
  sps.IBC                           = m_pcEncCfg->m_IBCMode != 0;
1229
1.43k
  sps.maxNumIBCMergeCand            = 6;
1230
1231
1.43k
  sps.idrRefParamList               = m_pcEncCfg->m_idrRefParamList;
1232
1.43k
  sps.dualITree                     = m_pcEncCfg->m_dualITree && m_pcEncCfg->m_internChromaFormat != VVENC_CHROMA_400;
1233
1.43k
  sps.MTS                           = m_pcEncCfg->m_MTS || m_pcEncCfg->m_MTSImplicit;
1234
1.43k
  sps.SMVD                          = m_pcEncCfg->m_SMVD;
1235
1.43k
  sps.AMVR                          = m_pcEncCfg->m_AMVRspeed != IMV_OFF;
1236
1.43k
  sps.LMChroma                      = m_pcEncCfg->m_LMChroma;
1237
1.43k
  sps.horCollocatedChroma           = m_pcEncCfg->m_horCollocatedChromaFlag;
1238
1.43k
  sps.verCollocatedChroma           = m_pcEncCfg->m_verCollocatedChromaFlag;
1239
1.43k
  sps.BDOF                          = m_pcEncCfg->m_BDOF;
1240
1.43k
  sps.DMVR                          = m_pcEncCfg->m_DMVR;
1241
1.43k
  sps.Affine                        = m_pcEncCfg->m_Affine;
1242
1.43k
  sps.PROF                          = m_pcEncCfg->m_PROF;
1243
1.43k
  sps.ProfPresent                   = m_pcEncCfg->m_PROF;
1244
1.43k
  sps.AffineType                    = m_pcEncCfg->m_AffineType;
1245
1.43k
  sps.MMVD                          = m_pcEncCfg->m_MMVD != 0;
1246
1.43k
  sps.fpelMmvd                      = m_pcEncCfg->m_allowDisFracMMVD;
1247
1.43k
  sps.GEO                           = m_pcEncCfg->m_Geo != 0;
1248
1.43k
  sps.MIP                           = m_pcEncCfg->m_MIP;
1249
1.43k
  sps.MRL                           = m_pcEncCfg->m_MRL;
1250
1.43k
  sps.BdofPresent                   = m_pcEncCfg->m_BDOF;
1251
1.43k
  sps.DmvrPresent                   = m_pcEncCfg->m_DMVR;
1252
1.43k
  sps.partitionOverrideEnabled      = true; // needed for the new MaxMTTDepth logic
1253
1.43k
  sps.resChangeInClvsEnabled        = m_pcEncCfg->m_resChangeInClvsEnabled;
1254
1.43k
  sps.rprEnabled                    = m_pcEncCfg->m_rprEnabledFlag != 0;
1255
1.43k
  sps.log2MinCodingBlockSize        = m_pcEncCfg->m_log2MinCodingBlockSize;
1256
1.43k
  sps.log2MaxTbSize                 = m_pcEncCfg->m_log2MaxTbSize;
1257
1.43k
  sps.temporalMVPEnabled            = m_pcEncCfg->m_TMVPModeId == 2 || m_pcEncCfg->m_TMVPModeId == 1;
1258
1.43k
  sps.LFNST                         = m_pcEncCfg->m_LFNST != 0;
1259
1.43k
  sps.entropyCodingSyncEnabled      = m_pcEncCfg->m_entropyCodingSyncEnabled;
1260
1.43k
  sps.entryPointsPresent            = m_pcEncCfg->m_entryPointsPresent;
1261
1.43k
  sps.depQuantEnabled               = m_pcEncCfg->m_DepQuantEnabled;
1262
1.43k
  sps.signDataHidingEnabled         = m_pcEncCfg->m_SignDataHidingEnabled;
1263
1.43k
  sps.MTSIntra                      = m_pcEncCfg->m_MTS ;
1264
1.43k
  sps.ISP                           = m_pcEncCfg->m_ISP;
1265
1.43k
  sps.transformSkip                 = m_pcEncCfg->m_TS != 0;
1266
1.43k
  sps.log2MaxTransformSkipBlockSize = m_pcEncCfg->m_TSsize;
1267
1.43k
  sps.BDPCM                         = m_pcEncCfg->m_useBDPCM != 0;
1268
1.43k
  sps.BCW                           = m_pcEncCfg->m_BCW;
1269
1270
4.29k
  for (uint32_t chType = 0; chType < MAX_NUM_CH; chType++)
1271
2.86k
  {
1272
2.86k
    sps.bitDepths.recon[chType]     = m_pcEncCfg->m_internalBitDepth[chType];
1273
2.86k
    sps.qpBDOffset[chType]          = 6 * (m_pcEncCfg->m_internalBitDepth[chType] - 8);
1274
2.86k
    sps.internalMinusInputBitDepth[chType] = std::max(0, (m_pcEncCfg->m_internalBitDepth[chType] - m_pcEncCfg->m_inputBitDepth[chType]));
1275
2.86k
  }
1276
1277
1.43k
  sps.alfEnabled                    = m_pcEncCfg->m_alf;
1278
1.43k
  sps.ccalfEnabled                  = m_pcEncCfg->m_ccalf && sps.alfEnabled && m_pcEncCfg->m_internChromaFormat != VVENC_CHROMA_400;
1279
1280
1.43k
  sps.saoEnabled                    = m_pcEncCfg->m_bUseSAO;
1281
1.43k
  sps.jointCbCr                     = m_pcEncCfg->m_JointCbCrMode;
1282
1.43k
  sps.maxTLayers                    = m_pcEncCfg->m_maxTLayer + 1;
1283
1.43k
  sps.rpl1CopyFromRpl0              = ! m_pcEncCfg->m_picReordering;
1284
1.43k
  sps.SbtMvp                        = m_pcEncCfg->m_SbTMVP;
1285
1.43k
  sps.CIIP                          = m_pcEncCfg->m_CIIP != 0;
1286
1.43k
  sps.SBT                           = m_pcEncCfg->m_SBT != 0;
1287
1288
1.43k
  CHECK( sps.maxTLayers > VVENC_MAX_TLAYER, "array index out of bounds" );
1289
10.0k
  for( int i = 0; i < sps.maxTLayers; i++ )
1290
8.59k
  {
1291
8.59k
    sps.maxDecPicBuffering[ i ]     = m_gopCfg->getMaxDecPicBuffering()[ i ];
1292
8.59k
    sps.numReorderPics[ i ]         = m_gopCfg->getNumReorderPics()[ i ];
1293
8.59k
  }
1294
1295
1.43k
  sps.vuiParametersPresent          = m_pcEncCfg->m_vuiParametersPresent;
1296
1297
1.43k
  if (sps.vuiParametersPresent)
1298
0
  {
1299
0
    VUI& vui = sps.vuiParameters;
1300
0
    vui.aspectRatioInfoPresent        = m_pcEncCfg->m_aspectRatioInfoPresent;
1301
0
    vui.aspectRatioConstantFlag       = true; // false if SampleAspectRatioInfoSEIEnabled, but this SEI is not used
1302
0
    vui.aspectRatioIdc                = m_pcEncCfg->m_aspectRatioIdc;
1303
0
    vui.sarWidth                      = m_pcEncCfg->m_sarWidth;
1304
0
    vui.sarHeight                     = m_pcEncCfg->m_sarHeight;
1305
0
    vui.colourDescriptionPresent      = m_pcEncCfg->m_colourDescriptionPresent;
1306
0
    vui.colourPrimaries               = m_pcEncCfg->m_colourPrimaries;
1307
0
    vui.transferCharacteristics       = m_pcEncCfg->m_transferCharacteristics;
1308
0
    vui.matrixCoefficients            = m_pcEncCfg->m_matrixCoefficients;
1309
0
    vui.chromaLocInfoPresent          = m_pcEncCfg->m_chromaLocInfoPresent;
1310
0
    vui.chromaSampleLocType           = m_pcEncCfg->m_chromaSampleLocType;
1311
0
    vui.chromaSampleLocTypeTopField   = 0;
1312
0
    vui.chromaSampleLocTypeBottomField= 0;
1313
0
    vui.overscanInfoPresent           = m_pcEncCfg->m_overscanInfoPresent;
1314
0
    vui.overscanAppropriateFlag       = m_pcEncCfg->m_overscanAppropriateFlag;
1315
0
    vui.videoFullRangeFlag            = m_pcEncCfg->m_videoFullRangeFlag;
1316
0
  }
1317
1318
1.43k
  sps.hrdParametersPresent            = m_pcEncCfg->m_hrdParametersPresent;
1319
1320
1.43k
  sps.numLongTermRefPicSPS            = NUM_LONG_TERM_REF_PIC_SPS;
1321
1.43k
  CHECK(!(NUM_LONG_TERM_REF_PIC_SPS <= MAX_NUM_LONG_TERM_REF_PICS), "Unspecified error");
1322
1.43k
  for (int k = 0; k < NUM_LONG_TERM_REF_PIC_SPS; k++)
1323
0
  {
1324
0
    sps.ltRefPicPocLsbSps[k]          = 0;
1325
0
    sps.usedByCurrPicLtSPS[k]         = 0;
1326
0
  }
1327
1.43k
  sps.chromaQpMappingTable.m_numQpTables = (m_pcEncCfg->m_chromaQpMappingTableParams.m_sameCQPTableForAllChromaFlag ? 1 : (sps.jointCbCr ? 3 : 2));
1328
1.43k
  sps.chromaQpMappingTable.setParams(m_pcEncCfg->m_chromaQpMappingTableParams, sps.qpBDOffset[ CH_C ]);
1329
1.43k
  sps.chromaQpMappingTable.derivedChromaQPMappingTables();
1330
1.43k
}
1331
1332
void EncGOP::xInitPPS(PPS &pps, const SPS &sps) const
1333
1.43k
{
1334
1.43k
  bool bUseDQP = m_pcEncCfg->m_cuQpDeltaSubdiv > 0;
1335
1.43k
  bUseDQP |= m_pcEncCfg->m_lumaLevelToDeltaQPEnabled == 1;
1336
1.43k
  bUseDQP |= m_pcEncCfg->m_usePerceptQPA;
1337
1.43k
  bUseDQP |= m_pcEncCfg->hasBlockQpOffsets();
1338
1339
1.43k
  if (m_pcEncCfg->m_costMode==VVENC_COST_SEQUENCE_LEVEL_LOSSLESS || m_pcEncCfg->m_costMode==VVENC_COST_LOSSLESS_CODING)
1340
0
  {
1341
0
    bUseDQP = false;
1342
0
  }
1343
1.43k
  if( m_pcEncCfg->m_maxDeltaQP == 0 )
1344
0
  {
1345
0
    bUseDQP = false;
1346
0
  }
1347
1348
  // pps ID already initialised.
1349
1.43k
  pps.spsId                         = sps.spsId;
1350
1.43k
  pps.jointCbCrQpOffsetPresent      = m_pcEncCfg->m_JointCbCrMode;
1351
1.43k
  pps.picWidthInLumaSamples         = m_pcEncCfg->m_PadSourceWidth;
1352
1.43k
  pps.picHeightInLumaSamples        = m_pcEncCfg->m_PadSourceHeight;
1353
1.43k
  if( pps.picWidthInLumaSamples == sps.maxPicWidthInLumaSamples && pps.picHeightInLumaSamples == sps.maxPicHeightInLumaSamples )
1354
1.43k
  {
1355
1.43k
    pps.conformanceWindow           = sps.conformanceWindow;
1356
1.43k
  }
1357
0
  else
1358
0
  {
1359
0
    pps.conformanceWindow.setWindow( m_pcEncCfg->m_confWinLeft, m_pcEncCfg->m_confWinRight, m_pcEncCfg->m_confWinTop, m_pcEncCfg->m_confWinBottom );
1360
0
  }
1361
1362
1.43k
  pps.picWidthInCtu                 = (pps.picWidthInLumaSamples + (sps.CTUSize-1)) / sps.CTUSize;
1363
1.43k
  pps.picHeightInCtu                = (pps.picHeightInLumaSamples + (sps.CTUSize-1)) / sps.CTUSize;
1364
1.43k
  pps.subPics.clear();
1365
1.43k
  pps.subPics.resize(1);
1366
1.43k
  pps.subPics[0].init( pps.picWidthInCtu, pps.picHeightInCtu, pps.picWidthInLumaSamples, pps.picHeightInLumaSamples);
1367
1.43k
  pps.useDQP                        = bUseDQP;
1368
1369
1.43k
  if ( m_pcEncCfg->m_cuChromaQpOffsetSubdiv >= 0 )
1370
0
  {
1371
    //th check how this is configured now    pps.cuChromaQpOffsetSubdiv = m_pcEncCfg->m_cuChromaQpOffsetSubdiv;
1372
0
    pps.chromaQpOffsetListLen = 0;
1373
0
    pps.setChromaQpOffsetListEntry(1, 6, 6, 6);
1374
0
  }
1375
1376
  // fix PPS init QP to 26 or 32 (depending on BD) to make concatenating bitstreams more robust
1377
1.43k
  pps.picInitQPMinus26 = 6 - sps.qpBDOffset[CH_L] / 2;
1378
1379
1.43k
  pps.chromaQpOffset[COMP_Y]          = 0;
1380
1.43k
  pps.chromaQpOffset[COMP_Cb]         = m_pcEncCfg->m_chromaCbQpOffset;
1381
1.43k
  pps.chromaQpOffset[COMP_Cr]         = m_pcEncCfg->m_chromaCrQpOffset;
1382
1.43k
  pps.chromaQpOffset[COMP_JOINT_CbCr] = m_pcEncCfg->m_chromaCbCrQpOffset;
1383
1384
1.43k
  bool bChromaDeltaQPEnabled = false;
1385
1.43k
  {
1386
1.43k
    bChromaDeltaQPEnabled = ( m_pcEncCfg->m_sliceChromaQpOffsetIntraOrPeriodic[ 0 ] || m_pcEncCfg->m_sliceChromaQpOffsetIntraOrPeriodic[ 1 ] );
1387
1.43k
    bChromaDeltaQPEnabled |= (m_pcEncCfg->m_usePerceptQPA || (m_pcEncCfg->m_LookAhead && m_pcRateCtrl->m_pcEncCfg->m_RCTargetBitrate > 0) || m_pcEncCfg->m_sliceChromaQpOffsetPeriodicity > 0) && (m_pcEncCfg->m_internChromaFormat != VVENC_CHROMA_400);
1388
1.43k
    if( ! bChromaDeltaQPEnabled && sps.dualITree && ( m_pcEncCfg->m_internChromaFormat != VVENC_CHROMA_400 ) )
1389
0
    {
1390
0
      bChromaDeltaQPEnabled = (m_pcEncCfg->m_chromaCbQpOffsetDualTree != 0 || m_pcEncCfg->m_chromaCrQpOffsetDualTree != 0 || m_pcEncCfg->m_chromaCbCrQpOffsetDualTree != 0);
1391
0
    }
1392
1.43k
    if( ! bChromaDeltaQPEnabled )
1393
0
    {
1394
0
      bChromaDeltaQPEnabled = m_gopCfg->isChromaDeltaQPEnabled();
1395
0
    }
1396
1.43k
  }
1397
1.43k
  pps.sliceChromaQpFlag                 = bChromaDeltaQPEnabled;
1398
1.43k
  pps.outputFlagPresent                 = false;
1399
1.43k
  pps.deblockingFilterOverrideEnabled   = !m_pcEncCfg->m_loopFilterOffsetInPPS;
1400
1.43k
  pps.deblockingFilterDisabled          = m_pcEncCfg->m_bLoopFilterDisable;
1401
1402
1.43k
  if (! pps.deblockingFilterDisabled)
1403
1.43k
  {
1404
5.72k
    for( int comp = 0; comp < MAX_NUM_COMP; comp++)
1405
4.29k
    {
1406
4.29k
      pps.deblockingFilterBetaOffsetDiv2[comp]  = m_pcEncCfg->m_loopFilterBetaOffsetDiv2[comp];
1407
4.29k
      pps.deblockingFilterTcOffsetDiv2[comp]    = m_pcEncCfg->m_loopFilterTcOffsetDiv2[comp];
1408
4.29k
    }
1409
1.43k
  }
1410
1411
  // deblockingFilterControlPresent is true if any of the settings differ from the inferred values:
1412
1.43k
  bool deblockingFilterControlPresent   = pps.deblockingFilterOverrideEnabled ||
1413
1.43k
                                          pps.deblockingFilterDisabled     ||
1414
1.43k
                                          pps.deblockingFilterBetaOffsetDiv2[COMP_Y] != 0 ||
1415
1.43k
                                          pps.deblockingFilterTcOffsetDiv2  [COMP_Y] != 0 ||
1416
1.43k
                                          pps.deblockingFilterBetaOffsetDiv2[COMP_Cb] != 0 ||
1417
1.43k
                                          pps.deblockingFilterTcOffsetDiv2  [COMP_Cb] != 0 ||
1418
1.43k
                                          pps.deblockingFilterBetaOffsetDiv2[COMP_Cr] != 0 ||
1419
1.43k
                                          pps.deblockingFilterTcOffsetDiv2  [COMP_Cr] != 0;
1420
1421
1.43k
  pps.deblockingFilterControlPresent    = deblockingFilterControlPresent;
1422
1.43k
  pps.cabacInitPresent                  = m_pcEncCfg->m_cabacInitPresent != 0;
1423
1.43k
  pps.loopFilterAcrossTilesEnabled      = !m_pcEncCfg->m_bDisableLFCrossTileBoundaryFlag;
1424
1.43k
  pps.loopFilterAcrossSlicesEnabled     = !m_pcEncCfg->m_bDisableLFCrossSliceBoundaryFlag;
1425
1.43k
  pps.rpl1IdxPresent                    = sps.rpl1IdxPresent;
1426
1427
1.43k
  const uint32_t chromaArrayType = (int)sps.separateColourPlane ? CHROMA_400 : sps.chromaFormatIdc;
1428
1.43k
  if( chromaArrayType != CHROMA_400  )
1429
1.43k
  {
1430
1.43k
    bool chromaQPOffsetNotZero = ( pps.chromaQpOffset[COMP_Cb] != 0 || pps.chromaQpOffset[COMP_Cr] != 0 || pps.jointCbCrQpOffsetPresent || pps.sliceChromaQpFlag || pps.chromaQpOffsetListLen );
1431
1.43k
    bool chromaDbfOffsetNotAsLuma = ( pps.deblockingFilterBetaOffsetDiv2[COMP_Cb] != pps.deblockingFilterBetaOffsetDiv2[COMP_Y]
1432
1.43k
                                   || pps.deblockingFilterBetaOffsetDiv2[COMP_Cr] != pps.deblockingFilterBetaOffsetDiv2[COMP_Y]
1433
1.43k
                                   || pps.deblockingFilterTcOffsetDiv2[COMP_Cb] != pps.deblockingFilterTcOffsetDiv2[COMP_Y]
1434
1.43k
                                   || pps.deblockingFilterTcOffsetDiv2[COMP_Cr] != pps.deblockingFilterTcOffsetDiv2[COMP_Y]);
1435
1.43k
    pps.usePPSChromaTool = chromaQPOffsetNotZero || chromaDbfOffsetNotAsLuma;
1436
1.43k
  }
1437
1438
1.43k
  pps.numRefIdxL0DefaultActive = std::max( m_gopCfg->getDefaultNumActive( 0 ), 1 );
1439
1.43k
  pps.numRefIdxL1DefaultActive = std::max( m_gopCfg->getDefaultNumActive( 1 ), 1 );
1440
1.43k
  CHECK( pps.numRefIdxL0DefaultActive > 15, "num default ref index active exceeds maximum value");
1441
1.43k
  CHECK( pps.numRefIdxL1DefaultActive > 15, "num default ref index active exceeds maximum value");
1442
1443
1.43k
  pps.noPicPartition = !m_pcEncCfg->m_picPartitionFlag;
1444
1.43k
  pps.ctuSize        = sps.CTUSize;
1445
1.43k
  pps.log2CtuSize    = Log2( sps.CTUSize );
1446
1447
1.43k
  xInitPPSforTiles( pps, sps );
1448
1449
1.43k
  pps.pcv            = new PreCalcValues( sps, pps, m_pcEncCfg->m_MaxQT );
1450
1.43k
}
1451
1452
void EncGOP::xInitPPSforTiles(PPS &pps,const SPS &sps) const
1453
1.43k
{
1454
1.43k
  pps.numExpTileCols = m_pcEncCfg->m_numExpTileCols;
1455
1.43k
  pps.numExpTileRows = m_pcEncCfg->m_numExpTileRows;
1456
1.43k
  pps.numSlicesInPic = m_pcEncCfg->m_numSlicesInPic;
1457
1458
1.43k
  if( pps.noPicPartition )
1459
1.43k
  {
1460
1.43k
    pps.tileColWidth.resize( 1, pps.picWidthInCtu );
1461
1.43k
    pps.tileRowHeight.resize( 1, pps.picHeightInCtu );
1462
1.43k
    pps.initTiles();
1463
1.43k
    pps.sliceMap.clear();
1464
1.43k
    pps.sliceMap.resize(1);
1465
1.43k
    pps.sliceMap[0].addCtusToSlice(0, pps.picWidthInCtu, 0, pps.picHeightInCtu, pps.picWidthInCtu);
1466
1.43k
  }
1467
0
  else
1468
0
  {
1469
0
    for( int i = 0; i < pps.numExpTileCols; i++ )
1470
0
    {
1471
0
      pps.tileColWidth.push_back( m_pcEncCfg->m_tileColumnWidth[i] );
1472
0
    }
1473
0
    for( int i = 0; i < pps.numExpTileRows; i++ )
1474
0
    {
1475
0
      pps.tileRowHeight.push_back( m_pcEncCfg->m_tileRowHeight[i] );
1476
0
    }
1477
0
    pps.initTiles();
1478
0
    pps.rectSlice            = true;
1479
0
    pps.tileIdxDeltaPresent  = false;
1480
0
    pps.initRectSliceMap( &sps );
1481
0
  }
1482
1.43k
}
1483
1484
void EncGOP::xInitRPL(SPS &sps) const
1485
1.43k
{
1486
1.43k
  m_gopCfg->getDefaultRPLLists( sps.rplList[ 0 ], sps.rplList[ 1 ] );
1487
1488
1.43k
  sps.rpl1IdxPresent = ( sps.rplList[ 0 ].size() != sps.rplList[ 1 ].size() );
1489
1490
  //Check if all delta POC of STRP in each RPL has the same sign
1491
  //Check RPLL0 first
1492
1.43k
  bool isAllEntriesinRPLHasSameSignFlag = true;
1493
4.29k
  for( int list = 0; list < 2; list++)
1494
2.86k
  {
1495
2.86k
    const RPLList& rplList = sps.rplList[list];
1496
2.86k
    uint32_t numRPL        = (uint32_t)rplList.size();
1497
1498
2.86k
    bool isFirstEntry = true;
1499
2.86k
    bool lastSign = true;        //true = positive ; false = negative
1500
5.72k
    for (uint32_t ii = 0; isAllEntriesinRPLHasSameSignFlag && ii < numRPL; ii++)
1501
2.86k
    {
1502
2.86k
      const ReferencePictureList& rpl = rplList[ii];
1503
5.72k
      for (uint32_t jj = 0; jj < rpl.numberOfActivePictures; jj++)
1504
4.29k
      {
1505
4.29k
        if(rpl.isLongtermRefPic[jj])
1506
0
          continue;
1507
1508
4.29k
        if( isFirstEntry )
1509
1.43k
        {
1510
1.43k
          lastSign = (rpl.refPicIdentifier[jj] >= 0) ? true : false;
1511
1.43k
          isFirstEntry = false;
1512
1.43k
        }
1513
2.86k
        else
1514
2.86k
        {
1515
2.86k
          int ref = ( jj == 0 && !isFirstEntry ) ? 0 : rpl.refPicIdentifier[jj-1];
1516
2.86k
          if (((rpl.refPicIdentifier[jj] - ref) >= 0 ) != lastSign)
1517
1.43k
          {
1518
1.43k
            isAllEntriesinRPLHasSameSignFlag = false;
1519
1.43k
            break;  // break the inner loop
1520
1.43k
          }
1521
2.86k
        }
1522
4.29k
      }
1523
2.86k
    }
1524
2.86k
  }
1525
1526
1.43k
  sps.allRplEntriesHasSameSign = isAllEntriesinRPLHasSameSignFlag;
1527
1528
1.43k
  bool isRpl1CopiedFromRpl0 = ( sps.rplList[ 0 ].size() == sps.rplList[ 1 ].size() );
1529
4.29k
  for( int i = 0; isRpl1CopiedFromRpl0 && i < (int)sps.rplList[ 0 ].size(); i++)
1530
2.86k
  {
1531
2.86k
    isRpl1CopiedFromRpl0 = ( sps.rplList[0][i].getNumRefEntries() == sps.rplList[1][i].getNumRefEntries() );
1532
2.86k
    if( isRpl1CopiedFromRpl0 )
1533
2.86k
    {
1534
4.29k
      for( int j = 0; j < sps.rplList[0][i].getNumRefEntries(); j++ )
1535
2.86k
      {
1536
2.86k
        if( sps.rplList[0][i].refPicIdentifier[j] != sps.rplList[1][i].refPicIdentifier[j] )
1537
1.43k
        {
1538
1.43k
          isRpl1CopiedFromRpl0 = false;
1539
1.43k
          break;
1540
1.43k
        }
1541
2.86k
      }
1542
2.86k
    }
1543
2.86k
  }
1544
1.43k
  sps.rpl1CopyFromRpl0 = isRpl1CopiedFromRpl0;
1545
1.43k
}
1546
1547
void EncGOP::xInitHrdParameters(SPS &sps)
1548
1.43k
{
1549
1.43k
  m_EncHRD.initHRDParameters( *m_pcEncCfg, sps );
1550
1551
1.43k
  sps.generalHrdParams = m_EncHRD.generalHrdParams;
1552
1553
11.4k
  for(int i = 0; i < VVENC_MAX_TLAYER; i++)
1554
10.0k
  {
1555
10.0k
    sps.olsHrdParams[i] = m_EncHRD.olsHrdParams[i];
1556
10.0k
  }
1557
1.43k
}
1558
1559
/** Function for deciding the nal_unit_type.
1560
 */
1561
1562
vvencNalUnitType EncGOP::xGetNalUnitType( const GOPEntry* _gopEntry ) const
1563
2.86k
{
1564
2.86k
  const GOPEntry& gopEntry = *_gopEntry;
1565
1566
2.86k
  if( gopEntry.m_POC == 0 && m_pcEncCfg->m_poc0idr )
1567
0
  {
1568
0
    return VVENC_NAL_UNIT_CODED_SLICE_IDR_N_LP;
1569
0
  }
1570
1571
2.86k
  if( gopEntry.m_isStartOfIntra )
1572
2.86k
  {
1573
2.86k
    if( m_pcEncCfg->m_DecodingRefreshType == VVENC_DRT_CRA || m_pcEncCfg->m_DecodingRefreshType == VVENC_DRT_CRA_CRE )
1574
2.86k
    {
1575
2.86k
      if( m_lastIDR == 0 && !m_pcEncCfg->m_poc0idr )
1576
2.86k
      {
1577
2.86k
        return VVENC_NAL_UNIT_CODED_SLICE_IDR_W_RADL;
1578
2.86k
      }
1579
0
      else
1580
0
      {
1581
0
        return VVENC_NAL_UNIT_CODED_SLICE_CRA;
1582
0
      }
1583
2.86k
    }
1584
0
    else if( m_pcEncCfg->m_DecodingRefreshType == VVENC_DRT_IDR_NO_RADL )
1585
0
    {
1586
0
      return VVENC_NAL_UNIT_CODED_SLICE_IDR_N_LP;
1587
0
    }
1588
0
    else
1589
0
    {
1590
0
      return VVENC_NAL_UNIT_CODED_SLICE_IDR_W_RADL;
1591
0
    }
1592
2.86k
  }
1593
1594
0
  if( m_pocCRA > 0 && gopEntry.m_POC < m_pocCRA )
1595
0
  {
1596
    // All leading pictures are being marked as TFD pictures here since current encoder uses all
1597
    // reference pictures while encoding leading pictures. An encoder can ensure that a leading
1598
    // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by
1599
    // controlling the reference pictures used for encoding that leading picture. Such a leading
1600
    // picture need not be marked as a TFD picture.
1601
0
    return VVENC_NAL_UNIT_CODED_SLICE_RASL;
1602
0
  }
1603
1604
0
  if( m_lastIDR > 0 && gopEntry.m_POC < m_lastIDR && m_pcEncCfg->m_DecodingRefreshType != VVENC_DRT_IDR_NO_RADL )
1605
0
  {
1606
0
    return VVENC_NAL_UNIT_CODED_SLICE_RADL;
1607
0
  }
1608
1609
0
  return VVENC_NAL_UNIT_CODED_SLICE_TRAIL;
1610
0
}
1611
1612
bool EncGOP::xIsSliceTemporalSwitchingPoint( const Slice* slice, const PicList& picList ) const
1613
1.43k
{
1614
1.43k
  if( slice->TLayer <= 0
1615
0
      || slice->nalUnitType == VVENC_NAL_UNIT_CODED_SLICE_RADL
1616
0
      || slice->nalUnitType == VVENC_NAL_UNIT_CODED_SLICE_RASL
1617
0
      || ! slice->isStepwiseTemporalLayerSwitchingPointCandidate( picList ) )
1618
1.43k
  {
1619
1.43k
    return false;
1620
1.43k
  }
1621
1622
0
  const GOPEntry& gopEntry = *(slice->pic->gopEntry);
1623
0
  const bool isSTSA        = gopEntry.m_isSTSA;
1624
0
  return isSTSA;
1625
1.43k
}
1626
1627
void EncGOP::xSetupPicAps( Picture* pic )
1628
1.43k
{
1629
  // manage global APS list
1630
1.43k
  m_globalApsList.push_back( new PicApsGlobal( pic->poc, pic->TLayer ) );
1631
1.43k
  CHECK( pic->picApsGlobal != nullptr, "Top level APS ptr must be nullptr" );
1632
1633
  // The list is kept near this size; the +2 covers up to two GOPs of processing delay (Threads=1 mode). The pictures in
1634
  // flight are not bounded by this size (GOP read-ahead, look-ahead stages), so an entry is deleted only after its last
1635
  // use: no picture set up later references it, and its own picture has filled it (initalized: finalizeReference wrote
1636
  // it before, or with IFP the copy at the ALF derivation; nothing writes it after). (Pictures skipped in a first pass
1637
  // never finish, but they have no entry: the first pass runs without ALF.)
1638
1.43k
  const size_t maxListSize = std::max( (int)MAX_NUM_APS, m_pcEncCfg->m_GOPSize ) * ( m_pcEncCfg->m_maxParallelFrames + 2 );
1639
1.43k
  if( m_globalApsList.size() > maxListSize )
1640
0
  {
1641
    // the finish task (or, with IFP, the APS copy at the ALF derivation) sets initalized under this mutex
1642
0
    std::unique_lock<std::mutex> lock( m_gopEncMutex, std::defer_lock );
1643
0
    if( m_pcEncCfg->m_numThreads > 0 ) lock.lock();
1644
0
    while( m_globalApsList.size() > maxListSize && m_globalApsList.front()->refCnt == 0 && m_globalApsList.front()->initalized )
1645
0
    {
1646
0
      delete m_globalApsList.front();
1647
0
      m_globalApsList.pop_front();
1648
0
    }
1649
0
  }
1650
1651
1.43k
  pic->picApsGlobal = m_globalApsList.back();
1652
1653
  // determine reference APS
1654
1.43k
  const bool mtPicParallel = m_pcEncCfg->m_numThreads > 0;
1655
1.43k
  if( mtPicParallel && pic->slices[0]->isIntra() )
1656
1.43k
  {
1657
    // reset APS propagation on Intra-Slice in MT-mode
1658
1.43k
    return;
1659
1.43k
  }
1660
1661
  // get previous APS (in coding order) to propagate from it
1662
  // in parallelization case (parallel pictures), we refer to APS from lower temporal layer
1663
  // NOTE: elements in the global APS list are following in coding order
1664
1665
0
  PicApsGlobal* refAps = nullptr;
1666
0
  auto curApsItr = std::find_if( m_globalApsList.begin(), m_globalApsList.end(), [pic]( auto p ) { return p->poc == pic->poc; } );
1667
0
  CHECK( curApsItr == m_globalApsList.end(), "Should not happen" );
1668
1669
0
  if( curApsItr != m_globalApsList.begin() )
1670
0
  {
1671
0
    if( mtPicParallel )
1672
0
    {
1673
0
      auto r_begin = std::reverse_iterator<std::deque<PicApsGlobal*>::iterator>(curApsItr);
1674
0
      auto r_end   = std::reverse_iterator<std::deque<PicApsGlobal*>::iterator>(m_globalApsList.begin());
1675
0
      auto refApsItr = ( pic->TLayer > 0 ) ? std::find_if( r_begin, r_end, [pic]( auto p ) { return p->tid  < pic->TLayer; } ):
1676
0
                                             std::find_if( r_begin, r_end, [pic]( auto p ) { return p->tid == pic->TLayer; } );
1677
0
      if( refApsItr == r_end )
1678
0
        return;
1679
0
      refAps = *refApsItr;
1680
0
    }
1681
0
    else
1682
0
    {
1683
0
      curApsItr--;
1684
0
      refAps = *curApsItr;
1685
0
    }
1686
0
    if( refAps )
1687
0
      refAps->refCnt++;
1688
0
  }
1689
1690
  //CHECK( !refAps, "Faied to get reference APS" );
1691
0
  pic->refApsGlobal = refAps;
1692
0
}
1693
1694
void EncGOP::xAnalyzeFilmGrain( Picture& pic )
1695
0
{
1696
  // Pictures come here in coding order. Analyzing them here rather than when their encoding starts keeps the choice
1697
  // of analyzed pictures, and the parameters each access unit signals, independent of the parallel encoding order.
1698
  // The analysis looks at the start picture of every GOP, which MCTF filtered for it: the first coded picture of its
1699
  // GOP in random access, normally the last in low delay.
1700
0
  if( !pic.m_picShared->getFgaFilteredBuf().valid() && !pic.m_picShared->fgaUsesFilteredBuf() )
1701
0
  {
1702
0
    return;
1703
0
  }
1704
0
  m_fgaTasks.emplace_back( new FgaTask );
1705
0
  FgaTask* task  = m_fgaTasks.back().get();
1706
0
  task->gop        = this;
1707
0
  task->pic        = &pic;
1708
0
  task->codingNum  = pic.gopEntry->m_codingNum;
1709
1710
  // The result applies from the picture after the previously analysed one; when PreProcess found a scene cut in
1711
  // between, from the cut, so that the pictures before it keep the parameters of their scene. The first analysis
1712
  // applies to all pictures before it as well. Pictures already written keep theirs (xAddFilmGrainParameters).
1713
0
  const bool first  = m_fgaPrevAnalysedPoc == std::numeric_limits<int>::min();
1714
0
  const int  cutPoc = pic.m_picShared->fgaSceneCut() ? pic.poc : pic.m_picShared->fgaLastSceneCutPoc();
1715
0
  task->sceneCut    = !first && cutPoc > m_fgaPrevAnalysedPoc;
1716
0
  task->startPoc    = first ? std::numeric_limits<int>::min() : task->sceneCut ? cutPoc : m_fgaPrevAnalysedPoc + 1;
1717
0
  m_fgaPrevAnalysedPoc = pic.poc;
1718
0
  const Barrier* previous = m_fgaLast ? &m_fgaLast->counter.done : nullptr;
1719
0
  m_fgaLast = task;
1720
1721
0
  static auto runTask = []( int, void* param )
1722
0
  {
1723
0
    FgaTask* t = static_cast<FgaTask*>( param );
1724
0
    t->gop->xRunFgaTask( *t );
1725
0
    return true;
1726
0
  };
1727
0
  if( m_threadPool )
1728
0
  {
1729
    // off the encoding path: the result is only needed when the access unit of the picture is written
1730
0
    m_threadPool->addBarrierTask( runTask, task, &task->counter, nullptr, { previous } );
1731
0
  }
1732
0
  else
1733
0
  {
1734
0
    runTask( 0, task );
1735
0
  }
1736
0
}
1737
1738
void EncGOP::xRunFgaTask( FgaTask& task )
1739
0
{
1740
0
  PicShared* shared         = task.pic->m_picShared;
1741
0
  PelStorage& fgaBuf        = shared->getFgaFilteredBuf();
1742
0
  PelStorage& residualBuf   = shared->getFgaResidualBuf();
1743
0
  const int residualWeight  = shared->fgaResidualWeight();
1744
0
  const bool ownBuf         = fgaBuf.valid();
1745
0
  const CPelUnitBuf denoised = ownBuf ? CPelUnitBuf( fgaBuf ) : CPelUnitBuf( task.pic->getFilteredOrigBuffer() );
1746
0
  if( residualWeight )
1747
0
  {
1748
0
    const CPelUnitBuf residual( residualBuf );
1749
0
    m_fgAnalyzer.estimateGrainParameters( task.pic->getOrigBuffer(), denoised, &residual, residualWeight, task.sceneCut );
1750
0
  }
1751
0
  else
1752
0
  {
1753
0
    m_fgAnalyzer.estimateGrainParameters( task.pic->getOrigBuffer(), denoised, nullptr, 0, task.sceneCut );
1754
0
  }
1755
0
  residualBuf.destroy();
1756
0
  if( ownBuf )
1757
0
  {
1758
0
    fgaBuf.destroy();
1759
0
  }
1760
0
  task.result = FilmGrainParam( m_fgAnalyzer, m_pcEncCfg->m_fgaStrength );
1761
0
}
1762
1763
// Whether a film grain analysis of the picture may still read its source.
1764
bool EncGOP::xFgaReadsSource( const Picture& pic ) const
1765
0
{
1766
0
  for( const auto& task : m_fgaTasks )
1767
0
  {
1768
0
    if( task->pic == &pic && task->counter.isBlocked() )
1769
0
    {
1770
0
      return true;
1771
0
    }
1772
0
  }
1773
0
  return false;
1774
0
}
1775
1776
void EncGOP::xWaitFgaTasks()
1777
1.43k
{
1778
1.43k
  for( auto& task : m_fgaTasks )
1779
0
  {
1780
0
    task->counter.wait();
1781
0
  }
1782
1.43k
}
1783
1784
void EncGOP::xInitPicsInCodingOrder( const PicList& picList )
1785
4.27k
{
1786
4.27k
  CHECK( m_pcEncCfg->m_maxParallelFrames <= 0 && m_gopEncListInput.size() > 0,  "no frame parallel processing enabled, but multiple pics in flight" );
1787
4.27k
  CHECK( m_pcEncCfg->m_maxParallelFrames <= 0 && m_gopEncListOutput.size() > 0, "no frame parallel processing enabled, but multiple pics in flight" );
1788
1789
  // loop over pic list, which is sorted in coding number order 
1790
8.55k
  for( auto it = picList.begin(); it != picList.end(); ++it )
1791
4.27k
  {
1792
4.27k
    auto pic = (*it);
1793
    // skip pics, which have already been initialized
1794
4.27k
    if( pic->isInitDone )
1795
2.84k
      continue;
1796
1797
    // update visual activity for last start of GOP picture
1798
    // this may have been changed in the shared picture data due to fixStartOfLastGop()
1799
1.43k
    if( pic->gopEntry->m_isStartOfGop && picList.back()->isFlush )
1800
1.43k
    {
1801
1.43k
      xUpdateVAStartOfLastGop( *pic );
1802
1.43k
    }
1803
1804
    // GOP QP adjustments
1805
1.43k
    if( (m_pcEncCfg->m_rateCap || m_pcEncCfg->m_GOPQPA || m_pcEncCfg->m_usePerceptQPA) && pic->gopEntry->m_isStartOfGop )
1806
1.43k
    {
1807
      // note: in case of rate cap, wait until the complete GOP is in the list and update-list is empty
1808
1.43k
      if( !m_pcEncCfg->m_rateCap ||
1809
0
        ((pic->gopEntry->m_gopNum != picList.back()->gopEntry->m_gopNum || picList.back()->isFlush) && m_rcUpdateList.empty()) )
1810
1.43k
      {
1811
1.43k
        xInitGopQpCascade( *pic, it, picList );
1812
1.43k
      }
1813
0
      else
1814
0
      {
1815
        // rate cap: wait until the condition is met
1816
0
        break;
1817
0
      }
1818
1.43k
    }
1819
1820
    // continue with next pic in increasing coding number order
1821
1.43k
    if( pic->gopEntry->m_codingNum != m_lastCodingNum + 1 && ! picList.back()->isFlush )
1822
0
      break;
1823
1824
1.43k
    CHECK( m_lastCodingNum == -1 && ! pic->gopEntry->m_isStartOfIntra, "encoding should start with an I-Slice" );
1825
1826
1.43k
    xForceScc( *pic );
1827
1828
    // initialize slice header
1829
1.43k
    pic->encTime.startTimer();
1830
1.43k
    xInitFirstSlice( *pic, picList, false );
1831
1.43k
    pic->encTime.stopTimer();
1832
1833
    // pictures ready for encoding
1834
1.43k
    m_gopEncListInput.push_back( pic );
1835
1.43k
    m_gopEncListOutput.push_back( pic );
1836
1837
1.43k
    if( m_pcEncCfg->m_alf && m_pcEncCfg->m_alfTempPred )
1838
1.43k
    {
1839
1.43k
        xSetupPicAps( pic );
1840
1.43k
    }
1841
1842
1.43k
    if( m_pcEncCfg->m_fga && !m_isPreAnalysis && m_pcRateCtrl->rcIsFinalPass )
1843
0
    {
1844
0
      xAnalyzeFilmGrain( *pic );
1845
0
    }
1846
1847
    // continue with next picture
1848
1.43k
    m_lastCodingNum = pic->gopEntry->m_codingNum;
1849
1850
    // in single threading initialize only one picture per encoding loop
1851
1.43k
    if( m_pcEncCfg->m_maxParallelFrames <= 0 )
1852
0
      break;
1853
1.43k
  }
1854
1855
4.27k
  CHECK( !(m_pcEncCfg->m_rateCap || m_pcEncCfg->m_GOPQPA || m_pcEncCfg->m_usePerceptQPA) && picList.size() && m_pcEncCfg->m_maxParallelFrames <= 0 && m_gopEncListInput.size() != 1,  "no new picture for encoding found" );
1856
4.27k
  CHECK( !(m_pcEncCfg->m_rateCap || m_pcEncCfg->m_GOPQPA || m_pcEncCfg->m_usePerceptQPA) && picList.size() && m_pcEncCfg->m_maxParallelFrames <= 0 && m_gopEncListOutput.size() != 1, "no new picture for encoding found" );
1857
4.27k
}
1858
1859
void EncGOP::xUpdateRcIfp()
1860
0
{
1861
  // deterministic behavior: RC update on next finished frame in sliding window coding order,
1862
  //                         evaluate only one finished frame at front of the list that makes place for the next frame
1863
  //                         whose parameters can be set using the finished frame bits info
1864
  //
1865
  // non-deterministic behavior: RC update on any finished frame
1866
1867
#if IFP_RC_DETERMINISTIC
1868
  if( m_rcUpdateList.front()->isEncoded && m_rcUpdateList.back()->encRCPic && ( m_rcUpdateList.front()->isFlush || m_rcUpdateList.size() == m_pcEncCfg->m_maxParallelFrames ) )
1869
  {   
1870
#endif
1871
0
    for( auto it = m_rcUpdateList.begin(); it != m_rcUpdateList.end(); )
1872
0
    {
1873
0
      auto pic = *it;
1874
0
      if( pic->isEncoded )
1875
0
      {
1876
0
        pic->actualTotalBits = pic->sliceDataStreams[0].getNumberOfWrittenBits();
1877
0
        pic->refCounter--;
1878
0
        m_pcRateCtrl->updateAfterPicEncRC( pic );
1879
0
        it = m_rcUpdateList.erase( it );
1880
0
      }
1881
0
      else
1882
0
      {
1883
0
        ++it;
1884
0
      }
1885
#if IFP_RC_DETERMINISTIC
1886
      // in deterministic case, only one frame is allowed to update the RC
1887
      break;
1888
#endif
1889
0
    }
1890
#if IFP_RC_DETERMINISTIC
1891
  }
1892
#endif
1893
0
}
1894
1895
inline bool getReorderedProcList( std::list<Picture*>& inputList, std::list<Picture*>& procList, const int maxSize, bool isIFP, bool restrictToGOP )
1896
0
{
1897
  // deliver frames of the same TID (temporal layer) and from the same GOP
1898
0
  const int procTL = inputList.size() ? inputList.front()->TLayer             : -1;
1899
0
  const int gopNum = inputList.size() ? inputList.front()->gopEntry->m_gopNum : -1;
1900
0
  bool added = false;
1901
0
  for( auto it = inputList.begin(); it != inputList.end(); )
1902
0
  {
1903
0
    auto pic = *it;
1904
0
    if( ( pic->gopEntry->m_gopNum == gopNum || !restrictToGOP )
1905
0
        && pic->TLayer == procTL
1906
0
        && ( isIFP ? pic->slices[ 0 ]->checkAllRefPicsAccessible(): pic->slices[ 0 ]->checkAllRefPicsReconstructed() ) )
1907
0
    {
1908
0
      pic->isInProcessList = true;
1909
0
      procList.push_back  ( pic );
1910
0
      it = inputList.erase( it );
1911
0
      added = true;
1912
0
    }
1913
0
    else
1914
0
    {
1915
0
      ++it;
1916
0
    }
1917
0
    if( (int)procList.size() >= maxSize )
1918
0
      break;
1919
0
  }
1920
0
  return added;
1921
0
}
1922
1923
inline void getProcListForOneGOP( std::list<Picture*>& inputList, std::list<Picture*>& procList )
1924
0
{
1925
  // provide frames of the same GOP
1926
0
  const int gopNum = inputList.size() ? inputList.front()->gopEntry->m_gopNum : -1;
1927
0
  for( auto it = inputList.begin(); it != inputList.end(); )
1928
0
  {
1929
0
    auto pic = *it;
1930
0
    if( pic->gopEntry->m_gopNum == gopNum )
1931
0
    {
1932
0
      procList.push_back  ( pic );
1933
0
      it = inputList.erase( it );
1934
0
    }
1935
0
    else
1936
0
    {
1937
0
      ++it;
1938
0
    }
1939
0
  }
1940
0
}
1941
1942
void EncGOP::xGetProcessingLists( std::list<Picture*>& procList, std::list<Picture*>& rcUpdateList, const bool lockStepMode )
1943
1.43k
{
1944
  // in lockstep mode, frames are reordered in a specific processing order
1945
1.43k
  if( lockStepMode )
1946
0
  {
1947
0
    if( m_pcEncCfg->m_ifpLines )
1948
0
    {
1949
      // prepare reordered list
1950
      // we need an additional reordering list to ensure causality of the coding order (ref.pics) on irregular GOP structures
1951
      // in the first step, the reordered list is filled
1952
      // in the second, the frames from reordered list are moved to proc. list up to required update-list size
1953
0
      const int maxUpdateListSize = m_pcEncCfg->m_maxParallelFrames;
1954
0
      if( rcUpdateList.size() < maxUpdateListSize && ( !m_gopEncListInput.empty() || !m_rcInputReorderList.empty()))
1955
0
      {
1956
0
        while( rcUpdateList.size() < maxUpdateListSize && ( !m_gopEncListInput.empty() || !m_rcInputReorderList.empty()) )
1957
0
        {
1958
0
          if( !m_rcInputReorderList.empty() )
1959
0
          {
1960
0
            auto pic = m_rcInputReorderList.front();
1961
0
            m_rcInputReorderList.pop_front();
1962
0
            pic->refCounter++;
1963
0
            procList.push_back( pic );
1964
0
            rcUpdateList.push_back( pic );
1965
0
          }
1966
0
          else
1967
0
          {
1968
0
            while( m_rcInputReorderList.size() < maxUpdateListSize && !m_gopEncListInput.empty() )
1969
0
            {
1970
0
              getReorderedProcList( m_gopEncListInput, m_rcInputReorderList, maxUpdateListSize, true, true );
1971
0
            }
1972
0
          }
1973
0
        }
1974
0
      }
1975
0
    }
1976
0
    else if( rcUpdateList.empty() )
1977
0
    {
1978
      // retrieve next lockstep chunk from reordered list
1979
0
      const int procTL         = m_gopEncListInput.size() ? m_gopEncListInput.front()->TLayer : -1;
1980
0
      const int minSerialDepth = m_pcEncCfg->m_maxParallelFrames > 2 ? 1 : 2;  // up to this temporal layer encode pictures only in serial mode
1981
0
      const int maxSize        = procTL <= minSerialDepth ? 1 : m_pcEncCfg->m_maxParallelFrames;
1982
0
      getReorderedProcList( m_gopEncListInput, procList, maxSize, false, true );
1983
0
      std::copy( procList.begin(), procList.end(), std::back_inserter(rcUpdateList) );
1984
0
    }
1985
0
  }
1986
1.43k
  else
1987
1.43k
  {
1988
    // regular coding mode (non-RC); the processing list may still hold pictures (fetched on every pass)
1989
1.43k
    const size_t numBefore = procList.size();
1990
    // in case of IFP, using the reordered list brings an additional speedup
1991
1.43k
    if( m_pcEncCfg->m_ifpLines )
1992
0
    {
1993
0
      const size_t inputListSize = m_gopEncListInput.size();
1994
1995
      // in case of GOP parallel processing, we do not put all the frames from the current GOP in proc.list, but top it
1996
      // up to MaxParallelFrames pictures on every pass: we want to add frames from the next GOP as soon as possible.
1997
0
      const size_t targetProcListSize = m_pcEncCfg->m_numParallelGOPs ? std::max<size_t>( numBefore, m_pcEncCfg->m_maxParallelFrames )
1998
0
                                                                      : numBefore + inputListSize;
1999
2000
0
      while( !m_gopEncListInput.empty() && procList.size() < targetProcListSize )
2001
0
      {
2002
0
        if( !getReorderedProcList( m_gopEncListInput, procList, (int)procList.size() + m_pcEncCfg->m_maxParallelFrames, true, !m_pcEncCfg->m_numParallelGOPs ) )
2003
0
          break;
2004
0
      }
2005
      // nothing to process and nothing added: no picture can ever start (pictures still in the list may just have to
2006
      // start first, so that their dependents become accessible)
2007
0
      if( m_gopEncListInput.size() == inputListSize && numBefore == 0 )
2008
0
        msg.log( VVENC_WARNING, "Processing list derivation: attempting to run in a deadlock" );
2009
0
    }
2010
1.43k
    else
2011
1.43k
    {
2012
1.43k
      if( m_pcEncCfg->m_rateCap ) // TODO helmrich: what about || *->m_GOPQPA?
2013
0
      {
2014
        // ensure that procList contains only pictures from one GOP
2015
0
        getProcListForOneGOP( m_gopEncListInput, procList );
2016
0
      }
2017
1.43k
      else
2018
1.43k
      {
2019
        // just pass the input list to processing list
2020
1.43k
        procList.splice( procList.end(), m_gopEncListInput );
2021
1.43k
        m_gopEncListInput.clear();
2022
1.43k
      }
2023
1.43k
    }
2024
1.43k
    if( m_pcEncCfg->m_RCTargetBitrate > 0 || m_pcEncCfg->m_rateCap )
2025
0
    {
2026
      // update-list is read only by RC and RateCapping here; with IFP alone its entries, taken in processing order but
2027
      // released in output order, stop being removed after the first pictures and the list grows for the whole encode.
2028
      // It takes the newly added pictures.
2029
0
      std::copy( std::next( procList.begin(), static_cast<std::ptrdiff_t>( numBefore ) ), procList.end(), std::back_inserter( rcUpdateList ) );
2030
0
    }
2031
1.43k
  }
2032
1.43k
  CHECK( ! rcUpdateList.empty() && m_gopEncListOutput.empty(), "first picture in RC update and in output list have to be the same" );
2033
1.43k
}
2034
2035
void EncGOP::xUpdateRateCap()
2036
0
{
2037
0
  for( auto it = m_rcUpdateList.begin(); it != m_rcUpdateList.end(); )
2038
0
  {
2039
0
    auto pic = *it;
2040
0
    if( pic->isEncoded )
2041
0
    {
2042
0
      const unsigned uibits = pic->sliceDataStreams[0].getNumberOfWrittenBits();
2043
2044
0
      if( !pic->gopEntry->m_isStartOfIntra && pic->gopEntry->m_scType == SCT_NONE )
2045
0
      {
2046
0
        xUpdateRateCapBits( pic, uibits );
2047
0
      }
2048
0
      else if( pic->gopEntry->m_isStartOfIntra && pic->gopEntry->m_gopNum == 0 && pic->poc < m_pcEncCfg->m_GOPSize && m_rcap.accumTargetBits * (uint32_t) m_pcEncCfg->m_GOPSize < uibits )
2049
0
      {
2050
0
        m_rcap.accumActualBits += uibits - m_rcap.accumTargetBits * (uint32_t) m_pcEncCfg->m_GOPSize; // capped CQF: compensate for overspending in first I-frame
2051
0
      }
2052
2053
0
      it = m_rcUpdateList.erase( it );
2054
0
    }
2055
0
    else
2056
0
    {
2057
0
      ++it;
2058
0
    }
2059
0
  }
2060
0
}
2061
2062
void EncGOP::xUpdateRateCapBits( const Picture* pic, const uint32_t uibits )
2063
0
{
2064
  // try to adjust the rate for the first GOP on the scene-cut (or start of the sequence)
2065
0
  if( pic->gopEntry->m_isStartOfGop )
2066
0
  {
2067
0
    m_rcap.gopAdaptedQPAdj = 0;
2068
0
  }
2069
0
  else if( pic->isSceneCutCheckAdjQP )
2070
0
  {
2071
0
    CHECK( uibits == 0 || m_rcap.accumTargetBits == 0, "Not expected" );
2072
0
    const double f = std::min (1.5, pow (uibits / double (3u * m_rcap.accumTargetBits), 0.25));
2073
0
    if( f > 1.0 )
2074
0
    {
2075
0
      const Slice* slice = pic->slices[0];
2076
0
      const double d = (105.0 / 128.0) * sqrt( (double)std::max( 1, slice->sliceQp ) ) * log( f ) / log( 2.0 );
2077
0
      m_rcap.gopAdaptedQPAdj = int(d + 0.5);
2078
0
      m_rcap.nonRateCapEstim = f;
2079
      //uibits = 3u * m_rcap.AccumTargetBits; // can be used to avoid overweighting of TL1 picture
2080
0
    }
2081
0
  }
2082
0
  m_rcap.accumActualBits += unsigned (0.5 + uibits * m_rcap.nonRateCapEstim);
2083
0
}
2084
2085
void EncGOP::xUpdateVAStartOfLastGop( Picture& keyPic ) const
2086
1.43k
{
2087
1.43k
  keyPic.picVA = keyPic.m_picShared->m_picVA;
2088
1.43k
}
2089
2090
void EncGOP::xInitGopQpCascade( Picture& keyPic, PicList::const_iterator picListBegin, const PicList& picList )
2091
1.43k
{
2092
1.43k
  CHECK( !keyPic.gopEntry->m_isStartOfGop, "Expecting key picture as start of GOP")
2093
1.43k
  uint32_t gopMotEstCount = 0, gopMotEstError = 0;
2094
1.43k
  const double resRatio4K = double (m_pcEncCfg->m_SourceWidth * m_pcEncCfg->m_SourceHeight) / (3840.0 * 2160.0);
2095
1.43k
  const bool isHighRes    = (std::min (m_pcEncCfg->m_SourceWidth, m_pcEncCfg->m_SourceHeight) > 1280);
2096
1.43k
  const int gopNum        = keyPic.gopEntry->m_gopNum;
2097
1.43k
  const bool keyPicIsIdrNLP      = xGetNalUnitType(keyPic.gopEntry) == VVENC_NAL_UNIT_CODED_SLICE_IDR_N_LP;
2098
1.43k
  PicList::const_iterator picItr = picListBegin;
2099
1.43k
  const bool nextKeyPicAfterIDR  = keyPicIsIdrNLP && (++picItr != picList.end()) && (*picItr)->gopEntry->m_isStartOfGop;
2100
2101
1.43k
  int dQP = 0;
2102
1.43k
  double qpStart = 24.0;
2103
1.43k
  unsigned num = 0, sum = 0;
2104
1.43k
  unsigned nSC = 0, sSC = 0;
2105
1.43k
  uint8_t gopMinNoiseLevels[QPA_MAX_NOISE_LEVELS];
2106
2107
1.43k
  std::fill_n (gopMinNoiseLevels, QPA_MAX_NOISE_LEVELS, 255u);
2108
2109
  // get spatial activity of current and previous TL0 pic
2110
1.43k
  int spVisActTL0[2] = { 0, 0 };
2111
1.43k
  for( auto ch : { CH_L, CH_C } )
2112
2.86k
  {
2113
2.86k
    const int count = ( keyPic.picVA.spatAct[ ch ] > 0 && keyPic.picVA.prevTL0spatAct[ ch ] > 0 ) ? 2 : 1;
2114
2.86k
    spVisActTL0[ch] = ( keyPic.picVA.spatAct[ ch ] + keyPic.picVA.prevTL0spatAct[ ch ] + ( count >> 1 ) ) / count;
2115
2.86k
  }
2116
2117
2.86k
  for (auto picItr = picListBegin; picItr != picList.end(); ++picItr)
2118
1.43k
  {
2119
1.43k
    auto pic = (*picItr);
2120
1.43k
    if( pic->gopEntry->m_gopNum == gopNum )
2121
1.43k
    {
2122
1.43k
      if( pic->m_picShared->m_picMotEstError > 0 )
2123
0
      {
2124
0
        CHECK( pic->isInitDone, "try to modify GOP qp of picture, which has already been initialized" );
2125
        // summarize motion errors of all MCTF filtered pictures in GOP
2126
0
        gopMotEstCount++;
2127
0
        gopMotEstError += pic->m_picShared->m_picMotEstError;
2128
        // go through ranges, search per-range minimum in GOP
2129
0
        for (int i = 0; i < QPA_MAX_NOISE_LEVELS; i++)
2130
0
        {
2131
0
          gopMinNoiseLevels[i] = std::min<uint8_t> (gopMinNoiseLevels[i], pic->m_picShared->m_minNoiseLevels[i]);
2132
0
        }
2133
0
      }
2134
1.43k
      nSC++;
2135
1.43k
      sSC += (pic->isSccStrong ? 1 : 0) + (pic->isSccWeak ? 1 : 0);
2136
2137
1.43k
      if( pic == &keyPic && nextKeyPicAfterIDR ) // consider a virtual GOP containing only one IDR pic
2138
0
        break;
2139
1.43k
    }
2140
1.43k
  }
2141
2142
1.43k
  gopMotEstError = (gopMotEstError + (gopMotEstCount >> 1)) / std::max (1u, gopMotEstCount);
2143
2144
12.8k
  for (int i = 0; i < QPA_MAX_NOISE_LEVELS; i++) // go through ranges again, find overall min-average in GOP
2145
11.4k
  {
2146
11.4k
    if (gopMinNoiseLevels[i] < 255)
2147
0
    {
2148
0
      num++;
2149
0
      sum += gopMinNoiseLevels[i];
2150
0
    }
2151
11.4k
  }
2152
2153
  // force 2nd-order filter
2154
1.43k
  const bool f2O = (m_pcEncCfg->m_usePerceptQPA) && (sSC >= (nSC >> 1)) && (sum < 18 * num); // low-noise SC
2155
  
2156
  // adapt GOP's QP offsets
2157
1.43k
  if (num > 0 && sum > 0)
2158
0
  {
2159
0
    qpStart += 0.5 * (6.0 * log ((double) sum / (double) num) / log (2.0) - 1.0 - 24.0); // see RateCtrl.cpp
2160
0
    if (m_pcEncCfg->m_GOPQPA)
2161
0
    {
2162
0
      if (((qpStart > 29) && (spVisActTL0[CH_L] > 600)) ||
2163
0
          ((qpStart > 27) && (spVisActTL0[CH_L] > 850)) || (spVisActTL0[CH_L] > 1300))
2164
0
      {
2165
0
        dQP += 1;
2166
0
      }
2167
0
      if ((qpStart < 24) && (spVisActTL0[CH_L] < 400))
2168
0
      {
2169
0
        dQP -= 1;
2170
0
      }
2171
0
    }
2172
0
  }
2173
1.43k
  qpStart += log (resRatio4K) / log (2.0); // ICIP23 paper
2174
2175
1.43k
  if (keyPic.gopEntry->m_scType == SCT_TL0_SCENE_CUT)
2176
0
  {
2177
0
    m_rcap.reset();
2178
0
  }
2179
2180
  // derive rate capping parameters
2181
1.43k
  if (m_pcEncCfg->m_rateCap)
2182
0
  {
2183
0
    const int bDepth = m_pcEncCfg->m_internalBitDepth[CH_L];
2184
0
    const int intraP = Clip3(m_pcEncCfg->m_GOPSize, 4 * VVENC_MAX_GOP, m_pcEncCfg->m_IntraPeriod);
2185
0
    const int visAct = std::max(uint16_t(spVisActTL0[CH_L] >> (12 - bDepth)), keyPic.picVA.visAct); // when vaY=0
2186
0
    const double apa = sqrt((m_pcEncCfg->m_internalUsePerceptQPATempFiltISlice ? 32.0 : 16.0) * double(1 << (2 * bDepth - 10)) / sqrt(resRatio4K)); // average picture activity
2187
0
    const int auxOff = (m_pcEncCfg->hasBlockQpOffsets() && !keyPic.m_picShared->m_ctuBimQpOffset.empty() ? keyPic.m_picShared->m_picAuxQpOffset : 0) + dQP;
2188
0
    const int iFrmQP = std::min(MAX_QP, m_pcEncCfg->m_QP + m_pcEncCfg->m_intraQPOffset + auxOff + int(floor(m_pcEncCfg->m_QPFraction + 3.0 * log(visAct / apa) / log(2.0) + 0.5)));
2189
0
    const int qp32BC = int(16384.0 + 7.21875 * pow((double)spVisActTL0[CH_L], 4.0 / 3.0) + 1.46875 * pow((double)spVisActTL0[CH_C], 4.0 / 3.0)) * (isHighRes ? 96 : 24); // TODO hlm
2190
0
    const int iFrmBC = int(0.5 + qp32BC * pow(2.0, (32.0 - iFrmQP) * 11.0 / 64.0) * pow(resRatio4K, 2.0 / 3.0)); // * HD tuning
2191
0
    const int  shift = (gopMotEstError < 32 ? 5 - (gopMotEstError >> 4) : 3);
2192
0
    if (keyPic.m_picShared->m_picMotEstError >= 256) gopMotEstError >>= 2; else // avoid 2 much capping at cuts
2193
0
    if (gopMotEstError >= 120) /*TODO tune this*/ gopMotEstError >>= 1;
2194
0
    const int bFrmBC = int((4.0 * iFrmBC * (intraP - 1)) / sqrt((double)std::max(spVisActTL0[CH_L], spVisActTL0[CH_C])) * std::max(int(gopMotEstError * gopMotEstError) >> (bDepth / 2), (keyPic.picVA.visActTL0 - visAct) >> shift) * pow(2.0, -1.0 * bDepth));
2195
0
    const int meanGopSizeInIntraP = intraP / ((intraP + m_pcEncCfg->m_GOPSize - 1) / m_pcEncCfg->m_GOPSize);
2196
2197
0
    const double eps = 1.0 - 1.0 / double(1u << std::min(31u, m_rcap.accumGopCounter));
2198
0
    const double nonKeyPicsFactor = (m_rcap.accumTargetBits == 0) ? 1.0 : pow((double)m_rcap.accumActualBits / ((meanGopSizeInIntraP - 1.0) * m_rcap.accumTargetBits), eps);
2199
0
    const unsigned bFrmBC_final = bFrmBC * nonKeyPicsFactor;
2200
0
    const unsigned targetBits = (unsigned)((bFrmBC + (intraP >> 1)) / (intraP - 1));
2201
0
    m_rcap.accumTargetBits += targetBits;
2202
0
    if (keyPic.gopEntry->m_isStartOfIntra && keyPic.gopEntry->m_gopNum == 0 && keyPic.poc < m_pcEncCfg->m_GOPSize && m_rcap.accumTargetBits * (int64_t)intraP < iFrmBC)
2203
0
    {
2204
0
      m_rcap.accumTargetBits = (iFrmBC + (intraP >> 1)) / intraP;
2205
0
    }
2206
0
    m_rcap.nonRateCapEstim = 1.0;     // changed in case of capping
2207
0
    m_rcap.gopAdaptedQPAdj = 0;       // changed in first GOP of scene
2208
2209
0
    const int  gopQP = (iFrmQP + MAX_QP + 1) >> 1;
2210
0
    const double fac = double(m_pcEncCfg->m_FrameScale * intraP) / m_pcEncCfg->m_FrameRate;
2211
0
    const double mBC = (m_pcEncCfg->m_RCMaxBitrate > 0 && m_pcEncCfg->m_RCMaxBitrate != INT32_MAX ? m_pcEncCfg->m_RCMaxBitrate * fac : 0.0);
2212
2213
0
    if (mBC > 0.0 && iFrmBC + bFrmBC_final > mBC) // max. I-period bit-count exceeded
2214
0
    {
2215
0
      m_rcap.nonRateCapEstim = double(iFrmBC + bFrmBC_final) / mBC;
2216
0
      const double d = std::max(0, gopQP) + (105.0 / 128.0) * sqrt((double)std::max(1, gopQP)) * log(m_rcap.nonRateCapEstim) / log(2.0);
2217
2218
0
      dQP += Clip3(0, MAX_QP, int(0.5 + d + 0.5 * std::max(0.0, qpStart - d))) - std::max(0, gopQP);
2219
0
    }
2220
0
  }
2221
2222
  // assign dQP to pictures 
2223
2.86k
  for (auto picItr = picListBegin; picItr != picList.end(); ++picItr)
2224
1.43k
  {
2225
1.43k
    auto pic = (*picItr);
2226
1.43k
    if( pic->gopEntry->m_gopNum == gopNum )
2227
1.43k
    {
2228
1.43k
      pic->gopAdaptedQP = dQP;
2229
1.43k
      pic->force2ndOrder = f2O;
2230
1.43k
    }
2231
1.43k
    if( pic == &keyPic && nextKeyPicAfterIDR ) // consider a virtual GOP containing only one IDR pic
2232
0
      break;
2233
1.43k
  }
2234
2235
1.43k
  keyPic.gopAdaptedQP = dQP; // TODO: add any additional key-frame offset here
2236
1.43k
  keyPic.force2ndOrder = f2O;
2237
1.43k
  if( m_pcEncCfg->m_disableForce2ndOderFilter )
2238
0
  {
2239
0
    keyPic.force2ndOrder = false;
2240
0
  }
2241
2242
1.43k
  if(m_pcEncCfg->m_rateCap)
2243
0
  {
2244
    // enable QP adjustment after coded Intra in the first GOP or on a scene cut
2245
    // NOTE: on some scene cuts, in case of low motion activity, targetBits equals zero (QPA)
2246
0
    if(m_rcap.accumGopCounter == 0 && m_rcap.accumTargetBits > 0 && !nextKeyPicAfterIDR)
2247
0
    {
2248
0
      for(auto picItr = picListBegin; picItr != picList.end(); ++picItr)
2249
0
      {
2250
0
        auto pic = (*picItr);
2251
        // just on the next picture in decoding order after start of GOP
2252
0
        if(pic->gopEntry->m_gopNum == gopNum && !pic->gopEntry->m_isStartOfGop)
2253
0
        {
2254
0
          pic->isSceneCutCheckAdjQP = true;
2255
0
          break;
2256
0
        }
2257
0
      }
2258
0
      for(auto picItr = picListBegin; picItr != picList.end(); ++picItr)
2259
0
      {
2260
0
        auto pic = (*picItr);
2261
0
        if(pic->gopEntry->m_gopNum == gopNum && !pic->gopEntry->m_isStartOfGop && !pic->isSceneCutCheckAdjQP)
2262
0
        {
2263
0
          pic->isSceneCutGOP = true;
2264
0
        }
2265
0
      }
2266
0
    }
2267
0
    m_rcap.accumGopCounter++;
2268
0
  }
2269
1.43k
}
2270
2271
void EncGOP::xInitFirstSlice( Picture& pic, const PicList& picList, bool isEncodeLtRef )
2272
1.43k
{
2273
1.43k
  memset( pic.cs->alfAps, 0, sizeof(pic.cs->alfAps));
2274
2275
1.43k
  const int curPoc          = pic.getPOC();
2276
1.43k
  Slice* slice              = pic.allocateNewSlice();
2277
1.43k
  pic.cs->picHeader         = new PicHeader;
2278
1.43k
  const SPS& sps            = *(slice->sps);
2279
1.43k
  vvencNalUnitType naluType = xGetNalUnitType( pic.gopEntry );
2280
1.43k
  const GOPEntry& gopEntry  = *pic.gopEntry;
2281
1.43k
  SliceType sliceType       = gopEntry.m_sliceType == 'B' ? VVENC_B_SLICE : ( gopEntry.m_sliceType == 'P' ? VVENC_P_SLICE : VVENC_I_SLICE );
2282
2283
  // correct slice type at start of intra period
2284
1.43k
  if( gopEntry.m_isStartOfIntra )
2285
1.43k
  {
2286
1.43k
    sliceType = VVENC_I_SLICE;
2287
1.43k
  }
2288
2289
  // update IRAP
2290
1.43k
  if( naluType == VVENC_NAL_UNIT_CODED_SLICE_IDR_W_RADL
2291
0
      || naluType == VVENC_NAL_UNIT_CODED_SLICE_IDR_N_LP
2292
0
      || naluType == VVENC_NAL_UNIT_CODED_SLICE_CRA )
2293
1.43k
  {
2294
1.43k
    m_associatedIRAPType = naluType;
2295
1.43k
    m_associatedIRAPPOC  = curPoc;
2296
1.43k
  }
2297
2298
  // update last IDR
2299
1.43k
  if( naluType == VVENC_NAL_UNIT_CODED_SLICE_IDR_W_RADL || naluType == VVENC_NAL_UNIT_CODED_SLICE_IDR_N_LP )
2300
1.43k
  {
2301
1.43k
    m_lastIDR = curPoc;
2302
1.43k
  }
2303
2304
1.43k
  slice->picHeader                 = pic.cs->picHeader;
2305
1.43k
  slice->independentSliceIdx       = 0;
2306
1.43k
  slice->sliceType                 = sliceType;
2307
1.43k
  slice->poc                       = curPoc;
2308
1.43k
  slice->TLayer                    = gopEntry.m_temporalId;
2309
1.43k
  slice->nalUnitType               = naluType;
2310
1.43k
  slice->lastIDR                   = m_lastIDR;
2311
1.43k
  slice->depQuantEnabled           = m_pcEncCfg->m_DepQuantEnabled;
2312
1.43k
  slice->signDataHidingEnabled     = m_pcEncCfg->m_SignDataHidingEnabled;
2313
2314
1.43k
  slice->picHeader->splitConsOverride = false;
2315
5.72k
  for( int i = 0; i < 3; i++ )
2316
4.29k
  {
2317
4.29k
    slice->picHeader->minQTSize[i]   = sps.minQTSize[i];
2318
4.29k
    slice->picHeader->maxMTTDepth[i] = sps.maxMTTDepth[i];
2319
4.29k
    slice->picHeader->maxBTSize[i]   = sps.maxBTSize[i];
2320
4.29k
    slice->picHeader->maxTTSize[i]   = sps.maxTTSize[i];
2321
4.29k
    if( ( i == 1 ) && ( m_pcEncCfg->m_maxMTTDepth >= 10 ) )
2322
0
    {
2323
0
      slice->picHeader->maxMTTDepth[i]    = int( m_pcEncCfg->m_maxMTTDepth / pow( 10, sps.maxTLayers - slice->TLayer - 1 ) ) % 10;
2324
0
      slice->picHeader->splitConsOverride = slice->picHeader->maxMTTDepth[i] != sps.maxMTTDepth[i];
2325
0
    }
2326
4.29k
  }
2327
2328
1.43k
  slice->associatedIRAPType        = m_associatedIRAPType;
2329
1.43k
  slice->associatedIRAP            = m_associatedIRAPPOC;
2330
1.43k
  CHECK( MAX_REF_PICS <= gopEntry.m_numRefPicsActive[ 0 ], "number of ref pics out of supported range" );
2331
1.43k
  CHECK( MAX_REF_PICS <= gopEntry.m_numRefPicsActive[ 1 ], "number of ref pics out of supported range" );
2332
1.43k
  slice->numRefIdx[REF_PIC_LIST_0] = gopEntry.m_numRefPicsActive[ 0 ];
2333
1.43k
  slice->numRefIdx[REF_PIC_LIST_1] = gopEntry.m_numRefPicsActive[ 1 ];
2334
1.43k
  slice->setDecodingRefreshMarking ( m_pocCRA, m_bRefreshPending, picList );
2335
1.43k
  slice->setDefaultClpRng          ( sps );
2336
2337
  // reference list
2338
1.43k
  xSelectReferencePictureList( slice );
2339
1.43k
  int missingPoc;
2340
1.43k
  int ipc = ( m_pcEncCfg->m_DecodingRefreshType == VVENC_DRT_IDR_NO_RADL ) ? m_pcEncCfg->m_IntraPeriod : 0;
2341
1.43k
  if ( slice->isRplPicMissing( picList, REF_PIC_LIST_0, missingPoc, ipc ) || slice->isRplPicMissing( picList, REF_PIC_LIST_1, missingPoc, ipc ) )
2342
0
  {
2343
0
    slice->createExplicitReferencePictureSetFromReference( picList, slice->rpl[0], slice->rpl[1], ipc );
2344
0
  }
2345
1.43k
  slice->applyReferencePictureListBasedMarking( picList, slice->rpl[0], slice->rpl[1], 0, *slice->pps, m_pcEncCfg->m_numThreads == 0 );
2346
2347
  // nalu type refinement
2348
1.43k
  if ( xIsSliceTemporalSwitchingPoint( slice, picList ) )
2349
0
  {
2350
0
    naluType = VVENC_NAL_UNIT_CODED_SLICE_STSA;
2351
0
    slice->nalUnitType = naluType;
2352
0
  }
2353
2354
1.43k
  const int maxTLayer  = m_pcEncCfg->m_picReordering && m_pcEncCfg->m_GOPSize > 1 ? vvenc::ceilLog2( m_pcEncCfg->m_GOPSize ) : 0;
2355
1.43k
  const int numRefCode = pic.useNumRefs ? m_pcEncCfg->m_numRefPicsSCC : m_pcEncCfg->m_numRefPics;
2356
1.43k
  const int tLayer     = slice->TLayer;
2357
1.43k
  const int numRefs    = numRefCode < 10 ? numRefCode : ( int( numRefCode / pow( 10, maxTLayer - tLayer ) ) % 10 );
2358
2359
  // reference list
2360
1.43k
  slice->numRefIdx[REF_PIC_LIST_0] = sliceType == VVENC_I_SLICE ? 0 : ( numRefs ? std::min( numRefs, slice->rpl[0]->numberOfActivePictures ) : slice->rpl[0]->numberOfActivePictures );
2361
1.43k
  slice->numRefIdx[REF_PIC_LIST_1] = sliceType != VVENC_B_SLICE ? 0 : ( numRefs ? std::min( numRefs, slice->rpl[1]->numberOfActivePictures ) : slice->rpl[1]->numberOfActivePictures );
2362
1.43k
  slice->constructRefPicList  ( picList, false, m_pcEncCfg->m_numThreads == 0 );
2363
2364
1.43k
  slice->setRefPOCList        ();
2365
1.43k
  slice->setList1IdxToList0Idx();
2366
1.43k
  slice->updateRefPicCounter  ( +1 );
2367
1.43k
  slice->setSMVDParam();
2368
2369
  // slice type refinement
2370
1.43k
  if ( sliceType == VVENC_B_SLICE && slice->numRefIdx[ REF_PIC_LIST_1 ] == 0 )
2371
0
  {
2372
0
    sliceType = VVENC_P_SLICE;
2373
0
    slice->sliceType = sliceType;
2374
0
  }
2375
2376
1.43k
  slice->picHeader->gdrPic      = false;
2377
1.43k
  slice->picHeader->disBdofFlag = false;
2378
1.43k
  slice->picHeader->disDmvrFlag = false;
2379
1.43k
  slice->picHeader->disProfFlag = false;
2380
2381
1.43k
  slice->picHeader->gdrOrIrapPic = slice->picHeader->gdrPic || slice->isIRAP();
2382
1.43k
  slice->picHeader->picInterSliceAllowed = sliceType != VVENC_I_SLICE;
2383
1.43k
  slice->picHeader->picIntraSliceAllowed = sliceType == VVENC_I_SLICE;
2384
2385
  // the slices' deblocking control, as in VTM: a slice is deblocked as the PPS says (a decoder infers
2386
  // sh_deblocking_filter_disabled_flag from the PPS when the slice does not override it), and a GOP entry's offsets
2387
  // apply only when the PPS lets slices override its parameters (LoopFilterOffsetInPPS 0) and deblocking is enabled
2388
1.43k
  slice->deblockingFilterDisable  = slice->pps->deblockingFilterDisabled;
2389
1.43k
  slice->deblockingFilterOverride = slice->pps->deblockingFilterOverrideEnabled && !slice->pps->deblockingFilterDisabled
2390
0
                                    && sliceType != VVENC_I_SLICE && (gopEntry.m_betaOffsetDiv2 || gopEntry.m_tcOffsetDiv2);
2391
2392
  // only the highest DeblockLastTLayers temporal layers are deblocked; the signed tLayer is compared, since without
2393
  // temporal layers m_maxTLayer - m_deblockLastTLayers is negative and no layer is at or below it (the unsigned
2394
  // slice->TLayer would compare it as a huge value)
2395
1.43k
  if( m_pcEncCfg->m_deblockLastTLayers > 0 && tLayer <= m_pcEncCfg->m_maxTLayer - m_pcEncCfg->m_deblockLastTLayers )
2396
0
  {
2397
0
    slice->deblockingFilterOverride = true;
2398
0
    slice->deblockingFilterDisable  = true;
2399
0
  }
2400
2401
1.43k
  if( slice->deblockingFilterOverride )
2402
0
  {
2403
0
    for( int comp = 0; comp < MAX_NUM_COMP; comp++)
2404
0
    {
2405
      //TODO: gopEntry.m_tcOffsetDiv2 and gopEntry.m_betaOffsetDiv2 are set with the luma value also for the chroma components (currently not used or all values are equal)
2406
0
      slice->deblockingFilterTcOffsetDiv2[comp]    = slice->picHeader->deblockingFilterTcOffsetDiv2[comp]   = gopEntry.m_tcOffsetDiv2   + m_pcEncCfg->m_loopFilterTcOffsetDiv2[comp];
2407
0
      slice->deblockingFilterBetaOffsetDiv2[comp]  = slice->picHeader->deblockingFilterBetaOffsetDiv2[comp] = gopEntry.m_betaOffsetDiv2 +   m_pcEncCfg->m_loopFilterBetaOffsetDiv2[comp];
2408
0
    }
2409
0
  }
2410
1.43k
  else
2411
1.43k
  {
2412
5.72k
    for( int comp = 0; comp < MAX_NUM_COMP; comp++)
2413
4.29k
    {
2414
4.29k
      slice->deblockingFilterTcOffsetDiv2[comp]    = slice->picHeader->deblockingFilterTcOffsetDiv2[comp]   = slice->pps->deblockingFilterTcOffsetDiv2[comp];
2415
4.29k
      slice->deblockingFilterBetaOffsetDiv2[comp]  = slice->picHeader->deblockingFilterBetaOffsetDiv2[comp] = slice->pps->deblockingFilterBetaOffsetDiv2[comp];
2416
4.29k
    }
2417
1.43k
  }
2418
2419
1.43k
  if (slice->pps->useDQP)
2420
1.43k
  {
2421
1.43k
    const uint32_t cuLumaQpSubdiv = (m_pcEncCfg->m_cuQpDeltaSubdiv > 0 ? (uint32_t) m_pcEncCfg->m_cuQpDeltaSubdiv : 0);
2422
2423
1.43k
    slice->picHeader->cuQpDeltaSubdivInter = m_pcEncCfg->m_usePerceptQPA ? 0 : cuLumaQpSubdiv;
2424
1.43k
    slice->picHeader->cuQpDeltaSubdivIntra = cuLumaQpSubdiv;
2425
1.43k
  }
2426
1.43k
  if( slice->pps->chromaQpOffsetListLen > 0)
2427
0
  {
2428
0
    const uint32_t cuChromaQpSubdiv = (m_pcEncCfg->m_cuChromaQpOffsetSubdiv > 0 ? (uint32_t) m_pcEncCfg->m_cuChromaQpOffsetSubdiv : 0);
2429
2430
0
    slice->picHeader->cuChromaQpOffsetSubdivInter = m_pcEncCfg->m_usePerceptQPA ? 0 : cuChromaQpSubdiv;
2431
0
    slice->picHeader->cuChromaQpOffsetSubdivIntra = cuChromaQpSubdiv;
2432
0
  }
2433
2434
1.43k
  slice->picHeader->ppsId = slice->pps->ppsId;
2435
1.43k
  slice->picHeader->spsId = slice->sps->spsId;
2436
2437
1.43k
  pic.cs->picHeader->pic = &pic;
2438
1.43k
  xInitSliceTMVPFlag ( pic.cs->picHeader, slice );
2439
1.43k
  xInitSliceMvdL1Zero( pic.cs->picHeader, slice );
2440
1.43k
  slice->picHeader->maxNumAffineMergeCand = sps.Affine ? sps.maxNumAffineMergeCand : ( sps.SbtMvp && slice->picHeader->enableTMVP ? 1 : 0 );
2441
2442
1.43k
  if( slice->nalUnitType == VVENC_NAL_UNIT_CODED_SLICE_RASL && m_pcEncCfg->m_rprRASLtoolSwitch )
2443
0
  {
2444
0
    slice->lmChromaCheckDisable = true;
2445
0
    pic.cs->picHeader->disDmvrFlag = true;
2446
0
    xUpdateRPRtmvp( pic.cs->picHeader, slice );
2447
0
  }
2448
2449
  // update RAS
2450
1.43k
  xUpdateRasInit( slice );
2451
2452
1.43k
  if( m_pcEncCfg->m_useAMaxBT )
2453
0
  {
2454
0
    m_BlkStat.setSliceMaxBT( *slice );
2455
0
  }
2456
2457
1.43k
  {
2458
1.43k
    bool identicalToSPS=true;
2459
1.43k
    const SPS* sps =slice->sps;
2460
1.43k
    PicHeader* picHeader = slice->picHeader;
2461
1.43k
    if (picHeader->picInterSliceAllowed)
2462
0
    {
2463
0
      identicalToSPS = (picHeader->minQTSize[1] == sps->minQTSize[1] &&
2464
0
                        picHeader->maxMTTDepth[1] == sps->maxMTTDepth[1] &&
2465
0
                        picHeader->maxBTSize[1] == sps->maxBTSize[1] &&
2466
0
                        picHeader->maxTTSize[1] == sps->maxTTSize[1] );
2467
0
    }
2468
2469
1.43k
    if (identicalToSPS && picHeader->picIntraSliceAllowed)
2470
1.43k
    {
2471
1.43k
      identicalToSPS = (picHeader->minQTSize[0] == sps->minQTSize[0] &&
2472
1.43k
                        picHeader->maxMTTDepth[0] == sps->maxMTTDepth[0] &&
2473
1.43k
                        picHeader->maxBTSize[0] == sps->maxBTSize[0] &&
2474
1.43k
                        picHeader->maxTTSize[0] == sps->maxTTSize[0] );
2475
1.43k
    }
2476
2477
1.43k
    if (identicalToSPS && sps->dualITree)
2478
1.43k
    {
2479
1.43k
      identicalToSPS = (picHeader->minQTSize[2] == sps->minQTSize[2] &&
2480
1.43k
                        picHeader->maxMTTDepth[2] == sps->maxMTTDepth[2] &&
2481
1.43k
                        picHeader->maxBTSize[2] == sps->maxBTSize[2] &&
2482
1.43k
                        picHeader->maxTTSize[2] == sps->maxTTSize[2] );
2483
1.43k
    }
2484
2485
1.43k
    if (identicalToSPS)
2486
1.43k
    {
2487
1.43k
      picHeader->splitConsOverride = false;
2488
1.43k
    }
2489
2490
1.43k
  }
2491
2492
1.43k
  CHECK( slice->TLayer != 0 && slice->sliceType == VVENC_I_SLICE, "Unspecified error" );
2493
2494
1.43k
  pic.cs->slice = slice;
2495
1.43k
  pic.isReferenced = true;
2496
2497
1.43k
  pic.picApsMap.clearActive();
2498
1.43k
  pic.picApsMap.setApsIdStart( ALF_CTB_MAX_NUM_APS );
2499
12.8k
  for ( int i = 0; i < ALF_CTB_MAX_NUM_APS; i++ )
2500
11.4k
  {
2501
11.4k
    const int apsMapIdx = ( i << NUM_APS_TYPE_LEN ) + ALF_APS;
2502
11.4k
    APS* alfAPS = pic.picApsMap.getPS( apsMapIdx );
2503
11.4k
    if ( alfAPS )
2504
0
    {
2505
0
      alfAPS->apsId      = MAX_UINT;
2506
0
      alfAPS->temporalId = MAX_INT;
2507
0
      alfAPS->poc        = MAX_INT;
2508
0
      pic.picApsMap.clearChangedFlag( apsMapIdx );
2509
0
      alfAPS->alfParam.reset();
2510
0
      alfAPS->ccAlfParam.reset();
2511
0
    }
2512
11.4k
  }
2513
1.43k
  CHECK( slice->enableDRAPSEI && m_pcEncCfg->m_maxParallelFrames, "Dependent Random Access Point is not supported by Frame Parallel Processing" );
2514
2515
1.43k
  pic.isInitDone = true;
2516
1.43k
}
2517
2518
void EncGOP::xInitSliceTMVPFlag( PicHeader* picHeader, const Slice* slice )
2519
1.43k
{
2520
1.43k
  if( m_pcEncCfg->m_TMVPModeId == 2 )
2521
0
  {
2522
0
    const GOPEntry& gopEntry = *(slice->pic->gopEntry);
2523
0
    picHeader->enableTMVP    = ! gopEntry.m_useBckwdOnly;
2524
0
  }
2525
1.43k
  else if( m_pcEncCfg->m_TMVPModeId == 1 )
2526
1.43k
  {
2527
1.43k
    picHeader->enableTMVP = true;
2528
1.43k
  }
2529
0
  else
2530
0
  {
2531
0
    picHeader->enableTMVP = false;
2532
0
  }
2533
2534
  // disable TMVP when current picture is the only ref picture
2535
1.43k
  if( slice->isIRAP() && slice->sps->IBC )
2536
1.43k
  {
2537
1.43k
    picHeader->enableTMVP = false;
2538
1.43k
  }
2539
1.43k
}
2540
2541
void EncGOP::xUpdateRPRtmvp( PicHeader* picHeader, Slice* slice )
2542
0
{
2543
0
  if( slice->sliceType != VVENC_I_SLICE && picHeader->enableTMVP && m_pcEncCfg->m_rprRASLtoolSwitch )
2544
0
  {
2545
0
    int colRefIdxL0 = -1, colRefIdxL1 = -1;
2546
2547
0
    for( int refIdx = 0; refIdx < slice->numRefIdx[REF_PIC_LIST_0]; refIdx++ )
2548
0
    {
2549
0
      if( !( slice->getRefPic( REF_PIC_LIST_0, refIdx )->slices[0]->nalUnitType != VVENC_NAL_UNIT_CODED_SLICE_RASL &&
2550
0
             slice->getRefPic( REF_PIC_LIST_0, refIdx )->poc <= m_pocCRA ) )
2551
0
      {
2552
0
        colRefIdxL0 = refIdx;
2553
0
        break;
2554
0
      }
2555
0
    }
2556
2557
0
    if( slice->sliceType == VVENC_B_SLICE )
2558
0
    {
2559
0
      for( int refIdx = 0; refIdx < slice->numRefIdx[REF_PIC_LIST_1]; refIdx++ )
2560
0
      {
2561
0
        if( !( slice->getRefPic( REF_PIC_LIST_1, refIdx )->slices[0]->nalUnitType != VVENC_NAL_UNIT_CODED_SLICE_RASL &&
2562
0
               slice->getRefPic( REF_PIC_LIST_1, refIdx )->poc <= m_pocCRA ) )
2563
0
        {
2564
0
          colRefIdxL1 = refIdx;
2565
0
          break;
2566
0
        }
2567
0
      }
2568
0
    }
2569
2570
0
    if( colRefIdxL0 >= 0 && colRefIdxL1 >= 0 )
2571
0
    {
2572
0
      const Picture *refPicL0 = slice->getRefPic( REF_PIC_LIST_0, colRefIdxL0 );
2573
0
      const Picture *refPicL1 = slice->getRefPic( REF_PIC_LIST_1, colRefIdxL1 );
2574
2575
0
      CHECK( !refPicL0->slices.size(), "Wrong L0 reference picture" );
2576
0
      CHECK( !refPicL1->slices.size(), "Wrong L1 reference picture" );
2577
2578
0
      const uint32_t uiColFromL0 = refPicL0->slices[0]->sliceQp > refPicL1->slices[0]->sliceQp;
2579
0
      picHeader->picColFromL0 = uiColFromL0;
2580
0
      slice->colFromL0Flag = uiColFromL0;
2581
0
      slice->colRefIdx = uiColFromL0 ? colRefIdxL0 : colRefIdxL1;
2582
0
      picHeader->colRefIdx = uiColFromL0 ? colRefIdxL0 : colRefIdxL1;
2583
0
    }
2584
0
    else if( colRefIdxL0 < 0 && colRefIdxL1 >= 0 )
2585
0
    {
2586
0
      picHeader->picColFromL0 = false;
2587
0
      slice->colFromL0Flag = false;
2588
0
      slice->colRefIdx = colRefIdxL1;
2589
0
      picHeader->colRefIdx = colRefIdxL1;
2590
0
    }
2591
0
    else if( colRefIdxL0 >= 0 && colRefIdxL1 < 0 )
2592
0
    {
2593
0
      picHeader->picColFromL0 = true;
2594
0
      slice->colFromL0Flag = true;
2595
0
      slice->colRefIdx = colRefIdxL0;
2596
0
      picHeader->colRefIdx = colRefIdxL0;
2597
0
    }
2598
0
    else
2599
0
    {
2600
0
      picHeader->enableTMVP = false;
2601
0
    }
2602
0
  }
2603
0
}
2604
2605
void EncGOP::xInitSliceMvdL1Zero( PicHeader* picHeader, const Slice* slice )
2606
1.43k
{
2607
1.43k
  bool bGPBcheck = false;
2608
1.43k
  if ( slice->sliceType == VVENC_B_SLICE)
2609
0
  {
2610
0
    if ( slice->numRefIdx[ 0 ] == slice->numRefIdx[ 1 ] )
2611
0
    {
2612
0
      bGPBcheck = true;
2613
0
      int i;
2614
0
      for ( i=0; i < slice->numRefIdx[ 1 ]; i++ )
2615
0
      {
2616
0
        if ( slice->getRefPOC( RefPicList( 1 ), i ) != slice->getRefPOC( RefPicList( 0 ), i ) )
2617
0
        {
2618
0
          bGPBcheck = false;
2619
0
          break;
2620
0
        }
2621
0
      }
2622
0
    }
2623
0
  }
2624
2625
1.43k
  if ( bGPBcheck )
2626
0
  {
2627
0
    picHeader->mvdL1Zero = true;
2628
0
  }
2629
1.43k
  else
2630
1.43k
  {
2631
1.43k
    picHeader->mvdL1Zero = false;
2632
1.43k
  }
2633
1.43k
}
2634
2635
void EncGOP::xSelectReferencePictureList( Slice* slice ) const
2636
1.43k
{
2637
1.43k
  const GOPEntry& gopEntry = *(slice->pic->gopEntry);
2638
2639
4.29k
  for( int l = 0; l < 2; l++ )
2640
2.86k
  {
2641
2.86k
    slice->rplIdx[ l ] = gopEntry.m_defaultRPLIdx;
2642
2.86k
    if( slice->rplIdx[ l ] >= 0 )
2643
2.86k
    {
2644
2.86k
      slice->rpl[ l ] = &(slice->sps->rplList[ l ][ slice->rplIdx[ l ] ]);
2645
2.86k
    }
2646
0
    else
2647
0
    {
2648
0
      slice->rplLocal[ l ].initFromGopEntry( gopEntry, l );
2649
0
      slice->rpl[ l ] = &slice->rplLocal[ l ];
2650
0
    }
2651
2.86k
  }
2652
1.43k
}
2653
2654
void EncGOP::xWritePicture( Picture& pic, AccessUnitList& au, bool isEncodeLtRef )
2655
1.43k
{
2656
  // first pass temporal down-sampling
2657
1.43k
  if( ( ! m_pcRateCtrl->rcIsFinalPass || m_isPreAnalysis ) && pic.gopEntry->m_skipFirstPass )
2658
0
  {
2659
0
    m_pcRateCtrl->addRCPassStats( pic.cs->slice->poc,
2660
0
        0,                /* qp */
2661
0
        0,                /* lambda */
2662
0
        pic.picVA.visAct,
2663
0
        0,                /* numBits */
2664
0
        0,                /* psnrY */
2665
0
        pic.cs->slice->isIntra(),
2666
0
        pic.cs->slice->TLayer,
2667
0
        pic.gopEntry->m_isStartOfIntra,
2668
0
        pic.gopEntry->m_isStartOfGop,
2669
0
        pic.gopEntry->m_gopNum,
2670
0
        pic.gopEntry->m_scType,
2671
0
        pic.picVA.spatAct[CH_L],
2672
0
        pic.m_picShared->m_picMotEstError,
2673
0
        pic.m_picShared->m_minNoiseLevels );
2674
0
    return;
2675
0
  }
2676
2677
1.43k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "bsfinal", 1 ) );
2678
1.43k
  pic.encTime.startTimer();
2679
2680
1.43k
  au.poc           = pic.poc;
2681
1.43k
  au.temporalLayer = pic.TLayer;
2682
1.43k
  au.refPic        = pic.isReferenced;
2683
1.43k
  au.userData      = pic.userData;
2684
1.43k
  if( ! pic.slices.empty() )
2685
1.43k
  {
2686
1.43k
    au.sliceType = pic.slices[ 0 ]->sliceType;
2687
1.43k
  }
2688
2689
1.43k
  if( pic.ctsValid )
2690
1.43k
  {
2691
1.43k
    const int64_t iDiffFrames = m_numPicsCoded - pic.poc - pic.picsInMissing;
2692
1.43k
    au.cts      = pic.cts;
2693
1.43k
    au.ctsValid = pic.ctsValid;
2694
1.43k
    if ( pic.picOutOffset )
2695
0
    {
2696
0
      m_numPicsOutOffset += pic.picOutOffset;
2697
0
    }
2698
1.43k
    if( m_pcEncCfg->m_TicksPerSecond > 0 )
2699
1.43k
      au.dts      = ( ( iDiffFrames - m_pcEncCfg->m_maxTLayer + m_numPicsOutOffset ) * m_ticksPerFrameMul4 ) / 4 + au.cts;
2700
0
    else
2701
0
      au.dts      = ( ( iDiffFrames - m_pcEncCfg->m_maxTLayer + m_numPicsOutOffset )) + au.cts;
2702
1.43k
    au.dtsValid = pic.ctsValid;
2703
1.43k
  }
2704
2705
1.43k
  pic.actualTotalBits += xWriteParameterSets( pic, au, m_HLSWriter );
2706
1.43k
  xWriteLeadingSEIs( pic, au );
2707
1.43k
  pic.actualTotalBits += xWritePictureSlices( pic, au, m_HLSWriter );
2708
2709
1.43k
  pic.encTime.stopTimer();
2710
2711
1.43k
  std::string digestStr;
2712
1.43k
  xWriteTrailingSEIs( pic, au, digestStr );
2713
1.43k
  xPrintPictureInfo ( pic, au, digestStr, m_pcEncCfg->m_printFrameMSE, isEncodeLtRef );
2714
1.43k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "bsfinal", 0 ) );
2715
1.43k
}
2716
2717
int EncGOP::xWriteParameterSets( Picture& pic, AccessUnitList& accessUnit, HLSWriter& hlsWriter )
2718
1.43k
{
2719
1.43k
  Slice* slice        = pic.slices[0];
2720
1.43k
  const SPS& sps      = *(slice->sps);
2721
1.43k
  const PPS& pps      = *(slice->pps);
2722
1.43k
  int actualTotalBits = 0;
2723
2724
1.43k
  if ( m_bFirstWrite || ( m_pcEncCfg->m_rewriteParamSets && slice->isIRAP() ) )
2725
1.43k
  {
2726
1.43k
    if (slice->sps->vpsId != 0)
2727
0
    {
2728
0
      actualTotalBits += xWriteVPS( accessUnit, pic.vps, hlsWriter );
2729
0
    }
2730
1.43k
    actualTotalBits += xWriteDCI( accessUnit, pic.dci, hlsWriter );
2731
1.43k
    actualTotalBits += xWriteSPS( accessUnit, &sps, hlsWriter );
2732
1.43k
    actualTotalBits += xWritePPS( accessUnit, &pps, &sps, hlsWriter );
2733
1.43k
    m_bFirstWrite = false;
2734
1.43k
  }
2735
2736
1.43k
  bool IrapOrGdrAu = slice->picHeader->gdrPic || (slice->isIRAP() && !slice->pps->mixedNaluTypesInPic);
2737
1.43k
  if ((( slice->vps->maxLayers > 1 && IrapOrGdrAu) || m_pcEncCfg->m_AccessUnitDelimiter) && !slice->nuhLayerId )
2738
0
  {
2739
0
    xWriteAccessUnitDelimiter( accessUnit, slice, IrapOrGdrAu, hlsWriter );
2740
0
  }
2741
2742
  // send ALF APS
2743
1.43k
  if ( sps.alfEnabled && (slice->alfEnabled[COMP_Y] || slice->ccAlfCbEnabled || slice->ccAlfCrEnabled ))
2744
0
  {
2745
0
    for ( int apsId = 0; apsId < ALF_CTB_MAX_NUM_APS; apsId++ )
2746
0
    {
2747
0
      ParameterSetMap<APS>& apsMap = pic.picApsMap;
2748
0
      const int apsMapIdx          = ( apsId << NUM_APS_TYPE_LEN ) + ALF_APS;
2749
0
      APS* aps                     = apsMap.getPS( apsMapIdx );
2750
0
      bool writeAps                = aps && apsMap.getChangedFlag( apsMapIdx );
2751
0
      if ( writeAps )
2752
0
      {
2753
0
        aps->chromaPresent = slice->sps->chromaFormatIdc != CHROMA_400;
2754
0
        aps->temporalId = slice->TLayer;
2755
0
        actualTotalBits += xWriteAPS( accessUnit, aps, hlsWriter, VVENC_NAL_UNIT_PREFIX_APS );
2756
0
        apsMap.clearChangedFlag( apsMapIdx );
2757
0
      }
2758
0
    }
2759
0
  }
2760
2761
1.43k
  return actualTotalBits;
2762
1.43k
}
2763
2764
int EncGOP::xWritePictureSlices( Picture& pic, AccessUnitList& accessUnit, HLSWriter& hlsWriter )
2765
1.43k
{
2766
1.43k
  Slice* slice        = pic.slices[ 0 ];
2767
1.43k
  const int numSlices = (int)( pic.slices.size() );
2768
1.43k
  unsigned  numBytes  = 0;
2769
2770
2.86k
  for ( int sliceIdx = 0; sliceIdx < numSlices; sliceIdx++ )
2771
1.43k
  {
2772
1.43k
    slice = pic.slices[ sliceIdx ];
2773
2774
1.43k
    if ( sliceIdx > 0 && slice->sliceType != VVENC_I_SLICE )
2775
0
    {
2776
0
      slice->checkColRefIdx( sliceIdx, &pic );
2777
0
    }
2778
2779
    // start slice NALUnit
2780
1.43k
    OutputNALUnit nalu( slice->nalUnitType, slice->TLayer );
2781
1.43k
    hlsWriter.setBitstream( &nalu.m_Bitstream );
2782
2783
    // slice header and data
2784
1.43k
    int bitsBeforeWriting = hlsWriter.getNumberOfWrittenBits();
2785
1.43k
    hlsWriter.codeSliceHeader( slice );
2786
1.43k
    pic.actualHeadBits += ( hlsWriter.getNumberOfWrittenBits() - bitsBeforeWriting );
2787
1.43k
    hlsWriter.codeTilesWPPEntryPoint( slice );
2788
1.43k
    xAttachSliceDataToNalUnit( nalu, &pic.sliceDataStreams[ sliceIdx ] );
2789
2790
1.43k
    accessUnit.push_back( new NALUnitEBSP( nalu ) );
2791
1.43k
    numBytes += unsigned( accessUnit.back()->m_nalUnitData.str().size() );
2792
1.43k
  }
2793
2794
1.43k
  xCabacZeroWordPadding( pic, slice, pic.sliceDataNumBins, numBytes, accessUnit.back()->m_nalUnitData );
2795
2796
1.43k
  return numBytes * 8;
2797
1.43k
}
2798
2799
// True when the two film grain characteristics SEI messages would be written with the same syntax element values.
2800
static bool sameFilmGrainCharacteristics( const SeiFgc& a, const SeiFgc& b )
2801
0
{
2802
0
  if( a.fgcCancelFlag || b.fgcCancelFlag )
2803
0
  {
2804
0
    return a.fgcCancelFlag == b.fgcCancelFlag;
2805
0
  }
2806
0
  if( a.filmGrainModelId != b.filmGrainModelId || a.separateColourDescriptionPresent != b.separateColourDescriptionPresent
2807
0
      || a.blendingModeId != b.blendingModeId || a.log2ScaleFactor != b.log2ScaleFactor || a.fgcPersistenceFlag != b.fgcPersistenceFlag )
2808
0
  {
2809
0
    return false;
2810
0
  }
2811
0
  if( a.separateColourDescriptionPresent
2812
0
      && ( a.filmGrainBitDepthLumaMinus8 != b.filmGrainBitDepthLumaMinus8 || a.filmGrainBitDepthChromaMinus8 != b.filmGrainBitDepthChromaMinus8
2813
0
           || a.filmGrainFullRangeFlag != b.filmGrainFullRangeFlag || a.filmGrainColourPrimaries != b.filmGrainColourPrimaries
2814
0
           || a.filmGrainTransferCharacteristics != b.filmGrainTransferCharacteristics || a.filmGrainMatrixCoeffs != b.filmGrainMatrixCoeffs ) )
2815
0
  {
2816
0
    return false;
2817
0
  }
2818
0
  for( int c = 0; c < MAX_NUM_COMP; c++ )
2819
0
  {
2820
0
    const SeiFgc::CompModel& ca = a.compModel[ c ];
2821
0
    const SeiFgc::CompModel& cb = b.compModel[ c ];
2822
    // as in SEIWriter: a component is written as present only with intervals and model values
2823
0
    const bool presentA = ca.presentFlag && ca.numIntensityIntervals > 0 && ca.numModelValues > 0;
2824
0
    const bool presentB = cb.presentFlag && cb.numIntensityIntervals > 0 && cb.numModelValues > 0;
2825
0
    if( presentA != presentB )
2826
0
    {
2827
0
      return false;
2828
0
    }
2829
0
    if( !presentA )
2830
0
    {
2831
0
      continue;
2832
0
    }
2833
0
    if( ca.numIntensityIntervals != cb.numIntensityIntervals || ca.numModelValues != cb.numModelValues )
2834
0
    {
2835
0
      return false;
2836
0
    }
2837
0
    for( int i = 0; i < ca.numIntensityIntervals; i++ )
2838
0
    {
2839
0
      const SeiFgc::CompModelIntensityValues& va = ca.intensityValues[ i ];
2840
0
      const SeiFgc::CompModelIntensityValues& vb = cb.intensityValues[ i ];
2841
0
      if( va.intensityIntervalLowerBound != vb.intensityIntervalLowerBound || va.intensityIntervalUpperBound != vb.intensityIntervalUpperBound
2842
0
          || !std::equal( va.compModelValue.begin(), va.compModelValue.begin() + ca.numModelValues, vb.compModelValue.begin() ) )
2843
0
      {
2844
0
        return false;
2845
0
      }
2846
0
    }
2847
0
  }
2848
0
  return true;
2849
0
}
2850
2851
// Adds the parameter set of a finished analysis. vvdec keeps synthesizing the grain of a component that a later SEI
2852
// marks as absent (fixed by its pull request 414, open in October 2026), so once a component had grain, a parameter set
2853
// without it signals one interval with scaling factor 0 instead.
2854
void EncGOP::xAddFilmGrainParameters( const FgaTask& task )
2855
0
{
2856
0
  FilmGrainParam param = task.result;
2857
0
  for( int c = 0; c < MAX_NUM_COMP; c++ )
2858
0
  {
2859
0
    SeiFgc::CompModel& cm = param.compModel[ c ];
2860
0
    if( m_pcEncCfg->m_fga && !cm.presentFlag && m_fgcCompSignalled[ c ] )
2861
0
    {
2862
0
      cm.presentFlag           = true;
2863
0
      cm.numIntensityIntervals = 1;
2864
0
      cm.numModelValues        = 1;
2865
0
      cm.intensityValues.resize( 1 );
2866
0
      cm.intensityValues[ 0 ].intensityIntervalLowerBound = 0;
2867
0
      cm.intensityValues[ 0 ].intensityIntervalUpperBound = 255;
2868
0
      cm.intensityValues[ 0 ].compModelValue.assign( 1, 0 );
2869
0
    }
2870
0
    m_fgcCompSignalled[ c ] = m_fgcCompSignalled[ c ] || cm.presentFlag;
2871
0
  }
2872
  // A set cannot apply to pictures whose access units are written already, so that xFilmGrainSeiNeeded, which compares
2873
  // a picture's set with the previous picture's, sees every change. In low delay (coding order = output order) the
2874
  // analysed picture is the last coded of its GOP and its set would otherwise start among the written pictures before
2875
  // it, compare equal with itself and never be signalled. In random access the analysed picture is coded before the
2876
  // rest of its GOP, so its set already starts after every written picture; the one exception, an IDR without leading
2877
  // pictures (idr_no_radl), coded after the pictures before it in output order, carries the message anyway.
2878
0
  int startPoc = task.startPoc;
2879
0
  if( !m_fgcWrittenPocs.empty() )
2880
0
  {
2881
0
    startPoc = std::max( startPoc, *m_fgcWrittenPocs.rbegin() + 1 );
2882
0
  }
2883
0
  m_fgcByStartPoc.erase( m_fgcByStartPoc.lower_bound( startPoc ), m_fgcByStartPoc.end() );
2884
0
  m_fgcByStartPoc[ startPoc ] = param;
2885
0
  while( m_fgcByStartPoc.size() > FGC_PARAM_SETS )
2886
0
  {
2887
    // the oldest set is dropped; the next one then applies to all earlier pictures, all of them written long ago
2888
0
    m_fgcByStartPoc.erase( m_fgcByStartPoc.begin() );
2889
0
    FilmGrainParam oldest = m_fgcByStartPoc.begin()->second;
2890
0
    m_fgcByStartPoc.erase( m_fgcByStartPoc.begin() );
2891
0
    m_fgcByStartPoc[ std::numeric_limits<int>::min() ] = oldest;
2892
0
  }
2893
0
}
2894
2895
const FilmGrainParam& EncGOP::xFilmGrainParametersAt( int poc ) const
2896
0
{
2897
0
  return std::prev( m_fgcByStartPoc.upper_bound( poc ) )->second;   // the first set starts at the lowest int
2898
0
}
2899
2900
// The film grain SEI of a parameter set; the components the configuration marks absent stay absent.
2901
SeiFgc EncGOP::xFilmGrainSei( const FilmGrainParam& param, ChromaFormat chromaFormat )
2902
0
{
2903
0
  SeiFgc sei;
2904
0
  m_seiEncoder.initSeiFgc( &sei );
2905
0
  sei.log2ScaleFactor = param.log2ScaleFactor;
2906
0
  for( int c = 0; c < getNumberValidComponents( chromaFormat ); c++ )
2907
0
  {
2908
0
    if( sei.compModel[ c ].presentFlag )
2909
0
    {
2910
0
      sei.compModel[ c ] = param.compModel[ c ];
2911
0
    }
2912
0
  }
2913
0
  return sei;
2914
0
}
2915
2916
// A persistent film grain SEI message applies to its picture and the following pictures in output order, up to the next
2917
// picture with a message, so repeating it in every access unit (45-60 bytes, 2-3.5% of a low rate encode) is not needed:
2918
// a picture needs it when the picture before it in output order signals other parameters. Random access points, where
2919
// decoding can start, always get the message, and so does a picture with no picture before it written yet in this coded
2920
// layer video sequence (the leading pictures of an IDR, of which the first in output order is not known in coding
2921
// order). Decoding from a CRA, vvdec skips its RASL pictures but applies their messages to the next decoded picture, so
2922
// the first picture after RASL pictures with a message gets one as well.
2923
bool EncGOP::xFilmGrainSeiNeeded( const Slice& slice, const SeiFgc& sei, ChromaFormat chromaFormat )
2924
0
{
2925
0
  if( slice.isIDRorBLA() )
2926
0
  {
2927
0
    m_fgcWrittenPocs.clear();   // a new coded layer video sequence, where no earlier message persists
2928
0
  }
2929
0
  const bool rasl         = slice.nalUnitType == VVENC_NAL_UNIT_CODED_SLICE_RASL;
2930
0
  const bool randomAccess = slice.isIRAP() || slice.picHeader->gdrPic;
2931
0
  const bool firstWritten = m_fgcWrittenPocs.lower_bound( slice.poc ) == m_fgcWrittenPocs.begin();
2932
0
  const bool afterRasl    = !rasl && m_fgcRaslSeiPending;
2933
0
  const bool changed      = !sameFilmGrainCharacteristics( xFilmGrainSei( xFilmGrainParametersAt( slice.poc - 1 ), chromaFormat ), sei );
2934
0
  const bool needed       = !sei.fgcPersistenceFlag || randomAccess || firstWritten || afterRasl || changed;
2935
2936
0
  m_fgcWrittenPocs.insert( slice.poc );
2937
0
  while( m_fgcWrittenPocs.size() > FGC_SEI_HISTORY )
2938
0
  {
2939
0
    m_fgcWrittenPocs.erase( m_fgcWrittenPocs.begin() );
2940
0
  }
2941
0
  m_fgcRaslSeiPending = rasl && ( m_fgcRaslSeiPending || needed );
2942
0
  return needed;
2943
0
}
2944
2945
// The grain the coding of a picture lost, for its film grain SEI: per component, the summed 16x16 DCT spectra of the
2946
// original's smoothest blocks and of the reconstruction, per 8-bit block mean (the intensity intervals are known only when the
2947
// SEI is written). Runs when the picture is finished, before its reconstruction can be released; only where
2948
// xScaleToLostGrain uses them (xFitsLostGrain).
2949
void EncGOP::xStoreLostGrainSpectra( Picture& pic ) const
2950
1.43k
{
2951
1.43k
  if( !xFitsLostGrain() )
2952
1.43k
  {
2953
1.43k
    return;
2954
1.43k
  }
2955
0
  for( int c = 0; c < getNumberValidComponents( pic.chromaFormat ); c++ )
2956
0
  {
2957
0
    const ComponentID compId = ComponentID( c );
2958
0
    m_fgAnalyzer.lostGrainSpectra( pic.getOrigBuf( compId ), pic.getRecoBuf( compId ),
2959
0
                                   m_pcEncCfg->m_internalBitDepth[ toChannelType( compId ) ], pic.lostGrainSpectra[ c ] );
2960
0
  }
2961
0
}
2962
2963
// The film grain SEIs are fitted to the grain the coding lost: with the improved analysis (--fga 2 and 3), in the final
2964
// pass, when the SEI is written with the pictures (not as one SEI for the whole sequence).
2965
bool EncGOP::xFitsLostGrain() const
2966
1.43k
{
2967
1.43k
  return m_pcEncCfg->m_fga >= 2 && m_pcEncCfg->m_fg.m_fgcSEIEnabled && !m_pcEncCfg->m_fg.m_fgcSEIPerPictureSEI
2968
0
         && m_pcRateCtrl->rcIsFinalPass && !m_isPreAnalysis;
2969
1.43k
}
2970
2971
// Drops the pooled sums or fitted values of this component and temporal layer whose intensity interval the picture's SEI
2972
// no longer has (a new analysis can change the intervals within a random access period), so the maps stay small.
2973
template<typename LostGrainMap>
2974
static void eraseOtherIntervals( LostGrainMap& map, int c, unsigned layer, const SeiFgc::CompModel& cm )
2975
0
{
2976
0
  for( auto it = map.begin(); it != map.end(); )
2977
0
  {
2978
0
    bool keep = std::get<0>( it->first ) != c || std::get<3>( it->first ) != layer;
2979
0
    for( int i = 0; !keep && i < cm.numIntensityIntervals; i++ )
2980
0
    {
2981
0
      keep = std::get<1>( it->first ) == cm.intensityValues[ i ].intensityIntervalLowerBound
2982
0
             && std::get<2>( it->first ) == cm.intensityValues[ i ].intensityIntervalUpperBound;
2983
0
    }
2984
0
    it = keep ? std::next( it ) : map.erase( it );
2985
0
  }
2986
0
}
Unexecuted instantiation: EncGOP.cpp:void vvenc::eraseOtherIntervals<std::__1::map<std::__1::tuple<int, int, int, unsigned int>, std::__1::deque<vvenc::EncGOP::LostGrainSums, std::__1::allocator<vvenc::EncGOP::LostGrainSums> >, std::__1::less<std::__1::tuple<int, int, int, unsigned int> >, std::__1::allocator<std::__1::pair<std::__1::tuple<int, int, int, unsigned int> const, std::__1::deque<vvenc::EncGOP::LostGrainSums, std::__1::allocator<vvenc::EncGOP::LostGrainSums> > > > > >(std::__1::map<std::__1::tuple<int, int, int, unsigned int>, std::__1::deque<vvenc::EncGOP::LostGrainSums, std::__1::allocator<vvenc::EncGOP::LostGrainSums> >, std::__1::less<std::__1::tuple<int, int, int, unsigned int> >, std::__1::allocator<std::__1::pair<std::__1::tuple<int, int, int, unsigned int> const, std::__1::deque<vvenc::EncGOP::LostGrainSums, std::__1::allocator<vvenc::EncGOP::LostGrainSums> > > > >&, int, unsigned int, vvenc::SeiFgc::CompModel const&)
Unexecuted instantiation: EncGOP.cpp:void vvenc::eraseOtherIntervals<std::__1::map<std::__1::tuple<int, int, int, unsigned int>, vvenc::EncGOP::LostGrainFitted, std::__1::less<std::__1::tuple<int, int, int, unsigned int> >, std::__1::allocator<std::__1::pair<std::__1::tuple<int, int, int, unsigned int> const, vvenc::EncGOP::LostGrainFitted> > > >(std::__1::map<std::__1::tuple<int, int, int, unsigned int>, vvenc::EncGOP::LostGrainFitted, std::__1::less<std::__1::tuple<int, int, int, unsigned int> >, std::__1::allocator<std::__1::pair<std::__1::tuple<int, int, int, unsigned int> const, vvenc::EncGOP::LostGrainFitted> > >&, int, unsigned int, vvenc::SeiFgc::CompModel const&)
2987
2988
// Both cut-offs are signalled (numModelValues 3), so that the fit can move them; missing values get their defaults
2989
// (horizontal 8, vertical = horizontal).
2990
static void signalBothCutoffs( SeiFgc::CompModel& cm )
2991
0
{
2992
0
  if( cm.numModelValues >= 3 )
2993
0
  {
2994
0
    return;
2995
0
  }
2996
0
  for( int i = 0; i < cm.numIntensityIntervals; i++ )
2997
0
  {
2998
0
    std::vector<int>& v = cm.intensityValues[ i ].compModelValue;
2999
0
    if( v.size() < 3 )
3000
0
    {
3001
0
      v.resize( 3 );
3002
0
    }
3003
0
    if( cm.numModelValues < 2 )
3004
0
    {
3005
0
      v[ 1 ] = 8;
3006
0
    }
3007
0
    v[ 2 ] = v[ 1 ];
3008
0
  }
3009
0
  cm.numModelValues = 3;
3010
0
}
3011
3012
// Fits each intensity interval's grain to the grain the coding lost: the analyzer measures the source's grain, but the
3013
// coding keeps part of it (the full synthesis would add it twice) and loses the fine band first (the analyzer's cut-offs
3014
// are those of the source's grain). Per component: the summed spectra of each interval over this picture and the previous
3015
// LOST_GRAIN_POOL - 1 pictures of its temporal layer (only those at most LOST_GRAIN_POOL_SPAN pictures back), then
3016
// xFitLostGrain or xFitLostGrainAr. Random access points start over. Frees
3017
// the picture's spectra.
3018
void EncGOP::xScaleToLostGrain( Picture& pic, const Slice& slice, SeiFgc& sei )
3019
0
{
3020
0
  constexpr int N = 16 * 16;
3021
0
  if( slice.isIRAP() || slice.picHeader->gdrPic )
3022
0
  {
3023
0
    m_lostGrainHistory.clear();
3024
0
    m_lostGrainShift.clear();
3025
0
    m_lostGrainFitted.clear();
3026
0
  }
3027
0
  for( int c = 0; c < getNumberValidComponents( pic.chromaFormat ); c++ )
3028
0
  {
3029
0
    SeiFgc::CompModel& cm = sei.compModel[ c ];
3030
0
    const std::vector<LostGrainSpectrum>& spectra = pic.lostGrainSpectra[ c ];
3031
0
    if( !cm.presentFlag || cm.numIntensityIntervals == 0 )
3032
0
    {
3033
0
      continue;
3034
0
    }
3035
0
    const bool arModel = sei.filmGrainModelId == 1;
3036
0
    if( !arModel )
3037
0
    {
3038
0
      signalBothCutoffs( cm );
3039
0
    }
3040
0
    const int n = cm.numIntensityIntervals;
3041
    // the picture's sums per interval: a block mean belongs to the first interval holding it
3042
0
    std::vector<LostGrainSums> sums( n );
3043
0
    for( const LostGrainSpectrum& s : spectra )
3044
0
    {
3045
0
      for( int i = 0; i < n; i++ )
3046
0
      {
3047
0
        const SeiFgc::CompModelIntensityValues& iv = cm.intensityValues[ i ];
3048
0
        if( s.mean8 >= iv.intensityIntervalLowerBound && s.mean8 <= iv.intensityIntervalUpperBound )
3049
0
        {
3050
0
          for( int k = 0; k < N; k++ )
3051
0
          {
3052
0
            sums[ i ].orig[ k ] += s.orig[ k ];
3053
0
            sums[ i ].reco[ k ] += s.reco[ k ];
3054
0
          }
3055
0
          sums[ i ].blocks += s.blocks;
3056
0
          break;
3057
0
        }
3058
0
      }
3059
0
    }
3060
    // pooled with the layer's previous pictures, then reduced to the fit's mean power per frequency group
3061
0
    std::vector<FGAnalyzer::LostGrainPower> power( n );
3062
0
    for( int i = 0; i < n; i++ )
3063
0
    {
3064
0
      const SeiFgc::CompModelIntensityValues& iv = cm.intensityValues[ i ];
3065
0
      const LostGrainKey key( c, iv.intensityIntervalLowerBound, iv.intensityIntervalUpperBound, slice.TLayer );
3066
0
      std::deque<LostGrainSums>& history = m_lostGrainHistory[ key ];
3067
0
      sums[ i ].poc = pic.poc;
3068
0
      history.push_back( sums[ i ] );
3069
0
      if( history.size() > LOST_GRAIN_POOL )
3070
0
      {
3071
0
        history.pop_front();
3072
0
      }
3073
0
      LostGrainSums pooled;
3074
0
      for( const LostGrainSums& h : history )
3075
0
      {
3076
0
        if( std::abs( pic.poc - h.poc ) > LOST_GRAIN_POOL_SPAN )
3077
0
        {
3078
0
          continue;
3079
0
        }
3080
0
        for( int k = 0; k < N; k++ )
3081
0
        {
3082
0
          pooled.orig[ k ] += h.orig[ k ];
3083
0
          pooled.reco[ k ] += h.reco[ k ];
3084
0
        }
3085
0
        pooled.blocks += h.blocks;
3086
0
      }
3087
0
      power[ i ] = FGAnalyzer::lostGrainPower( pooled.orig, pooled.reco, pooled.blocks );
3088
0
    }
3089
0
    const ComponentID compId   = ComponentID( c );
3090
0
    const int         bitDepth = m_pcEncCfg->m_internalBitDepth[ toChannelType( compId ) ];
3091
0
    if( arModel )
3092
0
    {
3093
0
      xFitLostGrainAr( c, slice.TLayer, bitDepth, sei.log2ScaleFactor, power, cm );
3094
0
    }
3095
0
    else
3096
0
    {
3097
0
      xFitLostGrain( c, slice.TLayer, bitDepth, c != COMP_Y && pic.chromaFormat == CHROMA_420, sei.log2ScaleFactor, power, cm );
3098
0
    }
3099
0
    eraseOtherIntervals( m_lostGrainHistory, c, slice.TLayer, cm );
3100
0
    eraseOtherIntervals( m_lostGrainFitted, c, slice.TLayer, cm );
3101
0
  }
3102
0
  for( auto& spectra : pic.lostGrainSpectra )
3103
0
  {
3104
0
    spectra.clear();
3105
0
    spectra.shrink_to_fit();
3106
0
  }
3107
0
}
3108
3109
// An interval needs this many pooled blocks to be fitted (xFitLostGrain).
3110
static constexpr int MIN_POOLED_BLOCKS = 32;
3111
3112
// One shift (dh, dw) of every interval's cut-offs, the same for all intervals of the component (so the synthesis's limit on
3113
// different cut-off pairs still holds), chosen by the blocks-weighted sum of the intervals' FGAnalyzer::lostGrainFit costs.
3114
// Luma shifts only toward finer grain (dh, dw >= 0): the coding loses luma grain from the fine end first. Chroma also shifts
3115
// toward coarser grain: the coding can lose nearly all of it, and the analyzer's chroma cut-offs can be finer than the
3116
// chroma grain (Top Gun, 4K HDR: cut-offs 7 / 6 put 49 % of the synthesized U grain at u + v 13-30, where the coding lost
3117
// 7 % of its U grain, and 10 % at 3-5, where it lost 44 %). Shifts are tried as 0, 1, -1, 2, -2, ... so that the smallest
3118
// wins a tie. Then per interval the scaling factor fitted at the shifted cut-offs, never more grain
3119
// power than FGAnalyzer::LOST_GRAIN_CAP_POWER times the analyzer's. An interval needs MIN_POOLED_BLOCKS pooled blocks
3120
// to be fitted. So that the synthesized grain does not pulse, per picture of a temporal layer the shift moves at most 1 and
3121
// the scaling factor rises at most max(1, s0 / 8) (s0 the analyzer's scaling factor) from its last value moved to the new
3122
// cut-offs at equal power; a lower fit is taken at once (a limit on the way down held the grain above the fit for many
3123
// pictures, see xFitLostGrainAr). A picture with nothing to fit keeps the shift, an interval without a fit keeps its last
3124
// grain power (at first the analyzer's).
3125
void EncGOP::xFitLostGrain( int c, unsigned layer, int bitDepth, bool chroma420, int log2ScaleFactor,
3126
                            const std::vector<FGAnalyzer::LostGrainPower>& power, SeiFgc::CompModel& cm )
3127
0
{
3128
0
  constexpr int MAX_SHIFT         = 12;
3129
  // static: the lambdas below read them without a capture (MSVC C3493). The cut-offs' range, which
3130
  // FGAnalyzer::lostGrainShape clips to as well (2 .. 14).
3131
0
  static constexpr int MIN_CUTOFF = 2;
3132
0
  static constexpr int MAX_CUTOFF = 14;
3133
0
  const int n = cm.numIntensityIntervals;
3134
0
  std::vector<int> s0( n ), h0( n ), w0( n );   // the analyzer's values
3135
0
  for( int i = 0; i < n; i++ )
3136
0
  {
3137
0
    const std::vector<int>& v = cm.intensityValues[ i ].compModelValue;
3138
0
    s0[ i ] = v[ 0 ];
3139
0
    h0[ i ] = v[ 1 ];
3140
0
    w0[ i ] = v[ 2 ];
3141
0
  }
3142
0
  const bool coarser   = c != COMP_Y;
3143
0
  const int  numShifts = coarser ? 2 * MAX_SHIFT + 1 : MAX_SHIFT + 1;
3144
0
  auto shiftAt = [coarser]( int k ) { return coarser ? ( k & 1 ? ( k + 1 ) / 2 : -k / 2 ) : k; };
3145
0
  auto cutoff  = [coarser]( int x ) { return coarser ? Clip3( MIN_CUTOFF, MAX_CUTOFF, x ) : std::min( MAX_CUTOFF, x ); };
3146
3147
  // Many shifts give an interval the same clipped cut-offs, so every interval is fitted once per distinct pair, when a
3148
  // shift first asks for it, and the grain's shape at a pair is computed once for all intervals.
3149
0
  static constexpr int NUM_CUTOFFS = MAX_CUTOFF - MIN_CUTOFF + 1;
3150
0
  struct Fit
3151
0
  {
3152
0
    double cost  = 0.0;
3153
0
    int    scale = 0;
3154
0
    bool   known = false;
3155
0
  };
3156
0
  struct IntervalFits
3157
0
  {
3158
0
    Fit at[ NUM_CUTOFFS ][ NUM_CUTOFFS ];
3159
0
  };
3160
0
  std::vector<IntervalFits>  intervalFits( n );
3161
0
  FGAnalyzer::LostGrainShape shapes    [ NUM_CUTOFFS ][ NUM_CUTOFFS ];
3162
0
  bool                       shapeKnown[ NUM_CUTOFFS ][ NUM_CUTOFFS ] = {};
3163
0
  auto fitAt = [&]( int i, int h, int w ) -> const Fit&
3164
0
  {
3165
0
    const int hIdx = Clip3( MIN_CUTOFF, MAX_CUTOFF, h ) - MIN_CUTOFF;
3166
0
    const int wIdx = Clip3( MIN_CUTOFF, MAX_CUTOFF, w ) - MIN_CUTOFF;
3167
0
    Fit& fit = intervalFits[ i ].at[ hIdx ][ wIdx ];
3168
0
    if( !fit.known )
3169
0
    {
3170
0
      if( !shapeKnown[ hIdx ][ wIdx ] )
3171
0
      {
3172
0
        shapes    [ hIdx ][ wIdx ] = FGAnalyzer::lostGrainShape( chroma420, hIdx + MIN_CUTOFF, wIdx + MIN_CUTOFF );
3173
0
        shapeKnown[ hIdx ][ wIdx ] = true;
3174
0
      }
3175
0
      fit.cost  = FGAnalyzer::lostGrainFit( power[ i ], bitDepth, chroma420, log2ScaleFactor, s0[ i ], h0[ i ], w0[ i ],
3176
0
                                            shapes[ hIdx ][ wIdx ], fit.scale );
3177
0
      fit.known = true;
3178
0
    }
3179
0
    return fit;
3180
0
  };
3181
3182
0
  double bestCost = -1.0;
3183
0
  int    bestH = 0, bestW = 0;
3184
0
  for( int kh = 0; kh < numShifts; kh++ )
3185
0
  {
3186
0
    const int dh = shiftAt( kh );
3187
0
    for( int kw = 0; kw < numShifts; kw++ )
3188
0
    {
3189
0
      const int dw = shiftAt( kw );
3190
0
      double total  = 0.0;
3191
0
      bool   fitted = false;
3192
0
      for( int i = 0; i < n; i++ )
3193
0
      {
3194
0
        if( power[ i ].blocks < MIN_POOLED_BLOCKS )
3195
0
        {
3196
0
          continue;
3197
0
        }
3198
0
        const double cost = fitAt( i, cutoff( h0[ i ] + dh ), cutoff( w0[ i ] + dw ) ).cost;
3199
0
        if( cost >= 0 )
3200
0
        {
3201
0
          total += cost * power[ i ].blocks;
3202
0
          fitted = true;
3203
0
        }
3204
0
      }
3205
0
      if( fitted && ( bestCost < 0 || total < bestCost - 1e-12 ) )
3206
0
      {
3207
0
        bestCost = total;
3208
0
        bestH    = dh;
3209
0
        bestW    = dw;
3210
0
      }
3211
0
    }
3212
0
  }
3213
0
  const auto layerKey  = std::make_pair( c, layer );
3214
0
  const auto lastShift = m_lostGrainShift.find( layerKey );
3215
0
  int dh = bestH, dw = bestW;
3216
0
  if( lastShift != m_lostGrainShift.end() )
3217
0
  {
3218
0
    const int lastH = lastShift->second.first, lastW = lastShift->second.second;
3219
0
    dh = bestCost < 0 ? lastH : Clip3( lastH - 1, lastH + 1, bestH );
3220
0
    dw = bestCost < 0 ? lastW : Clip3( lastW - 1, lastW + 1, bestW );
3221
0
  }
3222
0
  if( bestCost >= 0 )   // a picture with nothing to fit records no shift: the layer's first fit is then free, not 1 per picture from 0
3223
0
  {
3224
0
    m_lostGrainShift[ layerKey ] = std::make_pair( dh, dw );
3225
0
  }
3226
0
  for( int i = 0; i < n; i++ )
3227
0
  {
3228
0
    SeiFgc::CompModelIntensityValues& iv = cm.intensityValues[ i ];
3229
0
    const int h = cutoff( h0[ i ] + dh ), w = cutoff( w0[ i ] + dw );
3230
0
    const int analyzerScale = FGAnalyzer::equalPowerScale( s0[ i ], chroma420, h0[ i ], w0[ i ], h, w );   // the analyzer's power
3231
0
    const int cap           = FGAnalyzer::lostGrainCapScale( s0[ i ], chroma420, h0[ i ], w0[ i ], h, w );
3232
0
    const LostGrainKey key( c, iv.intensityIntervalLowerBound, iv.intensityIntervalUpperBound, layer );
3233
    // the interval's last value moved to the new cut-offs at equal power; before its first fit, the analyzer's grain, which
3234
    // is not recorded: the first fit is then free instead of starting max(1, s0 / 8) per picture down from the analyzer's
3235
0
    const auto last   = m_lostGrainFitted.find( key );
3236
0
    const bool fitted = last != m_lostGrainFitted.end();
3237
0
    const int  held   = fitted ? FGAnalyzer::equalPowerScale( last->second.scale, chroma420, last->second.h, last->second.w, h, w ) : analyzerScale;
3238
0
    int  scale = held;
3239
0
    const Fit* lostFit = power[ i ].blocks >= MIN_POOLED_BLOCKS ? &fitAt( i, h, w ) : nullptr;
3240
0
    const bool fits    = lostFit && lostFit->cost >= 0;
3241
0
    if( fits )
3242
0
    {
3243
0
      const int fit  = lostFit->scale;
3244
0
      const int step = std::max( 1, s0[ i ] / 8 );
3245
0
      scale = fitted ? std::min( fit, held + step ) : fit;
3246
0
    }
3247
0
    scale = std::min( scale, cap );
3248
0
    iv.compModelValue[ 0 ] = scale;
3249
0
    iv.compModelValue[ 1 ] = h;
3250
0
    iv.compModelValue[ 2 ] = w;
3251
0
    if( fits || fitted )
3252
0
    {
3253
0
      m_lostGrainFitted[ key ] = { h, w, scale };
3254
0
    }
3255
0
  }
3256
0
}
3257
3258
// The lost-grain fit of the auto-regressive model (--fga 3): the filter stays the analyzer's (one per component; fitting
3259
// its shape to the lost grain as well gained little: on Top Gun's sky the bands u + v 3-5 / 6-8 / 9-12 / 13-30 of
3260
// reconstruction plus synthesis reached 0.22 / 0.38 / 1.39 / 1.21 of the original's power against 0.21 / 0.31 / 1.32 /
3261
// 1.33), and every interval's scaling factor is fitted to the grain the coding lost (FGAnalyzer::lostGrainFitAr), at most
3262
// FGAnalyzer::LOST_GRAIN_CAP_POWER times the analyzer's grain power. Without it the whole analysed grain was synthesized
3263
// on top of the grain the coding kept. As in xFitLostGrain, an interval needs MIN_POOLED_BLOCKS pooled blocks to be
3264
// fitted and an interval without a fit keeps its last value (at first the analyzer's). A fit below the last value of the
3265
// interval and temporal layer is taken at once: a limit on the way down held the grain far above what the fit asked
3266
// for, and it did so for many pictures (gangster_chase: after one fit of 112 the fits fell to 84 and 48, the value only
3267
// to 105 and 97, and that picture had 1.96 times the source's finest band between neighbours at 1.0). On the way up the
3268
// scaling factor rises at most an eighth of its last value per picture of the layer (at least 1, at most s0 / 8), so
3269
// that the grain does not pulse; the price is that a value near 0 rises slowly.
3270
void EncGOP::xFitLostGrainAr( int c, unsigned layer, int bitDepth, int log2ScaleFactor,
3271
                              const std::vector<FGAnalyzer::LostGrainPower>& power, SeiFgc::CompModel& cm )
3272
0
{
3273
0
  if( cm.numIntensityIntervals == 0 )
3274
0
  {
3275
0
    return;
3276
0
  }
3277
  // the grain of the component's filter, computed anew only when the filter changed
3278
0
  const std::vector<int>& first = cm.intensityValues[ 0 ].compModelValue;
3279
0
  std::vector<int> filter( first.begin() + 1, first.end() );
3280
0
  filter.insert( filter.begin(), log2ScaleFactor );
3281
0
  if( m_arGrain[ c ].filter != filter )
3282
0
  {
3283
0
    const FGAnalyzer::ArGrain newGrain = FGAnalyzer::arGrain( first, log2ScaleFactor, bitDepth, c == COMP_Y );
3284
    // the scaling factors last written are in units of the old filter's grain: keep their grain level, so that a new
3285
    // analysis does not make the grain jump
3286
0
    for( auto& fitted : m_lostGrainFitted )
3287
0
    {
3288
0
      if( std::get<0>( fitted.first ) == c && !m_arGrain[ c ].filter.empty() && newGrain.stddevPerScale > 0.0 )
3289
0
      {
3290
0
        fitted.second.scale = (int) std::lround( fitted.second.scale * m_arGrain[ c ].grain.stddevPerScale / newGrain.stddevPerScale );
3291
0
      }
3292
0
    }
3293
0
    m_arGrain[ c ].grain  = newGrain;
3294
0
    m_arGrain[ c ].filter = filter;
3295
0
  }
3296
0
  const FGAnalyzer::ArGrain& grain = m_arGrain[ c ].grain;
3297
3298
0
  for( int i = 0; i < cm.numIntensityIntervals; i++ )
3299
0
  {
3300
0
    SeiFgc::CompModelIntensityValues& iv = cm.intensityValues[ i ];
3301
0
    const int s0 = iv.compModelValue[ 0 ];   // the analyzer's
3302
0
    const LostGrainKey key( c, iv.intensityIntervalLowerBound, iv.intensityIntervalUpperBound, layer );
3303
0
    const auto last   = m_lostGrainFitted.find( key );
3304
0
    const bool fitted = last != m_lostGrainFitted.end();
3305
0
    int  scale = fitted ? last->second.scale : s0;
3306
0
    int  fit;
3307
0
    const bool fits = power[ i ].blocks >= MIN_POOLED_BLOCKS && FGAnalyzer::lostGrainFitAr( power[ i ], grain, s0, fit ) >= 0;
3308
0
    if( fits )
3309
0
    {
3310
0
      const int step = std::max( 1, std::min( s0, scale ) / 8 );
3311
0
      scale = fitted ? std::min( fit, scale + step ) : fit;   // the first fit is free
3312
0
    }
3313
0
    scale = std::min( scale, FGAnalyzer::lostGrainCapScaleAr( s0 ) );
3314
0
    iv.compModelValue[ 0 ] = scale;
3315
0
    if( fits || fitted )
3316
0
    {
3317
0
      m_lostGrainFitted[ key ] = { 0, 0, scale };
3318
0
    }
3319
0
  }
3320
0
}
3321
3322
void EncGOP::xWriteLeadingSEIs( Picture& pic, AccessUnitList& accessUnit )
3323
1.43k
{
3324
1.43k
  const Slice* slice = pic.slices[ 0 ];
3325
1.43k
  SEIMessages leadingSeiMessages;
3326
3327
1.43k
  bool bpPresentInAU = false;
3328
3329
1.43k
  if((m_pcEncCfg->m_bufferingPeriodSEIEnabled) && (slice->isIRAP() || slice->nalUnitType == VVENC_NAL_UNIT_CODED_SLICE_GDR) &&
3330
0
    slice->nuhLayerId==slice->vps->layerId[0] && (slice->sps->hrdParametersPresent) && m_pcRateCtrl->rcIsFinalPass && !m_isPreAnalysis )
3331
0
  {
3332
0
    SEIBufferingPeriod *bufferingPeriodSEI = new SEIBufferingPeriod();
3333
0
    bool noLeadingPictures = ( (slice->nalUnitType!= VVENC_NAL_UNIT_CODED_SLICE_IDR_W_RADL) && (slice->nalUnitType!= VVENC_NAL_UNIT_CODED_SLICE_CRA) );
3334
0
    m_seiEncoder.initBufferingPeriodSEI(*bufferingPeriodSEI, noLeadingPictures);
3335
0
    m_EncHRD.bufferingPeriodSEI = *bufferingPeriodSEI;
3336
0
    m_EncHRD.bufferingPeriodInitialized = true;
3337
3338
0
    leadingSeiMessages.push_back(bufferingPeriodSEI);
3339
0
    bpPresentInAU = true;
3340
0
  }
3341
3342
//  if (m_pcEncCfg->m_dependentRAPIndicationSEIEnabled && slice->isDRAP )
3343
//  {
3344
//    SEIDependentRAPIndication *dependentRAPIndicationSEI = new SEIDependentRAPIndication();
3345
//    m_seiEncoder.initDrapSEI( dependentRAPIndicationSEI );
3346
//    leadingSeiMessages.push_back(dependentRAPIndicationSEI);
3347
//  }
3348
3349
1.43k
  if( m_pcEncCfg->m_pictureTimingSEIEnabled && m_pcEncCfg->m_bufferingPeriodSEIEnabled && m_pcRateCtrl->rcIsFinalPass && !m_isPreAnalysis )
3350
0
  {
3351
0
    SEIMessages nestedSeiMessages;
3352
0
    SEIMessages duInfoSeiMessages;
3353
0
    uint32_t numDU = 1;
3354
0
    m_seiEncoder.initPictureTimingSEI( leadingSeiMessages, nestedSeiMessages, duInfoSeiMessages, slice, numDU, bpPresentInAU );
3355
0
  }
3356
3357
1.43k
  if( m_pcEncCfg->m_preferredTransferCharacteristics )
3358
0
  {
3359
0
    SEIAlternativeTransferCharacteristics *seiAlternativeTransferCharacteristics = new SEIAlternativeTransferCharacteristics;
3360
0
    m_seiEncoder.initSEIAlternativeTransferCharacteristics( seiAlternativeTransferCharacteristics );
3361
0
    leadingSeiMessages.push_back(seiAlternativeTransferCharacteristics);
3362
0
  }
3363
3364
  // film grain SEI
3365
1.43k
  if ( m_pcEncCfg->m_fg.m_fgcSEIEnabled && !m_pcEncCfg->m_fg.m_fgcSEIPerPictureSEI )
3366
0
  {
3367
    // Access units are written in coding order. An analysis result is added with the access unit of the analyzed
3368
    // picture, the start picture of its GOP, and applies from its start POC on (xAddFilmGrainParameters).
3369
0
    while( !m_fgaTasks.empty() && m_fgaTasks.front()->codingNum <= pic.gopEntry->m_codingNum )
3370
0
    {
3371
0
      m_fgaTasks.front()->counter.wait();
3372
0
      xAddFilmGrainParameters( *m_fgaTasks.front() );
3373
      // the consumed task has run, so the task after it no longer looks at its barrier once that one has run too
3374
0
      m_fgaConsumed = std::move( m_fgaTasks.front() );
3375
0
      m_fgaTasks.pop_front();
3376
0
    }
3377
3378
0
    SeiFgc sei = xFilmGrainSei( xFilmGrainParametersAt( slice->poc ), pic.chromaFormat );
3379
    // With the improved analysis (--fga 2 and 3), every picture's message is scaled to the grain its coding lost, so every
3380
    // picture carries one.
3381
0
    const bool scaled = xFitsLostGrain();
3382
0
    if( scaled )
3383
0
    {
3384
0
      xScaleToLostGrain( pic, *slice, sei );
3385
0
    }
3386
0
    if( xFilmGrainSeiNeeded( *slice, sei, pic.chromaFormat ) || scaled )
3387
0
    {
3388
0
      leadingSeiMessages.push_back( new SeiFgc( sei ) );
3389
0
    }
3390
0
  }
3391
3392
  // mastering display colour volume
3393
1.43k
  if( (m_pcEncCfg->m_masteringDisplay[0] != 0 && m_pcEncCfg->m_masteringDisplay[1] != 0) ||
3394
1.43k
      m_pcEncCfg->m_masteringDisplay[8] )
3395
0
  {
3396
0
    SEIMasteringDisplayColourVolume *sei = new SEIMasteringDisplayColourVolume;
3397
0
    m_seiEncoder.initSEIMasteringDisplayColourVolume(sei);
3398
0
    leadingSeiMessages.push_back(sei);
3399
0
  }
3400
3401
  // content light level
3402
1.43k
  if( m_pcEncCfg->m_contentLightLevel[0] != 0 && m_pcEncCfg->m_contentLightLevel[1] != 0 )
3403
0
  {
3404
0
    SEIContentLightLevelInfo *seiCLL = new SEIContentLightLevelInfo;
3405
0
    m_seiEncoder.initSEIContentLightLevel(seiCLL);
3406
0
    leadingSeiMessages.push_back(seiCLL);
3407
0
  }
3408
3409
3410
  // Note: using accessUnit.end() works only as long as this function is called after slice coding and before EOS/EOB NAL units
3411
1.43k
  AccessUnitList::iterator pos = accessUnit.end();
3412
1.43k
  xWriteSEISeparately( VVENC_NAL_UNIT_PREFIX_SEI, leadingSeiMessages, accessUnit, pos, slice->TLayer, slice->sps );
3413
3414
1.43k
  deleteSEIs( leadingSeiMessages );
3415
1.43k
}
3416
3417
void EncGOP::xWriteTrailingSEIs( const Picture& pic, AccessUnitList& accessUnit, std::string& digestStr )
3418
1.43k
{
3419
1.43k
  const Slice* slice = pic.slices[ 0 ];
3420
1.43k
  SEIMessages trailingSeiMessages;
3421
3422
1.43k
  if ( m_pcEncCfg->m_decodedPictureHashSEIType != VVENC_HASHTYPE_NONE )
3423
0
  {
3424
0
    SEIDecodedPictureHash *decodedPictureHashSei = new SEIDecodedPictureHash();
3425
0
    const CPelUnitBuf recoBuf = pic.cs->getRecoBuf();
3426
0
    m_seiEncoder.initDecodedPictureHashSEI( *decodedPictureHashSei, recoBuf, digestStr, slice->sps->bitDepths );
3427
0
    if ( m_pcEncCfg->m_decodedPictureHashSEIType < VVENC_HASHTYPE_MD5_LOG )
3428
0
    {
3429
0
    trailingSeiMessages.push_back( decodedPictureHashSei );
3430
0
  }
3431
0
    else
3432
0
    {
3433
0
      delete decodedPictureHashSei;
3434
0
    }
3435
0
  }
3436
3437
  // Note: using accessUnit.end() works only as long as this function is called after slice coding and before EOS/EOB NAL units
3438
1.43k
  AccessUnitList::iterator pos = accessUnit.end();
3439
1.43k
  xWriteSEISeparately( VVENC_NAL_UNIT_SUFFIX_SEI, trailingSeiMessages, accessUnit, pos, slice->TLayer, slice->sps );
3440
3441
1.43k
  deleteSEIs( trailingSeiMessages );
3442
1.43k
}
3443
3444
int EncGOP::xWriteVPS ( AccessUnitList &accessUnit, const VPS *vps, HLSWriter& hlsWriter )
3445
0
{
3446
0
  OutputNALUnit nalu(VVENC_NAL_UNIT_VPS);
3447
0
  hlsWriter.setBitstream( &nalu.m_Bitstream );
3448
0
  hlsWriter.codeVPS( vps );
3449
0
  accessUnit.push_back(new NALUnitEBSP(nalu));
3450
0
  return (int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
3451
0
}
3452
3453
int EncGOP::xWriteDCI ( AccessUnitList &accessUnit, const DCI *dci, HLSWriter& hlsWriter )
3454
1.43k
{
3455
1.43k
  if (dci->dciId ==0)
3456
1.43k
  {
3457
1.43k
    return 0;
3458
1.43k
  }
3459
3460
0
  OutputNALUnit nalu(VVENC_NAL_UNIT_DCI);
3461
0
  hlsWriter.setBitstream( &nalu.m_Bitstream );
3462
0
  hlsWriter.codeDCI( dci );
3463
0
  accessUnit.push_back(new NALUnitEBSP(nalu));
3464
0
  return (int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
3465
1.43k
}
3466
3467
int EncGOP::xWriteSPS ( AccessUnitList &accessUnit, const SPS *sps, HLSWriter& hlsWriter )
3468
1.43k
{
3469
1.43k
  OutputNALUnit nalu(VVENC_NAL_UNIT_SPS);
3470
1.43k
  hlsWriter.setBitstream( &nalu.m_Bitstream );
3471
1.43k
  hlsWriter.codeSPS( sps );
3472
1.43k
  accessUnit.push_back(new NALUnitEBSP(nalu));
3473
1.43k
  return (int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
3474
1.43k
}
3475
3476
int EncGOP::xWritePPS ( AccessUnitList &accessUnit, const PPS *pps, const SPS *sps, HLSWriter& hlsWriter )
3477
1.43k
{
3478
1.43k
  OutputNALUnit nalu(VVENC_NAL_UNIT_PPS);
3479
1.43k
  hlsWriter.setBitstream( &nalu.m_Bitstream );
3480
1.43k
  hlsWriter.codePPS( pps, sps );
3481
1.43k
  accessUnit.push_back(new NALUnitEBSP(nalu));
3482
1.43k
  return (int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
3483
1.43k
}
3484
3485
int EncGOP::xWriteAPS( AccessUnitList &accessUnit, const APS *aps, HLSWriter& hlsWriter, vvencNalUnitType eNalUnitType )
3486
0
{
3487
0
  OutputNALUnit nalu(eNalUnitType, aps->temporalId);
3488
0
  hlsWriter.setBitstream(&nalu.m_Bitstream);
3489
0
  hlsWriter.codeAPS(aps);
3490
0
  accessUnit.push_back(new NALUnitEBSP(nalu));
3491
0
  return (int)(accessUnit.back()->m_nalUnitData.str().size()) * 8;
3492
0
}
3493
3494
void EncGOP::xWriteAccessUnitDelimiter ( AccessUnitList &accessUnit, Slice* slice, bool IrapOrGdr, HLSWriter& hlsWriter )
3495
0
{
3496
0
  OutputNALUnit nalu(VVENC_NAL_UNIT_ACCESS_UNIT_DELIMITER, slice->TLayer);
3497
0
  hlsWriter.setBitstream(&nalu.m_Bitstream);
3498
0
  hlsWriter.codeAUD( IrapOrGdr, 2-slice->sliceType );
3499
0
  accessUnit.push_front(new NALUnitEBSP(nalu));
3500
0
}
3501
3502
void EncGOP::xWriteSEI (vvencNalUnitType naluType, SEIMessages& seiMessages, AccessUnitList &accessUnit, AccessUnitList::iterator &auPos, int temporalId, const SPS *sps)
3503
0
{
3504
0
  if (seiMessages.empty())
3505
0
  {
3506
0
    return;
3507
0
  }
3508
0
  OutputNALUnit nalu(naluType, temporalId);
3509
0
  m_seiWriter.writeSEImessages(nalu.m_Bitstream, seiMessages, m_EncHRD, false, temporalId);
3510
0
  auPos = accessUnit.insert(auPos, new NALUnitEBSP(nalu));
3511
0
  auPos++;
3512
0
}
3513
3514
void EncGOP::xWriteSEISeparately (vvencNalUnitType naluType, SEIMessages& seiMessages, AccessUnitList &accessUnit, AccessUnitList::iterator &auPos, int temporalId, const SPS *sps)
3515
2.86k
{
3516
2.86k
  if (seiMessages.empty())
3517
2.86k
  {
3518
2.86k
    return;
3519
2.86k
  }
3520
0
  for (SEIMessages::const_iterator sei = seiMessages.begin(); sei!=seiMessages.end(); sei++ )
3521
0
  {
3522
0
    SEIMessages tmpMessages;
3523
0
    tmpMessages.push_back(*sei);
3524
0
    OutputNALUnit nalu(naluType, temporalId);
3525
0
    m_seiWriter.writeSEImessages(nalu.m_Bitstream, tmpMessages, m_EncHRD, false, temporalId);
3526
0
    auPos = accessUnit.insert(auPos, new NALUnitEBSP(nalu));
3527
0
    auPos++;
3528
0
  }
3529
0
}
3530
3531
/** Attaches the input bitstream to the stream in the output NAL unit
3532
    Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
3533
 *  \param codedSliceData contains the coded slice data (bitstream) to be concatenated to rNalu
3534
 *  \param rNalu          target NAL unit
3535
 */
3536
void EncGOP::xAttachSliceDataToNalUnit( OutputNALUnit& rNalu, const OutputBitstream* codedSliceData )
3537
1.43k
{
3538
  // Byte-align
3539
1.43k
  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
3540
3541
  // Perform bitstream concatenation
3542
1.43k
  if (codedSliceData->getNumberOfWrittenBits() > 0)
3543
1.43k
  {
3544
1.43k
    rNalu.m_Bitstream.addSubstream(codedSliceData);
3545
1.43k
  }
3546
1.43k
}
3547
3548
void EncGOP::xCabacZeroWordPadding( const Picture& pic, const Slice* slice, uint32_t binCountsInNalUnits, uint32_t numBytesInVclNalUnits, std::ostringstream &nalUnitData )
3549
1.43k
{
3550
1.43k
  const PPS &pps                     = *(slice->pps);
3551
1.43k
  const SPS &sps                     = *(slice->sps);
3552
1.43k
  const ChromaFormat format          = sps.chromaFormatIdc;
3553
1.43k
  const int log2subWidthCxsubHeightC = getComponentScaleX( COMP_Cb, format ) + getComponentScaleY( COMP_Cb, format );
3554
1.43k
  const int minCUSize                = pic.cs->pcv->minCUSize;
3555
1.43k
  const int paddedWidth              = ( (pps.picWidthInLumaSamples  + minCUSize - 1) / minCUSize) * minCUSize;
3556
1.43k
  const int paddedHeight             = ( (pps.picHeightInLumaSamples + minCUSize - 1) / minCUSize) * minCUSize;
3557
1.43k
  const int rawBits                  = paddedWidth * paddedHeight * ( sps.bitDepths[ CH_L ] + 2 * ( sps.bitDepths[ CH_C ] >> log2subWidthCxsubHeightC ) );
3558
1.43k
  const uint32_t threshold           = ( 32/3 ) * numBytesInVclNalUnits + ( rawBits/32 );
3559
1.43k
  if ( binCountsInNalUnits >= threshold )
3560
0
  {
3561
    // need to add additional cabac zero words (each one accounts for 3 bytes (=00 00 03)) to increase numBytesInVclNalUnits
3562
0
    const uint32_t targetNumBytesInVclNalUnits = ( ( binCountsInNalUnits - ( rawBits/32 ) ) * 3 + 31 ) / 32;
3563
3564
0
    if ( targetNumBytesInVclNalUnits>numBytesInVclNalUnits ) // It should be!
3565
0
    {
3566
0
      const uint32_t numberOfAdditionalBytesNeeded    = targetNumBytesInVclNalUnits - numBytesInVclNalUnits;
3567
0
      const uint32_t numberOfAdditionalCabacZeroWords = ( numberOfAdditionalBytesNeeded + 2 ) / 3;
3568
0
      const uint32_t numberOfAdditionalCabacZeroBytes = numberOfAdditionalCabacZeroWords * 3;
3569
0
      if ( m_pcEncCfg->m_cabacZeroWordPaddingEnabled )
3570
0
      {
3571
0
        std::vector<uint8_t> zeroBytesPadding(numberOfAdditionalCabacZeroBytes, uint8_t(0));
3572
0
        for( uint32_t i = 0; i < numberOfAdditionalCabacZeroWords; i++ )
3573
0
        {
3574
0
          zeroBytesPadding[ i * 3 + 2 ] = 3;  // 00 00 03
3575
0
        }
3576
0
        nalUnitData.write( reinterpret_cast<const char*>(&(zeroBytesPadding[ 0 ])), numberOfAdditionalCabacZeroBytes );
3577
0
        msg.log( VVENC_NOTICE, "Adding %d bytes of padding\n", numberOfAdditionalCabacZeroWords * 3 );
3578
0
      }
3579
0
      else
3580
0
      {
3581
0
        msg.log( VVENC_NOTICE, "Standard would normally require adding %d bytes of padding\n", numberOfAdditionalCabacZeroWords * 3 );
3582
0
      }
3583
0
    }
3584
0
  }
3585
1.43k
}
3586
3587
void EncGOP::xAddPSNRStats( const Picture* pic, CPelUnitBuf cPicD, AccessUnitList& accessUnit, bool printFrameMSE, double* PSNR_Y, bool isEncodeLtRef )
3588
1.43k
{
3589
1.43k
  const Slice* slice         = pic->slices[0];
3590
3591
1.43k
  double dPSNR[MAX_NUM_COMP];
3592
1.43k
  double MSEyuvframe[MAX_NUM_COMP];
3593
5.72k
  for (int i = 0; i < MAX_NUM_COMP; i++)
3594
4.29k
  {
3595
4.29k
    dPSNR[i]       = pic->psnr[i];
3596
4.29k
    MSEyuvframe[i] = pic->mse[i];
3597
4.29k
  }
3598
3599
  /* calculate the size of the access unit, excluding:
3600
   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
3601
   *  - SEI NAL units
3602
   */
3603
1.43k
  uint32_t numRBSPBytes = 0;
3604
5.72k
  for (AccessUnitList::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
3605
4.29k
  {
3606
4.29k
    uint32_t numRBSPBytes_nal = uint32_t((*it)->m_nalUnitData.str().size());
3607
4.29k
    if (m_pcEncCfg->m_summaryVerboseness > 0)
3608
0
    {
3609
0
      msg.log( VVENC_NOTICE, "*** %s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
3610
0
    }
3611
4.29k
    if( ( *it )->m_nalUnitType != VVENC_NAL_UNIT_PREFIX_SEI && ( *it )->m_nalUnitType != VVENC_NAL_UNIT_SUFFIX_SEI )
3612
4.29k
    {
3613
4.29k
      numRBSPBytes += numRBSPBytes_nal;
3614
4.29k
      if (it == accessUnit.begin() || (*it)->m_nalUnitType == VVENC_NAL_UNIT_VPS || (*it)->m_nalUnitType == VVENC_NAL_UNIT_DCI || (*it)->m_nalUnitType == VVENC_NAL_UNIT_SPS || (*it)->m_nalUnitType == VVENC_NAL_UNIT_PPS || (*it)->m_nalUnitType == VVENC_NAL_UNIT_PREFIX_APS || (*it)->m_nalUnitType == VVENC_NAL_UNIT_SUFFIX_APS)
3615
2.86k
      {
3616
2.86k
        numRBSPBytes += 4;
3617
2.86k
      }
3618
1.43k
      else
3619
1.43k
      {
3620
1.43k
        numRBSPBytes += 3;
3621
1.43k
      }
3622
4.29k
    }
3623
4.29k
  }
3624
1.43k
  const uint32_t uibits = numRBSPBytes * 8;
3625
3626
1.43k
  if (m_isPreAnalysis || !m_pcRateCtrl->rcIsFinalPass)
3627
0
  {
3628
0
    m_pcRateCtrl->addRCPassStats( slice->poc,
3629
0
                                  slice->sliceQp,
3630
0
                                  slice->getLambdas()[0],
3631
0
                                  pic->picVA.visAct,
3632
0
                                  uibits,
3633
0
                                  dPSNR[COMP_Y],
3634
0
                                  slice->isIntra(),
3635
0
                                  slice->TLayer,
3636
0
                                  pic->gopEntry->m_isStartOfIntra,
3637
0
                                  pic->gopEntry->m_isStartOfGop,
3638
0
                                  pic->gopEntry->m_gopNum,
3639
0
                                  pic->gopEntry->m_scType,
3640
0
                                  pic->picVA.spatAct[CH_L],
3641
0
                                  pic->m_picShared->m_picMotEstError,
3642
0
                                  pic->m_picShared->m_minNoiseLevels );
3643
0
  }
3644
3645
  //===== add PSNR =====
3646
1.43k
  m_AnalyzeAll.addResult(dPSNR, (double)uibits, MSEyuvframe
3647
1.43k
    , isEncodeLtRef
3648
1.43k
  );
3649
1.43k
  if ( slice->isIntra() )
3650
1.43k
  {
3651
1.43k
    m_AnalyzeI.addResult(dPSNR, (double)uibits, MSEyuvframe
3652
1.43k
      , isEncodeLtRef
3653
1.43k
    );
3654
1.43k
    *PSNR_Y = dPSNR[COMP_Y];
3655
1.43k
  }
3656
1.43k
  if ( slice->isInterP() )
3657
0
  {
3658
0
    m_AnalyzeP.addResult(dPSNR, (double)uibits, MSEyuvframe
3659
0
      , isEncodeLtRef
3660
0
    );
3661
0
    *PSNR_Y = dPSNR[COMP_Y];
3662
0
  }
3663
1.43k
  if ( slice->isInterB() )
3664
0
  {
3665
0
    m_AnalyzeB.addResult(dPSNR, (double)uibits, MSEyuvframe
3666
0
      , isEncodeLtRef
3667
0
    );
3668
0
    *PSNR_Y = dPSNR[COMP_Y];
3669
0
  }
3670
3671
1.43k
  char c = (slice->isIntra() ? 'I' : slice->isInterP() ? 'P' : 'B');
3672
1.43k
  if ( ! pic->isReferenced && pic->refCounter == 0 && ! m_pcEncCfg->m_maxParallelFrames )
3673
0
  {
3674
0
    c += 32;
3675
0
  }
3676
3677
  // create info string
3678
1.43k
  {
3679
1.43k
    if ((m_isPreAnalysis && m_pcRateCtrl->m_pcEncCfg->m_RCTargetBitrate > 0) || !m_pcRateCtrl->rcIsFinalPass)
3680
0
    {
3681
0
      std::string cInfo;
3682
0
      if( m_pcRateCtrl->rcIsFinalPass ) // single pass RC
3683
0
      {
3684
0
        cInfo = prnt("RC analyze poc %5d", slice->poc );
3685
0
      }
3686
0
      else
3687
0
      {
3688
0
        cInfo = prnt("RC pass %d/%d, analyze poc %5d",
3689
0
            m_pcRateCtrl->rcPass + 1,
3690
0
            m_pcEncCfg->m_RCNumPasses,
3691
0
            slice->poc );
3692
0
      }
3693
0
      accessUnit.InfoString.append( cInfo );
3694
0
    }
3695
1.43k
    else
3696
1.43k
    {
3697
1.43k
      std::stringstream sMctf;
3698
1.43k
      if( pic->gopEntry->m_mctfIndex >= 0 )
3699
0
        sMctf << ", TF " << pic->gopEntry->m_mctfIndex << ")";
3700
1.43k
      else
3701
1.43k
        sMctf << ")      ";
3702
3703
1.43k
      std::string cInfo = prnt("POC %5d TId: %1d (%10s, %c-SLICE, QP %d%s %10d bits",
3704
1.43k
          slice->poc,
3705
1.43k
          slice->TLayer,
3706
1.43k
          nalUnitTypeToString( slice->nalUnitType ),
3707
1.43k
          c,
3708
1.43k
          slice->sliceQp,
3709
1.43k
          sMctf.str().c_str(),
3710
1.43k
          uibits );
3711
3712
1.43k
      std::string yPSNR = dPSNR[COMP_Y]  == MAX_DOUBLE ? prnt(" [Y %7s dB    ", "inf" ) : prnt(" [Y %6.4lf dB    ", dPSNR[COMP_Y] );
3713
1.43k
      std::string uPSNR = dPSNR[COMP_Cb] == MAX_DOUBLE ? prnt("U %7s dB    ", "inf" ) : prnt("U %6.4lf dB    ", dPSNR[COMP_Cb] );
3714
1.43k
      std::string vPSNR = dPSNR[COMP_Cr] == MAX_DOUBLE ? prnt("V %7s dB]", "inf" ) : prnt("V %6.4lf dB]", dPSNR[COMP_Cr] );
3715
3716
1.43k
      accessUnit.InfoString.append( cInfo );
3717
1.43k
      accessUnit.InfoString.append( yPSNR );
3718
1.43k
      accessUnit.InfoString.append( uPSNR );
3719
1.43k
      accessUnit.InfoString.append( vPSNR );
3720
3721
1.43k
      if ( m_pcEncCfg->m_printHexPsnr )
3722
0
      {
3723
0
        uint64_t xPsnr[MAX_NUM_COMP];
3724
0
        for (int i = 0; i < MAX_NUM_COMP; i++)
3725
0
        {
3726
0
          std::copy(reinterpret_cast<uint8_t *>(&dPSNR[i]),
3727
0
              reinterpret_cast<uint8_t *>(&dPSNR[i]) + sizeof(dPSNR[i]),
3728
0
              reinterpret_cast<uint8_t *>(&xPsnr[i]));
3729
0
        }
3730
3731
0
        std::string yPSNRHex = dPSNR[COMP_Y]  == MAX_DOUBLE ? prnt(" [xY %16s", "inf") : prnt(" [xY %16" PRIx64,  xPsnr[COMP_Y] );
3732
0
        std::string uPSNRHex = dPSNR[COMP_Cb] == MAX_DOUBLE ? prnt(" xU %16s", "inf") : prnt(" xU %16" PRIx64, xPsnr[COMP_Cb] ) ;
3733
0
        std::string vPSNRHex = dPSNR[COMP_Cr] == MAX_DOUBLE ? prnt(" xV %16s]", "inf") : prnt(" xV %16" PRIx64 "]", xPsnr[COMP_Cr]);
3734
3735
0
        accessUnit.InfoString.append( yPSNRHex );
3736
0
        accessUnit.InfoString.append( uPSNRHex );
3737
0
        accessUnit.InfoString.append( vPSNRHex );
3738
0
      }
3739
3740
1.43k
      if( printFrameMSE )
3741
0
      {
3742
0
        std::string cFrameMSE = prnt( " [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMP_Y], MSEyuvframe[COMP_Cb], MSEyuvframe[COMP_Cr]);
3743
0
        accessUnit.InfoString.append( cFrameMSE );
3744
0
      }
3745
3746
1.43k
      std::string cEncTime = prnt(" [ET %5d ]", pic->encTime.getTimerInSec() );
3747
1.43k
      accessUnit.InfoString.append( cEncTime );
3748
3749
1.43k
      std::string cRefPics;
3750
4.29k
      for( int iRefList = 0; iRefList < 2; iRefList++ )
3751
2.86k
      {
3752
2.86k
        std::string tmp = prnt(" [L%d ", iRefList);
3753
2.86k
        cRefPics.append( tmp );
3754
2.86k
        for( int iRefIndex = 0; iRefIndex < slice->numRefIdx[ iRefList ]; iRefIndex++ )
3755
0
        {
3756
0
          tmp = prnt("%d ", slice->getRefPOC( RefPicList( iRefList ), iRefIndex));
3757
0
          cRefPics.append( tmp );
3758
0
        }
3759
2.86k
        cRefPics.append( "]" );
3760
2.86k
      }
3761
1.43k
      accessUnit.InfoString.append( cRefPics );
3762
1.43k
    }
3763
1.43k
  }
3764
1.43k
}
3765
3766
uint64_t EncGOP::xFindDistortionPlane( const CPelBuf& pic0, const CPelBuf& pic1, uint32_t rshift ) const
3767
0
{
3768
0
  uint64_t uiTotalDiff;
3769
0
  const  Pel*  pSrc0 = pic0.bufAt(0, 0);
3770
0
  const  Pel*  pSrc1 = pic1.bufAt(0, 0);
3771
3772
0
  CHECK(pic0.width  != pic1.width , "Unspecified error");
3773
0
  CHECK(pic0.height != pic1.height, "Unspecified error");
3774
3775
0
  if( rshift > 0 )
3776
0
  {
3777
0
    uiTotalDiff = 0;
3778
0
    for (int y = 0; y < pic0.height; y++)
3779
0
    {
3780
0
      for (int x = 0; x < pic0.width; x++)
3781
0
      {
3782
0
        Intermediate_Int iTemp = pSrc0[x] - pSrc1[x];
3783
0
        uiTotalDiff += uint64_t((iTemp * iTemp) >> rshift);
3784
0
      }
3785
0
      pSrc0 += pic0.stride;
3786
0
      pSrc1 += pic1.stride;
3787
0
    }
3788
0
  }
3789
0
  else
3790
0
  {
3791
0
    uiTotalDiff = 0;
3792
0
    for (int y = 0; y < pic0.height; y++)
3793
0
    {
3794
0
      for (int x = 0; x < pic0.width; x++)
3795
0
      {
3796
0
        Intermediate_Int iTemp = pSrc0[x] - pSrc1[x];
3797
0
        uiTotalDiff += uint64_t(iTemp * iTemp);
3798
0
      }
3799
0
      pSrc0 += pic0.stride;
3800
0
      pSrc1 += pic1.stride;
3801
0
    }
3802
0
  }
3803
3804
0
  return uiTotalDiff;
3805
0
}
3806
3807
void EncGOP::xPrintPictureInfo( const Picture& pic, AccessUnitList& accessUnit, const std::string& digestStr, bool printFrameMSE, bool isEncodeLtRef )
3808
1.43k
{
3809
1.43k
  double PSNR_Y;
3810
1.43k
  xAddPSNRStats( &pic, pic.getRecoBuf(), accessUnit, printFrameMSE, &PSNR_Y, isEncodeLtRef );
3811
3812
1.43k
  if( ! m_isPreAnalysis && m_pcRateCtrl->rcIsFinalPass )
3813
1.43k
  {
3814
1.43k
    std::string modeName;
3815
1.43k
    switch ( m_pcEncCfg->m_decodedPictureHashSEIType )
3816
1.43k
    {
3817
0
      case VVENC_HASHTYPE_MD5:
3818
0
      case VVENC_HASHTYPE_MD5_LOG:
3819
0
        modeName = "MD5";
3820
0
        break;
3821
0
      case VVENC_HASHTYPE_CRC:
3822
0
      case VVENC_HASHTYPE_CRC_LOG:
3823
0
        modeName = "CRC";
3824
0
        break;
3825
0
      case VVENC_HASHTYPE_CHECKSUM:
3826
0
      case VVENC_HASHTYPE_CHECKSUM_LOG:
3827
0
        modeName = "Checksum";
3828
0
        break;
3829
1.43k
      default:
3830
1.43k
        break;
3831
1.43k
    }
3832
3833
1.43k
    if ( modeName.length() )
3834
0
    {
3835
0
      std::string cDigist = prnt(" [%s:%s]", modeName.c_str(), digestStr.empty() ? "?" : digestStr.c_str() );
3836
0
      accessUnit.InfoString.append( cDigist );
3837
0
    }
3838
1.43k
  }
3839
3840
1.43k
  if( !accessUnit.InfoString.empty() && m_pcEncCfg->m_verbosity >= VVENC_NOTICE )
3841
0
  {
3842
0
    std::string cPicInfo = accessUnit.InfoString;
3843
0
    cPicInfo.append("\n");
3844
0
    const vvencMsgLevel msgLevel = m_isPreAnalysis ? VVENC_DETAILS : VVENC_NOTICE;
3845
0
    msg.log( msgLevel, cPicInfo.c_str() );
3846
0
    if( m_pcEncCfg->m_verbosity >= msgLevel ) fflush( stdout );
3847
0
  }
3848
1.43k
}
3849
3850
void EncGOP::xForceScc( Picture& pic )
3851
1.43k
{
3852
1.43k
  if( pic.gopEntry->m_isStartOfGop )
3853
1.43k
  {
3854
1.43k
    m_forceSCC = pic.m_picShared->m_forceSCC;
3855
1.43k
  }
3856
1.43k
  if( m_forceSCC && (!pic.isSccStrong || !pic.isSccWeak) )
3857
0
  {
3858
0
    pic.isSccStrong = true;
3859
0
    pic.isSccWeak = true;
3860
0
    pic.setSccFlags(m_pcEncCfg);
3861
0
  }
3862
1.43k
}
3863
3864
} // namespace vvenc
3865
3866
//! \}
3867