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/EncSlice.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     EncSlice.cpp
45
    \brief    slice encoder class
46
*/
47
48
#include "EncSlice.h"
49
#include "EncStage.h"
50
#include "EncLib.h"
51
#include "EncPicture.h"
52
#include "BitAllocation.h"
53
#include "CommonLib/UnitTools.h"
54
#include "CommonLib/Picture.h"
55
#include "CommonLib/TimeProfiler.h"
56
#include "CommonLib/dtrace_codingstruct.h"
57
#include "Utilities/NoMallocThreadPool.h"
58
59
#include <math.h>
60
#include "vvenc/vvencCfg.h"
61
62
//! \ingroup EncoderLib
63
//! \{
64
65
namespace vvenc {
66
67
#ifdef TRACE_ENABLE_ITT
68
static const __itt_domain* itt_domain_encode              = __itt_domain_create( "Encode" );
69
static const __itt_string_handle* itt_handle_ctuEncode    = __itt_string_handle_create( "Encode_CTU" );
70
static const __itt_string_handle* itt_handle_rspLfVer     = __itt_string_handle_create( "RspLfVer_CTU" );
71
static const __itt_string_handle* itt_handle_lfHor        = __itt_string_handle_create( "LfHor_CTU" );
72
static const __itt_string_handle* itt_handle_sao          = __itt_string_handle_create( "SAO_CTU" );
73
static const __itt_string_handle* itt_handle_alf_stat     = __itt_string_handle_create( "ALF_CTU_STAT" );
74
static const __itt_string_handle* itt_handle_alf_derive   = __itt_string_handle_create( "ALF_DERIVE" );
75
static const __itt_string_handle* itt_handle_alf_recon    = __itt_string_handle_create( "ALF_RECONSTRUCT" );
76
static const __itt_string_handle* itt_handle_ccalf_stat   = __itt_string_handle_create( "CCALF_CTU_STAT" );
77
static const __itt_string_handle* itt_handle_ccalf_derive = __itt_string_handle_create( "CCALF_DERIVE" );
78
static const __itt_string_handle* itt_handle_ccalf_recon  = __itt_string_handle_create( "CCALF_RECONSTRUCT" );
79
#endif
80
81
void setArbitraryWppPattern( const PreCalcValues& pcv, std::vector<int>& ctuAddrMap, int stepX = 1 )
82
5.72k
{
83
5.72k
  ctuAddrMap.resize( pcv.sizeInCtus, 0 );
84
5.72k
  std::vector<int> x_in_line( pcv.heightInCtus, 0 );
85
5.72k
  int x = 0, y = 0, addr = 0;
86
5.72k
  int y_top = 0;
87
5.72k
  const int step = stepX; // number of CTUs in x-direction to scan 
88
5.72k
  ctuAddrMap[addr++] = x++; // first entry (can be omitted)
89
13.7k
  while( addr < pcv.sizeInCtus )
90
8.99k
  {
91
    // fill entries in x-direction
92
8.99k
    int x1 = x;
93
21.8k
    while( x < std::min(x1 + step, (int)pcv.widthInCtus) )
94
12.8k
    {
95
      // general WPP condition (top-right CTU availability)
96
12.8k
      if( y > 0 && !( x_in_line[y - 1] - x >= 2 ) && x != pcv.widthInCtus - 1 )
97
0
        break;
98
12.8k
      ctuAddrMap[addr++] = y*pcv.widthInCtus + x;
99
12.8k
      x++;
100
12.8k
    }
101
8.99k
    x_in_line[y] = x;
102
        
103
8.99k
    y += 1;
104
105
8.99k
    if( y >= pcv.heightInCtus )
106
4.48k
    {
107
      // go up
108
4.48k
      if( x_in_line[y_top] >= pcv.widthInCtus )
109
4.48k
      {
110
4.48k
        y_top++;
111
4.48k
        if( y_top >= pcv.heightInCtus )
112
1.01k
        {
113
          // done
114
1.01k
          break;
115
1.01k
        }
116
4.48k
      }
117
3.47k
      y = y_top;
118
3.47k
    }
119
7.98k
    x = x_in_line[y];
120
121
7.98k
    CHECK( y >= pcv.heightInCtus, "Height in CTUs is exceeded" );
122
7.98k
  }
123
5.72k
}
124
125
struct TileLineEncRsrc
126
{
127
  BitEstimator            m_BitEstimator;
128
  CABACWriter             m_CABACEstimator;
129
  BitEstimator            m_SaoBitEstimator;
130
  CABACWriter             m_SaoCABACEstimator;
131
  BitEstimator            m_AlfBitEstimator;
132
  CABACWriter             m_AlfCABACEstimator;
133
  ReuseUniMv              m_ReuseUniMv;
134
  BlkUniMvInfoBuffer      m_BlkUniMvInfoBuffer;
135
  AffineProfList          m_AffineProfList;
136
  IbcBvCand               m_CachedBvs;
137
  EncSampleAdaptiveOffset m_encSao;
138
  int                     m_prevQp[ MAX_NUM_CH ];
139
10.2k
  TileLineEncRsrc( const VVEncCfg& encCfg ) : m_CABACEstimator( m_BitEstimator ), m_SaoCABACEstimator( m_SaoBitEstimator ), m_AlfCABACEstimator( m_AlfBitEstimator ) { m_AffineProfList.init( ! encCfg.m_picReordering ); }
140
};
141
142
struct PerThreadRsrc
143
{
144
  CtxCache  m_CtxCache;
145
  EncCu     m_encCu;
146
  PelStorage m_alfTempCtuBuf;
147
  PelStorage m_saoCtuBuf;      ///< pre-SAO samples of the CTU being filtered, see EncSampleAdaptiveOffset::loadCtuPreSao
148
};
149
150
ThreadRsrcPool::~ThreadRsrcPool()
151
1.43k
{
152
1.43k
  for( PerThreadRsrc* set : m_sets )
153
5.72k
  {
154
5.72k
    set->m_alfTempCtuBuf.destroy();
155
5.72k
    delete set;
156
5.72k
  }
157
1.43k
  m_sets.clear();
158
1.43k
}
159
160
void ThreadRsrcPool::init( const VVEncCfg& encCfg, const SPS& sps, const PPS& pps, std::vector<int>* const globalCtuQpVector, RateCtrl& rateCtrl, const int numSets )
161
1.43k
{
162
1.43k
  CHECK( !m_sets.empty(), "thread resources are already initialized" );
163
164
  // The quantizers of all sets share the read-only tables of the first set's quantizer.
165
1.43k
  TrQuant* firstTrQuant = nullptr;
166
167
1.43k
  m_sets.resize( numSets, nullptr );
168
1.43k
  for( PerThreadRsrc*& set : m_sets )
169
5.72k
  {
170
5.72k
    set = new PerThreadRsrc();
171
5.72k
    set->m_encCu.init( encCfg, sps, globalCtuQpVector, &rateCtrl, firstTrQuant );
172
5.72k
    firstTrQuant = firstTrQuant ? firstTrQuant : &set->m_encCu.getTrQuant();
173
5.72k
    set->m_alfTempCtuBuf.create( pps.pcv->chrFormat, Area( 0, 0, pps.pcv->maxCUSize + (MAX_ALF_PADDING_SIZE << 1), pps.pcv->maxCUSize + (MAX_ALF_PADDING_SIZE << 1) ), pps.pcv->maxCUSize, MAX_ALF_PADDING_SIZE, 0, false );
174
5.72k
    if( encCfg.m_bUseSAO )
175
5.72k
    {
176
5.72k
      set->m_saoCtuBuf.create( pps.pcv->chrFormat, Area( 0, 0, pps.pcv->maxCUSize, pps.pcv->maxCUSize ), 0, SAO_CTU_BUF_MARGIN, 0, false );
177
5.72k
    }
178
5.72k
  }
179
1.43k
}
180
181
struct CtuEncParam
182
{
183
  Picture*  pic;
184
  EncSlice* encSlice;
185
  int       ctuRsAddr;
186
  int       ctuPosX;
187
  int       ctuPosY;
188
  UnitArea  ctuArea;
189
  int       tileLineResIdx;
190
191
18.6k
  CtuEncParam() : pic( nullptr ), encSlice( nullptr ), ctuRsAddr( 0 ), ctuPosX( 0 ), ctuPosY( 0 ), ctuArea(), tileLineResIdx( 0 ) {}
192
  CtuEncParam( Picture* _p, EncSlice* _s, const int _r, const int _x, const int _y, const int _tileLineResIdx )
193
    : pic( _p )
194
    , encSlice( _s )
195
    , ctuRsAddr( _r )
196
    , ctuPosX( _x )
197
    , ctuPosY( _y )
198
    , ctuArea( pic->chromaFormat, pic->slices[0]->pps->pcv->getCtuArea( _x, _y ) )
199
0
    , tileLineResIdx( _tileLineResIdx ) {}
200
};
201
202
// ====================================================================================================================
203
// Constructor / destructor / create / destroy
204
// ====================================================================================================================
205
206
EncSlice::EncSlice()
207
5.72k
  : m_pcEncCfg           ( nullptr)
208
5.72k
  , m_threadRsrc         ( nullptr )
209
5.72k
  , m_globalCtuQpVector  ( nullptr )
210
5.72k
  , m_threadPool         ( nullptr )
211
5.72k
  , m_ctuTasksDoneCounter( nullptr )
212
5.72k
  , m_ctuEncDelay        ( 1 )
213
5.72k
  , m_pLoopFilter        ( nullptr )
214
5.72k
  , m_pALF               ( nullptr )
215
5.72k
  , m_pcRateCtrl         ( nullptr )
216
5.72k
  , m_CABACWriter        ( m_BinEncoder )
217
5.72k
  , m_encCABACTableIdx   ( VVENC_I_SLICE )
218
5.72k
{
219
5.72k
}
220
221
222
EncSlice::~EncSlice()
223
5.72k
{
224
5.72k
  for( auto* lnRsc : m_TileLineEncRsrc )
225
10.2k
  {
226
10.2k
    delete lnRsc;
227
10.2k
  }
228
5.72k
  m_TileLineEncRsrc.clear();
229
230
5.72k
  m_saoReconParams.clear();
231
232
24.3k
  for( int i = 0; i < m_saoStatData.size(); i++ )
233
18.6k
  {
234
74.4k
    for( int compIdx = 0; compIdx < MAX_NUM_COMP; compIdx++ )
235
55.8k
    {
236
55.8k
      delete[] m_saoStatData[ i ][ compIdx ];
237
55.8k
    }
238
18.6k
    delete[] m_saoStatData[ i ];
239
18.6k
  }
240
5.72k
  m_saoStatData.clear();
241
5.72k
}
242
243
void EncSlice::init( const VVEncCfg& encCfg,
244
                     const SPS& sps,
245
                     const PPS& pps,
246
                     std::vector<int>* const globalCtuQpVector,
247
                     LoopFilter& loopFilter,
248
                     EncAdaptiveLoopFilter& alf,
249
                     RateCtrl& rateCtrl,
250
                     NoMallocThreadPool* threadPool,
251
                     ThreadRsrcPool& threadRsrc,
252
                     WaitCounter* ctuTasksDoneCounter )
253
5.72k
{
254
5.72k
  m_pcEncCfg            = &encCfg;
255
5.72k
  m_pLoopFilter         = &loopFilter;
256
5.72k
  m_pALF                = &alf;
257
5.72k
  m_pcRateCtrl          = &rateCtrl;
258
5.72k
  m_threadPool          = threadPool;
259
5.72k
  m_threadRsrc          = &threadRsrc;
260
5.72k
  m_globalCtuQpVector   = globalCtuQpVector;
261
5.72k
  m_ctuTasksDoneCounter = ctuTasksDoneCounter;
262
5.72k
  m_syncPicCtx.resize( encCfg.m_entropyCodingSyncEnabled ? pps.getNumTileLineIds() : 0 );
263
264
  
265
5.72k
  const int maxCntRscr = ( encCfg.m_numThreads > 0 ) ? pps.getNumTileLineIds() : 1;
266
267
5.72k
  m_TileLineEncRsrc.resize( maxCntRscr, nullptr );
268
269
5.72k
  for( TileLineEncRsrc*& lnRsc : m_TileLineEncRsrc )
270
10.2k
  {
271
10.2k
    lnRsc = new TileLineEncRsrc( encCfg );
272
10.2k
    if( sps.saoEnabled )
273
10.2k
    {
274
10.2k
      lnRsc->m_encSao.init( encCfg );
275
10.2k
    }
276
10.2k
  }
277
278
  // the bottom rows of every CTU line one after another; the margin holds the top-left samples left of the picture
279
5.72k
  const PreCalcValues& pcv = *pps.pcv;
280
5.72k
  m_ctuLineBottoms.create( pcv.chrFormat, Area( 0, 0, pcv.widthInCtus << pcv.maxCUSizeLog2, pcv.heightInCtus * Picture::CTU_LINE_BOTTOM_ROWS ), 0, Picture::CTU_LINE_BOTTOM_ROWS );
281
282
5.72k
  const int sizeInCtus = pps.pcv->sizeInCtus;
283
5.72k
  m_processStates = std::vector<ProcessCtuState>( sizeInCtus );
284
5.72k
  m_saoReconParams.resize( sizeInCtus );
285
5.72k
  if( encCfg.m_bUseSAO )
286
5.72k
  {
287
5.72k
    m_saoPreFilterEdges.create( pps.pcv->chrFormat, *pps.pcv );
288
5.72k
  }
289
290
5.72k
  ::memset( m_saoDisabledRate, 0, sizeof( m_saoDisabledRate ) );
291
292
  // sao statistics
293
5.72k
  if( encCfg.m_bUseSAO )
294
5.72k
  {
295
5.72k
    m_saoStatData.resize( sizeInCtus );
296
24.3k
    for( int i = 0; i < sizeInCtus; i++ )
297
18.6k
    {
298
18.6k
      m_saoStatData[ i ] = new SAOStatData*[ MAX_NUM_COMP ];
299
74.4k
      for( int compIdx = 0; compIdx < MAX_NUM_COMP; compIdx++ )
300
55.8k
      {
301
55.8k
        m_saoStatData[ i ][ compIdx ] = new SAOStatData[ NUM_SAO_NEW_TYPES ];
302
55.8k
      }
303
18.6k
    }
304
5.72k
  }
305
5.72k
  ctuEncParams.resize( sizeInCtus );
306
5.72k
  setArbitraryWppPattern( *pps.pcv, m_ctuAddrMap, 3 );
307
308
5.72k
  const unsigned asuHeightInCtus = m_pALF->getAsuHeightInCtus();
309
5.72k
  const unsigned numDeriveLines  = encCfg.m_ifpLines ? 
310
5.72k
    std::min( ((encCfg.m_ifpLines & (~(asuHeightInCtus - 1))) + asuHeightInCtus), pps.pcv->heightInCtus ) : pps.pcv->heightInCtus;
311
5.72k
  m_alfDeriveCtu  = numDeriveLines * pps.pcv->widthInCtus - 1;
312
5.72k
  m_ccalfDeriveCtu = encCfg.m_ifpLines ? pps.pcv->widthInCtus * std::min((unsigned)encCfg.m_ifpLines + 1, pps.pcv->heightInCtus) - 1: pps.pcv->sizeInCtus - 1;
313
5.72k
}
314
315
316
void EncSlice::initPic( Picture* pic )
317
1.43k
{
318
1.43k
  Slice* slice = pic->cs->slice;
319
320
1.43k
  if( slice->pps->numTileCols * slice->pps->numTileRows > 1 )
321
0
  {
322
0
    slice->sliceMap = slice->pps->sliceMap[0];
323
0
  }
324
1.43k
  else
325
1.43k
  {
326
1.43k
    slice->sliceMap.addCtusToSlice( 0, pic->cs->pcv->widthInCtus, 0, pic->cs->pcv->heightInCtus, pic->cs->pcv->widthInCtus);
327
1.43k
  }
328
329
  // this ensures that independently encoded bitstream chunks can be combined to bit-equal
330
1.43k
  const SliceType cabacTableIdx = ! slice->pps->cabacInitPresent || slice->pendingRasInit ? slice->sliceType : m_encCABACTableIdx;
331
1.43k
  slice->encCABACTableIdx = cabacTableIdx;
332
333
  // set QP and lambda values
334
1.43k
  xInitSliceLambdaQP( slice );
335
336
  // Worker threads apply this state to their CU encoders when they reach the picture's CTUs. The id
337
  // tells pictures apart, also when this slice encoder is reused for the next picture.
338
1.43k
  static std::atomic<uint64_t> lastPicEncStateId{ 0 };
339
1.43k
  m_picEncState.pic        = pic;
340
1.43k
  m_picEncState.id         = ++lastPicEncStateId;
341
1.43k
  m_picEncState.syncPicCtx = m_syncPicCtx.data();
342
1.43k
  pic->m_ctuLineBottoms    = &m_ctuLineBottoms;
343
344
1.43k
  for( auto* lnRsc : m_TileLineEncRsrc )
345
2.55k
  {
346
2.55k
    lnRsc->m_ReuseUniMv.resetReusedUniMvs();
347
2.55k
  }
348
349
1.43k
  m_ctuEncDelay = 1;
350
1.43k
  if( pic->useIBC )
351
1.43k
  {
352
    // IBC needs unfiltered samples up to max IBC search range
353
    // therefore ensure that numCtuDelayLUT CTU's have been enocded first
354
    // assuming IBC localSearchRangeX / Y = 128
355
1.43k
    const int numCtuDelayLUT[ 3 ] = { 15, 3, 1 };
356
1.43k
    CHECK( pic->cs->pcv->maxCUSizeLog2 < 5 || pic->cs->pcv->maxCUSizeLog2 > 7, "invalid max CTUSize" );
357
1.43k
    m_ctuEncDelay = numCtuDelayLUT[ pic->cs->pcv->maxCUSizeLog2 - 5 ];
358
1.43k
  }
359
1.43k
}
360
361
362
363
void EncSlice::xInitSliceLambdaQP( Slice* slice )
364
1.43k
{
365
  // pre-compute lambda and QP
366
1.43k
  const bool rcp = (m_pcEncCfg->m_RCTargetBitrate > 0 && slice->pic->picInitialQP >= 0); // 2nd pass
367
1.43k
  int  iQP = Clip3 (-slice->sps->qpBDOffset[CH_L], MAX_QP, slice->pic->picInitialQP); // RC start QP
368
1.43k
  double dQP     = (rcp ? (double) slice->pic->picInitialQP : xGetQPForPicture (slice));
369
370
  // A fractional QP gives a fractional picture QP. Its integer part sets the slice QP and lambda as for an integer QP,
371
  // and its fraction raises some blocks or pictures by one QP: with QPA, the CTUs whose activity-based QP lies closest
372
  // to the next integer, see BitAllocation::applyQPAdaptationSlice; without QPA, a share of the pictures equal to the
373
  // fraction. Each block keeps the lambda of its integer QP, so the RD trade-off stays consistent.
374
1.43k
  slice->pic->picQPFraction = dQP - floor (dQP);
375
1.43k
  dQP -= slice->pic->picQPFraction;
376
1.43k
  if (!m_pcEncCfg->m_usePerceptQPA)
377
0
  {
378
    // The thresholds come from the low-discrepancy sequence frac(POC * (sqrt(2) - 1)), whose values stay evenly
379
    // spread also for the power-of-two POC spacing of one temporal layer, so every layer gets its share of raised QPs.
380
0
    const double ditherPos = slice->poc * 0.41421356237309515;
381
382
0
    if (slice->pic->picQPFraction > ditherPos - floor (ditherPos)) dQP += 1.0;
383
0
    slice->pic->picQPFraction = 0.0;
384
0
  }
385
386
1.43k
  double dLambda = (rcp ? slice->pic->picInitialLambda : xCalculateLambda (slice, slice->TLayer, dQP, dQP, iQP));
387
1.43k
  int sliceChromaQpOffsetIntraOrPeriodic[2] = { m_pcEncCfg->m_sliceChromaQpOffsetIntraOrPeriodic[0], m_pcEncCfg->m_sliceChromaQpOffsetIntraOrPeriodic[1] };
388
1.43k
  const int lookAheadRCCQpOffset = 0;   // was (m_pcEncCfg->m_RCTargetBitrate > 0 && m_pcEncCfg->m_LookAhead && CS::isDualITree (*slice->pic->cs) ? 1 : 0);
389
1.43k
  int cbQP = 0, crQP = 0, cbCrQP = 0;
390
391
1.43k
  if (m_pcEncCfg->m_usePerceptQPA) // adapt sliceChromaQpOffsetIntraOrPeriodic and pic->ctuAdaptedQP
392
1.43k
  {
393
1.43k
    const bool cqp = (slice->isIntra() && !slice->sps->IBC) || (m_pcEncCfg->m_sliceChromaQpOffsetPeriodicity > 0 && (slice->poc % m_pcEncCfg->m_sliceChromaQpOffsetPeriodicity) == 0);
394
1.43k
    const uint32_t startCtuTsAddr    = slice->sliceMap.ctuAddrInSlice[0];
395
1.43k
    const uint32_t boundingCtuTsAddr = slice->pic->cs->pcv->sizeInCtus;
396
397
1.43k
    if ((iQP = BitAllocation::applyQPAdaptationSlice (slice, m_pcEncCfg, iQP, dLambda, &slice->pic->picVA.visAct, // updates pic->picInitialQP
398
1.43k
                                                      *m_globalCtuQpVector, m_pcRateCtrl->getIntraPQPAStats(),
399
1.43k
                                                      (slice->pps->sliceChromaQpFlag && cqp ? sliceChromaQpOffsetIntraOrPeriodic : nullptr),
400
1.43k
                                                      m_pcRateCtrl->getMinNoiseLevels(), startCtuTsAddr, boundingCtuTsAddr)) != BitAllocation::QPA_QP_NOT_SET) // QP OK?
401
1.43k
    {
402
1.43k
      dLambda *= pow (2.0, ((double) iQP - dQP) / 3.0); // adjust lambda based on change of slice QP
403
1.43k
    }
404
0
    else iQP = (int) dQP; // revert to unadapted slice QP
405
1.43k
  }
406
0
  else if (rcp)
407
0
  {
408
0
    slice->pic->picInitialQP = -1; // no QPA - unused now
409
0
  }
410
411
1.43k
  if (slice->pps->sliceChromaQpFlag && CS::isDualITree (*slice->pic->cs) && !m_pcEncCfg->m_usePerceptQPA && (m_pcEncCfg->m_sliceChromaQpOffsetPeriodicity == 0))
412
0
  {
413
0
    cbQP = m_pcEncCfg->m_chromaCbQpOffsetDualTree + lookAheadRCCQpOffset; // QP offset for dual-tree
414
0
    crQP = m_pcEncCfg->m_chromaCrQpOffsetDualTree + lookAheadRCCQpOffset;
415
0
    cbCrQP = m_pcEncCfg->m_chromaCbCrQpOffsetDualTree + lookAheadRCCQpOffset;
416
0
  }
417
1.43k
  else if (slice->pps->sliceChromaQpFlag)
418
1.43k
  {
419
1.43k
    const GOPEntry &gopEntry             = *(slice->pic->gopEntry);
420
1.43k
    const bool bUseIntraOrPeriodicOffset = (slice->isIntra() && !slice->sps->IBC) || (m_pcEncCfg->m_sliceChromaQpOffsetPeriodicity > 0 && (slice->poc % m_pcEncCfg->m_sliceChromaQpOffsetPeriodicity) == 0);
421
422
1.43k
    cbQP = (bUseIntraOrPeriodicOffset ? sliceChromaQpOffsetIntraOrPeriodic[0] : gopEntry.m_CbQPoffset) + lookAheadRCCQpOffset;
423
1.43k
    crQP = (bUseIntraOrPeriodicOffset ? sliceChromaQpOffsetIntraOrPeriodic[1] : gopEntry.m_CrQPoffset) + lookAheadRCCQpOffset;
424
1.43k
    cbCrQP = (cbQP + crQP) >> 1; // use floor of average CbCr chroma QP offset for joint-CbCr coding
425
426
1.43k
    cbQP = Clip3 (-12, 12, cbQP + slice->pps->chromaQpOffset[COMP_Cb]) - slice->pps->chromaQpOffset[COMP_Cb];
427
1.43k
    crQP = Clip3 (-12, 12, crQP + slice->pps->chromaQpOffset[COMP_Cr]) - slice->pps->chromaQpOffset[COMP_Cr];
428
1.43k
    cbCrQP = Clip3 (-12, 12, cbCrQP + slice->pps->chromaQpOffset[COMP_JOINT_CbCr]) - slice->pps->chromaQpOffset[COMP_JOINT_CbCr];
429
1.43k
  }
430
431
1.43k
  slice->sliceChromaQpDelta[COMP_Cb] = Clip3 (-12, 12, cbQP);
432
1.43k
  slice->sliceChromaQpDelta[COMP_Cr] = Clip3 (-12, 12, crQP);
433
1.43k
  slice->sliceChromaQpDelta[COMP_JOINT_CbCr] = (slice->sps->jointCbCr ? Clip3 (-12, 12, cbCrQP) : 0);
434
435
  // SAO and ALF use the slice lambdas. The CU encoders get the picture lambda when a worker
436
  // thread binds them to this picture.
437
1.43k
  double dLambdas[MAX_NUM_COMP];
438
1.43k
  double weights [MAX_NUM_COMP];
439
1.43k
  EncCu::deriveComponentLambdas( *m_pcEncCfg, *slice, dLambda, iQP, dLambdas, weights );
440
1.43k
  slice->setLambdas( dLambdas );
441
1.43k
  m_picEncState.lambda = dLambda;
442
1.43k
  m_picEncState.qp     = iQP;
443
444
1.43k
  slice->sliceQp            = iQP;
445
1.43k
  slice->chromaQpAdjEnabled = slice->pps->chromaQpOffsetListLen > 0;
446
1.43k
}
447
448
static constexpr int MAX_DEF_TL_QP_OFFSET = 5; // deeper temporal layers (GOP 64) use the last offset
449
static constexpr int highTL[MAX_DEF_TL_QP_OFFSET + 1] = { -1, 0, 0, 2, 4, 5 };
450
451
// The picture QP before block QP offsets: the base QP plus the offset of the picture's temporal layer.
452
int EncSlice::getCascadeQP( const VVEncCfg& encCfg, const GOPEntry& gopEntry, const bool isIntra, int qp, const int lumaQpBDOffset )
453
1.43k
{
454
1.43k
  if (encCfg.m_usePerceptQPA)
455
1.43k
  {
456
1.43k
    const int tlayer = gopEntry.m_vtl;
457
458
1.43k
    qp = (isIntra ? std::min (qp, ((qp - std::min (3, floorLog2 (encCfg.m_GOPSize) - 4/*TODO 3 with JVET-AC0149?*/)) * 15 + 3) >> 4) : highTL[std::min (tlayer, MAX_DEF_TL_QP_OFFSET)] + ((qp * (16 + std::min (2, tlayer))) >> 4) + 0/*TODO +-1?*/);
459
1.43k
  }
460
0
  else if( isIntra )
461
0
  {
462
0
    qp += encCfg.m_intraQPOffset;
463
0
  }
464
0
  else
465
0
  {
466
0
    if( qp != -lumaQpBDOffset )
467
0
    {
468
      // adjust QP according to the QP offset for the GOP entry.
469
0
      qp += gopEntry.m_QPOffset;
470
471
      // adjust QP according to QPOffsetModel for the GOP entry.
472
0
      double dqpOffset = qp * gopEntry.m_QPOffsetModelScale + gopEntry.m_QPOffsetModelOffset + 0.5;
473
0
      int qpOffset = (int)floor( Clip3<double>( 0.0, 3.0, dqpOffset ) );
474
0
      qp += qpOffset;
475
0
    }
476
0
  }
477
1.43k
  return qp;
478
1.43k
}
479
480
double EncSlice::xGetQPForPicture( const Slice* slice )
481
1.43k
{
482
1.43k
  const int qp = xGetQPForPicture( slice, m_pcEncCfg->m_QP );
483
484
1.43k
  if( m_pcEncCfg->m_QPFraction <= 0.0 || m_pcEncCfg->m_costMode == VVENC_COST_LOSSLESS_CODING )
485
1.43k
  {
486
1.43k
    return qp;
487
1.43k
  }
488
  // With a fractional QP, interpolate linearly between the picture QPs of the two neighbouring integer QPs. The
489
  // per-picture QP rules (temporal layer scaling, offsets, clipping) are integer functions of the base QP, and the
490
  // interpolation keeps the result between them, so the rate moves smoothly from one integer QP to the next.
491
0
  const int qpNext = xGetQPForPicture( slice, m_pcEncCfg->m_QP + 1 );
492
493
0
  return qp + m_pcEncCfg->m_QPFraction * ( qpNext - qp );
494
1.43k
}
495
496
int EncSlice::xGetQPForPicture( const Slice* slice, const int baseQP )
497
1.43k
{
498
1.43k
  const int lumaQpBDOffset = slice->sps->qpBDOffset[ CH_L ];
499
1.43k
  int qp;
500
501
1.43k
  if ( m_pcEncCfg->m_costMode == VVENC_COST_LOSSLESS_CODING )
502
0
  {
503
0
    qp = LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP;
504
0
  }
505
1.43k
  else
506
1.43k
  {
507
1.43k
    qp = getCascadeQP( *m_pcEncCfg, *slice->pic->gopEntry, slice->isIntra(), baseQP + slice->pic->gopAdaptedQP, lumaQpBDOffset );
508
509
1.43k
    if( m_pcEncCfg->hasBlockQpOffsets() && !slice->pic->m_picShared->m_ctuBimQpOffset.empty() )
510
0
    {
511
0
      qp += slice->pic->m_picShared->m_picAuxQpOffset;
512
0
    }
513
1.43k
  }
514
1.43k
  qp = Clip3( -lumaQpBDOffset, MAX_QP, qp );
515
1.43k
  return qp;
516
1.43k
}
517
518
519
double EncSlice::xCalculateLambda( const Slice* slice,
520
                                   const int    depth, // slice GOP hierarchical depth.
521
                                   const double refQP, // initial slice-level QP
522
                                   const double dQP,   // initial double-precision QP
523
                                         int&   iQP )  // returned integer QP.
524
1.43k
{
525
1.43k
  const GOPEntry &gopEntry = *(slice->pic->gopEntry);
526
1.43k
  const int SHIFT_QP       = 12;
527
1.43k
  const int temporalId     = gopEntry.m_temporalId;
528
1.43k
  std::vector<double> intraLambdaModifiers;
529
1.43k
  for ( int i = 0; i < VVENC_MAX_TLAYER; i++ )
530
1.43k
  {
531
1.43k
    if( m_pcEncCfg->m_adIntraLambdaModifier[i] != 0.0 ) intraLambdaModifiers.push_back( m_pcEncCfg->m_adIntraLambdaModifier[i] );
532
1.43k
    else break;
533
1.43k
  }
534
535
1.43k
  int bitdepth_luma_qp_scale = 6
536
1.43k
                               * (slice->sps->bitDepths[ CH_L ] - 8
537
1.43k
                                  - DISTORTION_PRECISION_ADJUSTMENT(slice->sps->bitDepths[ CH_L ]));
538
1.43k
  double qp_temp = dQP + bitdepth_luma_qp_scale - SHIFT_QP;
539
  // Case #1: I or P-slices (key-frame)
540
1.43k
  double dQPFactor = gopEntry.m_QPFactor;
541
1.43k
  if( slice->sliceType == VVENC_I_SLICE )
542
1.43k
  {
543
1.43k
    if (m_pcEncCfg->m_dIntraQpFactor>=0.0 && gopEntry.m_sliceType != 'I')
544
0
    {
545
0
      dQPFactor = m_pcEncCfg->m_dIntraQpFactor;
546
0
    }
547
1.43k
    else
548
1.43k
    {
549
1.43k
      dQPFactor = 0.57;
550
1.43k
      if( ! m_pcEncCfg->m_lambdaFromQPEnable )
551
0
      {
552
0
        const int NumberBFrames = ( m_pcEncCfg->m_GOPSize - 1 );
553
0
        const double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05 * (double)NumberBFrames );
554
0
        dQPFactor *= dLambda_scale;
555
0
      }
556
1.43k
    }
557
1.43k
  }
558
0
  else if( m_pcEncCfg->m_lambdaFromQPEnable )
559
0
  {
560
0
    dQPFactor=0.57;
561
0
  }
562
563
1.43k
  double dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
564
565
1.43k
  if( !(m_pcEncCfg->m_lambdaFromQPEnable) && depth>0 )
566
0
  {
567
0
    double qp_temp_ref = refQP + bitdepth_luma_qp_scale - SHIFT_QP;
568
0
    dLambda *= Clip3(2.00, 4.00, (qp_temp_ref / 6.0));   // (j == B_SLICE && p_cur_frm->layer != 0 )
569
0
  }
570
571
  // if hadamard is used in ME process
572
1.43k
  if ( !m_pcEncCfg->m_bUseHADME && slice->sliceType != VVENC_I_SLICE )
573
0
  {
574
0
    dLambda *= 0.95;
575
0
  }
576
577
1.43k
  double lambdaModifier;
578
1.43k
  if( slice->sliceType != VVENC_I_SLICE || intraLambdaModifiers.empty())
579
1.43k
  {
580
1.43k
    lambdaModifier = m_pcEncCfg->m_adLambdaModifier[ temporalId ];
581
1.43k
  }
582
0
  else
583
0
  {
584
0
    lambdaModifier = intraLambdaModifiers[ (temporalId < intraLambdaModifiers.size()) ? temporalId : (intraLambdaModifiers.size()-1) ];
585
0
  }
586
1.43k
  dLambda *= lambdaModifier;
587
588
1.43k
  iQP = Clip3( -slice->sps->qpBDOffset[ CH_L ], MAX_QP, (int) floor( dQP + 0.5 ) );
589
590
1.43k
  if( m_pcEncCfg->m_DepQuantEnabled )
591
1.43k
  {
592
1.43k
    dLambda *= pow( 2.0, 0.25/3.0 ); // slight lambda adjustment for dependent quantization (due to different slope of quantizer)
593
1.43k
  }
594
595
  // NOTE: the lambda modifiers that are sometimes applied later might be best always applied in here.
596
1.43k
  return dLambda;
597
1.43k
}
598
599
600
// ====================================================================================================================
601
// Public member functions
602
// ====================================================================================================================
603
604
605
/** \param pic   picture class
606
 */
