Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/EncoderLib/EncModeCtrl.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     EncModeCtrl.cpp
45
    \brief    Encoder controller for trying out specific modes
46
*/
47
48
#include "EncCu.h"
49
50
#include "EncModeCtrl.h"
51
#include "CommonLib/RdCost.h"
52
#include "CommonLib/CodingStructure.h"
53
#include "CommonLib/Picture.h"
54
#include "CommonLib/UnitTools.h"
55
#include "CommonLib/dtrace_next.h"
56
57
#include <algorithm>
58
#include <cmath>
59
60
//! \ingroup EncoderLib
61
//! \{
62
63
namespace vvenc {
64
65
void CacheBlkInfoCtrl::create(int ctuSize)
66
5.72k
{
67
5.72k
  const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
68
5.72k
  const int maxSizeIdx  = MAX_CU_SIZE_IDX - MIN_CU_LOG2;
69
70
  //static constexpr size_t numCu = 7921;
71
72
5.72k
  size_t numCu = 0;
73
  
74
40.0k
  for( int wIdx = 0; wIdx < maxSizeIdx; wIdx++ )
75
34.3k
  {
76
240k
    for( int hIdx = 0; hIdx < maxSizeIdx; hIdx++ )
77
206k
    {
78
6.80M
      for( unsigned y = 0; y < numPos; y++ )
79
6.59M
      {
80
217M
        for( unsigned x = 0; x < numPos; x++ )
81
211M
        {
82
          // a block of width W might be offset of N * W + 1/2 W (bcs of TT), same for H
83
          // W = 1 << ( wIdx + 2 )
84
          // 1/2 W = 1 << ( wIdx + 1 )
85
          // remainder of (N+1/2)*W -> x & ( ( 1 << ( wIdx + 1 ) ) - 1 )
86
  
87
211M
          if( (x + (1 << (wIdx)) <= (ctuSize >> MIN_CU_LOG2))
88
148M
              && (y + (1 << (hIdx)) <= (ctuSize >> MIN_CU_LOG2))
89
104M
              && (((x << MIN_CU_LOG2) & ((1 << (wIdx + MIN_CU_LOG2 - 1)) - 1)) == 0)
90
68.8M
              && (((y << MIN_CU_LOG2) & ((1 << (hIdx + MIN_CU_LOG2 - 1)) - 1)) == 0) )
91
45.3M
          {
92
45.3M
            numCu++;
93
45.3M
          }
94
211M
        }
95
6.59M
      }
96
206k
    }
97
34.3k
  }
98
99
5.72k
  m_codedCUInfoBuf = new CodedCUInfo[numCu];
100
5.72k
  CodedCUInfo* cuInfo = m_codedCUInfoBuf;
101
102
40.0k
  for( int wIdx = 0; wIdx < maxSizeIdx; wIdx++ )
103
34.3k
  {
104
240k
    for( int hIdx = 0; hIdx < maxSizeIdx; hIdx++ )
105
206k
    {
106
6.80M
      for( unsigned y = 0; y < numPos; y++ )
107
6.59M
      {
108
217M
        for( unsigned x = 0; x < numPos; x++ )
109
211M
        {
110
          // a block of width W might be offset of N * W + 1/2 W (bcs of TT), same for H
111
          // W = 1 << ( wIdx + 2 )
112
          // 1/2 W = 1 << ( wIdx + 1 )
113
          // remainder of (N+1/2)*W -> x & ( ( 1 << ( wIdx + 1 ) ) - 1 )
114
115
211M
          if(( x + (1<<(wIdx)) <= ( ctuSize >> MIN_CU_LOG2 ) )
116
148M
            && ( y + (1<<(hIdx)) <= ( ctuSize >> MIN_CU_LOG2 ) )
117
104M
            && ( ( ( x << MIN_CU_LOG2 ) & ((1 << (wIdx + MIN_CU_LOG2 - 1)) - 1) ) == 0 )
118
68.8M
            && ( ( ( y << MIN_CU_LOG2 ) & ((1 << (hIdx + MIN_CU_LOG2 - 1)) - 1) ) == 0 ) )
119
45.3M
          {
120
45.3M
            m_codedCUInfo[wIdx][hIdx][x][y] = cuInfo++;
121
45.3M
            m_codedCUInfo[wIdx][hIdx][x][y]->poc       = -1;
122
45.3M
            m_codedCUInfo[wIdx][hIdx][x][y]->ctuRsAddr = -1;
123
45.3M
          }
124
165M
          else
125
165M
          {
126
165M
            m_codedCUInfo[wIdx][hIdx][x][y] = nullptr;
127
165M
          }
128
211M
        }
129
6.59M
      }
130
206k
    }
131
34.3k
  }
132
5.72k
}
133
134
void CacheBlkInfoCtrl::destroy()
135
5.72k
{
136
5.72k
  delete[] m_codedCUInfoBuf;
137
5.72k
  m_codedCUInfoBuf = nullptr;
138
5.72k
}
139
140
void CacheBlkInfoCtrl::init( const Slice &slice )
141
4.65k
{
142
4.65k
  m_pcv = slice.pps->pcv;
143
4.65k
}
144
145
void CacheBlkInfoCtrl::initBlk( const UnitArea& area, int poc )
146
156k
{
147
156k
  unsigned idx1, idx2, idx3, idx4;
148
156k
  getAreaIdxNew( area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
149
150
156k
  const int ctuRsAddr = getCtuAddr( area.lumaPos(), *m_pcv );
151
156k
  CodedCUInfo* cuInfo = m_codedCUInfo[idx1][idx2][idx3][idx4];
152
153
156k
  if( cuInfo->poc != poc || cuInfo->ctuRsAddr != ctuRsAddr )
154
112k
  {
155
112k
    GCC_WARNING_DISABLE_class_memaccess
156
112k
    memset( cuInfo, 0, sizeof( CodedCUInfo ) );
157
112k
    GCC_WARNING_RESET
158
159
112k
    cuInfo->poc       = poc;
160
112k
    cuInfo->ctuRsAddr = ctuRsAddr;
161
112k
  }
162
156k
}
163
164
CodedCUInfo& CacheBlkInfoCtrl::getBlkInfo( const UnitArea& area )
165
256k
{
166
256k
  unsigned idx1, idx2, idx3, idx4;
167
256k
  getAreaIdxNew( area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
168
//  DTRACE( g_trace_ctx, D_TMP, "%d loc %d %d %d %d\n", g_trace_ctx->getChannelCounter(D_TMP), idx1, idx2, idx3, idx4);
169
256k
  return *m_codedCUInfo[idx1][idx2][idx3][idx4];
170
256k
}
171
172
void CodedCUInfo::setMv( const RefPicList refPicList, const int iRefIdx, const Mv& rMv )
173
0
{
174
0
  if( iRefIdx >= MAX_STORED_CU_INFO_REFS ) return;
175
176
0
  saveMv [refPicList][iRefIdx] = rMv;
177
0
  validMv[refPicList][iRefIdx] = true;
178
0
}
179
180
bool CodedCUInfo::getMv( const RefPicList refPicList, const int iRefIdx, Mv& rMv ) const
181
0
{
182
0
  if( iRefIdx >= MAX_STORED_CU_INFO_REFS )
183
0
  {
184
0
    rMv = saveMv[refPicList][0];
185
0
    return false;
186
0
  }
187
188
0
  rMv = saveMv[refPicList][iRefIdx];
189
0
  return validMv[refPicList][iRefIdx];
190
0
}
191
192
uint8_t CacheBlkInfoCtrl::findBestSbt( const UnitArea& area, const uint32_t curPuSse )
193
0
{
194
0
  unsigned idx1, idx2, idx3, idx4;
195
0
  getAreaIdxNew( area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
196
0
  CodedCUInfo* pSbtSave = m_codedCUInfo[idx1][idx2][idx3][idx4];
197
198
0
  for( int i = 0; i < pSbtSave->numPuInfoStored; i++ )
199
0
  {
200
0
    if( curPuSse == pSbtSave->puSse[i] )
201
0
    {
202
0
      return pSbtSave->puSbt[i];
203
0
    }
204
0
  }
205
206
0
  return MAX_UCHAR;
207
0
}
208
209
bool CacheBlkInfoCtrl::saveBestSbt( const UnitArea& area, const uint32_t curPuSse, const uint8_t curPuSbt )
210
0
{
211
0
  unsigned idx1, idx2, idx3, idx4;
212
0
  getAreaIdxNew( area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
213
0
  CodedCUInfo* pSbtSave = m_codedCUInfo[idx1][idx2][idx3][idx4];
214
215
0
  if( pSbtSave->numPuInfoStored == SBT_NUM_SL )
216
0
  {
217
0
    return false;
218
0
  }
219
220
0
  pSbtSave->puSse[pSbtSave->numPuInfoStored] = curPuSse;
221
0
  pSbtSave->puSbt[pSbtSave->numPuInfoStored] = curPuSbt;
222
0
  pSbtSave->numPuInfoStored++;
223
224
0
  return true;
225
0
}
226
227
static bool isTheSameNbHood( const CodingUnit &cu, const CodingStructure& cs, const Partitioner &partitioner, int picW, int picH )
228
0
{
229
0
  if( cu.chType != partitioner.chType )
230
0
  {
231
0
    return false;
232
0
  }
233
234
0
  const PartitioningStack &ps = partitioner.getPartStack();
235
236
0
  int i = 1;
237
238
0
  for( ; i < ps.size(); i++ )
239
0
  {
240
0
    if( ps[i].split != CU::getSplitAtDepth( cu, i - 1 ) )
241
0
    {
242
0
      break;
243
0
    }
244
0
  }
245
246
0
  const UnitArea& cmnAnc = ps[i - 1].parts[ps[i - 1].idx];
247
0
  const UnitArea cuArea  = CS::getArea( cs, cu, partitioner.chType, partitioner.treeType );
248
249
0
  for( int i = 0; i < cmnAnc.blocks.size(); i++ )
250
0
  {
251
0
    if( i < cuArea.blocks.size() && cuArea.blocks[i].valid() && cuArea.blocks[i].pos() != cmnAnc.blocks[i].pos() )
252
0
    {
253
0
      return false;
254
0
    }
255
0
  }
256
257
0
  return true;
258
0
}
259
260
void BestEncInfoCache::create( const bool reuseCuResults, const ChromaFormat chFmt, const int ctuSize )
261
5.72k
{
262
5.72k
  m_reuseCuResults = reuseCuResults;
263
264
5.72k
  if( !m_reuseCuResults ) return;
265
266
0
  m_chFmt = chFmt;
267
0
  std::fill_n( &m_bestEncInfo[0][0][0][0], sizeof( m_bestEncInfo ) / sizeof( m_bestEncInfo[0][0][0][0] ), nullptr );
268
0
}
269
270
void BestEncInfoCache::destroy()
271
5.72k
{
272
5.72k
  if( !m_reuseCuResults ) return;
273
274
0
  std::fill_n( &m_bestEncInfo[0][0][0][0], sizeof( m_bestEncInfo ) / sizeof( m_bestEncInfo[0][0][0][0] ), nullptr );
275
0
  m_filledSlots.clear();
276
0
  m_entryArena.release();
277
0
  m_coeffArena.release();
278
0
  m_dmvrMvArena.release();
279
280
0
  m_pcv = nullptr;
281
0
}
282
283
void BestEncInfoCache::init( const Slice &slice )
284
4.65k
{
285
4.65k
  if( !m_reuseCuResults ) return;
286
287
  // A new CTU starts, and no result of the previous one can match its CUs.
288
0
  for( BestEncodingInfo** slot : m_filledSlots )
289
0
  {
290
0
    *slot = nullptr;
291
0
  }
292
0
  m_filledSlots.clear();
293
0
  m_entryArena.reset();
294
0
  m_coeffArena.reset();
295
0
  m_dmvrMvArena.reset();
296
297
0
  bool isInitialized = m_pcv;
298
299
0
  m_pcv = slice.pps->pcv;
300
301
0
  if( isInitialized ) return;
302
303
0
  m_dummyCS.pcv = m_pcv;
304
0
}
305
306
// Takes storage for the result of a CU with size indices wIdx and hIdx, set up the way the earlier
307
// fixed table of results was set up when it was created.
308
BestEncodingInfo* BestEncInfoCache::xNewEntry( const int wIdx, const int hIdx )
309
0
{
310
0
  BestEncodingInfo* encInfo = m_entryArena.take( 1 );
311
0
  encInfo->~BestEncodingInfo();
312
0
  new( encInfo ) BestEncodingInfo();
313
314
0
  const UnitArea area( m_chFmt, Area( 0, 0, 1 << ( wIdx + MIN_CU_LOG2 ), 1 << ( hIdx + MIN_CU_LOG2 ) ) );
315
316
0
  encInfo->cu.UnitArea::operator=( area );
317
0
  encInfo->tu.UnitArea::operator=( area );
318
319
0
  encInfo->cu.chType   = CH_L;
320
0
  encInfo->cu.treeType = TREE_D;
321
0
  encInfo->cu.modeType = MODE_TYPE_ALL;
322
0
  encInfo->cu.qp       = MAX_SCHAR;
323
0
  encInfo->tu.chType   = CH_L;
324
325
0
  if( hIdx >= 1 && wIdx >= 1 && ( wIdx + hIdx ) >= 3 )
326
0
  {
327
0
    const int dmvrSize = ( 1 << std::max( 0, ( wIdx + MIN_CU_LOG2 - DMVR_SUBCU_SIZE_LOG2 ) ) ) * ( 1 << std::max( 0, ( hIdx + MIN_CU_LOG2 - DMVR_SUBCU_SIZE_LOG2 ) ) );
328
0
    encInfo->cu.mvdL0SubPu = m_dmvrMvArena.take( dmvrSize );
329
0
  }
330
331
0
  TCoeffSig* coeff[MAX_NUM_TBLOCKS] = { 0, };
332
0
  for( int i = 0; i < area.blocks.size(); i++ )
333
0
  {
334
0
    coeff[i] = m_coeffArena.take( area.blocks[i].area() );
335
0
  }
336
337
0
  encInfo->tu.cs = &m_dummyCS;
338
0
  encInfo->tu.init( coeff );
339
340
0
  encInfo->poc      = -1;
341
0
  encInfo->testMode = EncTestMode();
342
0
  return encInfo;
343
0
}
344
345
bool BestEncInfoCache::setFromCs( const CodingStructure& cs, const EncTestMode& testMode, const Partitioner& partitioner )
346
98.3k
{
347
98.3k
  if( !m_reuseCuResults ) return false;
348
349
1
  if( cs.cus.size() != 1 || cs.tus.size() != 1 || partitioner.maxBTD <= 1 )
350
0
  {
351
0
    return false;
352
0
  }
353
354
1
  unsigned idx1, idx2, idx3, idx4;
355
1
  getAreaIdxNew( cs.area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
356
357
1
  BestEncodingInfo*& slot = m_bestEncInfo[idx1][idx2][idx3][idx4];
358
1
  if( !slot )
359
0
  {
360
0
    slot = xNewEntry( idx1, idx2 );
361
0
    m_filledSlots.push_back( &slot );
362
0
  }
363
1
  BestEncodingInfo& encInfo = *slot;
364
365
1
  encInfo.poc            =  cs.picture->poc;
366
1
  encInfo.cu.UnitArea::operator= ( *cs.cus.front() );
367
1
  encInfo.tu.UnitArea::operator= ( *cs.tus.front() );
368
1
  encInfo.cu             = *cs.cus.front();
369
1
  for( auto &blk : cs.tus.front()->blocks )
370
0
  {
371
0
    if( blk.valid() ) encInfo.tu.copyComponentFrom( *cs.tus.front(), blk.compID );
372
0
  }
373
1
  encInfo.testMode       = testMode;
374
1
  encInfo.dist           = cs.dist;
375
1
  encInfo.costEDO        = cs.costDbOffset;
376
377
1
  return true;
378
1
}
379
380
bool BestEncInfoCache::isReusingCuValid( const CodingStructure& cs, const Partitioner& partitioner, int qp )
381
156k
{
382
156k
  if( !m_reuseCuResults || partitioner.treeType == TREE_C || partitioner.maxBTD <= 1 || partitioner.currQgEnable() )
383
156k
  {
384
156k
    return false; //if save & load is allowed for chroma CUs, we should check whether luma info (pred, recon, etc) is the same, which is quite complex
385
156k
  }
386
387
0
  unsigned idx1, idx2, idx3, idx4;
388
0
  getAreaIdxNew( cs.area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
389
390
0
  const BestEncodingInfo* stored = m_bestEncInfo[idx1][idx2][idx3][idx4];
391
0
  if( !stored )
392
0
  {
393
0
    return false;
394
0
  }
395
0
  const BestEncodingInfo& encInfo = *stored;
396
397
0
  if( encInfo.cu.treeType != partitioner.treeType || encInfo.cu.modeType != partitioner.modeType )
398
0
  {
399
0
    return false;
400
0
  }
401
0
  if( encInfo.cu.qp != qp )
402
0
    return false;
403
  // the cheap tests first, the area and neighbourhood comparisons last
404
0
  if( cs.picture->poc != encInfo.poc
405
0
    || cs.currQP[partitioner.chType] != encInfo.cu.qp
406
0
    || CU::isIBC(encInfo.cu)
407
0
    || CS::getArea( cs, cs.area, partitioner.chType, partitioner.treeType ) != CS::getArea( cs, encInfo.cu, partitioner.chType, partitioner.treeType )
408
0
    || !isTheSameNbHood( encInfo.cu, cs, partitioner, (cs.picture->Y().width), (cs.picture->Y().height))
409
0
    )
410
0
  {
411
0
    return false;
412
0
  }
413
0
  else
414
0
  {
415
0
    return true;
416
0
  }
417
0
}
418
419
bool BestEncInfoCache::setCsFrom( CodingStructure& cs, EncTestMode& testMode, const Partitioner& partitioner ) const
420
0
{
421
0
  if( !m_reuseCuResults ) return false;
422
423
0
  unsigned idx1, idx2, idx3, idx4;
424
0
  getAreaIdxNew( cs.area.Y(), *m_pcv, idx1, idx2, idx3, idx4 );
425
426
0
  const BestEncodingInfo* stored = m_bestEncInfo[idx1][idx2][idx3][idx4];
427
0
  if( !stored )
428
0
  {
429
0
    return false;
430
0
  }
431
0
  const BestEncodingInfo& encInfo = *stored;
432
433
0
  if( cs.picture->poc != encInfo.poc 
434
0
    || CS::getArea( cs, cs.area, partitioner.chType, partitioner.treeType ) != CS::getArea( cs, encInfo.cu, partitioner.chType, partitioner.treeType ) 
435
0
    || !isTheSameNbHood( encInfo.cu, cs, partitioner, (cs.picture->Y().width), (cs.picture->Y().height))
436
0
    || partitioner.currQgEnable() || cs.currQP[partitioner.chType] != encInfo.cu.qp
437
0
    )
438
0
  {
439
0
    return false;
440
0
  }
441
442
0
  const UnitArea ua = CS::getArea( cs, cs.area, partitioner.chType, partitioner.treeType );
443
0
  CodingUnit     &cu = cs.addCU( ua, partitioner.chType );
444
0
  cu.treeType = partitioner.treeType;
445
0
  cu.modeType = partitioner.modeType;
446
0
  cu.initPuData();
447
0
  TransformUnit  &tu = cs.addTU( ua, partitioner.chType, &cu );
448
449
0
  cu          .repositionTo( encInfo.cu );
450
0
  cu          .repositionTo( encInfo.cu );
451
0
  tu          .repositionTo( encInfo.tu );
452
453
0
  cu          = encInfo.cu;
454
0
  cu          = encInfo.cu;
455
0
  for( auto &blk : tu.blocks )
456
0
  {
457
0
    if( blk.valid() ) tu.copyComponentFrom( encInfo.tu, blk.compID );
458
0
  }
459
460
0
  testMode    = encInfo.testMode;
461
0
  cs.dist     = encInfo.dist;
462
0
  cs.costDbOffset = encInfo.costEDO;
463
0
  return true;
464
0
}
465
466
467
//////////////////////////////////////////////////////////////////////////
468
// EncModeCtrl
469
//////////////////////////////////////////////////////////////////////////
470
471
// FastAMVR: where the motion search with quarter-sample MVDs and equal weights shows that AMVR cannot pay
472
static constexpr double   AMVR_ME_BEHIND_RATIO  = 1.1;   // it costs more than this times the best mode: a merge mode or intra is far ahead of any searched motion
473
static constexpr int      AMVR_MIN_MVD          = 2;     // its largest MVD component (quarter samples) is below this: every MVD is 0 or 1/4, no MVD bits to save
474
static constexpr int      AMVR_4PEL_MIN_MVD     = 16;    // ... below this (4 samples): no 4-sample MVDs, which round every MVD to 4 samples
475
476
void EncModeCtrl::init( const VVEncCfg& encCfg, RdCost* pRdCost )
477
5.72k
{
478
5.72k
  m_pcEncCfg = &encCfg;
479
5.72k
  m_pcRdCost = pRdCost;
480
5.72k
  comprCUCtx = nullptr;
481
482
5.72k
  CacheBlkInfoCtrl::create( encCfg.m_CTUSize );
483
5.72k
  BestEncInfoCache::create( encCfg.m_reuseCuResults, encCfg.m_internChromaFormat, encCfg.m_CTUSize );
484
5.72k
}
485
486
void EncModeCtrl::destroy()
487
5.72k
{
488
5.72k
  CacheBlkInfoCtrl::destroy();
489
5.72k
  BestEncInfoCache::destroy();
490
5.72k
}
491
492
void EncModeCtrl::initCTUEncoding( const Slice &slice )
493
4.65k
{
494
4.65k
  CacheBlkInfoCtrl::init( slice );
495
4.65k
  BestEncInfoCache::init( slice );
496
497
4.65k
  CHECK( !m_ComprCUCtxList.empty(), "Mode list is not empty at the beginning of a CTU" );
498
499
4.65k
  if( m_pcEncCfg->m_fastQtBtEnc )
500
4.65k
  {
501
4.65k
    m_skipThresholdE0023FastEnc = ((slice.getMinPictureDistance() <= PICTURE_DISTANCE_TH) ? FAST_SKIP_DEPTH : SKIP_DEPTH);
502
4.65k
  }
503
0
  else
504
0
  {
505
0
    m_skipThresholdE0023FastEnc = SKIP_DEPTH;
506
0
  }
507
4.65k
}
508
509
void EncModeCtrl::initCULevel( Partitioner &partitioner, const CodingStructure& cs, int  MergeSimpleFlag, const CodingUnit* cuLeft, const CodingUnit* cuAbove )
510
156k
{
511
  // Min/max depth
512
156k
  unsigned minDepth = 0;
513
156k
  unsigned maxDepth = cs.pcv->getMaxDepth( cs.slice->sliceType, partitioner.chType );
514
156k
  if( m_pcEncCfg->m_useFastLCTU )
515
156k
  {
516
156k
    partitioner.setMaxMinDepth(minDepth, maxDepth, cs, cs.picture->useQtbttSpeedUpMode, MergeSimpleFlag, cuLeft, cuAbove);
517
156k
  }
518
519
156k
  minDepth = std::max<unsigned>( minDepth, cs.pcv->getMinDepth( cs.slice->sliceType, partitioner.chType ) );
520
156k
  maxDepth = std::min<unsigned>( maxDepth, cs.pcv->getMaxDepth( cs.slice->sliceType, partitioner.chType ) );
521
522
156k
  m_ComprCUCtxList.push_back( ComprCUCtx( cs, minDepth, maxDepth ) );
523
156k
  comprCUCtx = &m_ComprCUCtxList.back();
524
525
156k
  const bool qtBeforeBt = ( (  cuLeft  &&  cuAbove  && cuLeft ->qtDepth > partitioner.currQtDepth && cuAbove->qtDepth > partitioner.currQtDepth )
526
153k
                         || (  cuLeft  && !cuAbove  && cuLeft ->qtDepth > partitioner.currQtDepth )
527
150k
                         || ( !cuLeft  &&  cuAbove  && cuAbove->qtDepth > partitioner.currQtDepth )
528
147k
                         || ( !cuAbove && !cuLeft   && cs.area.lwidth() >= ( 32 << cs.slice->TLayer ) )
529
131k
                         || ( m_pcEncCfg->m_qtbttSpeedUp > 1 && partitioner.maxBTD < ( ( cs.slice->isIntra() && !cs.sps->IBC ) ? 3 : 2 ) ) )
530
24.9k
                         && ( cs.area.lwidth() > ( cs.pcv->getMinQtSize( *cs.slice, partitioner.chType ) << 1 ) );
531
532
  // set features
533
156k
  ComprCUCtx &cuECtx    = *comprCUCtx;
534
156k
  cuECtx.qtBeforeBt     = qtBeforeBt;
535
156k
  cuECtx.doTriHorzSplit = true;
536
156k
  cuECtx.doTriVertSplit = true;
537
156k
  cuECtx.doMoreSplits   = 3;
538
156k
  cuECtx.isReusingCu    = isReusingCuValid( cs, partitioner, cs.baseQP );
539
156k
  cuECtx.didHorzSplit   = partitioner.canSplit( CU_HORZ_SPLIT, cs );
540
156k
  cuECtx.didVertSplit   = partitioner.canSplit( CU_VERT_SPLIT, cs );
541
156k
  cuECtx.doHorChromaSplit = true;
542
156k
  cuECtx.doVerChromaSplit = true;
543
156k
  cuECtx.doQtChromaSplit  = true;
544
545
156k
  if( m_pcEncCfg->m_contentBasedFastQtbt && cs.pcv->getMaxMTTDepth(*cs.slice, partitioner.chType))
546
156k
  {
547
156k
    const CompArea& currArea = partitioner.currArea().Y();
548
156k
    int cuHeight  = currArea.height;
549
156k
    int cuWidth   = currArea.width;
550
551
156k
    const bool condIntraInter = m_pcEncCfg->m_IntraPeriod == 1 ? ( partitioner.currBtDepth == 0 ) : ( cuHeight > 32 && cuWidth > 32 );
552
553
156k
    if( cuWidth == cuHeight && condIntraInter )
554
34.5k
    {
555
34.5k
      const CPelBuf bufCurrArea = cs.getOrgBuf( partitioner.currArea().block( COMP_Y ) );
556
557
34.5k
      int grad[4];
558
34.5k
      g_pelBufOP.absGradientSums( bufCurrArea.buf, bufCurrArea.stride, cuWidth, cuHeight, grad );
559
560
34.5k
      cuECtx.grad_horVal = (double)grad[0];
561
34.5k
      cuECtx.grad_verVal = (double)grad[1];
562
34.5k
      cuECtx.grad_dowVal = (double)grad[2];
563
34.5k
      cuECtx.grad_dupVal = (double)grad[3];
564
34.5k
    }
565
156k
  }
566
156k
}
567
568
void EncModeCtrl::finishCULevel( Partitioner &partitioner )
569
156k
{
570
156k
  m_ComprCUCtxList.pop_back();
571
156k
  comprCUCtx = m_ComprCUCtxList.size() ? &m_ComprCUCtxList.back() : nullptr;
572
156k
}
573
574
bool EncModeCtrl::trySplit( const EncTestMode& encTestmode, const CodingStructure &cs, Partitioner& partitioner, const EncTestMode& lastTestmode )
575
378k
{
576
378k
  ComprCUCtx& cuECtx = *comprCUCtx;
577
578
378k
  const PartSplit implicitSplit = partitioner.getImplicitSplit( cs );
579
378k
  const bool isBoundary         = implicitSplit != CU_DONT_SPLIT;
580
581
378k
  if( ( m_pcEncCfg->m_IntraPeriod == 1 ) && ( partitioner.chType == CH_C ) && ( !cuECtx.doQtChromaSplit ) )
582
0
  {
583
0
    cuECtx.maxDepth         = partitioner.currDepth;
584
0
  }
585
586
378k
  if( isBoundary )
587
95.9k
  {
588
95.9k
    if( encTestmode.type != ETM_SPLIT_QT )
589
37.8k
    {
590
37.8k
      return getPartSplit( encTestmode ) == implicitSplit;
591
37.8k
    }
592
58.0k
    else
593
58.0k
    {
594
58.0k
      return partitioner.canSplit( CU_QUAD_SPLIT, cs );
595
58.0k
    }
596
95.9k
  }
597
598
282k
  const Slice&           slice       = *cs.slice;
599
282k
  const uint32_t         width       = partitioner.currArea().lumaSize().width;
600
282k
  const CodingStructure *bestCS      = cuECtx.bestCS;
601
282k
  const CodingUnit      *bestCU      = cuECtx.bestCU;
602
603
282k
  if( cuECtx.minDepth > partitioner.currQtDepth && partitioner.canSplit( CU_QUAD_SPLIT, cs ) )
604
0
  {
605
    // enforce QT
606
0
    return encTestmode.type == ETM_SPLIT_QT;
607
0
  }
608
282k
  else if( encTestmode.type == ETM_SPLIT_QT && cuECtx.maxDepth <= partitioner.currQtDepth )
609
1.59k
  {
610
    // don't check this QT depth
611
1.59k
    return false;
612
1.59k
  }
613
614
281k
  CHECK( ! isModeSplit( encTestmode ), "wrong method" );
615
616
  //////////////////////////////////////////////////////////////////////////
617
  // skip-history rule - don't split further if at least for three past levels
618
  //                     in the split tree it was found that skip is the best mode
619
  //////////////////////////////////////////////////////////////////////////
620
281k
  int skipScore = 0;
621
622
281k
  if ((!slice.isIntra() || slice.sps->IBC) && cuECtx.isBestNoSplitSkip )
623
0
  {
624
0
    for( int i = 2; i <= m_ComprCUCtxList.size(); i++ )
625
0
    {
626
0
      if( ( m_ComprCUCtxList.end() - i )->isBestNoSplitSkip )
627
0
      {
628
0
        skipScore += 1;
629
0
      }
630
0
      else
631
0
      {
632
0
        break;
633
0
      }
634
0
    }
635
0
  }
636
637
281k
  const PartSplit split = getPartSplit( encTestmode );
638
281k
  if( !partitioner.canSplit( split, cs ) || skipScore >= 2 || ( skipScore == 1 && m_ComprCUCtxList.size() == 2 ) )
639
71.4k
  {
640
71.4k
    if( split == CU_HORZ_SPLIT ) cuECtx.didHorzSplit = false;
641
71.4k
    if( split == CU_VERT_SPLIT ) cuECtx.didVertSplit = false;
642
71.4k
    if( split == CU_QUAD_SPLIT ) cuECtx.didQuadSplit = false;
643
71.4k
    return false;
644
71.4k
  }
645
646
209k
  if( isChroma( partitioner.chType ) && !cuECtx.doHorChromaSplit && ( split == CU_HORZ_SPLIT || split == CU_TRIH_SPLIT ) )
647
0
  {
648
0
    if( split == CU_HORZ_SPLIT )
649
0
    {
650
0
      cuECtx.didHorzSplit = false;
651
0
    }
652
653
0
    return false;
654
0
  }
655
656
209k
  if( isChroma( partitioner.chType ) && !cuECtx.doVerChromaSplit && ( split == CU_VERT_SPLIT || split == CU_TRIV_SPLIT ) )
657
0
  {
658
0
    if( split == CU_VERT_SPLIT )
659
0
    {
660
0
      cuECtx.didVertSplit = false;
661
0
    }
662
663
0
    return false;
664
0
  }
665
666
209k
  if( m_pcEncCfg->m_contentBasedFastQtbt )
667
209k
  {
668
209k
    const CompArea& currArea = partitioner.currArea().Y();
669
209k
    int cuHeight  = currArea.height;
670
209k
    int cuWidth   = currArea.width;
671
672
209k
    const bool condIntraInter = m_pcEncCfg->m_IntraPeriod == 1 ? ( partitioner.currBtDepth == 0 ) : ( cuHeight > 32 && cuWidth > 32 );
673
674
209k
    if( cuWidth == cuHeight && condIntraInter && split != CU_QUAD_SPLIT )
675
12.1k
    {
676
12.1k
      const double th1 = m_pcEncCfg->m_IntraPeriod == 1 ?  1.2              :  1.0;
677
12.1k
      const double th2 = m_pcEncCfg->m_IntraPeriod == 1 ? (1.2 / sqrt( 2 )) : (1.0 / sqrt( 2 ));
678
679
12.1k
      if( cuECtx.grad_horVal > th1 * cuECtx.grad_verVal && cuECtx.grad_horVal > th2 * cuECtx.grad_dowVal && cuECtx.grad_horVal > th2 * cuECtx.grad_dupVal && ( split == CU_HORZ_SPLIT || split == CU_TRIH_SPLIT ) )
680
0
      {
681
0
        return false;
682
0
      }
683
12.1k
      if( th2 * cuECtx.grad_dupVal < cuECtx.grad_verVal && th2 * cuECtx.grad_dowVal < cuECtx.grad_verVal && th1 * cuECtx.grad_horVal < cuECtx.grad_verVal && ( split == CU_VERT_SPLIT || split == CU_TRIV_SPLIT ) )
684
0
      {
685
0
        return false;
686
0
      }
687
12.1k
    }
688
689
209k
    if( m_pcEncCfg->m_IntraPeriod == 1 && cuWidth <= 32 && cuHeight <= 32 && bestCS && bestCS->tus.size() == 1 && bestCU && bestCU->depth == partitioner.currDepth && partitioner.currBtDepth > 1 && isLuma( partitioner.chType ) )
690
0
    {
691
0
      if( !bestCU->rootCbf )
692
0
      {
693
0
        return false;
694
0
      }
695
0
    }
696
209k
  }
697
698
209k
  if( m_pcEncCfg->m_qtbttSpeedUp > 1 )
699
209k
  {
700
209k
    const int availDepth = cs.pcv->getMaxMTTDepth( slice, partitioner.chType ) - partitioner.currMtDepth;
701
209k
    if( bestCU && bestCU->skip && availDepth <= ( 3 - m_skipThresholdE0023FastEnc ) && !isModeSplit( lastTestmode ) && split != CU_QUAD_SPLIT )
702
0
    {
703
0
      return false;
704
0
    }
705
209k
  }
706
209k
  if( bestCU && bestCU->skip && bestCU->mtDepth >= m_skipThresholdE0023FastEnc && !isModeSplit( lastTestmode ) )
707
0
  {
708
0
    return false;
709
0
  }
710
711
209k
  bool resetFeature = false;
712
713
209k
  switch( split )
714
209k
  {
715
25.2k
    case CU_QUAD_SPLIT:
716
25.2k
      {
717
25.2k
        if( !cuECtx.qtBeforeBt && bestCU )
718
22.4k
        {
719
22.4k
          unsigned maxBTD        = cs.pcv->getMaxMTTDepth( slice, partitioner.chType );
720
22.4k
          const CodingUnit *cuBR = bestCS->cus.back();
721
22.4k
          unsigned height        = partitioner.currArea().lumaSize().height;
722
723
22.4k
          if(((bestCU->btDepth == 0 && maxBTD >= ((slice.isIntra() && !slice.sps->IBC) ? 3 : 2))
724
92
            || (bestCU->btDepth == 1 && cuBR && cuBR->btDepth == 1 && maxBTD >= ((slice.isIntra() && !slice.sps->IBC) ? 4 : 3)))
725
22.3k
            && (width <= MAX_TB_SIZEY && height <= MAX_TB_SIZEY)
726
22.3k
            && cuECtx.didHorzSplit && cuECtx.didVertSplit )
727
17.0k
          {
728
17.0k
            return false;
729
17.0k
          }
730
22.4k
        }
731
8.16k
        if( bestCS )
732
8.16k
        {
733
8.16k
          if( m_pcEncCfg->m_useEarlyCU == 2 && bestCS->cost != MAX_DOUBLE && bestCU && bestCU->skip && cuECtx.nonSkipWasTested && bestCS->cus.size() == 1 )
734
0
          {
735
0
            return false;
736
0
          }
737
738
8.16k
          int stopSplit = (m_pcEncCfg->m_FastInferMerge >> 4) && (bestCS->slice->TLayer > 4);
739
8.16k
          int limitBLsize = stopSplit ? 2048 : 1024;
740
8.16k
          if((m_pcEncCfg->m_useEarlyCU == 1 || stopSplit) && bestCS->cost != MAX_DOUBLE && bestCU && bestCU->skip && partitioner.currArea().lumaSize().area() < limitBLsize )
741
0
          {
742
0
            return false;
743
0
          }
744
8.16k
        }
745
8.16k
      }
746
8.16k
      break;
747
64.3k
    case CU_HORZ_SPLIT:
748
123k
    case CU_VERT_SPLIT:
749
123k
      resetFeature = true;
750
123k
      break;
751
34.2k
    case CU_TRIH_SPLIT:
752
34.2k
      if( cuECtx.didHorzSplit && bestCU && bestCU->btDepth == partitioner.currBtDepth && !bestCU->rootCbf )
753
27.8k
      {
754
27.8k
        return false;
755
27.8k
      }
756
757
6.42k
      if( m_pcEncCfg->m_qtbttSpeedUp > 1 )
758
6.42k
      {
759
        //unsigned maxBTD = cs.pcv->getMaxMTTDepth( slice, partitioner.chType );
760
6.42k
        if( /*maxBTD == 1 && */cuECtx.didHorzSplit && cuECtx.didVertSplit && cuECtx.bestCostHorzSplit > cuECtx.bestCostVertSplit )
761
1.81k
        {
762
1.81k
          return false;
763
1.81k
        }
764
6.42k
      }
765
766
4.60k
      if( !cuECtx.doTriHorzSplit )
767
16
      {
768
16
        return false;
769
16
      }
770
771
4.58k
      if (m_pcEncCfg->m_fastTTSplit && cuECtx.bestCostHorzSplit < MAX_DOUBLE)
772
3.52k
      {
773
3.52k
        if (cuECtx.bestCostBeforeSplit < MAX_DOUBLE && (cuECtx.bestCostHorzSplit > m_pcEncCfg->m_fastTT_th * cuECtx.bestCostBeforeSplit))
774
3.00k
        {
775
3.00k
          return false;
776
3.00k
        }
777
525
        if (cuECtx.bestCostVertSplit < MAX_DOUBLE && (cuECtx.bestCostHorzSplit > m_pcEncCfg->m_fastTT_th * cuECtx.bestCostVertSplit))
778
0
        {
779
0
          return false;
780
0
        }
781
525
      }
782
1.58k
      break;
783
26.8k
    case CU_TRIV_SPLIT:
784
26.8k
      if( cuECtx.didVertSplit && bestCU && bestCU->btDepth == partitioner.currBtDepth && !bestCU->rootCbf )
785
22.9k
      {
786
22.9k
        return false;
787
22.9k
      }
788
789
3.91k
      if( m_pcEncCfg->m_qtbttSpeedUp > 1 )
790
3.91k
      {
791
        //unsigned maxBTD = cs.pcv->getMaxMTTDepth( slice, partitioner.chType );
792
3.91k
        if( /*maxBTD == 1 && */cuECtx.didHorzSplit && cuECtx.didVertSplit && cuECtx.bestCostHorzSplit < cuECtx.bestCostVertSplit )
793
2.30k
        {
794
2.30k
          return false;
795
2.30k
        }
796
3.91k
      }
797
798
1.61k
      if( !cuECtx.doTriVertSplit )
799
45
      {
800
45
        return false;
801
45
      }
802
803
1.56k
      if (m_pcEncCfg->m_fastTTSplit && cuECtx.bestCostVertSplit < MAX_DOUBLE)
804
564
      {
805
564
        if (cuECtx.bestCostBeforeSplit < MAX_DOUBLE && (cuECtx.bestCostVertSplit > m_pcEncCfg->m_fastTT_th * cuECtx.bestCostBeforeSplit))
806
378
        {
807
378
          return false;
808
378
        }
809
186
        if (cuECtx.bestCostHorzSplit < MAX_DOUBLE && (cuECtx.bestCostVertSplit > m_pcEncCfg->m_fastTT_th * cuECtx.bestCostHorzSplit))
810
0
        {
811
0
          return false;
812
0
        }
813
186
      }
814
1.18k
      break;
815
1.18k
    default:
816
0
      THROW( "Only CU split modes are governed by the EncModeCtrl" );
817
0
      return false;
818
0
      break;
819
209k
  }
820
821
134k
  switch( split )
822
134k
  {
823
64.3k
    case CU_HORZ_SPLIT:
824
65.9k
    case CU_TRIH_SPLIT:
825
65.9k
      if( cuECtx.qtBeforeBt && cuECtx.didQuadSplit )
826
2.28k
      {
827
2.28k
        if( cuECtx.maxQtSubDepth > partitioner.currQtDepth + 1 )
828
0
        {
829
0
          if( resetFeature ) cuECtx.didHorzSplit = false;
830
0
          return false;
831
0
        }
832
2.28k
      }
833
65.9k
      break;
834
65.9k
    case CU_VERT_SPLIT:
835
60.1k
    case CU_TRIV_SPLIT:
836
60.1k
      if( cuECtx.qtBeforeBt && cuECtx.didQuadSplit )
837
2.35k
      {
838
2.35k
        if( cuECtx.maxQtSubDepth > partitioner.currQtDepth + 1 )
839
0
        {
840
0
          if( resetFeature ) cuECtx.didVertSplit = false;
841
0
          return false;
842
0
        }
843
2.35k
      }
844
60.1k
      break;
845
60.1k
    default:
846
8.16k
      break;
847
134k
  }
848
849
134k
  if( split == CU_QUAD_SPLIT )
850
8.16k
  {
851
8.16k
    cuECtx.didQuadSplit = m_pcEncCfg->m_qtbttSpeedUp <= 1 || !!cuECtx.doMoreSplits;
852
8.16k
  }
853
854
134k
  return m_pcEncCfg->m_qtbttSpeedUp <= 1 || !!cuECtx.doMoreSplits;
855
134k
}
856
857
bool EncModeCtrl::tryMode( const EncTestMode& encTestmode, const CodingStructure &cs, Partitioner& partitioner )
858
158k
{
859
158k
  CHECK( isModeSplit( encTestmode ), "wrong method");
860
861
158k
  ComprCUCtx& cuECtx = m_ComprCUCtxList.back();
862
863
158k
  if( cuECtx.minDepth > partitioner.currQtDepth && partitioner.canSplit( CU_QUAD_SPLIT, cs ) )
864
0
  {
865
    // enforce QT
866
0
    return false;
867
0
  }
868
869
158k
  const Slice&           slice        = *cs.slice;
870
158k
  const uint32_t         numComp      = getNumberValidComponents( slice.sps->chromaFormatIdc );
871
158k
  const CodedCUInfo      &relatedCU   = getBlkInfo( partitioner.currArea() );
872
158k
  const Area             &lumaArea    = partitioner.currArea().Y();
873
158k
  const CodingStructure* bestCS       = cuECtx.bestCS;
874
158k
  const EncTestMode      bestMode     = bestCS ?cuECtx.bestMode : EncTestMode();
875
876
158k
  if( encTestmode.type == ETM_INTRA )
877
98.3k
  {
878
    // if this is removed, the IntraSearch::xIntraCodingLumaQT needs to be adapted to support Intra TU split
879
    // also isXXAvailable in IntraPrediction.cpp need to be fixed to check availability within the same CU without isDecomp
880
98.3k
    if (m_pcEncCfg->m_FastInferMerge && !slice.isIntra() && !slice.isIRAP() && !(cs.area.lwidth() == 4 && cs.area.lheight() == 4) && !partitioner.isConsIntra())
881
0
    {
882
0
      if (bestCS && (bestCS->slice->TLayer > (m_pcEncCfg->m_maxTLayer - (m_pcEncCfg->m_FastInferMerge & 7)))
883
0
        && (bestCS->bestParent != nullptr) && bestCS->bestParent->cus.size() && (bestCS->bestParent->cus[0]->skip))
884
0
      {
885
0
        return false;
886
0
      }
887
0
    }
888
889
98.3k
    if( lumaArea.width > cs.sps->getMaxTbSize() || lumaArea.height > cs.sps->getMaxTbSize() )
890
0
    {
891
0
      return false;
892
0
    }
893
894
98.3k
    if (m_pcEncCfg->m_usePbIntraFast && (!cs.slice->isIntra() || cs.slice->sps->IBC) && cuECtx.interHad == 0 && cuECtx.bestCU && !CU::isIntra(*cuECtx.bestCU))
895
0
    {
896
0
      return false;
897
0
    }
898
899
    // INTRA MODES
900
98.3k
    if (cs.sps->IBC && !cuECtx.bestTU)
901
71.4k
    {
902
     // return true;
903
71.4k
    }
904
26.8k
    else
905
26.8k
    if( partitioner.isConsIntra() && !cuECtx.bestTU )
906
0
    {
907
      //return true;
908
0
    }
909
26.8k
    else
910
26.8k
    if ( lumaArea.width == 4 && lumaArea.height == 4 && !slice.isIntra() && !cuECtx.bestTU )
911
0
    {
912
      //return true;
913
0
    }
914
26.8k
    else
915
26.8k
    if (!(slice.isIRAP() || bestMode.type == ETM_INTRA || !cuECtx.bestTU ||
916
0
      ((!m_pcEncCfg->m_bDisableIntraCUsInInterSlices) && (!relatedCU.isInter || !relatedCU.isIBC) && (
917
0
                                    ( cuECtx.bestTU->cbf[0] != 0 ) ||
918
0
           ( ( numComp > COMP_Cb ) && cuECtx.bestTU->cbf[1] != 0 ) ||
919
0
           ( ( numComp > COMP_Cr ) && cuECtx.bestTU->cbf[2] != 0 )  // avoid very complex intra if it is unlikely
920
0
         ) ) ) )
921
0
    {
922
0
      return false;
923
0
    }
924
26.8k
    else
925
26.8k
    if( cuECtx.bestCS && cuECtx.bestCU && cuECtx.interHad )
926
26.8k
    {
927
      // Get SATD threshold from best Inter-CU
928
26.8k
      if( !cs.slice->isIRAP() && m_pcEncCfg->m_usePbIntraFast )
929
0
      {
930
0
        const DFunc dfunc = DF_HAD;
931
0
        DistParam distParam = m_pcRdCost->setDistParam( cs.getOrgBuf( COMP_Y ), cuECtx.bestCS->getPredBuf( COMP_Y ), cs.sps->bitDepths[ CH_L ], dfunc );
932
0
        cuECtx.interHad = distParam.distFunc( distParam );
933
0
      }
934
26.8k
    }
935
98.3k
    if ((m_pcEncCfg->m_IBCFastMethod > 1) && !cs.slice->isIntra()//IBC_FAST_METHOD_NOINTRA_IBCCBF0
936
0
      && (bestMode.type == ETM_IBC || bestMode.type == ETM_IBC_MERGE)
937
0
      && (!cuECtx.bestCU->Y().valid() || cuECtx.bestTU->cbf[0] == 0)
938
0
      && (!cuECtx.bestCU->Cb().valid() || cuECtx.bestTU->cbf[1] == 0)
939
0
      && (!cuECtx.bestCU->Cr().valid() || cuECtx.bestTU->cbf[2] == 0))
940
0
    {
941
0
      return false;
942
0
    }
943
98.3k
    if (m_pcEncCfg->m_FastIntraTools)
944
98.3k
    {
945
98.3k
      if (relatedCU.relatedCuIsValid)
946
15.8k
      {
947
15.8k
        cuECtx.relatedCuIsValid = relatedCU.relatedCuIsValid;
948
15.8k
      }
949
98.3k
      if (relatedCU.isIntra)
950
26.3k
      {
951
26.3k
        cuECtx.isIntra = relatedCU.isIntra;
952
26.3k
      }
953
98.3k
    }
954
98.3k
  }
955
60.0k
  else if( isModeInter( encTestmode ) )
956
0
  {
957
    // INTER MODES (ME + MERGE/SKIP)
958
0
    CHECK( slice.isIntra(), "Inter-mode should not be in the I-Slice mode list!" );
959
960
    // --- Check if we can quit current mode using SAVE/LOAD coding history
961
962
0
    if( encTestmode.type == ETM_INTER_ME )
963
0
    {
964
0
      if( encTestmode.opts == ETO_STANDARD )
965
0
      {
966
0
        if (m_pcEncCfg->m_FastInferMerge)
967
0
        {
968
0
          if (bestCS && (bestCS->slice->TLayer > (m_pcEncCfg->m_maxTLayer - (m_pcEncCfg->m_FastInferMerge & 7)))
969
0
            && (bestCS->bestParent != nullptr) && bestCS->bestParent->cus.size() && (bestCS->bestParent->cus[0]->skip))
970
0
          {
971
0
            return false;
972
0
          }
973
0
        }
974
0
        if( relatedCU.isSkip || relatedCU.isIntra )
975
0
        {
976
0
          return false;
977
0
        }
978
0
      }
979
0
    }
980
0
  }
981
60.0k
  else if (encTestmode.type == ETM_IBC || encTestmode.type == ETM_IBC_MERGE)
982
60.0k
  {
983
60.0k
    if ((m_pcEncCfg->m_IBCFastMethod > 1) && !(slice.isIRAP() || bestMode.type == ETM_INTRA || !cuECtx.bestTU ||
984
0
      ((!m_pcEncCfg->m_bDisableIntraCUsInInterSlices) && (!relatedCU.isInter || !relatedCU.isIBC) && (
985
0
        (cuECtx.bestTU->cbf[0] != 0) ||
986
0
        ((numComp > COMP_Cb) && cuECtx.bestTU->cbf[1] != 0) ||
987
0
        ((numComp > COMP_Cr) && cuECtx.bestTU->cbf[2] != 0)  // avoid very complex intra if it is unlikely
988
0
        ))))
989
0
    {
990
0
      return false;
991
0
    }
992
60.0k
    if ((m_pcEncCfg->m_IBCFastMethod > 3) &&(lumaArea.width == 4 && lumaArea.height == 4 && !slice.isIntra()))
993
0
    {
994
0
      return false;
995
0
    }
996
    // IBC MODES
997
60.0k
    return slice.sps->IBC && (partitioner.currArea().lumaSize().width < 128 && partitioner.currArea().lumaSize().height < 128);
998
60.0k
  }
999
0
  else
1000
0
  {
1001
0
    THROW("problem");
1002
0
    return false;
1003
0
  }
1004
1005
98.3k
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TRIED][0][!cs.slice->isIntra() + cs.slice->depth] );
1006
98.3k
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !cs.slice->isIntra(), g_cuCounters2D[CU_MODES_TRIED][Log2( cs.area.lheight() )][Log2( cs.area.lwidth() )] );
1007
98.3k
  return true;
1008
158k
}
1009
1010
1011
void EncModeCtrl::beforeSplit( Partitioner& partitioner )
1012
98.3k
{
1013
98.3k
  ComprCUCtx&           cuECtx  = m_ComprCUCtxList.back();
1014
1015
98.3k
  if( ! cuECtx.bestCS )
1016
0
    return;
1017
1018
98.3k
  CodedCUInfo    &relatedCU   = getBlkInfo( partitioner.currArea() );
1019
98.3k
  const CodingUnit&  bestCU   = *cuECtx.bestCU;
1020
1021
98.3k
  cuECtx.bestNsPredMode       = cuECtx.bestMode;
1022
98.3k
  cuECtx.bestCostBeforeSplit  = cuECtx.bestCS->cost;
1023
1024
98.3k
  setFromCs( *cuECtx.bestCS, cuECtx.bestMode, partitioner );
1025
1026
98.3k
  if( bestCU.skip )
1027
0
  {
1028
0
    cuECtx.doMoreSplits--;
1029
0
  }
1030
1031
98.3k
  if( partitioner.modeType == MODE_TYPE_INTRA && partitioner.chType == CH_L )
1032
0
  {
1033
0
    return; //not set best coding mode for intra coding pass
1034
0
  }
1035
1036
  // assume the non-split modes are done and set the marks for the best found mode
1037
98.3k
  if( CU::isInter( bestCU ) )
1038
0
  {
1039
0
    relatedCU.isInter     = true;
1040
0
    relatedCU.isSkip     |= bestCU.skip;
1041
0
    relatedCU.isMMVDSkip |= bestCU.mmvdSkip;
1042
0
    relatedCU.BcwIdx      = bestCU.BcwIdx;
1043
0
  }
1044
98.3k
  else if (CU::isIBC(bestCU))
1045
0
  {
1046
0
    relatedCU.isIBC = true;
1047
0
    relatedCU.isSkip |= bestCU.skip;
1048
0
  }
1049
98.3k
  else if( CU::isIntra( bestCU ) )
1050
98.3k
  {
1051
98.3k
    relatedCU.isIntra     = true;
1052
98.3k
    if (m_pcEncCfg->m_FastIntraTools)
1053
98.3k
    {
1054
98.3k
      if ( cuECtx.intraWasTested && (!relatedCU.relatedCuIsValid || cuECtx.bestCS->cost < relatedCU.bestCost))
1055
30.0k
      {
1056
30.0k
        relatedCU.bestCost = cuECtx.bestCS->cost;
1057
30.0k
        relatedCU.relatedCuIsValid = true;
1058
30.0k
      }
1059
98.3k
    }
1060
98.3k
  }
1061
98.3k
  cuECtx.isBestNoSplitSkip = bestCU.skip;
1062
98.3k
}
1063
1064
1065
bool EncModeCtrl::useModeResult( const EncTestMode& encTestmode, CodingStructure*& tempCS, Partitioner& partitioner, const bool useEDO )
1066
206k
{
1067
206k
  ComprCUCtx& cuECtx = m_ComprCUCtxList.back();
1068
1069
206k
  if( m_pcEncCfg->m_fastAMVR )
1070
0
  {
1071
0
    xNoteMotionSearchCost( encTestmode, *tempCS );
1072
0
  }
1073
1074
206k
  if(      encTestmode.type == ETM_SPLIT_BT_H )
1075
29.1k
  {
1076
29.1k
    cuECtx.bestCostHorzSplit = tempCS->cost;
1077
29.1k
  }
1078
177k
  else if( encTestmode.type == ETM_SPLIT_BT_V )
1079
28.7k
  {
1080
28.7k
    cuECtx.bestCostVertSplit = tempCS->cost;
1081
28.7k
  }
1082
148k
  else if( !isModeSplit( encTestmode ) && isModeInter( encTestmode ) && tempCS->cus.size() == 1 )
1083
0
  {
1084
0
    cuECtx.nonSkipWasTested |= !tempCS->cus.front()->skip;
1085
0
  }
1086
206k
  if (m_pcEncCfg->m_AMVRspeed && encTestmode.type == ETM_INTER_ME)
1087
0
  {
1088
0
    int imvMode = (encTestmode.opts & ETO_IMV) >> ETO_IMV_SHIFT;
1089
1090
0
    if (imvMode == 0)
1091
0
    {
1092
0
      if (tempCS->cost < cuECtx.bestCostNoImv )
1093
0
      {
1094
0
        cuECtx.bestCostNoImv = tempCS->cost;
1095
0
      }
1096
0
    }
1097
0
  }
1098
1099
206k
  if( encTestmode.type == ETM_SPLIT_QT )
1100
22.8k
  {
1101
22.8k
    int maxQtD = 0;
1102
22.8k
    for( const auto& cu : tempCS->cus )
1103
89.1k
    {
1104
89.1k
      maxQtD = std::max<int>( maxQtD, cu->qtDepth );
1105
89.1k
    }
1106
22.8k
    cuECtx.maxQtSubDepth = maxQtD;
1107
22.8k
  }
1108
1109
206k
  int maxMtD = tempCS->pcv->getMaxMTTDepth( *tempCS->slice, partitioner.chType ) + partitioner.currImplicitBtDepth;
1110
1111
206k
  if( encTestmode.type == ETM_SPLIT_BT_H )
1112
29.1k
  {
1113
29.1k
    if( tempCS->cus.size() > 2 )
1114
1.09k
    {
1115
1.09k
      int h_2   = tempCS->area.blocks[partitioner.chType].height / 2;
1116
1.09k
      int cu1_h = tempCS->cus.front()->blocks[partitioner.chType].height;
1117
1.09k
      int cu2_h = tempCS->cus.back() ->blocks[partitioner.chType].height;
1118
1119
1.09k
      cuECtx.doTriHorzSplit = cu1_h < h_2 || cu2_h < h_2 || partitioner.currMtDepth + 1 == maxMtD;
1120
1.09k
    }
1121
29.1k
  }
1122
177k
  else if( encTestmode.type == ETM_SPLIT_BT_V )
1123
28.7k
  {
1124
28.7k
    if( tempCS->cus.size() > 2 )
1125
1.23k
    {
1126
1.23k
      int w_2   = tempCS->area.blocks[partitioner.chType].width / 2;
1127
1.23k
      int cu1_w = tempCS->cus.front()->blocks[partitioner.chType].width;
1128
1.23k
      int cu2_w = tempCS->cus.back() ->blocks[partitioner.chType].width;
1129
1130
1.23k
      cuECtx.doTriVertSplit = cu1_w < w_2 || cu2_w < w_2 || partitioner.currMtDepth + 1 == maxMtD;
1131
1.23k
    }
1132
28.7k
  }
1133
1134
206k
  if( encTestmode.type == ETM_SPLIT_BT_V || encTestmode.type == ETM_SPLIT_BT_H || encTestmode.type == ETM_SPLIT_QT )
1135
80.7k
  {
1136
80.7k
    bool isAllSkip = true;
1137
1138
80.7k
    for( const auto& cu : tempCS->cus )
1139
179k
    {
1140
179k
      isAllSkip &= cu->skip;
1141
179k
    }
1142
1143
80.7k
    if( isAllSkip ) cuECtx.doMoreSplits--;
1144
80.7k
    if( isAllSkip && encTestmode.type == ETM_SPLIT_QT )
1145
0
                    cuECtx.doMoreSplits--;
1146
80.7k
  }
1147
1148
  // for now just a simple decision based on RD-cost or choose tempCS if bestCS is not yet coded
1149
206k
  if( tempCS->cost != MAX_DOUBLE && ( !cuECtx.bestCS || ( ( tempCS->cost + ( useEDO ? tempCS->costDbOffset : 0 ) ) < ( cuECtx.bestCS->cost + ( useEDO ? cuECtx.bestCS->costDbOffset : 0 ) ) ) ) )
1150
186k
  {
1151
186k
    cuECtx.bestCS   = tempCS;
1152
186k
    cuECtx.bestCU   = tempCS->cus[0];
1153
186k
    cuECtx.bestTU   = cuECtx.bestCU->firstTU;
1154
186k
    cuECtx.bestMode = encTestmode;
1155
1156
186k
    return true;
1157
186k
  }
1158
19.8k
  else
1159
19.8k
  {
1160
19.8k
    return false;
1161
19.8k
  }
1162
206k
}
1163
1164
//////////////////////////////////////////////////////////////////////////
1165
// FastAMVR: AMVR (MVDs in whole, 4 or half samples) pays where coding the MVD coarsely saves bits, or where the
1166
// half-sample filter predicts better, and only where a searched motion vector is near the node's best mode at all.
1167
// The motion search with quarter-sample MVDs and equal bi-prediction weights, made before it, shows where it cannot.
1168
//////////////////////////////////////////////////////////////////////////
1169
1170
// The largest MVD component in quarter samples that a CU found by motion search codes: per list in use and per control
1171
// point (one unless affine). The MVDs of the second list of an SMVD CU are not coded.
1172
static int largestMvdInQuarterSamples( const CodingUnit& cu )
1173
0
{
1174
0
  static constexpr int QUARTER_SHIFT = MV_FRACTIONAL_BITS_INTERNAL - 2;   // MVDs are kept in 1/16 samples
1175
0
  const int controlPoints = !cu.affine ? 1 : cu.affineType == AFFINEMODEL_6PARAM ? 3 : 2;
1176
0
  int largest = 0;
1177
0
  for( int list = 0; list < NUM_REF_PIC_LIST_01; list++ )
1178
0
  {
1179
0
    if( !( cu.interDir >> list & 1 ) || ( list == REF_PIC_LIST_1 && cu.smvdMode ) )
1180
0
    {
1181
0
      continue;
1182
0
    }
1183
0
    for( int point = 0; point < controlPoints; point++ )
1184
0
    {
1185
0
      largest = std::max( { largest, abs( cu.mvd[list][point].hor ) >> QUARTER_SHIFT, abs( cu.mvd[list][point].ver ) >> QUARTER_SHIFT } );
1186
0
    }
1187
0
  }
1188
0
  return largest;
1189
0
}
1190
1191
// Keeps the best RD cost of the motion search with quarter-sample MVDs and equal weights (called by useModeResult);
1192
// without the deblocking cost offset of EDO, as skipsAmvrSearch compares it with the best mode's RD cost
1193
void EncModeCtrl::xNoteMotionSearchCost( const EncTestMode& encTestmode, const CodingStructure& tempCS )
1194
0
{
1195
0
  if( encTestmode.type != ETM_INTER_ME || tempCS.cost == MAX_DOUBLE || tempCS.cus.empty() || !comprCUCtx )
1196
0
  {
1197
0
    return;
1198
0
  }
1199
0
  const CodingUnit& cu = *tempCS.cus.front();
1200
0
  if( cu.imv == IMV_OFF && cu.BcwIdx == BCW_DEFAULT && tempCS.cost < comprCUCtx->meCost )
1201
0
  {
1202
0
    comprCUCtx->meCost = tempCS.cost;
1203
0
  }
1204
0
}
1205
1206
void EncModeCtrl::noteMotionSearchMvd( const CodingUnit& cu )
1207
0
{
1208
0
  if( m_pcEncCfg->m_fastAMVR && comprCUCtx )
1209
0
  {
1210
0
    comprCUCtx->meLargestMvd = largestMvdInQuarterSamples( cu );
1211
0
  }
1212
0
}
1213
1214
// True where the AMVR search of the current node is not made: its best mode bestCS is skip (as AMVR speeds 3 and 4
1215
// do), or the motion search is far behind it or found MVDs too small to save bits on. The last two need a result of
1216
// the motion search.
1217
bool EncModeCtrl::skipsAmvrSearch( const CodingStructure& bestCS ) const
1218
0
{
1219
0
  if( !m_pcEncCfg->m_fastAMVR || !comprCUCtx || bestCS.cus.empty() )
1220
0
  {
1221
0
    return false;
1222
0
  }
1223
0
  const ComprCUCtx& cuECtx      = *comprCUCtx;
1224
0
  const bool        hasMeResult = cuECtx.meLargestMvd >= 0 && cuECtx.meCost != MAX_DOUBLE;
1225
0
  return bestCS.cus.front()->skip
1226
0
      || ( hasMeResult && ( cuECtx.meCost > AMVR_ME_BEHIND_RATIO * bestCS.cost || cuECtx.meLargestMvd < AMVR_MIN_MVD ) );
1227
0
}
1228
1229
// True where the AMVR search of the current node leaves out 4-sample MVDs
1230
bool EncModeCtrl::skips4PelAmvr() const
1231
0
{
1232
0
  return m_pcEncCfg->m_fastAMVR && comprCUCtx && comprCUCtx->meLargestMvd >= 0 && comprCUCtx->meLargestMvd < AMVR_4PEL_MIN_MVD;
1233
0
}
1234
1235
} // namespace vvenc
1236
1237
//! \}
1238