607
void EncSlice::compressSlice( Picture* pic )
608
1.43k
{
609
1.43k
  PROFILER_SCOPE_AND_STAGE( 1, g_timeProfiler, P_COMPRESS_SLICE );
610
1.43k
  CodingStructure& cs         = *pic->cs;
611
1.43k
  Slice* const slice          = cs.slice;
612
1.43k
  uint32_t  startCtuTsAddr    = slice->sliceMap.ctuAddrInSlice[0];
613
1.43k
  uint32_t  boundingCtuTsAddr = pic->cs->pcv->sizeInCtus;
614
615
1.43k
  cs.pcv      = slice->pps->pcv;
616
1.43k
  cs.fracBits = 0;
617
618
1.43k
  if( startCtuTsAddr == 0 )
619
1.43k
  {
620
1.43k
    cs.initStructData( slice->sliceQp );
621
1.43k
  }
622
623
1.43k
  for( auto* lnRsrc : m_TileLineEncRsrc )
624
2.55k
  {
625
2.55k
    lnRsrc->m_CABACEstimator    .initCtxModels( *slice );
626
2.55k
    lnRsrc->m_SaoCABACEstimator .initCtxModels( *slice );
627
2.55k
    lnRsrc->m_AlfCABACEstimator .initCtxModels( *slice );
628
2.55k
    lnRsrc->m_AffineProfList    .resetAffineMVList();
629
2.55k
    lnRsrc->m_BlkUniMvInfoBuffer.resetUniMvList();
630
2.55k
    lnRsrc->m_CachedBvs         .resetIbcBvCand();
631
632
2.55k
    if( slice->sps->saoEnabled && pic->useSAO )
633
2.55k
    {
634
2.55k
      lnRsrc->m_encSao          .initSlice( slice );
635
2.55k
    }
636
2.55k
  }
637
638
1.43k
  if( slice->sps->fpelMmvd && !slice->picHeader->disFracMMVD )
639
1.43k
  {
640
1.43k
    slice->picHeader->disFracMMVD = ( pic->lwidth() * pic->lheight() > 1920 * 1080 ) ? true : false;
641
1.43k
  }
642
643
1.43k
  xProcessCtus( pic, startCtuTsAddr, boundingCtuTsAddr );
644
1.43k
}
645
646
void setJointCbCrModes( CodingStructure& cs, const Position topLeftLuma, const Size sizeLuma )
647
1.43k
{
648
1.43k
  bool              sgnFlag = true;
649
650
1.43k
  if( isChromaEnabled( cs.picture->chromaFormat) )
651
1.43k
  {
652
1.43k
    const CompArea  cbArea  = CompArea( COMP_Cb, cs.picture->chromaFormat, Area(topLeftLuma,sizeLuma), true );
653
1.43k
    const CompArea  crArea  = CompArea( COMP_Cr, cs.picture->chromaFormat, Area(topLeftLuma,sizeLuma), true );
654
655
1.43k
    const CPelBuf   orgCb   = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getFiltOrigBuf( cbArea ): cs.picture->getOrigBuf( cbArea );
656
1.43k
    const CPelBuf   orgCr   = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getFiltOrigBuf( crArea ): cs.picture->getOrigBuf( crArea );
657
1.43k
    const int       x0      = ( cbArea.x > 0 ? 0 : 1 );
658
1.43k
    const int       y0      = ( cbArea.y > 0 ? 0 : 1 );
659
1.43k
    const int       x1      = ( cbArea.x + cbArea.width  < cs.picture->Cb().width  ? cbArea.width  : cbArea.width  - 1 );
660
1.43k
    const int       y1      = ( cbArea.y + cbArea.height < cs.picture->Cb().height ? cbArea.height : cbArea.height - 1 );
661
1.43k
    const int       cbs     = orgCb.stride;
662
1.43k
    const int       crs     = orgCr.stride;
663
1.43k
    const Pel*      pCb     = orgCb.buf + y0 * cbs + x0;
664
1.43k
    const Pel*      pCr     = orgCr.buf + y0 * crs + x0;
665
666
    // determine inter-chroma transform sign from correlation between high-pass filtered (i.e., zero-mean) Cb and Cr planes
667
1.43k
    const int64_t   sumCbCr = g_pelBufOP.highPassCorrelation( pCb, cbs, pCr, crs, x1 - x0, y1 - y0, cs.sps->bitDepths[CH_C] );
668
669
1.43k
    sgnFlag = ( sumCbCr < 0 );
670
1.43k
  }
671
672
1.43k
  cs.slice->picHeader->jointCbCrSign = sgnFlag;
673
1.43k
}
674
675
struct CtuPos
676
{
677
  const int ctuPosX;
678
  const int ctuPosY;
679
  const int ctuRsAddr;
680
681
4.65k
  CtuPos( int _x, int _y, int _a ) : ctuPosX( _x ), ctuPosY( _y ), ctuRsAddr( _a ) {}
682
};
683
684
class CtuTsIterator
685
{
686
  private:
687
    const CodingStructure& cs;
688
    const int        m_startTsAddr;
689
    const int        m_endTsAddr;
690
    std::vector<int> m_ctuAddrMap;
691
          int        m_ctuTsAddr;
692
693
  private:
694
    int getNextTsAddr( const int _tsAddr ) const
695
4.65k
    {
696
4.65k
      const PreCalcValues& pcv  = *cs.pcv;
697
4.65k
      const int startSliceRsRow = m_startTsAddr / pcv.widthInCtus;
698
4.65k
      const int startSliceRsCol = m_startTsAddr % pcv.widthInCtus;
699
4.65k
      const int endSliceRsRow   = (m_endTsAddr - 1) / pcv.widthInCtus;
700
4.65k
      const int endSliceRsCol   = (m_endTsAddr - 1) % pcv.widthInCtus;
701
4.65k
            int ctuTsAddr = _tsAddr;
702
4.65k
      CHECK( ctuTsAddr > m_endTsAddr, "error: array index out of bounds" );
703
6.08k
      while( ctuTsAddr < m_endTsAddr )
704
4.65k
      {
705
4.65k
        ctuTsAddr++;
706
4.65k
        const int ctuRsAddr = ctuTsAddr; 
707
4.65k
        if( cs.slice->pps->rectSlice
708
4.65k
            && ( (ctuRsAddr / pcv.widthInCtus) < startSliceRsRow
709
4.65k
              || (ctuRsAddr / pcv.widthInCtus) > endSliceRsRow
710
3.22k
              || (ctuRsAddr % pcv.widthInCtus) < startSliceRsCol
711
3.22k
              || (ctuRsAddr % pcv.widthInCtus) > endSliceRsCol ) )
712
1.43k
          continue;
713
3.22k
        break;
714
4.65k
      }
715
4.65k
      return ctuTsAddr;
716
4.65k
    }
717
718
    int mapAddr( const int _addr ) const
719
4.65k
    {
720
4.65k
      if( _addr < 0 )
721
0
        return _addr;
722
4.65k
      if( _addr >= m_ctuAddrMap.size() )
723
0
        return _addr;
724
4.65k
      return m_ctuAddrMap[ _addr ];
725
4.65k
    }
726
727
  public:
728
1.43k
    CtuTsIterator( const CodingStructure& _cs, int _s, int _e,       std::vector<int>& _m         ) : cs( _cs ), m_startTsAddr( _s ), m_endTsAddr( _e ), m_ctuAddrMap( _m ), m_ctuTsAddr( _s ) {}
729
0
    CtuTsIterator( const CodingStructure& _cs, int _s, int _e, bool _wpp                          ) : cs( _cs ), m_startTsAddr( _s ), m_endTsAddr( _e ),                     m_ctuTsAddr( _s ) { if( _wpp ) setWppPattern(); }
730
0
    CtuTsIterator( const CodingStructure& _cs, int _s, int _e, const std::vector<int>& _m         ) : cs( _cs ), m_startTsAddr( _s ), m_endTsAddr( _e ), m_ctuAddrMap( _m ), m_ctuTsAddr( _s ) {}
731
1.43k
    CtuTsIterator( const CodingStructure& _cs, int _s, int _e, const std::vector<int>& _m, int _c ) : cs( _cs ), m_startTsAddr( _s ), m_endTsAddr( _e ), m_ctuAddrMap( _m ), m_ctuTsAddr( std::max( _s, _c ) ) {}
732
1.43k
    CtuTsIterator( const CodingStructure& _cs, int _s, int _e, const std::vector<int>* _m, bool _wpp ) : cs( _cs ), m_startTsAddr( _s ), m_endTsAddr( _e ), m_ctuTsAddr( _s ) {  if( _wpp ) m_ctuAddrMap = *_m;  }
733
734
10.3k
    virtual ~CtuTsIterator() { m_ctuAddrMap.clear(); }
735
736
4.65k
    CtuTsIterator& operator++()                { m_ctuTsAddr = getNextTsAddr( m_ctuTsAddr ); return *this; }
737
0
    CtuTsIterator  operator++(int)             { auto retval = *this; ++(*this); return retval; }
738
0
    bool operator==(CtuTsIterator other) const { return m_ctuTsAddr == other.m_ctuTsAddr; }
739
6.08k
    bool operator!=(CtuTsIterator other) const { return m_ctuTsAddr != other.m_ctuTsAddr; }
740
4.65k
    CtuPos operator*()                   const { const int ctuRsAddr = mapAddr( m_ctuTsAddr );  return CtuPos( ctuRsAddr % cs.pcv->widthInCtus, ctuRsAddr / cs.pcv->widthInCtus, ctuRsAddr ); }
741
742
1.43k
    CtuTsIterator begin() { return CtuTsIterator( cs, m_startTsAddr, m_endTsAddr, m_ctuAddrMap ); };
743
1.43k
    CtuTsIterator end()   { return CtuTsIterator( cs, m_startTsAddr, m_endTsAddr, m_ctuAddrMap, m_endTsAddr ); };
744
745
    using iterator_category = std::forward_iterator_tag;
746
    using value_type        = int;
747
    using pointer           = int*;
748
    using reference         = int&;
749
    using difference_type   = ptrdiff_t;
750
751
    void setWppPattern()
752
0
    {
753
0
      const PreCalcValues& pcv = *cs.pcv;
754
0
      m_ctuAddrMap.resize( pcv.sizeInCtus, 0 );
755
0
      int addr = 0;
756
0
      for( int i = 1; i < pcv.sizeInCtus; i++ )
757
0
      {
758
0
        int x = addr % pcv.widthInCtus;
759
0
        int y = addr / pcv.widthInCtus;
760
0
        x -= 1;
761
0
        y += 1;
762
0
        if( x < 0 || y >= pcv.heightInCtus )
763
0
        {
764
0
          x += 1 + y;
765
0
          y  = 0;
766
0
        }
767
0
        if( x >= pcv.widthInCtus )
768
0
        {
769
0
          y += ( x - pcv.widthInCtus ) + 1;
770
0
          x  = pcv.widthInCtus - 1;
771
0
        }
772
0
        addr = y * pcv.widthInCtus + x;
773
0
        m_ctuAddrMap[ i ] = addr;
774
0
      }
775
0
    }
776
};
777
778
void EncSlice::saoDisabledRate( CodingStructure& cs, SAOBlkParam* reconParams )
779
0
{
780
0
  EncSampleAdaptiveOffset::disabledRate( cs, m_saoDisabledRate, reconParams, m_pcEncCfg->m_saoEncodingRate, m_pcEncCfg->m_saoEncodingRateChroma, m_pcEncCfg->m_internChromaFormat );
781
0
}
782
783
void EncSlice::finishCompressSlice( Picture* pic, Slice& slice )
784
1.43k
{
785
1.43k
  CodingStructure& cs = *pic->cs;
786
787
  // every CTU is encoded: nothing reads the line bottoms any more, and this slice encoder will keep the next picture's
788
1.43k
  pic->m_ctuLineBottoms = nullptr;
789
790
  // finalize
791
1.43k
  if( slice.sps->saoEnabled && pic->useSAO )
792
1.43k
  {
793
    // store disabled statistics
794
1.43k
    if( !m_pcEncCfg->m_numThreads )
795
0
      saoDisabledRate( cs, &m_saoReconParams[ 0 ] );
796
797
    // set slice header flags
798
1.43k
    CHECK( m_saoEnabled[ COMP_Cb ] != m_saoEnabled[ COMP_Cr ], "Unspecified error");
799
1.43k
    for( auto s : pic->slices )
800
1.43k
    {
801
1.43k
      s->saoEnabled[ CH_L ] = m_saoEnabled[ COMP_Y  ];
802
1.43k
      s->saoEnabled[ CH_C ] = m_saoEnabled[ COMP_Cb ];
803
1.43k
    }
804
1.43k
  }
805
1.43k
}
806
807
void EncSlice::xProcessCtus( Picture* pic, const unsigned startCtuTsAddr, const unsigned boundingCtuTsAddr )
808
1.43k
{
809
1.43k
  PROFILER_SCOPE_TOP_LEVEL_EXT( 1, g_timeProfiler, P_IGNORE, pic->cs );
810
1.43k
  CodingStructure& cs      = *pic->cs;
811
1.43k
  Slice&           slice   = *cs.slice;
812
1.43k
  const PreCalcValues& pcv = *cs.pcv;
813
814
  // initialization
815
1.43k
  if( slice.sps->jointCbCr )
816
1.43k
  {
817
1.43k
    setJointCbCrModes( cs, Position(0, 0), cs.area.lumaSize() );
818
1.43k
  }
819
820
1.43k
  if( slice.sps->saoEnabled && pic->useSAO )
821
1.43k
  {
822
    // check SAO enabled or disabled
823
1.43k
    EncSampleAdaptiveOffset::decidePicParams( cs, m_saoDisabledRate, m_saoEnabled, m_pcEncCfg->m_saoEncodingRate, m_pcEncCfg->m_saoEncodingRateChroma, m_pcEncCfg->m_internChromaFormat );
824
825
1.43k
    m_saoAllDisabled = true;
826
5.72k
    for( int compIdx = 0; compIdx < getNumberValidComponents( pcv.chrFormat ); compIdx++ )
827
4.29k
    {
828
4.29k
      m_saoAllDisabled &= ! m_saoEnabled[ compIdx ];
829
4.29k
    }
830
831
1.43k
    std::fill( m_saoReconParams.begin(), m_saoReconParams.end(), SAOBlkParam() );
832
1.43k
  }
833
0
  else
834
0
  {
835
0
    m_saoAllDisabled = true;
836
0
  }
837
838
1.43k
  if( slice.sps->alfEnabled )
839
1.43k
  {
840
1.43k
    m_pALF->initEncProcess( slice );
841
1.43k
  }
842
843
1.43k
  std::fill( m_processStates.begin(), m_processStates.end(), CTU_ENCODE );
844
845
  // fill encoder parameter list
846
1.43k
  int idx = 0;
847
1.43k
  const std::vector<int> base = slice.sliceMap.ctuAddrInSlice;
848
1.43k
  auto ctuIter = CtuTsIterator( cs, startCtuTsAddr, boundingCtuTsAddr, &m_ctuAddrMap, m_pcEncCfg->m_numThreads > 0 );
849
1.43k
  for( auto ctuPos : ctuIter )
850
4.65k
  {
851
4.65k
    ctuEncParams[ idx ].pic       = pic;
852
4.65k
    ctuEncParams[ idx ].encSlice  = this;
853
4.65k
    ctuEncParams[ idx ].ctuRsAddr = ctuPos.ctuRsAddr;
854
4.65k
    ctuEncParams[ idx ].ctuPosX   = ctuPos.ctuPosX;
855
4.65k
    ctuEncParams[ idx ].ctuPosY   = ctuPos.ctuPosY;
856
4.65k
    ctuEncParams[ idx ].ctuArea   = UnitArea( pic->chromaFormat, slice.pps->pcv->getCtuArea( ctuPos.ctuPosX, ctuPos.ctuPosY ) );
857
858
4.65k
    if( m_pcEncCfg->m_numThreads > 0 )
859
4.65k
    {
860
4.65k
      ctuEncParams[idx].tileLineResIdx = slice.pps->getTileLineId( ctuPos.ctuPosX, ctuPos.ctuPosY );
861
4.65k
    }
862
0
    else
863
0
    {
864
0
      ctuEncParams[idx].tileLineResIdx = 0;
865
0
    }
866
4.65k
    idx++;
867
4.65k
  }
868
869
  //for( int i = 0; i < idx; i++ )
870
  //{
871
  //  for( int j = i; j < idx; j++ )
872
  //  {
873
  //    if( ctuEncParams[i].tileLineResIdx != ctuEncParams[j].tileLineResIdx ) continue;
874
  //
875
  //    CHECK( ctuEncParams[i].ctuPosY != ctuEncParams[j].ctuPosY, "Not the same CTU line!" );
876
  //    CHECK( slice.pps->getTileIdx( ctuEncParams[i].ctuPosX, ctuEncParams[i].ctuPosY ) != slice.pps->getTileIdx( ctuEncParams[j].ctuPosX, ctuEncParams[j].ctuPosY ), "Not the same tile!" );
877
  //  }
878
  //}
879
880
1.43k
  CHECK( idx != pcv.sizeInCtus, "array index out of bounds" );
881
882
  // process ctu's until last ctu is done
883
1.43k
  if( m_pcEncCfg->m_numThreads > 0 )
884
1.43k
  {
885
    // the picture started first gets free threads first: it frees its picture encoder soonest for the next ready picture
886
1.43k
    const int64_t taskPriority = 1 + pic->encStartOrder;
887
1.43k
    for( auto& ctuEncParam : ctuEncParams )
888
4.65k
    {
889
4.65k
      m_threadPool->addBarrierTask( EncSlice::xProcessCtuTask<false>,
890
4.65k
                                    &ctuEncParam,
891
4.65k
                                    m_ctuTasksDoneCounter,
892
4.65k
                                    nullptr,
893
4.65k
                                    {},
894
4.65k
                                    EncSlice::xProcessCtuTask<true>,
895
4.65k
                                    taskPriority );
896
4.65k
    }
897
1.43k
  }
898
0
  else
899
0
  {
900
0
    do
901
0
    {
902
0
      for( auto& ctuEncParam : ctuEncParams )
903
0
      {
904
0
        if( m_processStates[ctuEncParam.ctuRsAddr] != PROCESS_DONE )
905
0
          EncSlice::xProcessCtuTask<false>( 0, &ctuEncParam );
906
0
      }
907
0
      DTRACE_PIC_COMP_COND( m_processStates[ 0 ] == SAO_FILTER && m_processStates[ boundingCtuTsAddr - 1 ] == SAO_FILTER, D_REC_CB_LUMA_LF,   cs, cs.getRecoBuf(), COMP_Y  );
908
0
      DTRACE_PIC_COMP_COND( m_processStates[ 0 ] == SAO_FILTER && m_processStates[ boundingCtuTsAddr - 1 ] == SAO_FILTER, D_REC_CB_CHROMA_LF, cs, cs.getRecoBuf(), COMP_Cb );
909
0
      DTRACE_PIC_COMP_COND( m_processStates[ 0 ] == SAO_FILTER && m_processStates[ boundingCtuTsAddr - 1 ] == SAO_FILTER, D_REC_CB_CHROMA_LF, cs, cs.getRecoBuf(), COMP_Cr );
910
0
      DTRACE_PIC_COMP_COND( m_processStates[ 0 ] == ALF_GET_STATISTICS && m_processStates[ boundingCtuTsAddr - 1 ] == ALF_GET_STATISTICS, D_REC_CB_LUMA_SAO,   cs, cs.getRecoBuf(), COMP_Y  );
911
0
      DTRACE_PIC_COMP_COND( m_processStates[ 0 ] == ALF_GET_STATISTICS && m_processStates[ boundingCtuTsAddr - 1 ] == ALF_GET_STATISTICS, D_REC_CB_CHROMA_SAO, cs, cs.getRecoBuf(), COMP_Cb );
912
0
      DTRACE_PIC_COMP_COND( m_processStates[ 0 ] == ALF_GET_STATISTICS && m_processStates[ boundingCtuTsAddr - 1 ] == ALF_GET_STATISTICS, D_REC_CB_CHROMA_SAO, cs, cs.getRecoBuf(), COMP_Cr );
913
0
    }
914
0
    while( m_processStates[ boundingCtuTsAddr - 1 ] != PROCESS_DONE );
915
0
  }
916
1.43k
}
917
918
inline bool checkCtuTaskNbTop( const PPS& pps, const int& ctuPosX, const int& ctuPosY, const int& ctuRsAddr, const ProcessCtuState* processStates, const TaskType tskType, bool override = false )
919
1.21M
{
920
1.21M
  return ctuPosY > 0 && ( override || pps.canFilterCtuBdry( ctuPosX, ctuPosY, 0, -1 ) ) && processStates[ ctuRsAddr - pps.pcv->widthInCtus ] <= tskType;
921
1.21M
}
922
923
inline bool checkCtuTaskNbBot( const PPS& pps, const int& ctuPosX, const int& ctuPosY, const int& ctuRsAddr, const ProcessCtuState* processStates, const TaskType tskType, bool override = false )
924
472k
{
925
472k
  return ctuPosY + 1 < pps.pcv->heightInCtus && ( override || pps.canFilterCtuBdry( ctuPosX, ctuPosY, 0, 1 ) ) && processStates[ ctuRsAddr     + pps.pcv->widthInCtus ] <= tskType;
926
472k
}
927
928
inline bool checkCtuTaskNbRgt( const PPS& pps, const int& ctuPosX, const int& ctuPosY, const int& ctuRsAddr, const ProcessCtuState* processStates, const TaskType tskType, bool override = false )
929
760k
{
930
760k
  return ctuPosX + 1 < pps.pcv->widthInCtus && ( override || pps.canFilterCtuBdry( ctuPosX, ctuPosY, 1, 0 ) ) && processStates[ ctuRsAddr + 1 ] <= tskType;
931
760k
}
932
933
inline bool checkCtuTaskNbTopRgt( const PPS& pps, const int& ctuPosX, const int& ctuPosY, const int& ctuRsAddr, const ProcessCtuState* processStates, const TaskType tskType, bool override = false )
934
415k
{
935
415k
  return ctuPosY > 0 && ctuPosX + 1 < pps.pcv->widthInCtus && ( override || pps.canFilterCtuBdry( ctuPosX, ctuPosY, 1, -1 ) ) && processStates[ ctuRsAddr - pps.pcv->widthInCtus + 1 ] <= tskType;
936
415k
}
937
938
inline bool checkCtuTaskNbBotRgt( const PPS& pps, const int& ctuPosX, const int& ctuPosY, const int& ctuRsAddr, const ProcessCtuState* processStates, const TaskType tskType, const int rightOffset = 1, bool override = false )
939
1.45M
{
940
1.45M
  return ctuPosX + rightOffset < pps.pcv->widthInCtus && ctuPosY + 1 < pps.pcv->heightInCtus && ( override || pps.canFilterCtuBdry( ctuPosX, ctuPosY, rightOffset, 1 ) ) && processStates[ ctuRsAddr + rightOffset + pps.pcv->widthInCtus ] <= tskType;
941
1.45M
}
942
943
// With IFP, below the derivation lines the CCALF statistics are read only by selectCcAlfFilterForCtuLine. They are unused
944
// once the derivation has turned CCALF off for Cb and Cr, and are skipped then.
945
bool EncSlice::xCcAlfStatsUnused( const ProcessCtuState* processStates, const int ctuRsAddr ) const
946
2.55k
{
947
2.55k
  if( !m_pcEncCfg->m_ifpLines )
948
2.55k
    return false;
949
  // above the derivation lines the statistics feed the derivation; below them they are needed until its decision is known
950
0
  if( ctuRsAddr <= (int)m_ccalfDeriveCtu || processStates[ m_ccalfDeriveCtu ] < CCALF_RECONSTRUCT )
951
0
    return false;
952
  // the flags are final here: the derivation task sets them before its atomic state store to CCALF_RECONSTRUCT
953
0
  const CcAlfFilterParam& ccAlfParam = m_pALF->getCcAlfFilterParam();
954
0
  return !ccAlfParam.ccAlfFilterEnabled[COMP_Cb - 1] && !ccAlfParam.ccAlfFilterEnabled[COMP_Cr - 1];
955
0
}
956
957
template<bool checkReadyState>
958
bool EncSlice::xProcessCtuTask( int threadIdx, void* taskParam )
959
13.8M
{
960
13.8M
  CtuEncParam* ctuEncParam       = static_cast<CtuEncParam*>( taskParam );
961
13.8M
  Picture* pic                   = ctuEncParam->pic;
962
13.8M
  EncSlice* encSlice             = ctuEncParam->encSlice;
963
13.8M
  CodingStructure& cs            = *pic->cs;
964
13.8M
  Slice&           slice         = *cs.slice;
965
13.8M
  const PPS&       pps           = *slice.pps;
966
13.8M
  const PreCalcValues& pcv       = *cs.pcv;
967
13.8M
  const int ctuRsAddr            = ctuEncParam->ctuRsAddr;
968
13.8M
  const int ctuPosX              = ctuEncParam->ctuPosX;
969
13.8M
  const int ctuPosY              = ctuEncParam->ctuPosY;
970
13.8M
  const int x                    = ctuPosX << pcv.maxCUSizeLog2;
971
13.8M
  const int y                    = ctuPosY << pcv.maxCUSizeLog2;
972
13.8M
  const int width                = std::min( pcv.maxCUSize, pcv.lumaWidth  - x );
973
13.8M
  const int height               = std::min( pcv.maxCUSize, pcv.lumaHeight - y );
974
13.8M
  const int ctuStride            = pcv.widthInCtus;
975
13.8M
  const int lineIdx              = ctuEncParam->tileLineResIdx;
976
13.8M
  ProcessCtuState* processStates = encSlice->m_processStates.data();
977
13.8M
  const UnitArea& ctuArea        = ctuEncParam->ctuArea;
978
13.8M
  const bool wppSyncEnabled      = cs.sps->entropyCodingSyncEnabled;
979
13.8M
  const TaskType currState       = processStates[ ctuRsAddr ];
980
13.8M
  const unsigned syncLines       = encSlice->m_pcEncCfg->m_ifpLines;
981
982
13.8M
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "poc", cs.slice->poc ) );
983
13.8M
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "ctu", ctuRsAddr ) );
984
13.8M
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "final", processStates[ ctuRsAddr ] == CTU_ENCODE ? 0 : 1 ) );
985
986
  // process ctu's line wise from left to right
987
13.8M
  const bool tileParallel = encSlice->m_pcEncCfg->m_tileParallelCtuEnc;
988
13.8M
  if( tileParallel && currState == CTU_ENCODE && ctuPosX > 0 && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX - 1, ctuPosY ) )
989
0
    ; // for CTU_ENCODE on tile boundaries, allow parallel processing of tiles
990
13.8M
  else if( ctuPosX > 0 && processStates[ ctuRsAddr - 1 ] <= currState && currState < PROCESS_DONE )
991
7.05M
    return false;
992
993
6.81M
  switch( currState )
994
6.81M
  {
995
    // encode
996
1.50M
    case CTU_ENCODE:
997
1.50M
      {
998
        // CTU line-wise inter-frame parallel processing synchronization
999
1.50M
        if( syncLines )
1000
0
        {
1001
0
          const bool lineStart = ctuPosX == 0 || ( tileParallel && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX - 1, ctuPosY ) );
1002
0
          if( lineStart && !refPicCtuLineReady( slice, ctuPosY + (int)syncLines, pcv ) )
1003
0
          {
1004
0
            return false;
1005
0
          }
1006
0
        }
1007
1008
        // general wpp conditions, top and top-right ctu have to be encoded
1009
1.50M
        if( encSlice->m_pcEncCfg->m_tileParallelCtuEnc && ctuPosY > 0 && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX, ctuPosY - 1 ) )
1010
0
          ; // allow parallel processing of CTU-encoding on independent tiles
1011
1.50M
        else if( ctuPosY > 0                                  && processStates[ ctuRsAddr - ctuStride     ] <= CTU_ENCODE )
1012
1.04M
          return false;
1013
460k
        else if( ctuPosY > 0 && ctuPosX + 1 < pcv.widthInCtus && processStates[ ctuRsAddr - ctuStride + 1 ] <= CTU_ENCODE && !wppSyncEnabled )
1014
450k
          return false;
1015
        
1016
9.30k
        if( checkReadyState )
1017
4.65k
          return true;
1018
1019
#ifdef TRACE_ENABLE_ITT
1020
        std::stringstream ss;
1021
        ss << "Encode_" << slice.poc << "_CTU_" << ctuPosY << "_" << ctuPosX;
1022
        __itt_string_handle* itt_handle_ctuEncode = __itt_string_handle_create( ss.str().c_str() );
1023
#endif
1024
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ctuEncode );
1025
1026
4.65k
        TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1027
4.65k
        PerThreadRsrc* taskRsrc      = &encSlice->m_threadRsrc->get( threadIdx );
1028
4.65k
        EncCu& encCu                 = taskRsrc->m_encCu;
1029
1030
4.65k
        encCu.bindToPicture( encSlice->m_picEncState );
1031
4.65k
        encCu.setCtuEncRsrc( &lineEncRsrc->m_CABACEstimator, &taskRsrc->m_CtxCache, &lineEncRsrc->m_ReuseUniMv, &lineEncRsrc->m_BlkUniMvInfoBuffer, &lineEncRsrc->m_AffineProfList, &lineEncRsrc->m_CachedBvs );
1032
4.65k
        encCu.encodeCtu( pic, lineEncRsrc->m_prevQp, ctuPosX, ctuPosY );
1033
1034
        // cleanup line memory when last ctu in line done to reduce overall memory consumption
1035
4.65k
        if( encSlice->m_pcEncCfg->m_ensureWppBitEqual && ( ctuPosX == pcv.widthInCtus - 1 || slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX + 1, ctuPosY ) ) )
1036
2.55k
        {
1037
2.55k
          lineEncRsrc->m_AffineProfList    .resetAffineMVList();
1038
2.55k
          lineEncRsrc->m_BlkUniMvInfoBuffer.resetUniMvList();
1039
2.55k
          lineEncRsrc->m_ReuseUniMv        .resetReusedUniMvs();
1040
2.55k
          lineEncRsrc->m_CachedBvs         .resetIbcBvCand();
1041
2.55k
        }
1042
1043
        // the line below reads these rows unfiltered (Picture::getRecoAboveCtuTop), and deblocking may start before it does
1044
4.65k
        if( ctuPosY + 1 < pcv.heightInCtus )
1045
2.16k
        {
1046
2.16k
          pic->keepCtuBottomRows( ctuArea );
1047
2.16k
        }
1048
1049
4.65k
        DTRACE_UPDATE( g_trace_ctx, std::make_pair( "final", 1 ) );
1050
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_ctuEncode );
1051
1052
4.65k
        processStates[ ctuRsAddr ] = LF_VER;
1053
4.65k
      }
1054
0
      break;
1055
1056
    // vertical loopfilter
1057
2.45M
    case LF_VER:
1058
2.45M
      {
1059
        // clip check to right tile border (CTU_ENCODE pre-processing delay due to IBC)
1060
2.45M
        const int tileCol = slice.pps->ctuToTileCol[ctuPosX];
1061
2.45M
        const int lastCtuPosXInTile = slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1062
2.45M
        const int checkRight = std::min<int>( encSlice->m_ctuEncDelay, lastCtuPosXInTile - ctuPosX );
1063
1064
2.45M
        const bool hasTiles = encSlice->m_pcEncCfg->m_tileParallelCtuEnc && slice.pps->getNumTiles() > 1;
1065
1066
        // need to check line above bcs of tiling, which allows CTU_ENCODE to run independently across tiles
1067
2.45M
        if( hasTiles )
1068
0
        {
1069
0
          if( ctuPosY > 0 )
1070
0
          {
1071
0
            for( int i = -!!ctuPosX; i <= checkRight; i++ )
1072
0
              if( pps.canFilterCtuBdry( ctuPosX, ctuPosY, i, -1 ) && processStates[ctuRsAddr - ctuStride + i] <= CTU_ENCODE )
1073
0
                return false;
1074
0
          }
1075
0
        }
1076
        
1077
        // ensure all surrounding ctu's are encoded (intra pred requires non-reshaped and unfiltered residual, IBC requires unfiltered samples too)
1078
        // check right with max offset (due to WPP condition above, this implies top-right has been already encoded)
1079
3.88M
        for( int i = hasTiles ? -!!ctuPosX : checkRight; i <= checkRight; i++ )
1080
2.45M
          if( pps.canFilterCtuBdry( ctuPosX, ctuPosY, i, 0 ) && processStates[ctuRsAddr + i] <= CTU_ENCODE )
1081
1.02M
            return false;
1082
1083
        // No wait for the line below: it reads the unfiltered rows above it from the kept CTU bottoms (keepCtuBottomRows).
1084
        // IBC reads far deeper into the unfiltered picture, so with IBC the bottom right CTU (1 CTU delay) must be encoded
1085
        // first; at the right picture border this checks the bottom CTU.
1086
1.43M
        if( pic->useIBC )
1087
1.43M
        {
1088
1.43M
          const int checkBottomRight = std::min<int>( 1, lastCtuPosXInTile - ctuPosX );
1089
1.43M
          if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CTU_ENCODE, checkBottomRight ) )
1090
1.42M
            return false;
1091
1.43M
        }
1092
1093
9.30k
        if( checkReadyState )
1094
4.65k
          return true;
1095
1096
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_rspLfVer );
1097
1098
        // loopfilter
1099
4.65k
        if( !cs.pps->deblockingFilterControlPresent || !cs.pps->deblockingFilterDisabled || cs.pps->deblockingFilterOverrideEnabled )
1100
4.65k
        {
1101
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_DEBLOCK_FILTER, &cs, CH_L );
1102
          // calculate filter strengths
1103
4.65k
          encSlice->m_pLoopFilter->calcFilterStrengthsCTU( cs, ctuArea, true );
1104
1105
          // vertical filter
1106
4.65k
          PelUnitBuf reco = cs.picture->getRecoBuf();
1107
4.65k
          encSlice->m_pLoopFilter->xDeblockArea<EDGE_VER>( cs, ctuArea, MAX_NUM_CH, reco );
1108
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1109
4.65k
        }
1110
1111
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_rspLfVer );
1112
1113
4.65k
        processStates[ ctuRsAddr ] = LF_HOR;
1114
4.65k
      }
1115
0
      break;
1116
1117
    // horizontal loopfilter
1118
404k
    case LF_HOR:
1119
404k
      {
1120
        // ensure horizontal ordering (from top to bottom)
1121
404k
        if( checkCtuTaskNbTop   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR ) )         
1122
135k
          return false;
1123
1124
        // ensure vertical loop filter of neighbor ctu's will not modify current residual
1125
        // check top, top-right and right ctu
1126
        // (top, top-right checked implicitly due to ordering check above)
1127
269k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_VER ) )
1128
260k
          return false;
1129
1130
9.30k
        if( checkReadyState )
1131
4.65k
          return true;
1132
1133
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_lfHor );
1134
1135
4.65k
        if( !cs.pps->deblockingFilterControlPresent || !cs.pps->deblockingFilterDisabled || cs.pps->deblockingFilterOverrideEnabled )
1136
4.65k
        {
1137
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_DEBLOCK_FILTER, &cs, CH_L );
1138
4.65k
          PelUnitBuf reco = cs.picture->getRecoBuf();
1139
4.65k
          encSlice->m_pLoopFilter->xDeblockArea<EDGE_HOR>( cs, ctuArea, MAX_NUM_CH, reco );
1140
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1141
4.65k
        }
1142
1143
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_lfHor );
1144
1145
4.65k
        processStates[ ctuRsAddr ] = SAO_FILTER;
1146
4.65k
      }
1147
0
      break;
1148
1149
    // SAO filter
1150
806k
    case SAO_FILTER:
1151
806k
      {
1152
        // general wpp conditions, top and top-right ctu have to be filtered
1153
806k
        if( checkCtuTaskNbTop   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER, true ) ) return false;
1154
415k
        if( checkCtuTaskNbTopRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER, true ) ) return false;
1155
1156
        // ensure loop filter of neighbor ctu's will not modify current residual
1157
        // sao processing dependents on +1 pixel to each side
1158
        // due to wpp condition above, only right, bottom and bottom-right ctu have to be checked
1159
281k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR,    true ) ) return false;
1160
263k
        if( checkCtuTaskNbBot   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR,    true ) ) return false;
1161
19.0k
        if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR, 1, true ) ) return false;
1162
1163
9.30k
        if( checkReadyState )
1164
4.65k
          return true;
1165
1166
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_sao );
1167
1168
        // SAO filter
1169
4.65k
        if( slice.sps->saoEnabled && pic->useSAO )
1170
4.65k
        {
1171
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_SAO, &cs, CH_L );
1172
4.65k
          TileLineEncRsrc* lineEncRsrc    = encSlice->m_TileLineEncRsrc[ lineIdx ];
1173
4.65k
          PerThreadRsrc* taskRsrc         = &encSlice->m_threadRsrc->get( threadIdx );
1174
4.65k
          EncSampleAdaptiveOffset& encSao = lineEncRsrc->m_encSao;
1175
1176
4.65k
          encSao.setCtuEncRsrc( &lineEncRsrc->m_SaoCABACEstimator, &taskRsrc->m_CtxCache, &taskRsrc->m_saoCtuBuf );
1177
4.65k
          encSao.loadCtuPreSao( cs, ctuArea, ctuPosY, encSlice->m_saoPreFilterEdges );
1178
4.65k
          encSao.getCtuStatistics( cs, encSlice->m_saoStatData, ctuArea, ctuRsAddr );
1179
4.65k
          encSao.decideCtuParams( cs, encSlice->m_saoStatData, encSlice->m_saoEnabled, encSlice->m_saoAllDisabled, ctuArea, ctuRsAddr, &encSlice->m_saoReconParams[ 0 ], cs.picture->getSAO() );
1180
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1181
4.65k
        }
1182
1183
        // ALF border extension
1184
4.65k
        if( cs.sps->alfEnabled )
1185
4.65k
        {
1186
          // we have to do some kind of position aware boundary padding
1187
          // it's done here because the conditions are readable
1188
4.65k
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1189
4.65k
          const int fltSize  = ( MAX_ALF_FILTER_LENGTH + 1 ) >> 1;
1190
4.65k
          const int xL       = ( ctuPosX == 0 )                 ? ( x-fltSize       ) : ( x );
1191
4.65k
          const int xR       = ( ctuPosX+1 == pcv.widthInCtus ) ? ( x+width+fltSize ) : ( x+width );
1192
1193
4.65k
          if( ctuPosX == 0 )                  recoBuf.extendBorderPelLft( y, height, fltSize );
1194
4.65k
          if( ctuPosX+1 == pcv.widthInCtus )  recoBuf.extendBorderPelRgt( y, height, fltSize );
1195
4.65k
          if( ctuPosY == 0 )                  recoBuf.extendBorderPelTop( xL, xR-xL, fltSize );
1196
4.65k
          if( ctuPosY+1 == pcv.heightInCtus ) recoBuf.extendBorderPelBot( xL, xR-xL, fltSize );
1197
1198
4.65k
          encSlice->m_pALF->copyCTUforALF(cs, ctuPosX, ctuPosY);
1199
4.65k
        }
1200
1201
        // The motion of the CTU is final, and so is its DMVR refinement, which only temporal motion vector
1202
        // prediction uses.
1203
4.65k
        if( cs.hasColocatedMotionBuf() )
1204
4.65k
        {
1205
4.65k
          CS::setColocatedMotionCTU( cs, ctuPosX, ctuPosY, slice.sps->DMVR && !slice.picHeader->disDmvrFlag );
1206
4.65k
        }
1207
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_sao );
1208
1209
4.65k
        const int tileCol = slice.pps->ctuToTileCol[ctuPosX];
1210
4.65k
        const int lastCtuColInTileRow = slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1211
4.65k
        if( ctuPosX == lastCtuColInTileRow )
1212
2.55k
        {
1213
2.55k
          processStates[ctuRsAddr] = ALF_GET_STATISTICS;
1214
2.55k
        }
1215
2.09k
        else
1216
2.09k
        {
1217
2.09k
          processStates[ctuRsAddr] = PROCESS_DONE;
1218
2.09k
          return true;
1219
2.09k
        }
1220
4.65k
      }
1221
2.55k
      break;
1222
1223
209k
    case ALF_GET_STATISTICS:
1224
209k
      {
1225
        // ensure all surrounding ctu's are filtered (ALF will use pixels of adjacent CTU's)
1226
        // due to wpp condition above in SAO_FILTER, only right, bottom and bottom-right ctu have to be checked
1227
209k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1228
209k
        if( checkCtuTaskNbBot   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1229
5.11k
        if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1230
1231
5.11k
        if( checkReadyState )
1232
2.55k
          return true;
1233
1234
2.56k
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_stat );
1235
1236
        // ALF pre-processing
1237
2.56k
        if( slice.sps->alfEnabled )
1238
2.55k
        {
1239
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1240
2.55k
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1241
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1242
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1243
4.65k
          {
1244
4.65k
            encSlice->m_pALF->getStatisticsCTU( *cs.picture, cs, recoBuf, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1245
4.65k
          }
1246
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1247
2.55k
        }
1248
1249
2.56k
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_stat );
1250
1251
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1252
2.56k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1253
2.56k
        processStates[ctuRsAddr] = (ctuRsAddr < deriveFilterCtu) ? ALF_RECONSTRUCT: ALF_DERIVE_FILTER;
1254
2.56k
      }
1255
0
      break;
1256
1257
475k
    case ALF_DERIVE_FILTER:
1258
475k
      {
1259
475k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1260
475k
        if( ctuRsAddr == deriveFilterCtu )
1261
475k
        {
1262
          // ensure statistics from all previous ctu's have been collected
1263
475k
          int numCheckLines = deriveFilterCtu / pcv.widthInCtus + 1;
1264
511k
          for( int y = 0; y < numCheckLines; y++ )
1265
508k
          {
1266
543k
            for( int tileCol = 0; tileCol < slice.pps->numTileCols; tileCol++ )
1267
508k
            {
1268
508k
              const int lastCtuInTileRow = y * pcv.widthInCtus + slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1269
508k
              if( processStates[lastCtuInTileRow] <= ALF_GET_STATISTICS )
1270
473k
                return false;
1271
508k
            }
1272
508k
          }
1273
475k
        }
1274
0
        else if( syncLines )
1275
0
        {
1276
          // ALF bitstream coding dependency for the sub-sequent ctu-lines
1277
0
          if( processStates[deriveFilterCtu] < ALF_RECONSTRUCT || checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, ALF_DERIVE_FILTER ) ) 
1278
0
            return false;
1279
0
        }
1280
2.86k
        if( checkReadyState )
1281
1.43k
          return true;
1282
1283
1.43k
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_derive );
1284
        // ALF post-processing
1285
1.43k
        if( slice.sps->alfEnabled )
1286
1.43k
        {
1287
1.43k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1288
1.43k
          if( ctuRsAddr == deriveFilterCtu )
1289
1.43k
          {
1290
1.43k
            encSlice->m_pALF->initDerivation( slice );
1291
1.43k
            encSlice->m_pALF->deriveFilter( *cs.picture, cs, slice.getLambdas(), deriveFilterCtu + 1 );
1292
1.43k
            encSlice->m_pALF->reconstructCoeffAPSs( cs, cs.slice->alfEnabled[COMP_Y], cs.slice->alfEnabled[COMP_Cb] || cs.slice->alfEnabled[COMP_Cr], false );
1293
1.43k
          }
1294
0
          else if( syncLines )
1295
0
          {
1296
            // in sync lines mode: derive/select filter for the remaining lines
1297
0
            TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1298
0
            PerThreadRsrc*   taskRsrc    = &encSlice->m_threadRsrc->get( threadIdx );
1299
0
            const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1300
0
            for(int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++)
1301
0
            {
1302
0
              encSlice->m_pALF->selectFilterForCTU( cs, &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, ctu );
1303
0
            }
1304
0
          }
1305
1.43k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1306
1.43k
        }
1307
1308
1.43k
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_derive );
1309
1.43k
        processStates[ ctuRsAddr ] = ALF_RECONSTRUCT;
1310
1.43k
      }
1311
0
      break;
1312
1313
734k
    case ALF_RECONSTRUCT:
1314
734k
      {
1315
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1316
734k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1317
734k
        if( processStates[deriveFilterCtu] < ALF_RECONSTRUCT )
1318
729k
          return false;
1319
5.11k
        else if( syncLines && ctuRsAddr > deriveFilterCtu && encSlice->m_pALF->getAsuHeightInCtus() > 1 )
1320
0
        {
1321
0
          const int asuHeightInCtus = encSlice->m_pALF->getAsuHeightInCtus();
1322
0
          const int botCtuLineInAsu = std::min( (( ctuPosY & ( ~(asuHeightInCtus - 1) ) ) + asuHeightInCtus - 1), (int)pcv.heightInCtus - 1 );
1323
0
          if( processStates[botCtuLineInAsu * ctuStride + ctuPosX] < ALF_RECONSTRUCT ) 
1324
0
            return false;
1325
0
        }
1326
1327
5.11k
        if( checkReadyState )
1328
2.55k
          return true;
1329
1330
2.55k
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_recon );
1331
1332
2.55k
        if( slice.sps->alfEnabled )
1333
2.55k
        {
1334
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1335
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1336
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1337
4.65k
          {
1338
4.65k
            encSlice->m_pALF->reconstructCTU_MT( *cs.picture, cs, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1339
4.65k
          }
1340
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1341
2.55k
        }
1342
1343
2.55k
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_recon );
1344
2.55k
        processStates[ctuRsAddr] = CCALF_GET_STATISTICS;
1345
        // neighbours waiting for this state may run now, while this task goes on with the next stage
1346
2.55k
        if( encSlice->m_threadPool )
1347
2.55k
        {
1348
2.55k
          encSlice->m_threadPool->signalProgress();
1349
2.55k
        }
1350
2.55k
      }
1351
      // dont break, no additional deps, can continue straigt away!
1352
      //break;
1353
1354
2.55k
    case CCALF_GET_STATISTICS:
1355
2.55k
      {
1356
        // No wait for the lines above and below: the statistics read their luma from the pre-ALF copy, complete since
1357
        // ALF_GET_STATISTICS waited for SAO below, and their chroma only inside this line
1358
2.55k
        if( checkReadyState )
1359
0
          return true;
1360
1361
2.55k
        const bool statsUnused = encSlice->xCcAlfStatsUnused( processStates, ctuRsAddr );
1362
1363
2.55k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_stat );
1364
1365
        // ALF pre-processing
1366
2.55k
        if( slice.sps->ccalfEnabled && !statsUnused )
1367
2.55k
        {
1368
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L);
1369
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1370
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1371
4.65k
          {
1372
4.65k
            encSlice->m_pALF->deriveStatsForCcAlfFilteringCTU( cs, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1373
4.65k
          }
1374
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1375
2.55k
        }
1376
1377
2.55k
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_stat );
1378
1379
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1380
2.55k
        processStates[ctuRsAddr] = (ctuRsAddr < encSlice->m_ccalfDeriveCtu) ? CCALF_RECONSTRUCT: CCALF_DERIVE_FILTER;
1381
2.55k
      }
1382
0
      break;
1383
1384
130k
    case CCALF_DERIVE_FILTER:
1385
130k
      {
1386
        // synchronization dependencies
1387
130k
        const unsigned deriveFilterCtu = encSlice->m_ccalfDeriveCtu;
1388
130k
        if( ctuRsAddr == deriveFilterCtu )
1389
130k
        {
1390
          // ensure statistics from all previous ctu's have been collected
1391
130k
          int numCheckLines = deriveFilterCtu / pcv.widthInCtus + 1;
1392
149k
          for( int y = 0; y < numCheckLines; y++ )
1393
146k
          {
1394
165k
            for( int tileCol = 0; tileCol < slice.pps->numTileCols; tileCol++ )
1395
146k
            {
1396
146k
              const int lastCtuInTileRow = y * pcv.widthInCtus + slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1397
146k
              if( processStates[lastCtuInTileRow] <= CCALF_GET_STATISTICS )
1398
127k
                return false;
1399
146k
            }
1400
146k
          }
1401
130k
        }
1402
0
        else if( syncLines )
1403
0
        {
1404
          // ALF bitstream coding dependency for the sub-sequent CTU-lines
1405
0
          if( processStates[deriveFilterCtu] < CCALF_RECONSTRUCT || checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CCALF_DERIVE_FILTER ) ) 
1406
0
            return false;
1407
0
        }
1408
2.86k
        if( checkReadyState )
1409
1.43k
          return true;
1410
1411
1.43k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_derive );
1412
1413
        // start task
1414
1.43k
        if( slice.sps->ccalfEnabled )
1415
1.43k
        {
1416
1.43k
          if( ctuRsAddr == deriveFilterCtu )
1417
1.43k
          {
1418
1.43k
            encSlice->m_pALF->deriveCcAlfFilter( *cs.picture, cs, encSlice->m_ccalfDeriveCtu + 1 );
1419
1.43k
          }
1420
0
          else if( syncLines )
1421
0
          {
1422
            // in sync lines mode: derive/select filter for the remaining lines
1423
0
            TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1424
0
            PerThreadRsrc*   taskRsrc    = &encSlice->m_threadRsrc->get( threadIdx );
1425
0
            const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1426
0
            encSlice->m_pALF->selectCcAlfFilterForCtuLine( cs, COMP_Cb, cs.getRecoBuf(), &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, firstCtuInRow, ctuRsAddr );
1427
0
            encSlice->m_pALF->selectCcAlfFilterForCtuLine( cs, COMP_Cr, cs.getRecoBuf(), &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, firstCtuInRow, ctuRsAddr );
1428
0
          }
1429
1.43k
        }
1430
1.43k
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_derive );
1431
1432
        // IFP: the ALF filters (derived before, at ALF_DERIVE_FILTER) and the CC-ALF filters are final now
1433
1.43k
        if( ctuRsAddr == deriveFilterCtu && syncLines && encSlice->m_alfFiltersDerived )
1434
0
        {
1435
0
          encSlice->m_alfFiltersDerived( *cs.picture );
1436
0
        }
1437
1438
1.43k
        processStates[ctuRsAddr] = CCALF_RECONSTRUCT;
1439
1.43k
      }
1440
0
      break;
1441
1442
36.8k
    case CCALF_RECONSTRUCT:
1443
36.8k
      {
1444
        // start ccalf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1445
36.8k
        const unsigned deriveFilterCtu = encSlice->m_ccalfDeriveCtu;
1446
36.8k
        if( processStates[deriveFilterCtu] < CCALF_RECONSTRUCT )
1447
31.7k
          return false;
1448
1449
5.11k
        if( syncLines )
1450
0
        {
1451
          // ensure line-by-line reconstruction due to line synchronization
1452
0
          if( checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CCALF_RECONSTRUCT ) ) return false;
1453
0
        }
1454
1455
5.11k
        if( checkReadyState )
1456
2.55k
          return true;
1457
1458
2.56k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_recon );
1459
1460
2.56k
        if( slice.sps->ccalfEnabled )
1461
2.55k
        {
1462
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1463
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1464
4.65k
          {
1465
4.65k
            encSlice->m_pALF->applyCcAlfFilterCTU( cs, COMP_Cb, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1466
4.65k
            encSlice->m_pALF->applyCcAlfFilterCTU( cs, COMP_Cr, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1467
4.65k
          }
1468
2.55k
        }
1469
1470
2.56k
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_recon );
1471
1472
        // extend pic border
1473
        // CCALF reconstruction stage is done per tile, ensure that all tiles in current CTU row are done  
1474
2.56k
        if( ++(pic->m_tileColsDone->at(ctuPosY)) >= pps.numTileCols )
1475
2.55k
        {
1476
2.55k
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1477
2.55k
          const int margin = cs.picture->margin;
1478
2.55k
          recoBuf.extendBorderPelLft( y, height, margin );
1479
2.55k
          recoBuf.extendBorderPelRgt( y, height, margin );
1480
2.55k
          if(ctuPosY == 0)
1481
1.43k
            recoBuf.extendBorderPelTop( -margin, pcv.lumaWidth + 2 * margin, margin );
1482
2.55k
          if(ctuPosY + 1 == pcv.heightInCtus)
1483
1.43k
            recoBuf.extendBorderPelBot( -margin, pcv.lumaWidth + 2 * margin, margin );
1484
1485
          // for IFP lines synchro, do an additional increment signaling that CTU row is ready
1486
2.55k
          if( syncLines )
1487
0
            ++(pic->m_tileColsDone->at( ctuPosY ));
1488
2.55k
        }
1489
1490
        // perform finish only once for whole picture
1491
2.56k
        const unsigned finishCtu = pcv.sizeInCtus - 1;
1492
2.56k
        if( ctuRsAddr < finishCtu )
1493
1.12k
        {
1494
1.12k
          processStates[ctuRsAddr] = PROCESS_DONE;
1495
          // processing done => terminate thread
1496
1.12k
          return true;
1497
1.12k
        }
1498
1.43k
        processStates[ctuRsAddr] = FINISH_SLICE;
1499
        // the last row may make other pictures' CTU tasks ready, while this task goes on to finish the slice
1500
1.43k
        if( encSlice->m_threadPool )
1501
1.43k
        {
1502
1.43k
          encSlice->m_threadPool->signalProgress();
1503
1.43k
        }
1504
1.43k
      }
1505
1506
59.9k
    case FINISH_SLICE:
1507
59.9k
      {
1508
59.9k
        CHECK( ctuRsAddr != pcv.sizeInCtus - 1, "invalid state, finish slice only once for last ctu" );
1509
1510
        // ensure all coding tasks have been done for all previous ctu's
1511
123k
        for( int i = 0; i < ctuRsAddr; i++ )
1512
121k
          if( processStates[ i ] < FINISH_SLICE )
1513
57.7k
            return false;
1514
1515
2.14k
        if( checkReadyState )
1516
705
          return true;
1517
1518
1.43k
        encSlice->finishCompressSlice( cs.picture, slice );
1519
1520
1.43k
        processStates[ ctuRsAddr ] = PROCESS_DONE;
1521
        // processing done => terminate thread
1522
1.43k
        return true;
1523
2.14k
      }
1524
1525
0
    case PROCESS_DONE:
1526
0
      CHECK( true, "process state is PROCESS_DONE, but thread is still running" );
1527
0
      return true;
1528
1529
0
    default:
1530
0
      CHECK( true, "unknown process state" );
1531
0
      return true;
1532
6.81M
  }
1533
1534
24.5k
  return false;
1535
6.81M
}
bool vvenc::EncSlice::xProcessCtuTask<false>(int, void*)
Line
Count
Source
959
29.8k
{
960
29.8k
  CtuEncParam* ctuEncParam       = static_cast<CtuEncParam*>( taskParam );
961
29.8k
  Picture* pic                   = ctuEncParam->pic;
962
29.8k
  EncSlice* encSlice             = ctuEncParam->encSlice;
963
29.8k
  CodingStructure& cs            = *pic->cs;
964
29.8k
  Slice&           slice         = *cs.slice;
965
29.8k
  const PPS&       pps           = *slice.pps;
966
29.8k
  const PreCalcValues& pcv       = *cs.pcv;
967
29.8k
  const int ctuRsAddr            = ctuEncParam->ctuRsAddr;
968
29.8k
  const int ctuPosX              = ctuEncParam->ctuPosX;
969
29.8k
  const int ctuPosY              = ctuEncParam->ctuPosY;
970
29.8k
  const int x                    = ctuPosX << pcv.maxCUSizeLog2;
971
29.8k
  const int y                    = ctuPosY << pcv.maxCUSizeLog2;
972
29.8k
  const int width                = std::min( pcv.maxCUSize, pcv.lumaWidth  - x );
973
29.8k
  const int height               = std::min( pcv.maxCUSize, pcv.lumaHeight - y );
974
29.8k
  const int ctuStride            = pcv.widthInCtus;
975
29.8k
  const int lineIdx              = ctuEncParam->tileLineResIdx;
976
29.8k
  ProcessCtuState* processStates = encSlice->m_processStates.data();
977
29.8k
  const UnitArea& ctuArea        = ctuEncParam->ctuArea;
978
29.8k
  const bool wppSyncEnabled      = cs.sps->entropyCodingSyncEnabled;
979
29.8k
  const TaskType currState       = processStates[ ctuRsAddr ];
980
29.8k
  const unsigned syncLines       = encSlice->m_pcEncCfg->m_ifpLines;
981
982
29.8k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "poc", cs.slice->poc ) );
983
29.8k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "ctu", ctuRsAddr ) );
984
29.8k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "final", processStates[ ctuRsAddr ] == CTU_ENCODE ? 0 : 1 ) );
985
986
  // process ctu's line wise from left to right
987
29.8k
  const bool tileParallel = encSlice->m_pcEncCfg->m_tileParallelCtuEnc;
988
29.8k
  if( tileParallel && currState == CTU_ENCODE && ctuPosX > 0 && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX - 1, ctuPosY ) )
989
0
    ; // for CTU_ENCODE on tile boundaries, allow parallel processing of tiles
990
29.8k
  else if( ctuPosX > 0 && processStates[ ctuRsAddr - 1 ] <= currState && currState < PROCESS_DONE )
991
0
    return false;
992
993
29.8k
  switch( currState )
994
29.8k
  {
995
    // encode
996
4.65k
    case CTU_ENCODE:
997
4.65k
      {
998
        // CTU line-wise inter-frame parallel processing synchronization
999
4.65k
        if( syncLines )
1000
0
        {
1001
0
          const bool lineStart = ctuPosX == 0 || ( tileParallel && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX - 1, ctuPosY ) );
1002
0
          if( lineStart && !refPicCtuLineReady( slice, ctuPosY + (int)syncLines, pcv ) )
1003
0
          {
1004
0
            return false;
1005
0
          }
1006
0
        }
1007
1008
        // general wpp conditions, top and top-right ctu have to be encoded
1009
4.65k
        if( encSlice->m_pcEncCfg->m_tileParallelCtuEnc && ctuPosY > 0 && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX, ctuPosY - 1 ) )
1010
0
          ; // allow parallel processing of CTU-encoding on independent tiles
1011
4.65k
        else if( ctuPosY > 0                                  && processStates[ ctuRsAddr - ctuStride     ] <= CTU_ENCODE )
1012
0
          return false;
1013
4.65k
        else if( ctuPosY > 0 && ctuPosX + 1 < pcv.widthInCtus && processStates[ ctuRsAddr - ctuStride + 1 ] <= CTU_ENCODE && !wppSyncEnabled )
1014
0
          return false;
1015
        
1016
4.65k
        if( checkReadyState )
1017
0
          return true;
1018
1019
#ifdef TRACE_ENABLE_ITT
1020
        std::stringstream ss;
1021
        ss << "Encode_" << slice.poc << "_CTU_" << ctuPosY << "_" << ctuPosX;
1022
        __itt_string_handle* itt_handle_ctuEncode = __itt_string_handle_create( ss.str().c_str() );
1023
#endif
1024
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ctuEncode );
1025
1026
4.65k
        TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1027
4.65k
        PerThreadRsrc* taskRsrc      = &encSlice->m_threadRsrc->get( threadIdx );
1028
4.65k
        EncCu& encCu                 = taskRsrc->m_encCu;
1029
1030
4.65k
        encCu.bindToPicture( encSlice->m_picEncState );
1031
4.65k
        encCu.setCtuEncRsrc( &lineEncRsrc->m_CABACEstimator, &taskRsrc->m_CtxCache, &lineEncRsrc->m_ReuseUniMv, &lineEncRsrc->m_BlkUniMvInfoBuffer, &lineEncRsrc->m_AffineProfList, &lineEncRsrc->m_CachedBvs );
1032
4.65k
        encCu.encodeCtu( pic, lineEncRsrc->m_prevQp, ctuPosX, ctuPosY );
1033
1034
        // cleanup line memory when last ctu in line done to reduce overall memory consumption
1035
4.65k
        if( encSlice->m_pcEncCfg->m_ensureWppBitEqual && ( ctuPosX == pcv.widthInCtus - 1 || slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX + 1, ctuPosY ) ) )
1036
2.55k
        {
1037
2.55k
          lineEncRsrc->m_AffineProfList    .resetAffineMVList();
1038
2.55k
          lineEncRsrc->m_BlkUniMvInfoBuffer.resetUniMvList();
1039
2.55k
          lineEncRsrc->m_ReuseUniMv        .resetReusedUniMvs();
1040
2.55k
          lineEncRsrc->m_CachedBvs         .resetIbcBvCand();
1041
2.55k
        }
1042
1043
        // the line below reads these rows unfiltered (Picture::getRecoAboveCtuTop), and deblocking may start before it does
1044
4.65k
        if( ctuPosY + 1 < pcv.heightInCtus )
1045
2.16k
        {
1046
2.16k
          pic->keepCtuBottomRows( ctuArea );
1047
2.16k
        }
1048
1049
4.65k
        DTRACE_UPDATE( g_trace_ctx, std::make_pair( "final", 1 ) );
1050
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_ctuEncode );
1051
1052
4.65k
        processStates[ ctuRsAddr ] = LF_VER;
1053
4.65k
      }
1054
0
      break;
1055
1056
    // vertical loopfilter
1057
4.65k
    case LF_VER:
1058
4.65k
      {
1059
        // clip check to right tile border (CTU_ENCODE pre-processing delay due to IBC)
1060
4.65k
        const int tileCol = slice.pps->ctuToTileCol[ctuPosX];
1061
4.65k
        const int lastCtuPosXInTile = slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1062
4.65k
        const int checkRight = std::min<int>( encSlice->m_ctuEncDelay, lastCtuPosXInTile - ctuPosX );
1063
1064
4.65k
        const bool hasTiles = encSlice->m_pcEncCfg->m_tileParallelCtuEnc && slice.pps->getNumTiles() > 1;
1065
1066
        // need to check line above bcs of tiling, which allows CTU_ENCODE to run independently across tiles
1067
4.65k
        if( hasTiles )
1068
0
        {
1069
0
          if( ctuPosY > 0 )
1070
0
          {
1071
0
            for( int i = -!!ctuPosX; i <= checkRight; i++ )
1072
0
              if( pps.canFilterCtuBdry( ctuPosX, ctuPosY, i, -1 ) && processStates[ctuRsAddr - ctuStride + i] <= CTU_ENCODE )
1073
0
                return false;
1074
0
          }
1075
0
        }
1076
        
1077
        // ensure all surrounding ctu's are encoded (intra pred requires non-reshaped and unfiltered residual, IBC requires unfiltered samples too)
1078
        // check right with max offset (due to WPP condition above, this implies top-right has been already encoded)
1079
9.30k
        for( int i = hasTiles ? -!!ctuPosX : checkRight; i <= checkRight; i++ )
1080
4.65k
          if( pps.canFilterCtuBdry( ctuPosX, ctuPosY, i, 0 ) && processStates[ctuRsAddr + i] <= CTU_ENCODE )
1081
0
            return false;
1082
1083
        // No wait for the line below: it reads the unfiltered rows above it from the kept CTU bottoms (keepCtuBottomRows).
1084
        // IBC reads far deeper into the unfiltered picture, so with IBC the bottom right CTU (1 CTU delay) must be encoded
1085
        // first; at the right picture border this checks the bottom CTU.
1086
4.65k
        if( pic->useIBC )
1087
4.65k
        {
1088
4.65k
          const int checkBottomRight = std::min<int>( 1, lastCtuPosXInTile - ctuPosX );
1089
4.65k
          if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CTU_ENCODE, checkBottomRight ) )
1090
0
            return false;
1091
4.65k
        }
1092
1093
4.65k
        if( checkReadyState )
1094
0
          return true;
1095
1096
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_rspLfVer );
1097
1098
        // loopfilter
1099
4.65k
        if( !cs.pps->deblockingFilterControlPresent || !cs.pps->deblockingFilterDisabled || cs.pps->deblockingFilterOverrideEnabled )
1100
4.65k
        {
1101
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_DEBLOCK_FILTER, &cs, CH_L );
1102
          // calculate filter strengths
1103
4.65k
          encSlice->m_pLoopFilter->calcFilterStrengthsCTU( cs, ctuArea, true );
1104
1105
          // vertical filter
1106
4.65k
          PelUnitBuf reco = cs.picture->getRecoBuf();
1107
4.65k
          encSlice->m_pLoopFilter->xDeblockArea<EDGE_VER>( cs, ctuArea, MAX_NUM_CH, reco );
1108
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1109
4.65k
        }
1110
1111
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_rspLfVer );
1112
1113
4.65k
        processStates[ ctuRsAddr ] = LF_HOR;
1114
4.65k
      }
1115
0
      break;
1116
1117
    // horizontal loopfilter
1118
4.65k
    case LF_HOR:
1119
4.65k
      {
1120
        // ensure horizontal ordering (from top to bottom)
1121
4.65k
        if( checkCtuTaskNbTop   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR ) )         
1122
0
          return false;
1123
1124
        // ensure vertical loop filter of neighbor ctu's will not modify current residual
1125
        // check top, top-right and right ctu
1126
        // (top, top-right checked implicitly due to ordering check above)
1127
4.65k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_VER ) )
1128
0
          return false;
1129
1130
4.65k
        if( checkReadyState )
1131
0
          return true;
1132
1133
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_lfHor );
1134
1135
4.65k
        if( !cs.pps->deblockingFilterControlPresent || !cs.pps->deblockingFilterDisabled || cs.pps->deblockingFilterOverrideEnabled )
1136
4.65k
        {
1137
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_DEBLOCK_FILTER, &cs, CH_L );
1138
4.65k
          PelUnitBuf reco = cs.picture->getRecoBuf();
1139
4.65k
          encSlice->m_pLoopFilter->xDeblockArea<EDGE_HOR>( cs, ctuArea, MAX_NUM_CH, reco );
1140
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1141
4.65k
        }
1142
1143
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_lfHor );
1144
1145
4.65k
        processStates[ ctuRsAddr ] = SAO_FILTER;
1146
4.65k
      }
1147
0
      break;
1148
1149
    // SAO filter
1150
4.65k
    case SAO_FILTER:
1151
4.65k
      {
1152
        // general wpp conditions, top and top-right ctu have to be filtered
1153
4.65k
        if( checkCtuTaskNbTop   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER, true ) ) return false;
1154
4.65k
        if( checkCtuTaskNbTopRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER, true ) ) return false;
1155
1156
        // ensure loop filter of neighbor ctu's will not modify current residual
1157
        // sao processing dependents on +1 pixel to each side
1158
        // due to wpp condition above, only right, bottom and bottom-right ctu have to be checked
1159
4.65k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR,    true ) ) return false;
1160
4.65k
        if( checkCtuTaskNbBot   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR,    true ) ) return false;
1161
4.65k
        if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR, 1, true ) ) return false;
1162
1163
4.65k
        if( checkReadyState )
1164
0
          return true;
1165
1166
4.65k
        ITT_TASKSTART( itt_domain_encode, itt_handle_sao );
1167
1168
        // SAO filter
1169
4.65k
        if( slice.sps->saoEnabled && pic->useSAO )
1170
4.65k
        {
1171
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_SAO, &cs, CH_L );
1172
4.65k
          TileLineEncRsrc* lineEncRsrc    = encSlice->m_TileLineEncRsrc[ lineIdx ];
1173
4.65k
          PerThreadRsrc* taskRsrc         = &encSlice->m_threadRsrc->get( threadIdx );
1174
4.65k
          EncSampleAdaptiveOffset& encSao = lineEncRsrc->m_encSao;
1175
1176
4.65k
          encSao.setCtuEncRsrc( &lineEncRsrc->m_SaoCABACEstimator, &taskRsrc->m_CtxCache, &taskRsrc->m_saoCtuBuf );
1177
4.65k
          encSao.loadCtuPreSao( cs, ctuArea, ctuPosY, encSlice->m_saoPreFilterEdges );
1178
4.65k
          encSao.getCtuStatistics( cs, encSlice->m_saoStatData, ctuArea, ctuRsAddr );
1179
4.65k
          encSao.decideCtuParams( cs, encSlice->m_saoStatData, encSlice->m_saoEnabled, encSlice->m_saoAllDisabled, ctuArea, ctuRsAddr, &encSlice->m_saoReconParams[ 0 ], cs.picture->getSAO() );
1180
4.65k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1181
4.65k
        }
1182
1183
        // ALF border extension
1184
4.65k
        if( cs.sps->alfEnabled )
1185
4.65k
        {
1186
          // we have to do some kind of position aware boundary padding
1187
          // it's done here because the conditions are readable
1188
4.65k
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1189
4.65k
          const int fltSize  = ( MAX_ALF_FILTER_LENGTH + 1 ) >> 1;
1190
4.65k
          const int xL       = ( ctuPosX == 0 )                 ? ( x-fltSize       ) : ( x );
1191
4.65k
          const int xR       = ( ctuPosX+1 == pcv.widthInCtus ) ? ( x+width+fltSize ) : ( x+width );
1192
1193
4.65k
          if( ctuPosX == 0 )                  recoBuf.extendBorderPelLft( y, height, fltSize );
1194
4.65k
          if( ctuPosX+1 == pcv.widthInCtus )  recoBuf.extendBorderPelRgt( y, height, fltSize );
1195
4.65k
          if( ctuPosY == 0 )                  recoBuf.extendBorderPelTop( xL, xR-xL, fltSize );
1196
4.65k
          if( ctuPosY+1 == pcv.heightInCtus ) recoBuf.extendBorderPelBot( xL, xR-xL, fltSize );
1197
1198
4.65k
          encSlice->m_pALF->copyCTUforALF(cs, ctuPosX, ctuPosY);
1199
4.65k
        }
1200
1201
        // The motion of the CTU is final, and so is its DMVR refinement, which only temporal motion vector
1202
        // prediction uses.
1203
4.65k
        if( cs.hasColocatedMotionBuf() )
1204
4.65k
        {
1205
4.65k
          CS::setColocatedMotionCTU( cs, ctuPosX, ctuPosY, slice.sps->DMVR && !slice.picHeader->disDmvrFlag );
1206
4.65k
        }
1207
4.65k
        ITT_TASKEND( itt_domain_encode, itt_handle_sao );
1208
1209
4.65k
        const int tileCol = slice.pps->ctuToTileCol[ctuPosX];
1210
4.65k
        const int lastCtuColInTileRow = slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1211
4.65k
        if( ctuPosX == lastCtuColInTileRow )
1212
2.55k
        {
1213
2.55k
          processStates[ctuRsAddr] = ALF_GET_STATISTICS;
1214
2.55k
        }
1215
2.09k
        else
1216
2.09k
        {
1217
2.09k
          processStates[ctuRsAddr] = PROCESS_DONE;
1218
2.09k
          return true;
1219
2.09k
        }
1220
4.65k
      }
1221
2.55k
      break;
1222
1223
2.55k
    case ALF_GET_STATISTICS:
1224
2.55k
      {
1225
        // ensure all surrounding ctu's are filtered (ALF will use pixels of adjacent CTU's)
1226
        // due to wpp condition above in SAO_FILTER, only right, bottom and bottom-right ctu have to be checked
1227
2.55k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1228
2.55k
        if( checkCtuTaskNbBot   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1229
2.55k
        if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1230
1231
2.55k
        if( checkReadyState )
1232
0
          return true;
1233
1234
2.55k
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_stat );
1235
1236
        // ALF pre-processing
1237
2.55k
        if( slice.sps->alfEnabled )
1238
2.55k
        {
1239
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1240
2.55k
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1241
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1242
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1243
4.65k
          {
1244
4.65k
            encSlice->m_pALF->getStatisticsCTU( *cs.picture, cs, recoBuf, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1245
4.65k
          }
1246
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1247
2.55k
        }
1248
1249
2.55k
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_stat );
1250
1251
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1252
2.55k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1253
2.55k
        processStates[ctuRsAddr] = (ctuRsAddr < deriveFilterCtu) ? ALF_RECONSTRUCT: ALF_DERIVE_FILTER;
1254
2.55k
      }
1255
0
      break;
1256
1257
1.43k
    case ALF_DERIVE_FILTER:
1258
1.43k
      {
1259
1.43k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1260
1.43k
        if( ctuRsAddr == deriveFilterCtu )
1261
1.43k
        {
1262
          // ensure statistics from all previous ctu's have been collected
1263
1.43k
          int numCheckLines = deriveFilterCtu / pcv.widthInCtus + 1;
1264
3.99k
          for( int y = 0; y < numCheckLines; y++ )
1265
2.55k
          {
1266
5.11k
            for( int tileCol = 0; tileCol < slice.pps->numTileCols; tileCol++ )
1267
2.55k
            {
1268
2.55k
              const int lastCtuInTileRow = y * pcv.widthInCtus + slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1269
2.55k
              if( processStates[lastCtuInTileRow] <= ALF_GET_STATISTICS )
1270
0
                return false;
1271
2.55k
            }
1272
2.55k
          }
1273
1.43k
        }
1274
0
        else if( syncLines )
1275
0
        {
1276
          // ALF bitstream coding dependency for the sub-sequent ctu-lines
1277
0
          if( processStates[deriveFilterCtu] < ALF_RECONSTRUCT || checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, ALF_DERIVE_FILTER ) ) 
1278
0
            return false;
1279
0
        }
1280
1.43k
        if( checkReadyState )
1281
0
          return true;
1282
1283
1.43k
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_derive );
1284
        // ALF post-processing
1285
1.43k
        if( slice.sps->alfEnabled )
1286
1.43k
        {
1287
1.43k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1288
1.43k
          if( ctuRsAddr == deriveFilterCtu )
1289
1.43k
          {
1290
1.43k
            encSlice->m_pALF->initDerivation( slice );
1291
1.43k
            encSlice->m_pALF->deriveFilter( *cs.picture, cs, slice.getLambdas(), deriveFilterCtu + 1 );
1292
1.43k
            encSlice->m_pALF->reconstructCoeffAPSs( cs, cs.slice->alfEnabled[COMP_Y], cs.slice->alfEnabled[COMP_Cb] || cs.slice->alfEnabled[COMP_Cr], false );
1293
1.43k
          }
1294
0
          else if( syncLines )
1295
0
          {
1296
            // in sync lines mode: derive/select filter for the remaining lines
1297
0
            TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1298
0
            PerThreadRsrc*   taskRsrc    = &encSlice->m_threadRsrc->get( threadIdx );
1299
0
            const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1300
0
            for(int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++)
1301
0
            {
1302
0
              encSlice->m_pALF->selectFilterForCTU( cs, &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, ctu );
1303
0
            }
1304
0
          }
1305
1.43k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1306
1.43k
        }
1307
1308
1.43k
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_derive );
1309
1.43k
        processStates[ ctuRsAddr ] = ALF_RECONSTRUCT;
1310
1.43k
      }
1311
0
      break;
1312
1313
2.55k
    case ALF_RECONSTRUCT:
1314
2.55k
      {
1315
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1316
2.55k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1317
2.55k
        if( processStates[deriveFilterCtu] < ALF_RECONSTRUCT )
1318
0
          return false;
1319
2.55k
        else if( syncLines && ctuRsAddr > deriveFilterCtu && encSlice->m_pALF->getAsuHeightInCtus() > 1 )
1320
0
        {
1321
0
          const int asuHeightInCtus = encSlice->m_pALF->getAsuHeightInCtus();
1322
0
          const int botCtuLineInAsu = std::min( (( ctuPosY & ( ~(asuHeightInCtus - 1) ) ) + asuHeightInCtus - 1), (int)pcv.heightInCtus - 1 );
1323
0
          if( processStates[botCtuLineInAsu * ctuStride + ctuPosX] < ALF_RECONSTRUCT ) 
1324
0
            return false;
1325
0
        }
1326
1327
2.55k
        if( checkReadyState )
1328
0
          return true;
1329
1330
2.55k
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_recon );
1331
1332
2.55k
        if( slice.sps->alfEnabled )
1333
2.55k
        {
1334
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1335
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1336
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1337
4.65k
          {
1338
4.65k
            encSlice->m_pALF->reconstructCTU_MT( *cs.picture, cs, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1339
4.65k
          }
1340
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1341
2.55k
        }
1342
1343
2.55k
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_recon );
1344
2.55k
        processStates[ctuRsAddr] = CCALF_GET_STATISTICS;
1345
        // neighbours waiting for this state may run now, while this task goes on with the next stage
1346
2.55k
        if( encSlice->m_threadPool )
1347
2.55k
        {
1348
2.55k
          encSlice->m_threadPool->signalProgress();
1349
2.55k
        }
1350
2.55k
      }
1351
      // dont break, no additional deps, can continue straigt away!
1352
      //break;
1353
1354
2.55k
    case CCALF_GET_STATISTICS:
1355
2.55k
      {
1356
        // No wait for the lines above and below: the statistics read their luma from the pre-ALF copy, complete since
1357
        // ALF_GET_STATISTICS waited for SAO below, and their chroma only inside this line
1358
2.55k
        if( checkReadyState )
1359
0
          return true;
1360
1361
2.55k
        const bool statsUnused = encSlice->xCcAlfStatsUnused( processStates, ctuRsAddr );
1362
1363
2.55k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_stat );
1364
1365
        // ALF pre-processing
1366
2.55k
        if( slice.sps->ccalfEnabled && !statsUnused )
1367
2.55k
        {
1368
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L);
1369
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1370
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1371
4.65k
          {
1372
4.65k
            encSlice->m_pALF->deriveStatsForCcAlfFilteringCTU( cs, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1373
4.65k
          }
1374
2.55k
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1375
2.55k
        }
1376
1377
2.55k
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_stat );
1378
1379
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1380
2.55k
        processStates[ctuRsAddr] = (ctuRsAddr < encSlice->m_ccalfDeriveCtu) ? CCALF_RECONSTRUCT: CCALF_DERIVE_FILTER;
1381
2.55k
      }
1382
0
      break;
1383
1384
1.43k
    case CCALF_DERIVE_FILTER:
1385
1.43k
      {
1386
        // synchronization dependencies
1387
1.43k
        const unsigned deriveFilterCtu = encSlice->m_ccalfDeriveCtu;
1388
1.43k
        if( ctuRsAddr == deriveFilterCtu )
1389
1.43k
        {
1390
          // ensure statistics from all previous ctu's have been collected
1391
1.43k
          int numCheckLines = deriveFilterCtu / pcv.widthInCtus + 1;
1392
3.99k
          for( int y = 0; y < numCheckLines; y++ )
1393
2.55k
          {
1394
5.11k
            for( int tileCol = 0; tileCol < slice.pps->numTileCols; tileCol++ )
1395
2.55k
            {
1396
2.55k
              const int lastCtuInTileRow = y * pcv.widthInCtus + slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1397
2.55k
              if( processStates[lastCtuInTileRow] <= CCALF_GET_STATISTICS )
1398
0
                return false;
1399
2.55k
            }
1400
2.55k
          }
1401
1.43k
        }
1402
0
        else if( syncLines )
1403
0
        {
1404
          // ALF bitstream coding dependency for the sub-sequent CTU-lines
1405
0
          if( processStates[deriveFilterCtu] < CCALF_RECONSTRUCT || checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CCALF_DERIVE_FILTER ) ) 
1406
0
            return false;
1407
0
        }
1408
1.43k
        if( checkReadyState )
1409
0
          return true;
1410
1411
1.43k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_derive );
1412
1413
        // start task
1414
1.43k
        if( slice.sps->ccalfEnabled )
1415
1.43k
        {
1416
1.43k
          if( ctuRsAddr == deriveFilterCtu )
1417
1.43k
          {
1418
1.43k
            encSlice->m_pALF->deriveCcAlfFilter( *cs.picture, cs, encSlice->m_ccalfDeriveCtu + 1 );
1419
1.43k
          }
1420
0
          else if( syncLines )
1421
0
          {
1422
            // in sync lines mode: derive/select filter for the remaining lines
1423
0
            TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1424
0
            PerThreadRsrc*   taskRsrc    = &encSlice->m_threadRsrc->get( threadIdx );
1425
0
            const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1426
0
            encSlice->m_pALF->selectCcAlfFilterForCtuLine( cs, COMP_Cb, cs.getRecoBuf(), &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, firstCtuInRow, ctuRsAddr );
1427
0
            encSlice->m_pALF->selectCcAlfFilterForCtuLine( cs, COMP_Cr, cs.getRecoBuf(), &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, firstCtuInRow, ctuRsAddr );
1428
0
          }
1429
1.43k
        }
1430
1.43k
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_derive );
1431
1432
        // IFP: the ALF filters (derived before, at ALF_DERIVE_FILTER) and the CC-ALF filters are final now
1433
1.43k
        if( ctuRsAddr == deriveFilterCtu && syncLines && encSlice->m_alfFiltersDerived )
1434
0
        {
1435
0
          encSlice->m_alfFiltersDerived( *cs.picture );
1436
0
        }
1437
1438
1.43k
        processStates[ctuRsAddr] = CCALF_RECONSTRUCT;
1439
1.43k
      }
1440
0
      break;
1441
1442
2.55k
    case CCALF_RECONSTRUCT:
1443
2.55k
      {
1444
        // start ccalf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1445
2.55k
        const unsigned deriveFilterCtu = encSlice->m_ccalfDeriveCtu;
1446
2.55k
        if( processStates[deriveFilterCtu] < CCALF_RECONSTRUCT )
1447
0
          return false;
1448
1449
2.55k
        if( syncLines )
1450
0
        {
1451
          // ensure line-by-line reconstruction due to line synchronization
1452
0
          if( checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CCALF_RECONSTRUCT ) ) return false;
1453
0
        }
1454
1455
2.55k
        if( checkReadyState )
1456
0
          return true;
1457
1458
2.55k
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_recon );
1459
1460
2.55k
        if( slice.sps->ccalfEnabled )
1461
2.55k
        {
1462
2.55k
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1463
7.21k
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1464
4.65k
          {
1465
4.65k
            encSlice->m_pALF->applyCcAlfFilterCTU( cs, COMP_Cb, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1466
4.65k
            encSlice->m_pALF->applyCcAlfFilterCTU( cs, COMP_Cr, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1467
4.65k
          }
1468
2.55k
        }
1469
1470
2.55k
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_recon );
1471
1472
        // extend pic border
1473
        // CCALF reconstruction stage is done per tile, ensure that all tiles in current CTU row are done  
1474
2.55k
        if( ++(pic->m_tileColsDone->at(ctuPosY)) >= pps.numTileCols )
1475
2.55k
        {
1476
2.55k
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1477
2.55k
          const int margin = cs.picture->margin;
1478
2.55k
          recoBuf.extendBorderPelLft( y, height, margin );
1479
2.55k
          recoBuf.extendBorderPelRgt( y, height, margin );
1480
2.55k
          if(ctuPosY == 0)
1481
1.43k
            recoBuf.extendBorderPelTop( -margin, pcv.lumaWidth + 2 * margin, margin );
1482
2.55k
          if(ctuPosY + 1 == pcv.heightInCtus)
1483
1.43k
            recoBuf.extendBorderPelBot( -margin, pcv.lumaWidth + 2 * margin, margin );
1484
1485
          // for IFP lines synchro, do an additional increment signaling that CTU row is ready
1486
2.55k
          if( syncLines )
1487
0
            ++(pic->m_tileColsDone->at( ctuPosY ));
1488
2.55k
        }
1489
1490
        // perform finish only once for whole picture
1491
2.55k
        const unsigned finishCtu = pcv.sizeInCtus - 1;
1492
2.55k
        if( ctuRsAddr < finishCtu )
1493
1.12k
        {
1494
1.12k
          processStates[ctuRsAddr] = PROCESS_DONE;
1495
          // processing done => terminate thread
1496
1.12k
          return true;
1497
1.12k
        }
1498
1.43k
        processStates[ctuRsAddr] = FINISH_SLICE;
1499
        // the last row may make other pictures' CTU tasks ready, while this task goes on to finish the slice
1500
1.43k
        if( encSlice->m_threadPool )
1501
1.43k
        {
1502
1.43k
          encSlice->m_threadPool->signalProgress();
1503
1.43k
        }
1504
1.43k
      }
1505
1506
2.13k
    case FINISH_SLICE:
1507
2.13k
      {
1508
2.13k
        CHECK( ctuRsAddr != pcv.sizeInCtus - 1, "invalid state, finish slice only once for last ctu" );
1509
1510
        // ensure all coding tasks have been done for all previous ctu's
1511
6.00k
        for( int i = 0; i < ctuRsAddr; i++ )
1512
4.57k
          if( processStates[ i ] < FINISH_SLICE )
1513
705
            return false;
1514
1515
1.43k
        if( checkReadyState )
1516
0
          return true;
1517
1518
1.43k
        encSlice->finishCompressSlice( cs.picture, slice );
1519
1520
1.43k
        processStates[ ctuRsAddr ] = PROCESS_DONE;
1521
        // processing done => terminate thread
1522
1.43k
        return true;
1523
1.43k
      }
1524
1525
0
    case PROCESS_DONE:
1526
0
      CHECK( true, "process state is PROCESS_DONE, but thread is still running" );
1527
0
      return true;
1528
1529
0
    default:
1530
0
      CHECK( true, "unknown process state" );
1531
0
      return true;
1532
29.8k
  }
1533
1534
24.5k
  return false;
1535
29.8k
}
bool vvenc::EncSlice::xProcessCtuTask<true>(int, void*)
Line
Count
Source
959
13.8M
{
960
13.8M
  CtuEncParam* ctuEncParam       = static_cast<CtuEncParam*>( taskParam );
961
13.8M
  Picture* pic                   = ctuEncParam->pic;
962
13.8M
  EncSlice* encSlice             = ctuEncParam->encSlice;
963
13.8M
  CodingStructure& cs            = *pic->cs;
964
13.8M
  Slice&           slice         = *cs.slice;
965
13.8M
  const PPS&       pps           = *slice.pps;
966
13.8M
  const PreCalcValues& pcv       = *cs.pcv;
967
13.8M
  const int ctuRsAddr            = ctuEncParam->ctuRsAddr;
968
13.8M
  const int ctuPosX              = ctuEncParam->ctuPosX;
969
13.8M
  const int ctuPosY              = ctuEncParam->ctuPosY;
970
13.8M
  const int x                    = ctuPosX << pcv.maxCUSizeLog2;
971
13.8M
  const int y                    = ctuPosY << pcv.maxCUSizeLog2;
972
13.8M
  const int width                = std::min( pcv.maxCUSize, pcv.lumaWidth  - x );
973
13.8M
  const int height               = std::min( pcv.maxCUSize, pcv.lumaHeight - y );
974
13.8M
  const int ctuStride            = pcv.widthInCtus;
975
13.8M
  const int lineIdx              = ctuEncParam->tileLineResIdx;
976
13.8M
  ProcessCtuState* processStates = encSlice->m_processStates.data();
977
13.8M
  const UnitArea& ctuArea        = ctuEncParam->ctuArea;
978
13.8M
  const bool wppSyncEnabled      = cs.sps->entropyCodingSyncEnabled;
979
13.8M
  const TaskType currState       = processStates[ ctuRsAddr ];
980
13.8M
  const unsigned syncLines       = encSlice->m_pcEncCfg->m_ifpLines;
981
982
13.8M
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "poc", cs.slice->poc ) );
983
13.8M
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "ctu", ctuRsAddr ) );
984
13.8M
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "final", processStates[ ctuRsAddr ] == CTU_ENCODE ? 0 : 1 ) );
985
986
  // process ctu's line wise from left to right
987
13.8M
  const bool tileParallel = encSlice->m_pcEncCfg->m_tileParallelCtuEnc;
988
13.8M
  if( tileParallel && currState == CTU_ENCODE && ctuPosX > 0 && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX - 1, ctuPosY ) )
989
0
    ; // for CTU_ENCODE on tile boundaries, allow parallel processing of tiles
990
13.8M
  else if( ctuPosX > 0 && processStates[ ctuRsAddr - 1 ] <= currState && currState < PROCESS_DONE )
991
7.05M
    return false;
992
993
6.78M
  switch( currState )
994
6.78M
  {
995
    // encode
996
1.49M
    case CTU_ENCODE:
997
1.49M
      {
998
        // CTU line-wise inter-frame parallel processing synchronization
999
1.49M
        if( syncLines )
1000
0
        {
1001
0
          const bool lineStart = ctuPosX == 0 || ( tileParallel && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX - 1, ctuPosY ) );
1002
0
          if( lineStart && !refPicCtuLineReady( slice, ctuPosY + (int)syncLines, pcv ) )
1003
0
          {
1004
0
            return false;
1005
0
          }
1006
0
        }
1007
1008
        // general wpp conditions, top and top-right ctu have to be encoded
1009
1.49M
        if( encSlice->m_pcEncCfg->m_tileParallelCtuEnc && ctuPosY > 0 && slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX, ctuPosY - 1 ) )
1010
0
          ; // allow parallel processing of CTU-encoding on independent tiles
1011
1.49M
        else if( ctuPosY > 0                                  && processStates[ ctuRsAddr - ctuStride     ] <= CTU_ENCODE )
1012
1.04M
          return false;
1013
455k
        else if( ctuPosY > 0 && ctuPosX + 1 < pcv.widthInCtus && processStates[ ctuRsAddr - ctuStride + 1 ] <= CTU_ENCODE && !wppSyncEnabled )
1014
450k
          return false;
1015
        
1016
4.65k
        if( checkReadyState )
1017
4.65k
          return true;
1018
1019
#ifdef TRACE_ENABLE_ITT
1020
        std::stringstream ss;
1021
        ss << "Encode_" << slice.poc << "_CTU_" << ctuPosY << "_" << ctuPosX;
1022
        __itt_string_handle* itt_handle_ctuEncode = __itt_string_handle_create( ss.str().c_str() );
1023
#endif
1024
18.4E
        ITT_TASKSTART( itt_domain_encode, itt_handle_ctuEncode );
1025
1026
18.4E
        TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1027
18.4E
        PerThreadRsrc* taskRsrc      = &encSlice->m_threadRsrc->get( threadIdx );
1028
18.4E
        EncCu& encCu                 = taskRsrc->m_encCu;
1029
1030
18.4E
        encCu.bindToPicture( encSlice->m_picEncState );
1031
18.4E
        encCu.setCtuEncRsrc( &lineEncRsrc->m_CABACEstimator, &taskRsrc->m_CtxCache, &lineEncRsrc->m_ReuseUniMv, &lineEncRsrc->m_BlkUniMvInfoBuffer, &lineEncRsrc->m_AffineProfList, &lineEncRsrc->m_CachedBvs );
1032
18.4E
        encCu.encodeCtu( pic, lineEncRsrc->m_prevQp, ctuPosX, ctuPosY );
1033
1034
        // cleanup line memory when last ctu in line done to reduce overall memory consumption
1035
18.4E
        if( encSlice->m_pcEncCfg->m_ensureWppBitEqual && ( ctuPosX == pcv.widthInCtus - 1 || slice.pps->getTileIdx( ctuPosX, ctuPosY ) != slice.pps->getTileIdx( ctuPosX + 1, ctuPosY ) ) )
1036
0
        {
1037
0
          lineEncRsrc->m_AffineProfList    .resetAffineMVList();
1038
0
          lineEncRsrc->m_BlkUniMvInfoBuffer.resetUniMvList();
1039
0
          lineEncRsrc->m_ReuseUniMv        .resetReusedUniMvs();
1040
0
          lineEncRsrc->m_CachedBvs         .resetIbcBvCand();
1041
0
        }
1042
1043
        // the line below reads these rows unfiltered (Picture::getRecoAboveCtuTop), and deblocking may start before it does
1044
18.4E
        if( ctuPosY + 1 < pcv.heightInCtus )
1045
0
        {
1046
0
          pic->keepCtuBottomRows( ctuArea );
1047
0
        }
1048
1049
18.4E
        DTRACE_UPDATE( g_trace_ctx, std::make_pair( "final", 1 ) );
1050
18.4E
        ITT_TASKEND( itt_domain_encode, itt_handle_ctuEncode );
1051
1052
18.4E
        processStates[ ctuRsAddr ] = LF_VER;
1053
18.4E
      }
1054
0
      break;
1055
1056
    // vertical loopfilter
1057
2.45M
    case LF_VER:
1058
2.45M
      {
1059
        // clip check to right tile border (CTU_ENCODE pre-processing delay due to IBC)
1060
2.45M
        const int tileCol = slice.pps->ctuToTileCol[ctuPosX];
1061
2.45M
        const int lastCtuPosXInTile = slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1062
2.45M
        const int checkRight = std::min<int>( encSlice->m_ctuEncDelay, lastCtuPosXInTile - ctuPosX );
1063
1064
2.45M
        const bool hasTiles = encSlice->m_pcEncCfg->m_tileParallelCtuEnc && slice.pps->getNumTiles() > 1;
1065
1066
        // need to check line above bcs of tiling, which allows CTU_ENCODE to run independently across tiles
1067
2.45M
        if( hasTiles )
1068
0
        {
1069
0
          if( ctuPosY > 0 )
1070
0
          {
1071
0
            for( int i = -!!ctuPosX; i <= checkRight; i++ )
1072
0
              if( pps.canFilterCtuBdry( ctuPosX, ctuPosY, i, -1 ) && processStates[ctuRsAddr - ctuStride + i] <= CTU_ENCODE )
1073
0
                return false;
1074
0
          }
1075
0
        }
1076
        
1077
        // ensure all surrounding ctu's are encoded (intra pred requires non-reshaped and unfiltered residual, IBC requires unfiltered samples too)
1078
        // check right with max offset (due to WPP condition above, this implies top-right has been already encoded)
1079
3.87M
        for( int i = hasTiles ? -!!ctuPosX : checkRight; i <= checkRight; i++ )
1080
2.45M
          if( pps.canFilterCtuBdry( ctuPosX, ctuPosY, i, 0 ) && processStates[ctuRsAddr + i] <= CTU_ENCODE )
1081
1.02M
            return false;
1082
1083
        // No wait for the line below: it reads the unfiltered rows above it from the kept CTU bottoms (keepCtuBottomRows).
1084
        // IBC reads far deeper into the unfiltered picture, so with IBC the bottom right CTU (1 CTU delay) must be encoded
1085
        // first; at the right picture border this checks the bottom CTU.
1086
1.42M
        if( pic->useIBC )
1087
1.42M
        {
1088
1.42M
          const int checkBottomRight = std::min<int>( 1, lastCtuPosXInTile - ctuPosX );
1089
1.42M
          if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CTU_ENCODE, checkBottomRight ) )
1090
1.42M
            return false;
1091
1.42M
        }
1092
1093
4.65k
        if( checkReadyState )
1094
4.65k
          return true;
1095
1096
18.4E
        ITT_TASKSTART( itt_domain_encode, itt_handle_rspLfVer );
1097
1098
        // loopfilter
1099
18.4E
        if( !cs.pps->deblockingFilterControlPresent || !cs.pps->deblockingFilterDisabled || cs.pps->deblockingFilterOverrideEnabled )
1100
0
        {
1101
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_DEBLOCK_FILTER, &cs, CH_L );
1102
          // calculate filter strengths
1103
0
          encSlice->m_pLoopFilter->calcFilterStrengthsCTU( cs, ctuArea, true );
1104
1105
          // vertical filter
1106
0
          PelUnitBuf reco = cs.picture->getRecoBuf();
1107
0
          encSlice->m_pLoopFilter->xDeblockArea<EDGE_VER>( cs, ctuArea, MAX_NUM_CH, reco );
1108
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1109
0
        }
1110
1111
18.4E
        ITT_TASKEND( itt_domain_encode, itt_handle_rspLfVer );
1112
1113
18.4E
        processStates[ ctuRsAddr ] = LF_HOR;
1114
18.4E
      }
1115
0
      break;
1116
1117
    // horizontal loopfilter
1118
400k
    case LF_HOR:
1119
400k
      {
1120
        // ensure horizontal ordering (from top to bottom)
1121
400k
        if( checkCtuTaskNbTop   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR ) )         
1122
135k
          return false;
1123
1124
        // ensure vertical loop filter of neighbor ctu's will not modify current residual
1125
        // check top, top-right and right ctu
1126
        // (top, top-right checked implicitly due to ordering check above)
1127
264k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_VER ) )
1128
260k
          return false;
1129
1130
4.65k
        if( checkReadyState )
1131
4.65k
          return true;
1132
1133
18.4E
        ITT_TASKSTART( itt_domain_encode, itt_handle_lfHor );
1134
1135
18.4E
        if( !cs.pps->deblockingFilterControlPresent || !cs.pps->deblockingFilterDisabled || cs.pps->deblockingFilterOverrideEnabled )
1136
0
        {
1137
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_DEBLOCK_FILTER, &cs, CH_L );
1138
0
          PelUnitBuf reco = cs.picture->getRecoBuf();
1139
0
          encSlice->m_pLoopFilter->xDeblockArea<EDGE_HOR>( cs, ctuArea, MAX_NUM_CH, reco );
1140
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1141
0
        }
1142
1143
18.4E
        ITT_TASKEND( itt_domain_encode, itt_handle_lfHor );
1144
1145
18.4E
        processStates[ ctuRsAddr ] = SAO_FILTER;
1146
18.4E
      }
1147
0
      break;
1148
1149
    // SAO filter
1150
802k
    case SAO_FILTER:
1151
802k
      {
1152
        // general wpp conditions, top and top-right ctu have to be filtered
1153
802k
        if( checkCtuTaskNbTop   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER, true ) ) return false;
1154
410k
        if( checkCtuTaskNbTopRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER, true ) ) return false;
1155
1156
        // ensure loop filter of neighbor ctu's will not modify current residual
1157
        // sao processing dependents on +1 pixel to each side
1158
        // due to wpp condition above, only right, bottom and bottom-right ctu have to be checked
1159
276k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR,    true ) ) return false;
1160
258k
        if( checkCtuTaskNbBot   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR,    true ) ) return false;
1161
14.4k
        if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, LF_HOR, 1, true ) ) return false;
1162
1163
4.65k
        if( checkReadyState )
1164
4.65k
          return true;
1165
1166
1
        ITT_TASKSTART( itt_domain_encode, itt_handle_sao );
1167
1168
        // SAO filter
1169
1
        if( slice.sps->saoEnabled && pic->useSAO )
1170
0
        {
1171
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_SAO, &cs, CH_L );
1172
0
          TileLineEncRsrc* lineEncRsrc    = encSlice->m_TileLineEncRsrc[ lineIdx ];
1173
0
          PerThreadRsrc* taskRsrc         = &encSlice->m_threadRsrc->get( threadIdx );
1174
0
          EncSampleAdaptiveOffset& encSao = lineEncRsrc->m_encSao;
1175
1176
0
          encSao.setCtuEncRsrc( &lineEncRsrc->m_SaoCABACEstimator, &taskRsrc->m_CtxCache, &taskRsrc->m_saoCtuBuf );
1177
0
          encSao.loadCtuPreSao( cs, ctuArea, ctuPosY, encSlice->m_saoPreFilterEdges );
1178
0
          encSao.getCtuStatistics( cs, encSlice->m_saoStatData, ctuArea, ctuRsAddr );
1179
0
          encSao.decideCtuParams( cs, encSlice->m_saoStatData, encSlice->m_saoEnabled, encSlice->m_saoAllDisabled, ctuArea, ctuRsAddr, &encSlice->m_saoReconParams[ 0 ], cs.picture->getSAO() );
1180
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1181
0
        }
1182
1183
        // ALF border extension
1184
1
        if( cs.sps->alfEnabled )
1185
0
        {
1186
          // we have to do some kind of position aware boundary padding
1187
          // it's done here because the conditions are readable
1188
0
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1189
0
          const int fltSize  = ( MAX_ALF_FILTER_LENGTH + 1 ) >> 1;
1190
0
          const int xL       = ( ctuPosX == 0 )                 ? ( x-fltSize       ) : ( x );
1191
0
          const int xR       = ( ctuPosX+1 == pcv.widthInCtus ) ? ( x+width+fltSize ) : ( x+width );
1192
1193
0
          if( ctuPosX == 0 )                  recoBuf.extendBorderPelLft( y, height, fltSize );
1194
0
          if( ctuPosX+1 == pcv.widthInCtus )  recoBuf.extendBorderPelRgt( y, height, fltSize );
1195
0
          if( ctuPosY == 0 )                  recoBuf.extendBorderPelTop( xL, xR-xL, fltSize );
1196
0
          if( ctuPosY+1 == pcv.heightInCtus ) recoBuf.extendBorderPelBot( xL, xR-xL, fltSize );
1197
1198
0
          encSlice->m_pALF->copyCTUforALF(cs, ctuPosX, ctuPosY);
1199
0
        }
1200
1201
        // The motion of the CTU is final, and so is its DMVR refinement, which only temporal motion vector
1202
        // prediction uses.
1203
1
        if( cs.hasColocatedMotionBuf() )
1204
0
        {
1205
0
          CS::setColocatedMotionCTU( cs, ctuPosX, ctuPosY, slice.sps->DMVR && !slice.picHeader->disDmvrFlag );
1206
0
        }
1207
1
        ITT_TASKEND( itt_domain_encode, itt_handle_sao );
1208
1209
1
        const int tileCol = slice.pps->ctuToTileCol[ctuPosX];
1210
1
        const int lastCtuColInTileRow = slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1211
1
        if( ctuPosX == lastCtuColInTileRow )
1212
0
        {
1213
0
          processStates[ctuRsAddr] = ALF_GET_STATISTICS;
1214
0
        }
1215
1
        else
1216
1
        {
1217
1
          processStates[ctuRsAddr] = PROCESS_DONE;
1218
1
          return true;
1219
1
        }
1220
1
      }
1221
0
      break;
1222
1223
206k
    case ALF_GET_STATISTICS:
1224
206k
      {
1225
        // ensure all surrounding ctu's are filtered (ALF will use pixels of adjacent CTU's)
1226
        // due to wpp condition above in SAO_FILTER, only right, bottom and bottom-right ctu have to be checked
1227
206k
        if( checkCtuTaskNbRgt   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1228
206k
        if( checkCtuTaskNbBot   ( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1229
2.55k
        if( checkCtuTaskNbBotRgt( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, SAO_FILTER ) ) return false;
1230
1231
2.55k
        if( checkReadyState )
1232
2.55k
          return true;
1233
1234
1
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_stat );
1235
1236
        // ALF pre-processing
1237
1
        if( slice.sps->alfEnabled )
1238
0
        {
1239
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1240
0
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1241
0
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1242
0
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1243
0
          {
1244
0
            encSlice->m_pALF->getStatisticsCTU( *cs.picture, cs, recoBuf, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1245
0
          }
1246
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1247
0
        }
1248
1249
1
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_stat );
1250
1251
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1252
1
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1253
1
        processStates[ctuRsAddr] = (ctuRsAddr < deriveFilterCtu) ? ALF_RECONSTRUCT: ALF_DERIVE_FILTER;
1254
1
      }
1255
0
      break;
1256
1257
474k
    case ALF_DERIVE_FILTER:
1258
474k
      {
1259
474k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1260
474k
        if( ctuRsAddr == deriveFilterCtu )
1261
474k
        {
1262
          // ensure statistics from all previous ctu's have been collected
1263
474k
          int numCheckLines = deriveFilterCtu / pcv.widthInCtus + 1;
1264
507k
          for( int y = 0; y < numCheckLines; y++ )
1265
505k
          {
1266
538k
            for( int tileCol = 0; tileCol < slice.pps->numTileCols; tileCol++ )
1267
505k
            {
1268
505k
              const int lastCtuInTileRow = y * pcv.widthInCtus + slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1269
505k
              if( processStates[lastCtuInTileRow] <= ALF_GET_STATISTICS )
1270
473k
                return false;
1271
505k
            }
1272
505k
          }
1273
474k
        }
1274
0
        else if( syncLines )
1275
0
        {
1276
          // ALF bitstream coding dependency for the sub-sequent ctu-lines
1277
0
          if( processStates[deriveFilterCtu] < ALF_RECONSTRUCT || checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, ALF_DERIVE_FILTER ) ) 
1278
0
            return false;
1279
0
        }
1280
1.43k
        if( checkReadyState )
1281
1.43k
          return true;
1282
1283
0
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_derive );
1284
        // ALF post-processing
1285
0
        if( slice.sps->alfEnabled )
1286
0
        {
1287
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1288
0
          if( ctuRsAddr == deriveFilterCtu )
1289
0
          {
1290
0
            encSlice->m_pALF->initDerivation( slice );
1291
0
            encSlice->m_pALF->deriveFilter( *cs.picture, cs, slice.getLambdas(), deriveFilterCtu + 1 );
1292
0
            encSlice->m_pALF->reconstructCoeffAPSs( cs, cs.slice->alfEnabled[COMP_Y], cs.slice->alfEnabled[COMP_Cb] || cs.slice->alfEnabled[COMP_Cr], false );
1293
0
          }
1294
0
          else if( syncLines )
1295
0
          {
1296
            // in sync lines mode: derive/select filter for the remaining lines
1297
0
            TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1298
0
            PerThreadRsrc*   taskRsrc    = &encSlice->m_threadRsrc->get( threadIdx );
1299
0
            const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1300
0
            for(int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++)
1301
0
            {
1302
0
              encSlice->m_pALF->selectFilterForCTU( cs, &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, ctu );
1303
0
            }
1304
0
          }
1305
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1306
0
        }
1307
1308
0
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_derive );
1309
0
        processStates[ ctuRsAddr ] = ALF_RECONSTRUCT;
1310
0
      }
1311
0
      break;
1312
1313
732k
    case ALF_RECONSTRUCT:
1314
732k
      {
1315
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1316
732k
        const unsigned deriveFilterCtu = encSlice->m_alfDeriveCtu;
1317
732k
        if( processStates[deriveFilterCtu] < ALF_RECONSTRUCT )
1318
729k
          return false;
1319
2.55k
        else if( syncLines && ctuRsAddr > deriveFilterCtu && encSlice->m_pALF->getAsuHeightInCtus() > 1 )
1320
0
        {
1321
0
          const int asuHeightInCtus = encSlice->m_pALF->getAsuHeightInCtus();
1322
0
          const int botCtuLineInAsu = std::min( (( ctuPosY & ( ~(asuHeightInCtus - 1) ) ) + asuHeightInCtus - 1), (int)pcv.heightInCtus - 1 );
1323
0
          if( processStates[botCtuLineInAsu * ctuStride + ctuPosX] < ALF_RECONSTRUCT ) 
1324
0
            return false;
1325
0
        }
1326
1327
2.55k
        if( checkReadyState )
1328
2.55k
          return true;
1329
1330
0
        ITT_TASKSTART( itt_domain_encode, itt_handle_alf_recon );
1331
1332
0
        if( slice.sps->alfEnabled )
1333
0
        {
1334
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L );
1335
0
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1336
0
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1337
0
          {
1338
0
            encSlice->m_pALF->reconstructCTU_MT( *cs.picture, cs, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1339
0
          }
1340
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1341
0
        }
1342
1343
0
        ITT_TASKEND( itt_domain_encode, itt_handle_alf_recon );
1344
0
        processStates[ctuRsAddr] = CCALF_GET_STATISTICS;
1345
        // neighbours waiting for this state may run now, while this task goes on with the next stage
1346
0
        if( encSlice->m_threadPool )
1347
0
        {
1348
0
          encSlice->m_threadPool->signalProgress();
1349
0
        }
1350
0
      }
1351
      // dont break, no additional deps, can continue straigt away!
1352
      //break;
1353
1354
0
    case CCALF_GET_STATISTICS:
1355
0
      {
1356
        // No wait for the lines above and below: the statistics read their luma from the pre-ALF copy, complete since
1357
        // ALF_GET_STATISTICS waited for SAO below, and their chroma only inside this line
1358
0
        if( checkReadyState )
1359
0
          return true;
1360
1361
0
        const bool statsUnused = encSlice->xCcAlfStatsUnused( processStates, ctuRsAddr );
1362
1363
0
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_stat );
1364
1365
        // ALF pre-processing
1366
0
        if( slice.sps->ccalfEnabled && !statsUnused )
1367
0
        {
1368
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_ALF, &cs, CH_L);
1369
0
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1370
0
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1371
0
          {
1372
0
            encSlice->m_pALF->deriveStatsForCcAlfFilteringCTU( cs, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1373
0
          }
1374
0
          PROFILER_EXT_ACCUM_AND_START_NEW_SET( 1, _TPROF, P_IGNORE, &cs, CH_L );
1375
0
        }
1376
1377
0
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_stat );
1378
1379
        // start alf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1380
0
        processStates[ctuRsAddr] = (ctuRsAddr < encSlice->m_ccalfDeriveCtu) ? CCALF_RECONSTRUCT: CCALF_DERIVE_FILTER;
1381
0
      }
1382
0
      break;
1383
1384
129k
    case CCALF_DERIVE_FILTER:
1385
129k
      {
1386
        // synchronization dependencies
1387
129k
        const unsigned deriveFilterCtu = encSlice->m_ccalfDeriveCtu;
1388
129k
        if( ctuRsAddr == deriveFilterCtu )
1389
129k
        {
1390
          // ensure statistics from all previous ctu's have been collected
1391
129k
          int numCheckLines = deriveFilterCtu / pcv.widthInCtus + 1;
1392
145k
          for( int y = 0; y < numCheckLines; y++ )
1393
144k
          {
1394
160k
            for( int tileCol = 0; tileCol < slice.pps->numTileCols; tileCol++ )
1395
144k
            {
1396
144k
              const int lastCtuInTileRow = y * pcv.widthInCtus + slice.pps->tileColBd[tileCol] + slice.pps->tileColWidth[tileCol] - 1;
1397
144k
              if( processStates[lastCtuInTileRow] <= CCALF_GET_STATISTICS )
1398
127k
                return false;
1399
144k
            }
1400
144k
          }
1401
129k
        }
1402
0
        else if( syncLines )
1403
0
        {
1404
          // ALF bitstream coding dependency for the sub-sequent CTU-lines
1405
0
          if( processStates[deriveFilterCtu] < CCALF_RECONSTRUCT || checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CCALF_DERIVE_FILTER ) ) 
1406
0
            return false;
1407
0
        }
1408
1.43k
        if( checkReadyState )
1409
1.43k
          return true;
1410
1411
0
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_derive );
1412
1413
        // start task
1414
0
        if( slice.sps->ccalfEnabled )
1415
0
        {
1416
0
          if( ctuRsAddr == deriveFilterCtu )
1417
0
          {
1418
0
            encSlice->m_pALF->deriveCcAlfFilter( *cs.picture, cs, encSlice->m_ccalfDeriveCtu + 1 );
1419
0
          }
1420
0
          else if( syncLines )
1421
0
          {
1422
            // in sync lines mode: derive/select filter for the remaining lines
1423
0
            TileLineEncRsrc* lineEncRsrc = encSlice->m_TileLineEncRsrc[ lineIdx ];
1424
0
            PerThreadRsrc*   taskRsrc    = &encSlice->m_threadRsrc->get( threadIdx );
1425
0
            const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1426
0
            encSlice->m_pALF->selectCcAlfFilterForCtuLine( cs, COMP_Cb, cs.getRecoBuf(), &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, firstCtuInRow, ctuRsAddr );
1427
0
            encSlice->m_pALF->selectCcAlfFilterForCtuLine( cs, COMP_Cr, cs.getRecoBuf(), &lineEncRsrc->m_AlfCABACEstimator, &taskRsrc->m_CtxCache, firstCtuInRow, ctuRsAddr );
1428
0
          }
1429
0
        }
1430
0
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_derive );
1431
1432
        // IFP: the ALF filters (derived before, at ALF_DERIVE_FILTER) and the CC-ALF filters are final now
1433
0
        if( ctuRsAddr == deriveFilterCtu && syncLines && encSlice->m_alfFiltersDerived )
1434
0
        {
1435
0
          encSlice->m_alfFiltersDerived( *cs.picture );
1436
0
        }
1437
1438
0
        processStates[ctuRsAddr] = CCALF_RECONSTRUCT;
1439
0
      }
1440
0
      break;
1441
1442
34.2k
    case CCALF_RECONSTRUCT:
1443
34.2k
      {
1444
        // start ccalf filter derivation either for a sub-set of CTUs (syncLines mode) or for the whole picture (regular mode)
1445
34.2k
        const unsigned deriveFilterCtu = encSlice->m_ccalfDeriveCtu;
1446
34.2k
        if( processStates[deriveFilterCtu] < CCALF_RECONSTRUCT )
1447
31.7k
          return false;
1448
1449
2.55k
        if( syncLines )
1450
0
        {
1451
          // ensure line-by-line reconstruction due to line synchronization
1452
0
          if( checkCtuTaskNbTop( pps, ctuPosX, ctuPosY, ctuRsAddr, processStates, CCALF_RECONSTRUCT ) ) return false;
1453
0
        }
1454
1455
2.55k
        if( checkReadyState )
1456
2.55k
          return true;
1457
1458
3
        ITT_TASKSTART( itt_domain_encode, itt_handle_ccalf_recon );
1459
1460
3
        if( slice.sps->ccalfEnabled )
1461
0
        {
1462
0
          const int firstCtuInRow = ctuRsAddr + 1 - slice.pps->tileColWidth[slice.pps->ctuToTileCol[ctuPosX]];
1463
0
          for( int ctu = firstCtuInRow; ctu <= ctuRsAddr; ctu++ )
1464
0
          {
1465
0
            encSlice->m_pALF->applyCcAlfFilterCTU( cs, COMP_Cb, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1466
0
            encSlice->m_pALF->applyCcAlfFilterCTU( cs, COMP_Cr, ctu, encSlice->m_threadRsrc->get( threadIdx ).m_alfTempCtuBuf );
1467
0
          }
1468
0
        }
1469
1470
3
        ITT_TASKEND( itt_domain_encode, itt_handle_ccalf_recon );
1471
1472
        // extend pic border
1473
        // CCALF reconstruction stage is done per tile, ensure that all tiles in current CTU row are done  
1474
3
        if( ++(pic->m_tileColsDone->at(ctuPosY)) >= pps.numTileCols )
1475
0
        {
1476
0
          PelUnitBuf recoBuf = cs.picture->getRecoBuf();
1477
0
          const int margin = cs.picture->margin;
1478
0
          recoBuf.extendBorderPelLft( y, height, margin );
1479
0
          recoBuf.extendBorderPelRgt( y, height, margin );
1480
0
          if(ctuPosY == 0)
1481
0
            recoBuf.extendBorderPelTop( -margin, pcv.lumaWidth + 2 * margin, margin );
1482
0
          if(ctuPosY + 1 == pcv.heightInCtus)
1483
0
            recoBuf.extendBorderPelBot( -margin, pcv.lumaWidth + 2 * margin, margin );
1484
1485
          // for IFP lines synchro, do an additional increment signaling that CTU row is ready
1486
0
          if( syncLines )
1487
0
            ++(pic->m_tileColsDone->at( ctuPosY ));
1488
0
        }
1489
1490
        // perform finish only once for whole picture
1491
3
        const unsigned finishCtu = pcv.sizeInCtus - 1;
1492
3
        if( ctuRsAddr < finishCtu )
1493
0
        {
1494
0
          processStates[ctuRsAddr] = PROCESS_DONE;
1495
          // processing done => terminate thread
1496
0
          return true;
1497
0
        }
1498
3
        processStates[ctuRsAddr] = FINISH_SLICE;
1499
        // the last row may make other pictures' CTU tasks ready, while this task goes on to finish the slice
1500
3
        if( encSlice->m_threadPool )
1501
0
        {
1502
0
          encSlice->m_threadPool->signalProgress();
1503
0
        }
1504
3
      }
1505
1506
57.7k
    case FINISH_SLICE:
1507
57.7k
      {
1508
57.7k
        CHECK( ctuRsAddr != pcv.sizeInCtus - 1, "invalid state, finish slice only once for last ctu" );
1509
1510
        // ensure all coding tasks have been done for all previous ctu's
1511
117k
        for( int i = 0; i < ctuRsAddr; i++ )
1512
116k
          if( processStates[ i ] < FINISH_SLICE )
1513
57.0k
            return false;
1514
1515
708
        if( checkReadyState )
1516
705
          return true;
1517
1518
3
        encSlice->finishCompressSlice( cs.picture, slice );
1519
1520
3
        processStates[ ctuRsAddr ] = PROCESS_DONE;
1521
        // processing done => terminate thread
1522
3
        return true;
1523
708
      }
1524
1525
0
    case PROCESS_DONE:
1526
0
      CHECK( true, "process state is PROCESS_DONE, but thread is still running" );
1527
0
      return true;
1528
1529
0
    default:
1530
0
      CHECK( true, "unknown process state" );
1531
0
      return true;
1532
6.78M
  }
1533
1534
0
  return false;
1535
6.78M
}
1536
1537
void EncSlice::encodeSliceData( Picture* pic )
1538
1.43k
{
1539
1.43k
  CodingStructure& cs              = *pic->cs;
1540
1.43k
  Slice* const slice               = cs.slice;
1541
1.43k
  const uint32_t startCtuTsAddr    = slice->sliceMap.ctuAddrInSlice[0];
1542
1.43k
  const uint32_t boundingCtuTsAddr = cs.pcv->sizeInCtus;
1543
1.43k
  const bool wavefrontsEnabled     = slice->sps->entropyCodingSyncEnabled;
1544
1545
  // this ensures that independently encoded bitstream chunks can be combined to bit-equal
1546
1.43k
  const SliceType cabacTableIdx = ! slice->pps->cabacInitPresent || slice->pendingRasInit ? slice->sliceType : m_encCABACTableIdx;
1547
1.43k
  slice->encCABACTableIdx = cabacTableIdx;
1548
1549
  // initialise entropy coder for the slice
1550
1.43k
  m_CABACWriter.initCtxModels( *slice );
1551
1552
1.43k
  DTRACE( g_trace_ctx, D_HEADER, "=========== POC: %d ===========\n", slice->poc );
1553
1554
1.43k
  int prevQP[MAX_NUM_CH];
1555
1.43k
  prevQP[0] = prevQP[1] = slice->sliceQp;
1556
1557
1.43k
  const PreCalcValues& pcv        = *cs.pcv;
1558
1.43k
  const uint32_t widthInCtus      = pcv.widthInCtus;
1559
1.43k
  uint32_t uiSubStrm              = 0;
1560
1.43k
  const int numSubstreamsColumns  = slice->pps->numTileCols;
1561
1.43k
  const int numSubstreamRows      = slice->sps->entropyCodingSyncEnabled ? pic->cs->pcv->heightInCtus : slice->pps->numTileRows;
1562
1.43k
  const int numSubstreams         = std::max<int>( numSubstreamRows * numSubstreamsColumns, 0/*(int)pic->brickMap->bricks.size()*/ );
1563
1.43k
  std::vector<OutputBitstream> substreamsOut( numSubstreams );
1564
1565
1.43k
  slice->clearSubstreamSizes();
1566
1567
6.08k
  for( uint32_t ctuTsAddr = startCtuTsAddr; ctuTsAddr < boundingCtuTsAddr; ctuTsAddr++ )
1568
4.65k
  {
1569
4.65k
    const uint32_t ctuRsAddr            = slice->sliceMap.ctuAddrInSlice[ctuTsAddr];
1570
4.65k
    const uint32_t ctuXPosInCtus        = ctuRsAddr % widthInCtus;
1571
4.65k
    const uint32_t ctuYPosInCtus        = ctuRsAddr / widthInCtus;
1572
4.65k
    const uint32_t tileXPosInCtus       = slice->pps->tileColBd[cs.pps->ctuToTileCol[ctuXPosInCtus]];
1573
4.65k
    const uint32_t tileYPosInCtus       = slice->pps->tileRowBd[cs.pps->ctuToTileRow[ctuYPosInCtus]];
1574
1575
4.65k
    DTRACE_UPDATE( g_trace_ctx, std::make_pair( "ctu", ctuRsAddr ) );
1576
1577
4.65k
    const Position pos (ctuXPosInCtus * pcv.maxCUSize, ctuYPosInCtus * pcv.maxCUSize);
1578
4.65k
    const UnitArea ctuArea (cs.area.chromaFormat, Area(pos.x, pos.y, pcv.maxCUSize, pcv.maxCUSize));
1579
4.65k
    CHECK( uiSubStrm >= numSubstreams, "array index out of bounds" );
1580
4.65k
    m_CABACWriter.initBitstream( &substreamsOut[ uiSubStrm ] );
1581
1582
    // set up CABAC contexts' state for this CTU
1583
4.65k
    if (ctuXPosInCtus == tileXPosInCtus && ctuYPosInCtus == tileYPosInCtus )
1584
1.43k
    {
1585
1.43k
      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
1586
0
      {
1587
0
        m_CABACWriter.initCtxModels( *slice );
1588
0
      }
1589
1.43k
      prevQP[0] = prevQP[1] = slice->sliceQp;
1590
1.43k
    }
1591
3.22k
    else if (ctuXPosInCtus == tileXPosInCtus && wavefrontsEnabled)
1592
0
    {
1593
      // Synchronize cabac probabilities with upper-right CTU if it's available and at the start of a line.
1594
0
      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
1595
0
      {
1596
0
        m_CABACWriter.initCtxModels( *slice );
1597
0
      }
1598
0
      if( cs.getCURestricted( pos.offset( 0, -1 ), pos, slice->independentSliceIdx, slice->pps->getTileIdx( ctuXPosInCtus, ctuYPosInCtus ), CH_L, TREE_D ) )
1599
0
      {
1600
        // Top-right is available, so use it.
1601
0
        m_CABACWriter.getCtx() = m_entropyCodingSyncContextState;
1602
0
      }
1603
0
      prevQP[0] = prevQP[1] = slice->sliceQp;
1604
0
    }
1605
1606
4.65k
    m_CABACWriter.coding_tree_unit( cs, ctuArea, prevQP, ctuRsAddr );
1607
1608
    // store probabilities of second CTU in line into buffer
1609
4.65k
    if( ctuXPosInCtus == tileXPosInCtus && wavefrontsEnabled )
1610
0
    {
1611
0
      m_entropyCodingSyncContextState = m_CABACWriter.getCtx();
1612
0
    }
1613
1614
    // terminate the sub-stream, if required (end of slice-segment, end of tile, end of wavefront-CTU-row):
1615
4.65k
    bool isMoreCTUsinSlice = ctuTsAddr != (boundingCtuTsAddr - 1);
1616
4.65k
    bool isLastCTUinTile   = isMoreCTUsinSlice && slice->pps->getTileIdx( ctuRsAddr ) != slice->pps->getTileIdx( slice->sliceMap.ctuAddrInSlice[ctuTsAddr+1] );
1617
4.65k
    bool isLastCTUinWPP    = wavefrontsEnabled && isMoreCTUsinSlice && !isLastCTUinTile && ( (slice->sliceMap.ctuAddrInSlice[ctuTsAddr+1] % widthInCtus) == cs.pps->tileColBd[cs.pps->ctuToTileCol[slice->sliceMap.ctuAddrInSlice[ctuTsAddr+1] % widthInCtus]] ); //TODO: adjust tile bound condition
1618
1619
4.65k
    if (isLastCTUinWPP || !isMoreCTUsinSlice || isLastCTUinTile )         // this the the last CTU of either tile/brick/WPP/slice
1620
1.43k
    {
1621
1.43k
      m_CABACWriter.end_of_slice();
1622
1623
      // Byte-alignment in slice_data() when new tile
1624
1.43k
      substreamsOut[ uiSubStrm ].writeByteAlignment();
1625
1626
1.43k
      if (isMoreCTUsinSlice) //Byte alignment only when it is not the last substream in the slice
1627
0
      {
1628
        // write sub-stream size
1629
0
        slice->addSubstreamSize( ( substreamsOut[ uiSubStrm ].getNumberOfWrittenBits() >> 3 ) + substreamsOut[ uiSubStrm ].countStartCodeEmulations() );
1630
0
      }
1631
1.43k
      uiSubStrm++;
1632
1.43k
    }
1633
4.65k
  } // CTU-loop
1634
1635
1.43k
  if(slice->pps->cabacInitPresent)
1636
0
  {
1637
0
    m_encCABACTableIdx = m_CABACWriter.getCtxInitId( *slice );
1638
0
  }
1639
1.43k
  else
1640
1.43k
  {
1641
1.43k
    m_encCABACTableIdx = slice->sliceType;
1642
1.43k
  }
1643
1644
  // concatenate substreams
1645
1.43k
  OutputBitstream& outStream = pic->sliceDataStreams[ 0/*slice->sliceIdx*/ ];
1646
2.86k
  for ( int i = 0; i < slice->getNumberOfSubstreamSizes() + 1; i++ )
1647
1.43k
  {
1648
1.43k
    outStream.addSubstream( &(substreamsOut[ i ]) );
1649
1.43k
  }
1650
1.43k
  pic->sliceDataNumBins += m_CABACWriter.getNumBins();
1651
1.43k
}
1652
1653
} // namespace vvenc
1654
1655
//! \}
1656