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/IntraSearch.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     EncSearch.cpp
45
 *  \brief    encoder intra search class
46
 */
47
48
#include "IntraSearch.h"
49
#include "EncPicture.h"
50
#include "CommonLib/CommonDef.h"
51
#include "CommonLib/Rom.h"
52
#include "CommonLib/Picture.h"
53
#include "CommonLib/UnitTools.h"
54
#include "CommonLib/dtrace_next.h"
55
#include "CommonLib/dtrace_buffer.h"
56
#include <math.h>
57
#include "vvenc/vvencCfg.h"
58
59
//! \ingroup EncoderLib
60
//! \{
61
62
namespace vvenc {
63
64
#define PLTCtx(c) SubCtx( Ctx::Palette, c )
65
66
IntraSearch::IntraSearch()
67
5.72k
  : m_pSaveCS       (nullptr)
68
5.72k
  , m_pcEncCfg      (nullptr)
69
5.72k
  , m_pcTrQuant     (nullptr)
70
5.72k
  , m_pcRdCost      (nullptr)
71
5.72k
  , m_CABACEstimator(nullptr)
72
5.72k
  , m_CtxCache      (nullptr)
73
5.72k
{
74
5.72k
}
75
76
void IntraSearch::init(const VVEncCfg &encCfg, TrQuant *pTrQuant, RdCost *pRdCost, SortedPelUnitBufs<SORTED_BUFS> *pSortedPelUnitBufs, XUCache &unitCache )
77
5.72k
{
78
5.72k
  IntraPrediction::init( encCfg.m_internChromaFormat, encCfg.m_internalBitDepth[ CH_L ] );
79
80
5.72k
  m_pcEncCfg          = &encCfg;
81
5.72k
  m_pcTrQuant         = pTrQuant;
82
5.72k
  m_pcRdCost          = pRdCost;
83
5.72k
  m_SortedPelUnitBufs = pSortedPelUnitBufs;
84
85
5.72k
  const ChromaFormat chrFormat = encCfg.m_internChromaFormat;
86
5.72k
  const int maxCUSize          = encCfg.m_CTUSize;
87
88
5.72k
  Area area = Area( 0, 0, maxCUSize, maxCUSize );
89
90
5.72k
  m_pTempCS = new CodingStructure( unitCache, nullptr );
91
5.72k
  m_pBestCS = new CodingStructure( unitCache, nullptr );
92
93
5.72k
  m_pTempCS->createForSearch( chrFormat, area );
94
5.72k
  m_pBestCS->createForSearch( chrFormat, area );
95
96
5.72k
  const int uiNumSaveLayersToAllocate = 3;
97
5.72k
  m_pSaveCS = new CodingStructure*[uiNumSaveLayersToAllocate];
98
22.9k
  for( int layer = 0; layer < uiNumSaveLayersToAllocate; layer++ )
99
17.1k
  {
100
17.1k
    m_pSaveCS[ layer ] = new CodingStructure( unitCache, nullptr );
101
17.1k
    m_pSaveCS[ layer ]->createForSearch( chrFormat, Area( 0, 0, maxCUSize, maxCUSize ) );
102
17.1k
    m_pSaveCS[ layer ]->initStructData();
103
17.1k
  }
104
105
5.72k
  CompArea chromaArea( COMP_Cb, chrFormat, area, true );
106
34.3k
  for( int i = 0; i < 5; i++ )
107
28.6k
  {
108
28.6k
    m_orgResiCb[i].create( chromaArea );
109
28.6k
    m_orgResiCr[i].create( chromaArea );
110
28.6k
  }
111
112
5.72k
  const int maxTbSize = std::min( maxCUSize, MAX_TB_SIZEY );
113
5.72k
  CompArea  preselPredArea( COMP_Cb, chrFormat, Area( 0, 0, maxTbSize, maxTbSize ), true );
114
5.72k
  m_preselPredMaxArea = preselPredArea.area();
115
5.72k
  m_preselPreds.resize( 2 * NUM_PRESEL_CHROMA_PREDS * m_preselPredMaxArea );
116
5.72k
}
117
118
void IntraSearch::destroy()
119
5.72k
{
120
5.72k
  if ( m_pSaveCS )
121
5.72k
  {
122
5.72k
    const int uiNumSaveLayersToAllocate = 3;
123
22.9k
    for( int layer = 0; layer < uiNumSaveLayersToAllocate; layer++ )
124
17.1k
    {
125
17.1k
      if ( m_pSaveCS[ layer ] ) { m_pSaveCS[ layer ]->destroy(); delete m_pSaveCS[ layer ]; }
126
17.1k
    }
127
5.72k
    delete[] m_pSaveCS;
128
5.72k
    m_pSaveCS = nullptr;
129
5.72k
  }
130
131
5.72k
  if( m_pTempCS )
132
5.72k
  {
133
5.72k
    m_pTempCS->destroy();
134
5.72k
    delete m_pTempCS; m_pTempCS = nullptr;
135
5.72k
  }
136
137
5.72k
  if( m_pBestCS )
138
5.72k
  {
139
5.72k
    m_pBestCS->destroy();
140
5.72k
    delete m_pBestCS; m_pBestCS = nullptr;
141
5.72k
  }
142
5.72k
}
143
144
IntraSearch::~IntraSearch()
145
5.72k
{
146
5.72k
  destroy();
147
5.72k
}
148
149
void IntraSearch::setCtuEncRsrc( CABACWriter* cabacEstimator, CtxCache *ctxCache )
150
4.65k
{
151
4.65k
  m_CABACEstimator = cabacEstimator;
152
4.65k
  m_CtxCache       = ctxCache;
153
4.65k
}
154
155
//////////////////////////////////////////////////////////////////////////
156
// INTRA PREDICTION
157
//////////////////////////////////////////////////////////////////////////
158
static constexpr double COST_UNKNOWN = -65536.0;
159
160
double IntraSearch::xFindInterCUCost( CodingUnit &cu )
161
30.0k
{
162
30.0k
  if( CU::isConsIntra(cu) && !cu.slice->isIntra() )
163
0
  {
164
    //search corresponding inter CU cost
165
0
    for( int i = 0; i < m_numCuInSCIPU; i++ )
166
0
    {
167
0
      if( cu.lumaPos() == m_cuAreaInSCIPU[i].pos() && cu.lumaSize() == m_cuAreaInSCIPU[i].size() )
168
0
      {
169
0
        return m_cuCostInSCIPU[i];
170
0
      }
171
0
    }
172
0
  }
173
30.0k
  return COST_UNKNOWN;
174
30.0k
}
175
176
// The bits of a mode only add to its cost, so a mode whose distortion alone reaches the last entry of the full cost list
177
// cannot enter that list, whatever its bits. The list is the only reader of the bits, and coding them takes longer than this test.
178
template<size_t N>
179
static inline bool xCostCannotEnterList( const Distortion dist, const static_vector<double, N>& costs, const size_t numCands )
180
843k
{
181
843k
  return costs.size() >= numCands && ( double ) dist >= costs[numCands - 1];
182
843k
}
183
184
// Within one candidate loop of xEstimateLumaRdModeList (MIP, MRL and ISP fixed) every intra_luma_pred_mode estimate starts from
185
// the same contexts and reads each of them at most once, so a mode's bits depend only on its class: the first mode of a class
186
// is coded, the others of that class take its bits.
187
static constexpr int NUM_MODE_BIT_CLASSES = NUM_MOST_PROBABLE_MODES + 2;
188
189
// The number of symbols of a truncated binary code of numSymbols (<= 256) symbols that take one bin less than the others
190
// (see CABACWriter::xWriteTruncBinCode)
191
static constexpr int truncBinNumShort( const int numSymbols )
192
275k
{
193
275k
  return ( 2 << g_tbMax[numSymbols] ) - numSymbols;
194
275k
}
195
196
// A regular mode's class: its index in the MPM list, else the length of the truncated binary code of its rank among the other
197
// modes
198
static inline int lumaModeBitsClass( const unsigned mode, const unsigned* mpmLst )
199
663k
{
200
663k
  static constexpr int numShort = truncBinNumShort( NUM_LUMA_MODE - NUM_MOST_PROBABLE_MODES );
201
663k
  int rank = mode;
202
4.29M
  for( int i = 0; i < NUM_MOST_PROBABLE_MODES; i++ )
203
3.69M
  {
204
3.69M
    if( mode == mpmLst[i] )
205
65.7k
    {
206
65.7k
      return i;
207
65.7k
    }
208
3.63M
    rank -= mpmLst[i] < mode ? 1 : 0;
209
3.63M
  }
210
597k
  return NUM_MOST_PROBABLE_MODES + ( rank < numShort ? 0 : 1 );
211
663k
}
212
213
// A MIP mode's class: the length of its truncated binary code (the transposed flag is one bypass bin either way)
214
static inline int mipModeBitsClass( const unsigned mode, const int numModes )
215
275k
{
216
275k
  return int( mode ) < truncBinNumShort( numModes ) ? 0 : 1;
217
275k
}
218
219
void IntraSearch::xEstimateLumaRdModeList(int& numModesForFullRD,
220
  static_vector<ModeInfo, FAST_UDI_MAX_RDMODE_NUM>& RdModeList,
221
  static_vector<ModeInfo, FAST_UDI_MAX_RDMODE_NUM>& HadModeList,
222
  static_vector<double, FAST_UDI_MAX_RDMODE_NUM>& CandCostList,
223
  static_vector<double, FAST_UDI_MAX_RDMODE_NUM>& CandHadList, CodingUnit& cu, bool testMip )
224
30.0k
{
225
30.0k
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTRA_EST_RD_CAND, cu.cs, CH_L );
226
30.0k
  const uint16_t intra_ctx_size = Ctx::IntraLumaMpmFlag.size() + Ctx::IntraLumaPlanarFlag.size() + Ctx::MultiRefLineIdx.size() + Ctx::ISPMode.size() + Ctx::MipFlag.size();
227
30.0k
  const TempCtx  ctxStartIntraCtx(m_CtxCache, SubCtx(CtxSet(Ctx::IntraLumaMpmFlag(), intra_ctx_size), m_CABACEstimator->getCtx()));
228
30.0k
  const double   sqrtLambdaForFirstPass = m_pcRdCost->getMotionLambda() * FRAC_BITS_SCALE;
229
30.0k
  const int numModesAvailable = NUM_LUMA_MODE; // total number of Intra modes
230
231
30.0k
  CHECK(numModesForFullRD >= numModesAvailable, "Too many modes for full RD search");
232
233
30.0k
  const SPS& sps     = *cu.cs->sps;
234
30.0k
  const bool fastMip = sps.MIP && m_pcEncCfg->m_useFastMIP;
235
236
  // this should always be true
237
30.0k
  CHECK( !cu.Y().valid(), "CU is not valid" );
238
239
30.0k
  const CompArea& area = cu.Y();
240
241
30.0k
  const UnitArea localUnitArea(area.chromaFormat, Area(0, 0, area.width, area.height));
242
30.0k
  if( testMip)
243
22.7k
  {
244
22.7k
    numModesForFullRD += fastMip ? numModesForFullRD - std::min( m_pcEncCfg->m_useFastMIP, numModesForFullRD )
245
22.7k
                                 : numModesForFullRD;
246
22.7k
    m_SortedPelUnitBufs->prepare( localUnitArea, numModesForFullRD + 1 );
247
22.7k
  }
248
7.28k
  else
249
7.28k
  {
250
7.28k
    m_SortedPelUnitBufs->prepare( localUnitArea, numModesForFullRD );
251
7.28k
  }
252
253
30.0k
  CPelBuf piOrg   = cu.cs->getOrgBuf(COMP_Y);
254
30.0k
  PelBuf piPred  = m_SortedPelUnitBufs->getTestBuf(COMP_Y);
255
256
30.0k
  DistParam distParam    = m_pcRdCost->setDistParam( piOrg, piPred, sps.bitDepths[ CH_L ], DF_HAD_2SAD); // Use HAD (SATD) cost
257
258
30.0k
  const int numHadCand = (testMip ? 2 : 1) * 3;
259
260
  //*** Derive (regular) candidates using Hadamard
261
30.0k
  cu.mipFlag = false;
262
30.0k
  cu.multiRefIdx = 0;
263
264
  //===== init pattern for luma prediction =====
265
30.0k
  initIntraPatternChType(cu, cu.Y(), true);
266
267
30.0k
  bool satdChecked[NUM_INTRA_MODE] = { false };
268
269
30.0k
  const unsigned* mpmLst = m_searchMpmLst;   // derived for this CU in estIntraPredLumaQT
270
271
  // the bits of each class (see lumaModeBitsClass) in the current candidate loop, unknownBits until its first mode is coded
272
30.0k
  const uint64_t unknownBits = std::numeric_limits<uint64_t>::max();
273
30.0k
  uint64_t classBits[NUM_MODE_BIT_CLASSES];
274
30.0k
  std::fill_n( classBits, NUM_MODE_BIT_CLASSES, unknownBits );
275
30.0k
  auto fracModeBitsOfClass = [&]( const int cls ) -> uint64_t
276
938k
  {
277
#if !defined( _DEBUG )   // debug builds code every mode and check it against its class
278
    if( classBits[cls] != unknownBits )
279
    {
280
      return classBits[cls];
281
    }
282
#endif
283
938k
    const uint64_t fracModeBits = xFracModeBitsIntraLuma( cu, mpmLst );
284
938k
    m_CABACEstimator->getCtx() = SubCtx( CtxSet( Ctx::IntraLumaMpmFlag(), intra_ctx_size ), ctxStartIntraCtx );
285
938k
    CHECKD( classBits[cls] != unknownBits && classBits[cls] != fracModeBits, "intra mode bits differ within a class" );
286
938k
    classBits[cls] = fracModeBits;
287
938k
    return fracModeBits;
288
938k
  };
289
290
30.0k
  const int decMsk = ( 1 << m_pcEncCfg->m_IntraEstDecBit ) - 1;
291
292
30.0k
  m_parentCandList.resize( 0 );
293
30.0k
  m_parentCandList.reserve( ( numModesAvailable >> m_pcEncCfg->m_IntraEstDecBit ) + 2 );
294
295
  // the prediction parameters of every mode for this block size, taken once (the loop below changes only the mode)
296
30.0k
  const LumaModeParam* lumaParams = getLumaParamRow( cu );
297
298
2.04M
  for( unsigned mode = 0; mode < numModesAvailable; mode++ )
299
2.01M
  {
300
    // Skip checking extended Angular modes in the first round of SATD
301
2.01M
    if( mode > DC_IDX && ( mode & decMsk ) )
302
1.47M
    {
303
1.47M
      continue;
304
1.47M
    }
305
306
540k
    m_parentCandList.push_back( ModeInfo( false, false, 0, NOT_INTRA_SUBPARTITIONS, mode ) );
307
540k
  }
308
   
309
120k
  for( int decDst = 1 << m_pcEncCfg->m_IntraEstDecBit; decDst > 0; decDst >>= 1 )
310
90.1k
  {
311
811k
    for( unsigned idx = 0; idx < m_parentCandList.size(); idx++ )
312
721k
    {
313
721k
      int modeParent = m_parentCandList[idx].modeId;
314
315
721k
      int off = decDst & decMsk;
316
721k
      int inc = decDst << 1;
317
318
721k
#if 1 // INTRA_AS_IN_VTM
319
721k
      if( off != 0 && ( modeParent <= ( DC_IDX + 1 ) || modeParent >= ( NUM_LUMA_MODE - 1 ) ) )
320
117k
      {
321
117k
        continue;
322
117k
      }
323
324
603k
#endif
325
1.27M
      for( int mode = modeParent - off; mode < modeParent + off + 1; mode += inc )
326
666k
      {
327
666k
        if( satdChecked[mode] || mode < 0 || mode >= NUM_LUMA_MODE )
328
2.75k
        {
329
2.75k
          continue;
330
2.75k
        }
331
332
664k
        cu.intraDir[0] = mode;
333
334
664k
        if( lumaParams )
335
664k
        {
336
664k
          setLumaModeParams( lumaParams[mode] );
337
664k
        }
338
0
        else
339
0
        {
340
0
          initPredIntraParams( cu, cu.Y(), sps );
341
0
        }
342
664k
        distParam.cur.buf = piPred.buf = m_SortedPelUnitBufs->getTestBuf().Y().buf;
343
664k
        predIntraAng( COMP_Y, piPred, cu );
344
345
        // Use the min between SAD and HAD as the cost criterion
346
        // SAD is scaled by 2 to align with the scaling of HAD
347
664k
        Distortion minSadHad = distParam.distFunc( distParam );
348
349
664k
        if( xCostCannotEnterList( minSadHad, CandCostList, numModesForFullRD ) )
350
824
        {
351
824
          updateCandList( ModeInfo( false, false, 0, NOT_INTRA_SUBPARTITIONS, mode ), ( double ) minSadHad, HadModeList, CandHadList, numHadCand );
352
824
          satdChecked[mode] = true;
353
824
          continue;
354
824
        }
355
356
663k
        const uint64_t fracModeBits = fracModeBitsOfClass( lumaModeBitsClass( mode, mpmLst ) );
357
358
663k
        double cost = ( double ) minSadHad + ( double ) fracModeBits * sqrtLambdaForFirstPass;
359
663k
        DTRACE( g_trace_ctx, D_INTRA_COST, "IntraHAD: %u, %llu, %f (%d)\n", minSadHad, fracModeBits, cost, mode );
360
361
663k
        int insertPos = -1;
362
663k
        updateCandList( ModeInfo( false, false, 0, NOT_INTRA_SUBPARTITIONS, mode ), cost, RdModeList, CandCostList, numModesForFullRD, &insertPos );
363
663k
        updateCandList( ModeInfo( false, false, 0, NOT_INTRA_SUBPARTITIONS, mode ), ( double ) minSadHad, HadModeList, CandHadList, numHadCand );
364
663k
        m_SortedPelUnitBufs->insert( insertPos, ( int ) RdModeList.size() );
365
366
663k
        satdChecked[mode] = true;
367
663k
      }
368
603k
    }
369
370
90.1k
    m_parentCandList.resize( RdModeList.size() );
371
90.1k
    std::copy( RdModeList.cbegin(), RdModeList.cend(), m_parentCandList.begin() );
372
90.1k
  }
373
374
30.0k
  const bool isFirstLineOfCtu = (((cu.block(COMP_Y).y)&((cu.cs->sps)->CTUSize - 1)) == 0);
375
30.0k
  if( m_pcEncCfg->m_MRL && ! isFirstLineOfCtu )
376
17.9k
  {
377
17.9k
    cu.multiRefIdx = 1;
378
17.9k
    unsigned  multiRefMPM [NUM_MOST_PROBABLE_MODES];
379
17.9k
    CU::getIntraMPMs(cu, multiRefMPM);
380
381
53.7k
    for (int mRefNum = 1; mRefNum < MRL_NUM_REF_LINES; mRefNum++)
382
35.8k
    {
383
35.8k
      int multiRefIdx = MULTI_REF_LINE_IDX[mRefNum];
384
385
35.8k
      cu.multiRefIdx = multiRefIdx;
386
35.8k
      initIntraPatternChType(cu, cu.Y(), true);
387
388
215k
      for (int x = 1; x < NUM_MOST_PROBABLE_MODES; x++)
389
179k
      {
390
179k
        cu.intraDir[0] = multiRefMPM[x];
391
179k
        initPredIntraParams(cu, cu.Y(), sps);
392
179k
        distParam.cur.buf = piPred.buf = m_SortedPelUnitBufs->getTestBuf().Y().buf;
393
179k
        predIntraAng(COMP_Y, piPred, cu);
394
395
        // Use the min between SAD and SATD as the cost criterion
396
        // SAD is scaled by 2 to align with the scaling of HAD
397
179k
        Distortion minSadHad = distParam.distFunc(distParam);
398
399
179k
        if( xCostCannotEnterList( minSadHad, CandCostList, numModesForFullRD ) )
400
245
        {
401
245
          updateCandList( ModeInfo( false, false, multiRefIdx, NOT_INTRA_SUBPARTITIONS, cu.intraDir[0] ), ( double ) minSadHad, HadModeList, CandHadList, numHadCand );
402
245
          continue;
403
245
        }
404
405
        // NB xFracModeBitsIntra will not affect the mode for chroma that may have already been pre-estimated.
406
179k
        uint64_t fracModeBits = xFracModeBitsIntraLuma( cu, mpmLst );
407
408
        //restore ctx
409
179k
        m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::IntraLumaMpmFlag(), intra_ctx_size), ctxStartIntraCtx);
410
411
179k
        double cost = (double) minSadHad + (double) fracModeBits * sqrtLambdaForFirstPass;
412
//        DTRACE(g_trace_ctx, D_INTRA_COST, "IntraMRL: %u, %llu, %f (%d)\n", minSadHad, fracModeBits, cost, cu.intraDir[0]);
413
414
179k
        int insertPos = -1;
415
179k
        updateCandList( ModeInfo( false, false, multiRefIdx, NOT_INTRA_SUBPARTITIONS, cu.intraDir[0] ), cost, RdModeList,  CandCostList, numModesForFullRD, &insertPos );
416
179k
        updateCandList( ModeInfo( false, false, multiRefIdx, NOT_INTRA_SUBPARTITIONS, cu.intraDir[0] ), (double)minSadHad, HadModeList, CandHadList,  numHadCand );
417
179k
        m_SortedPelUnitBufs->insert(insertPos, (int)RdModeList.size());
418
179k
      }
419
35.8k
    }
420
17.9k
    cu.multiRefIdx = 0;
421
17.9k
  }
422
423
30.0k
  if (testMip)
424
22.7k
  {
425
22.7k
    cu.mipFlag = true;
426
22.7k
    cu.multiRefIdx = 0;
427
428
22.7k
    double mipHadCost[MAX_NUM_MIP_MODE];
429
22.7k
    std::fill_n( mipHadCost, MAX_NUM_MIP_MODE, MAX_DOUBLE );
430
431
22.7k
    initIntraPatternChType(cu, cu.Y());
432
22.7k
    initIntraMip( cu );
433
434
22.7k
    const int transpOff    = getNumModesMip( cu.Y() );
435
22.7k
    const int numModesFull = (transpOff << 1);
436
22.7k
    std::fill_n( classBits, NUM_MODE_BIT_CLASSES, unknownBits );   // MIP's own classes
437
438
297k
    for( uint32_t uiModeFull = 0; uiModeFull < numModesFull; uiModeFull++ )
439
275k
    {
440
275k
      const bool     isTransposed = (uiModeFull >= transpOff ? true : false);
441
275k
      const uint32_t uiMode       = (isTransposed ? uiModeFull - transpOff : uiModeFull);
442
443
275k
      cu.mipTransposedFlag = isTransposed;
444
275k
      cu.intraDir[CH_L] = uiMode;
445
275k
      distParam.cur.buf = piPred.buf = m_SortedPelUnitBufs->getTestBuf().Y().buf;
446
275k
      predIntraMip(piPred, cu);
447
448
      // Use the min between SAD and HAD as the cost criterion
449
      // SAD is scaled by 2 to align with the scaling of HAD
450
275k
      Distortion minSadHad = distParam.distFunc(distParam);
451
452
275k
      const uint64_t fracModeBits = fracModeBitsOfClass( mipModeBitsClass( uiMode, transpOff ) );
453
454
275k
      double cost = double(minSadHad) + double(fracModeBits) * sqrtLambdaForFirstPass;
455
275k
      mipHadCost[uiModeFull] = cost;
456
275k
      DTRACE(g_trace_ctx, D_INTRA_COST, "IntraMIP: %u, %llu, %f (%d)\n", minSadHad, fracModeBits, cost, uiModeFull);
457
458
275k
      int insertPos = -1;
459
275k
      updateCandList( ModeInfo( true, isTransposed, 0, NOT_INTRA_SUBPARTITIONS, cu.intraDir[0] ), cost, RdModeList,  CandCostList, numModesForFullRD+1, &insertPos );
460
275k
      updateCandList( ModeInfo( true, isTransposed, 0, NOT_INTRA_SUBPARTITIONS, cu.intraDir[0] ), 0.8*(double)minSadHad, HadModeList, CandHadList,  numHadCand );
461
275k
      m_SortedPelUnitBufs->insert(insertPos, (int)RdModeList.size());
462
275k
    }
463
464
22.7k
    const double thresholdHadCost = 1.0 + 1.4 / sqrt((double)(cu.lwidth()*cu.lheight()));
465
22.7k
    xReduceHadCandList(RdModeList, CandCostList, *m_SortedPelUnitBufs, numModesForFullRD, thresholdHadCost, mipHadCost, cu, fastMip);
466
22.7k
  }
467
468
30.0k
  if( m_pcEncCfg->m_bFastUDIUseMPMEnabled )
469
30.0k
  {
470
30.0k
    const int numMPMs = NUM_MOST_PROBABLE_MODES;
471
30.0k
    unsigned  intraMpms[numMPMs];
472
473
30.0k
    cu.multiRefIdx = 0;
474
475
30.0k
    const int numCand = CU::getIntraMPMs( cu, intraMpms );
476
30.0k
    ModeInfo mostProbableMode(false, false, 0, NOT_INTRA_SUBPARTITIONS, 0);
477
478
60.9k
    for( int j = 0; j < numCand; j++ )
479
30.9k
    {
480
30.9k
      bool mostProbableModeIncluded = false;
481
30.9k
      mostProbableMode.modeId = intraMpms[j];
482
483
157k
      for( int i = 0; i < numModesForFullRD; i++ )
484
126k
      {
485
126k
        mostProbableModeIncluded |= ( mostProbableMode == RdModeList[i] );
486
126k
      }
487
30.9k
      if( !mostProbableModeIncluded )
488
171
      {
489
171
        numModesForFullRD++;
490
171
        RdModeList.push_back( mostProbableMode );
491
171
        CandCostList.push_back(0);
492
171
      }
493
30.9k
    }
494
30.0k
  }
495
30.0k
}
496
497
bool IntraSearch::estIntraPredLumaQT(CodingUnit &cu, Partitioner &partitioner, double bestCost)
498
30.0k
{
499
30.0k
  CU::getIntraMPMs( cu, m_searchMpmLst );
500
30.0k
  m_searchMpmArea  = cu.Y();
501
30.0k
  m_searchMpmValid = true;
502
503
30.0k
  const bool validReturn = xEstIntraPredLumaQT( cu, partitioner, bestCost );
504
505
30.0k
  m_searchMpmValid = false;
506
30.0k
  return validReturn;
507
30.0k
}
508
509
bool IntraSearch::xEstIntraPredLumaQT(CodingUnit &cu, Partitioner &partitioner, double bestCost)
510
30.0k
{
511
30.0k
  CodingStructure       &cs           = *cu.cs;
512
30.0k
  const int             width         = partitioner.currArea().lwidth();
513
30.0k
  const int             height        = partitioner.currArea().lheight();
514
515
  //===== loop over partitions =====
516
517
30.0k
  const TempCtx ctxStart           ( m_CtxCache, m_CABACEstimator->getCtx() );
518
30.0k
  m_modeBestResi.known = false;
519
520
  // variables for saving fast intra modes scan results across multiple LFNST passes
521
30.0k
  double costInterCU = xFindInterCUCost( cu );
522
523
30.0k
  bool validReturn = false;
524
525
  //===== determine set of modes to be tested (using prediction signal only) =====
526
30.0k
  int numModesAvailable = NUM_LUMA_MODE; // total number of Intra modes
527
30.0k
  static_vector<ModeInfo, FAST_UDI_MAX_RDMODE_NUM> RdModeList;
528
30.0k
  static_vector<ModeInfo, FAST_UDI_MAX_RDMODE_NUM> HadModeList;
529
30.0k
  static_vector<double, FAST_UDI_MAX_RDMODE_NUM> CandCostList;
530
30.0k
  static_vector<double, FAST_UDI_MAX_RDMODE_NUM> CandHadList;
531
532
30.0k
  int numModesForFullRD = g_aucIntraModeNumFast_UseMPM_2D[Log2(width) - MIN_CU_LOG2][Log2(height) - MIN_CU_LOG2];
533
30.0k
  if (m_pcEncCfg->m_numIntraModesFullRD > 0)
534
0
    numModesForFullRD=m_pcEncCfg->m_numIntraModesFullRD;
535
536
#if INTRA_FULL_SEARCH
537
  numModesForFullRD = numModesAvailable;
538
#endif
539
30.0k
  const SPS& sps = *cu.cs->sps;
540
30.0k
  const bool mipAllowed = sps.MIP && cu.lwidth() <= sps.getMaxTbSize() && cu.lheight() <= sps.getMaxTbSize() && ((cu.lfnstIdx == 0) || allowLfnstWithMip(cu.lumaSize()));
541
30.0k
  const int SizeThr     = 8 >> std::max( 0, m_pcEncCfg->m_useFastMIP - 1 );
542
30.0k
  const bool testMip    = mipAllowed && ( cu.lwidth() <= ( SizeThr * cu.lheight() ) && cu.lheight() <= ( SizeThr * cu.lwidth() ) ) && ( cu.lwidth() <= MIP_MAX_WIDTH && cu.lheight() <= MIP_MAX_HEIGHT );
543
30.0k
  bool testISP = sps.ISP && CU::canUseISP(width, height, cu.cs->sps->getMaxTbSize());
544
30.0k
  if (testISP)
545
30.0k
  {
546
30.0k
    int numTotalPartsHor = (int)width >> floorLog2(CU::getISPSplitDim(width, height, TU_1D_VERT_SPLIT));
547
30.0k
    int numTotalPartsVer = (int)height >> floorLog2(CU::getISPSplitDim(width, height, TU_1D_HORZ_SPLIT));
548
30.0k
    m_ispTestedModes[0].init(numTotalPartsHor, numTotalPartsVer, 0);
549
    // the total number of subpartitions is modified to take into account the cases where LFNST cannot be combined with
550
    // ISP due to size restrictions
551
30.0k
    numTotalPartsHor = sps.LFNST && CU::canUseLfnstWithISP(cu.Y(), HOR_INTRA_SUBPARTITIONS) ? numTotalPartsHor : 0;
552
30.0k
    numTotalPartsVer = sps.LFNST && CU::canUseLfnstWithISP(cu.Y(), VER_INTRA_SUBPARTITIONS) ? numTotalPartsVer : 0;
553
90.1k
    for (int j = 1; j < NUM_LFNST_NUM_PER_SET; j++)
554
60.0k
    {
555
60.0k
      m_ispTestedModes[j].init(numTotalPartsHor, numTotalPartsVer, 0);
556
60.0k
    }
557
30.0k
    testISP = m_ispTestedModes[0].numTotalParts[0];
558
30.0k
  }
559
0
  else
560
0
  {
561
0
    m_ispTestedModes[0].init(0, 0, 0);
562
0
  }
563
564
30.0k
  xEstimateLumaRdModeList(numModesForFullRD, RdModeList, HadModeList, CandCostList, CandHadList, cu, testMip);
565
566
30.0k
  CHECK( (size_t)numModesForFullRD != RdModeList.size(), "Inconsistent state!" );
567
568
  // after this point, don't use numModesForFullRD
569
30.0k
  if( m_pcEncCfg->m_usePbIntraFast && !cs.slice->isIntra() && RdModeList.size() < numModesAvailable )
570
0
  {
571
0
    double pbintraRatio = m_pcEncCfg->m_usePbIntraFast == 1 && ( cs.area.lwidth() >= 16 && cs.area.lheight() >= 16 ) ? 1.2 : PBINTRA_RATIO;
572
573
0
    int maxSize = -1;
574
0
    ModeInfo bestMipMode;
575
0
    int bestMipIdx = -1;
576
0
    for( int idx = 0; idx < RdModeList.size(); idx++ )
577
0
    {
578
0
      if( RdModeList[idx].mipFlg )
579
0
      {
580
0
        bestMipMode = RdModeList[idx];
581
0
        bestMipIdx = idx;
582
0
        break;
583
0
      }
584
0
    }
585
0
    const int numHadCand = 3;
586
0
    for (int k = numHadCand - 1; k >= 0; k--)
587
0
    {
588
0
      if (CandHadList.size() < (k + 1) || CandHadList[k] > cs.interHad * pbintraRatio) { maxSize = k; }
589
0
    }
590
0
    if (maxSize > 0)
591
0
    {
592
0
      RdModeList.resize(std::min<size_t>(RdModeList.size(), maxSize));
593
0
      if( bestMipIdx >= 0 )
594
0
      {
595
0
        if( RdModeList.size() <= bestMipIdx )
596
0
        {
597
0
          RdModeList.push_back(bestMipMode);
598
0
          m_SortedPelUnitBufs->swap( maxSize, bestMipIdx );
599
0
        }
600
0
      }
601
0
    }
602
0
    if (maxSize == 0)
603
0
    {
604
0
      cs.dist = MAX_DISTORTION;
605
0
      cs.interHad = 0;
606
0
      return false;
607
0
    }
608
0
  }
609
610
  //===== check modes (using r-d costs) =====
611
30.0k
  ModeInfo bestPUMode;
612
613
30.0k
  CodingStructure *csTemp = m_pTempCS;
614
30.0k
  CodingStructure *csBest = m_pBestCS;
615
616
30.0k
  csTemp->slice   = csBest->slice   = cs.slice;
617
30.0k
  csTemp->picture = csBest->picture = cs.picture;
618
30.0k
  csTemp->compactResize( cu );
619
30.0k
  csBest->compactResize( cu );
620
30.0k
  csTemp->initStructData();
621
30.0k
  csBest->initStructData();
622
623
30.0k
  int   bestLfnstIdx  = 0;
624
30.0k
  const bool useBDPCM = cs.picture->useBDPCM;
625
30.0k
  int   NumBDPCMCand  = (useBDPCM && sps.BDPCM && CU::bdpcmAllowed(cu, ComponentID(partitioner.chType))) ? 2 : 0;
626
30.0k
  int   bestbdpcmMode = 0;
627
30.0k
  int   bestISP       = 0;
628
30.0k
  int   bestMrl       = 0;
629
30.0k
  bool  bestMip       = 0;
630
30.0k
  int   EndMode       = (int)RdModeList.size();
631
30.0k
  bool  useISPlfnst   = testISP && sps.LFNST;
632
30.0k
  bool  noLFNST_ts    = false;
633
30.0k
  double bestCostIsp[2] = { MAX_DOUBLE, MAX_DOUBLE };
634
30.0k
  bool disableMTS = false;
635
30.0k
  bool disableLFNST = false;
636
30.0k
  bool disableDCT2test = false;
637
30.0k
  if (m_pcEncCfg->m_FastIntraTools)
638
30.0k
  {
639
30.0k
    int speedIntra = 0;
640
30.0k
    xSpeedUpIntra(bestCost, EndMode, speedIntra, cu);
641
30.0k
    disableMTS = (speedIntra >> 2 ) & 0x1;
642
30.0k
    disableLFNST = (speedIntra >> 1) & 0x1;
643
30.0k
    disableDCT2test = speedIntra>>3;
644
30.0k
    if (disableLFNST)
645
26.8k
    {
646
26.8k
      noLFNST_ts = true;
647
26.8k
      useISPlfnst = false;
648
26.8k
    }
649
30.0k
    if (speedIntra & 0x1)
650
26.8k
    {
651
26.8k
      testISP = false;
652
26.8k
    }
653
30.0k
  }
654
655
161k
  for (int mode_cur = 0; mode_cur < EndMode + NumBDPCMCand; mode_cur++)
656
131k
  {
657
131k
    int mode = mode_cur;
658
131k
    if (mode_cur >= EndMode)
659
8.29k
    {
660
8.29k
      mode = mode_cur - EndMode ? -1 : -2;
661
8.29k
      testISP = false;
662
8.29k
    }
663
    // set CU/PU to luma prediction mode
664
131k
    ModeInfo testMode;
665
131k
    int noISP = 0;
666
131k
    int endISP = testISP ? 2 : 0;
667
131k
    bool noLFNST = false || noLFNST_ts;
668
131k
    if (mode && useISPlfnst)
669
10.4k
    {
670
10.4k
      noLFNST |= (bestCostIsp[0] > (bestCostIsp[1] * 1.4));
671
10.4k
      if (mode > 2)
672
2.80k
      {
673
2.80k
        endISP = 0;
674
2.80k
        testISP = false;
675
2.80k
      }
676
10.4k
    }
677
131k
    if (testISP)
678
6.73k
    {
679
6.73k
      xSpeedUpISP(1, testISP, mode, noISP, endISP, cu, RdModeList, bestPUMode, bestISP, bestLfnstIdx);
680
6.73k
    }
681
131k
    int startISP = 0;
682
131k
    if (disableDCT2test && mode && bestISP)
683
0
    {
684
0
      startISP = endISP ? 1 : 0;
685
0
    }
686
272k
    for (int ispM = startISP; ispM <= endISP; ispM++)
687
141k
    {
688
141k
      if (ispM && (ispM == noISP))
689
69
      {
690
69
        continue;
691
69
      }
692
693
140k
      if (mode < 0)
694
8.29k
      {
695
8.29k
        cu.bdpcmM[CH_L] = -mode;
696
8.29k
        testMode = ModeInfo(false, false, 0, NOT_INTRA_SUBPARTITIONS, cu.bdpcmM[CH_L] == 2 ? VER_IDX : HOR_IDX);
697
8.29k
      }
698
132k
      else
699
132k
      {
700
132k
        testMode = RdModeList[mode];
701
132k
        cu.bdpcmM[CH_L] = 0;
702
132k
      }
703
704
140k
      cu.ispMode = ispM;
705
140k
      cu.mipFlag = testMode.mipFlg;
706
140k
      cu.mipTransposedFlag = testMode.mipTrFlg;
707
140k
      cu.multiRefIdx = testMode.mRefId;
708
140k
      cu.intraDir[CH_L] = testMode.modeId;
709
140k
      if (cu.ispMode && xSpeedUpISP(0, testISP, mode, noISP, endISP, cu, RdModeList, bestPUMode, bestISP, 0) )
710
3.52k
      {
711
3.52k
        continue;
712
3.52k
      }
713
137k
      if (m_pcEncCfg->m_FastIntraTools && (cu.ispMode || sps.LFNST || sps.MTS))
714
137k
      {
715
137k
        m_ispTestedModes[0].intraWasTested = true;
716
137k
      }
717
137k
      CHECK(cu.mipFlag && cu.multiRefIdx, "Error: combination of MIP and MRL not supported");
718
137k
      CHECK(cu.multiRefIdx && (cu.intraDir[0] == PLANAR_IDX), "Error: combination of MRL and Planar mode not supported");
719
137k
      CHECK(cu.ispMode && cu.mipFlag, "Error: combination of ISP and MIP not supported");
720
137k
      CHECK(cu.ispMode && cu.multiRefIdx, "Error: combination of ISP and MRL not supported");
721
722
      // determine residual for partition
723
137k
      cs.initSubStructure(*csTemp, partitioner.chType, cs.area, true);
724
137k
      int doISP = (((cu.ispMode == 0) && noLFNST) || (useISPlfnst && mode && cu.ispMode && (bestLfnstIdx == 0)) || disableLFNST) ? -mode : mode;
725
      // the contexts are ctxStart's on entry (the reset below follows every call)
726
137k
      xIntraCodingLumaQT(*csTemp, partitioner, m_SortedPelUnitBufs->getBufFromSortedList(mode), bestCost, doISP, disableMTS, ctxStart);
727
728
137k
      DTRACE(g_trace_ctx, D_INTRA_COST, "IntraCost T [x=%d,y=%d,w=%d,h=%d] %f (%d,%d,%d,%d,%d,%d) \n", cu.blocks[0].x,
729
137k
        cu.blocks[0].y, width, height, csTemp->cost, testMode.modeId, testMode.ispMod,
730
137k
        cu.multiRefIdx, cu.mipFlag, cu.lfnstIdx, cu.mtsFlag);
731
732
137k
      if (cu.ispMode && !csTemp->cus[0]->firstTU->cbf[COMP_Y])
733
2.24k
      {
734
2.24k
        csTemp->cost = MAX_DOUBLE;
735
2.24k
        csTemp->costDbOffset = 0;
736
2.24k
      }
737
137k
      if (useISPlfnst)
738
19.9k
      {
739
19.9k
        int n = (cu.ispMode == 0) ? 0 : 1;
740
19.9k
        bestCostIsp[n] = csTemp->cost < bestCostIsp[n] ? csTemp->cost : bestCostIsp[n];
741
19.9k
      }
742
743
      // check r-d cost
744
137k
      if (csTemp->cost < csBest->cost)
745
37.6k
      {
746
37.6k
        validReturn   = true;
747
37.6k
        std::swap(csTemp, csBest);
748
37.6k
        m_modeBestResi.swap( m_trialBestResi );
749
37.6k
        bestPUMode    = testMode;
750
37.6k
        bestLfnstIdx  = csBest->cus[0]->lfnstIdx;
751
37.6k
        bestISP       = csBest->cus[0]->ispMode;
752
37.6k
        bestMip       = csBest->cus[0]->mipFlag;
753
37.6k
        bestMrl       = csBest->cus[0]->multiRefIdx;
754
37.6k
        bestbdpcmMode = cu.bdpcmM[CH_L];
755
37.6k
        m_ispTestedModes[bestLfnstIdx].bestSplitSoFar = ISPType(bestISP);
756
37.6k
        if (csBest->cost < bestCost)
757
37.6k
        {
758
37.6k
          bestCost = csBest->cost;
759
37.6k
        }
760
37.6k
        if ((csBest->getTU(partitioner.chType)->mtsIdx[COMP_Y] == MTS_SKIP) && ( floorLog2(csBest->getTU(partitioner.chType)->blocks[COMP_Y].area()) >= 6 ))
761
4.92k
        {
762
4.92k
          noLFNST_ts = 1;
763
4.92k
        }
764
37.6k
      }
765
766
      // reset context models (xIntraCodingLumaQT leaves its last test's contexts or, where xKeepLumaResiOfTrial took
767
      // those, a stale set: nothing reads them)
768
137k
      m_CABACEstimator->getCtx() = ctxStart;
769
770
137k
      csTemp->releaseIntermediateData();
771
772
137k
      if (m_pcEncCfg->m_fastLocalDualTreeMode && CU::isConsIntra(cu) && !cu.slice->isIntra() && csBest->cost != MAX_DOUBLE && costInterCU != COST_UNKNOWN && mode >= 0)
773
0
      {
774
0
        if( (m_pcEncCfg->m_fastLocalDualTreeMode == 2) || (csBest->cost > costInterCU * 1.5))
775
0
        {
776
          //Note: only try one intra mode, which is especially useful to reduce EncT for LDB case (around 4%)
777
0
          EndMode = 0;
778
0
          break;
779
0
        }
780
0
      }
781
137k
    }
782
131k
  } // Mode loop
783
784
30.0k
  if (m_pcEncCfg->m_FastIntraTools && (sps.ISP|| sps.LFNST || sps.MTS))
785
30.0k
  {
786
30.0k
    int bestMode = csBest->getTU(partitioner.chType)->mtsIdx[COMP_Y] ? 4 : 0;
787
30.0k
    bestMode |= bestLfnstIdx ? 2 : 0;
788
30.0k
    bestMode |= bestISP ? 1 : 0;
789
30.0k
    m_ispTestedModes[0].bestIntraMode = bestMode;
790
30.0k
  }
791
30.0k
  cu.ispMode = bestISP;
792
30.0k
  if( validReturn )
793
30.0k
  {
794
30.0k
    cs.useSubStructure( *csBest, partitioner.chType, TREE_D, cu.singleChan( CH_L ), true );
795
796
    //=== update PU data ====
797
30.0k
    cu.lfnstIdx           = bestLfnstIdx;
798
30.0k
    cu.mipTransposedFlag  = bestPUMode.mipTrFlg;
799
30.0k
    cu.intraDir[CH_L]     = bestPUMode.modeId;
800
30.0k
    cu.bdpcmM[CH_L]       = bestbdpcmMode;
801
30.0k
    cu.mipFlag            = bestMip;
802
30.0k
    cu.multiRefIdx        = bestMrl;
803
30.0k
  }
804
0
  else
805
0
  {
806
0
    THROW("fix this");
807
0
  }
808
809
30.0k
  csBest->releaseIntermediateData();
810
811
30.0k
  return validReturn;
812
30.0k
}
813
814
void IntraSearch::estIntraPredChromaQT( CodingUnit& cu, Partitioner& partitioner, const double maxCostAllowed )
815
68.2k
{
816
68.2k
  PROFILER_SCOPE_AND_STAGE_EXT( 0, _TPROF, P_INTRA_CHROMA, cu.cs, CH_C );
817
68.2k
  const TempCtx ctxStart( m_CtxCache, m_CABACEstimator->getCtx() );
818
68.2k
  CodingStructure &cs   = *cu.cs;
819
68.2k
  bool lumaUsesISP      = !CU::isSepTree(cu) && cu.ispMode;
820
68.2k
  PartSplit ispType     = lumaUsesISP ? CU::getISPType(cu, COMP_Y) : TU_NO_ISP;
821
68.2k
  double bestCostSoFar  = maxCostAllowed;
822
68.2k
  const uint32_t numberValidComponents = getNumberValidComponents( cu.chromaFormat );
823
68.2k
  const bool useBDPCM   = cs.picture->useBDPCM;
824
825
68.2k
  uint32_t   uiBestMode = 0;
826
68.2k
  Distortion uiBestDist = 0;
827
68.2k
  double     dBestCost  = MAX_DOUBLE;
828
68.2k
  bool       ctxCoded   = false;   // the estimator holds ctxStart's contexts until the first mode is coded
829
830
  //----- init mode list ----
831
68.2k
  {
832
68.2k
    uint32_t  uiMinMode = 0;
833
68.2k
    uint32_t  uiMaxMode = NUM_CHROMA_MODE;
834
835
68.2k
    const int reducedModeNumber = uiMaxMode >> (m_pcEncCfg->m_reduceIntraChromaModesFullRD ? 1 : 2);
836
    //----- check chroma modes -----
837
68.2k
    uint32_t chromaCandModes[ NUM_CHROMA_MODE ];
838
68.2k
    CU::getIntraChromaCandModes( cu, chromaCandModes );
839
840
    // create a temporary CS
841
68.2k
    CodingStructure &saveCS = *m_pSaveCS[0];
842
68.2k
    saveCS.pcv      = cs.pcv;
843
68.2k
    saveCS.picture  = cs.picture;
844
68.2k
    saveCS.area.repositionTo( cs.area );
845
68.2k
    saveCS.clearTUs();
846
847
68.2k
    if( !CU::isSepTree(cu) && cu.ispMode )
848
0
    {
849
0
      saveCS.clearCUs();
850
0
    }
851
852
68.2k
    if( CU::isSepTree(cu) )
853
68.2k
    {
854
68.2k
      if( partitioner.canSplit( TU_MAX_TR_SPLIT, cs ) )
855
0
      {
856
0
        partitioner.splitCurrArea( TU_MAX_TR_SPLIT, cs );
857
858
0
        do
859
0
        {
860
0
          cs.addTU( CS::getArea( cs, partitioner.currArea(), partitioner.chType, partitioner.treeType ), partitioner.chType, &cu ).depth = partitioner.currTrDepth;
861
0
        } while( partitioner.nextPart( cs ) );
862
863
0
        partitioner.exitCurrSplit();
864
0
      }
865
68.2k
      else
866
68.2k
        cs.addTU( CS::getArea( cs, partitioner.currArea(), partitioner.chType, partitioner.treeType ), partitioner.chType, &cu );
867
68.2k
    }
868
869
    // create a store for the TUs
870
68.2k
    std::vector<TransformUnit*> orgTUs;
871
68.2k
    for( const auto &ptu : cs.tus )
872
68.2k
    {
873
      // for split TUs in HEVC, add the TUs without Chroma parts for correct setting of Cbfs
874
68.2k
      if (lumaUsesISP || cu.contains(*ptu, CH_C))
875
68.2k
      {
876
68.2k
        saveCS.addTU( *ptu, partitioner.chType, nullptr );
877
68.2k
        orgTUs.push_back( ptu );
878
68.2k
      }
879
68.2k
    }
880
881
    // SATD pre-selecting.
882
68.2k
    int     satdModeList  [NUM_CHROMA_MODE] = { 0 };
883
68.2k
    int64_t satdSortedCost[NUM_CHROMA_MODE] = { 0 };
884
68.2k
    bool    modeDisable[NUM_INTRA_MODE + 1] = { false }; // use intra mode idx to check whether enable
885
886
68.2k
    CodingStructure& cs = *(cu.cs);
887
68.2k
    CompArea areaCb = cu.Cb();
888
68.2k
    CompArea areaCr = cu.Cr();
889
68.2k
    CPelBuf orgCb  = cs.getOrgBuf (COMP_Cb);
890
68.2k
    PelBuf predCb  = cs.getPredBuf(COMP_Cb);
891
68.2k
    CPelBuf orgCr  = cs.getOrgBuf (COMP_Cr);
892
68.2k
    PelBuf predCr  = cs.getPredBuf(COMP_Cr);
893
894
68.2k
    DistParam distParamSadCb  = m_pcRdCost->setDistParam( orgCb, predCb, cu.cs->sps->bitDepths[ CH_C ], DF_SAD);
895
68.2k
    DistParam distParamSatdCb = m_pcRdCost->setDistParam( orgCb, predCb, cu.cs->sps->bitDepths[ CH_C ], DF_HAD);
896
68.2k
    DistParam distParamSadCr  = m_pcRdCost->setDistParam( orgCr, predCr, cu.cs->sps->bitDepths[ CH_C ], DF_SAD);
897
68.2k
    DistParam distParamSatdCr = m_pcRdCost->setDistParam( orgCr, predCr, cu.cs->sps->bitDepths[ CH_C ], DF_HAD);
898
899
68.2k
    cu.intraDir[1] = MDLM_L_IDX; // temporary assigned, just to indicate this is a MDLM mode. for luma down-sampling operation.
900
901
68.2k
    initIntraPatternChType(cu, cu.Cb());
902
68.2k
    initIntraPatternChType(cu, cu.Cr());
903
68.2k
    loadLMLumaRecPels(cu, cu.Cb());
904
905
    // keep the predictions for the RD checks when the CU's chroma block fits a slot (the RD checks reuse them only when
906
    // it is one transform block) and the pre-selection does not predict with a chroma BDPCM left on the CU, which the
907
    // RD checks of these modes reset
908
68.2k
    const bool keepPreds = areaCb.area() <= m_preselPredMaxArea && !cu.bdpcmM[CH_C];
909
68.2k
    const SizeType slotSize = areaCb.area(); // the Cr block has the Cb block's size
910
68.2k
    Pel* const     slots    = m_preselPreds.data();
911
68.2k
    int            numKept  = 0;
912
68.2k
    if( keepPreds )
913
68.2k
    {
914
      // point the prediction and distortion views at slot 0 with the block's width as stride; per mode, only their
915
      // buffer pointers move to the next slot
916
68.2k
      predCb = preselPred( 0, COMP_Cb, areaCb );
917
68.2k
      predCr = preselPred( 0, COMP_Cr, areaCr );
918
68.2k
      distParamSadCb.cur = distParamSatdCb.cur = predCb;
919
68.2k
      distParamSadCr.cur = distParamSatdCr.cur = predCr;
920
68.2k
    }
921
922
614k
    for (int idx = uiMinMode; idx < uiMaxMode; idx++)
923
546k
    {
924
546k
      int mode = chromaCandModes[idx];
925
546k
      satdModeList[idx] = mode;
926
546k
      if (CU::isLMCMode(mode) && ( !CU::isLMCModeEnabled(cu, mode) || cu.slice->lmChromaCheckDisable ) )
927
58.7k
      {
928
58.7k
        continue;
929
58.7k
      }
930
487k
      if ((mode == LM_CHROMA_IDX) || (mode == PLANAR_IDX) || (mode == DM_CHROMA_IDX)) // only pre-check regular modes and MDLM modes, not including DM ,Planar, and LM
931
118k
      {
932
118k
        continue;
933
118k
      }
934
935
368k
      if( keepPreds )
936
368k
      {
937
368k
        CHECKD( numKept == NUM_PRESEL_CHROMA_PREDS, "more pre-checked chroma modes than slots" );
938
368k
        Pel* slotCb = slots + 2 * numKept * slotSize;
939
368k
        distParamSadCb.cur.buf = distParamSatdCb.cur.buf = predCb.buf = slotCb;
940
368k
        distParamSadCr.cur.buf = distParamSatdCr.cur.buf = predCr.buf = slotCb + slotSize;
941
368k
        m_preselPredMode[numKept++] = mode;
942
368k
      }
943
944
368k
      cu.intraDir[1]    = mode; // temporary assigned, for SATD checking.
945
946
368k
      const bool isLMCMode = CU::isLMCMode(mode);
947
368k
      if( isLMCMode )
948
97.3k
      {
949
97.3k
        predIntraChromaLM(COMP_Cb, predCb, cu, areaCb, mode);
950
97.3k
      }
951
270k
      else
952
270k
      {
953
270k
        initPredIntraParams(cu, cu.Cb(), *cs.sps);
954
270k
        predIntraAng(COMP_Cb, predCb, cu);
955
270k
      }
956
368k
      int64_t sadCb = distParamSadCb.distFunc(distParamSadCb) * 2;
957
368k
      int64_t satdCb = distParamSatdCb.distFunc(distParamSatdCb);
958
368k
      int64_t sad = std::min(sadCb, satdCb);
959
960
368k
      if( isLMCMode )
961
97.3k
      {
962
97.3k
        predIntraChromaLM(COMP_Cr, predCr, cu, areaCr, mode);
963
97.3k
      }
964
270k
      else
965
270k
      {
966
270k
        initPredIntraParams(cu, cu.Cr(), *cs.sps);
967
270k
        predIntraAng(COMP_Cr, predCr, cu);
968
270k
      }
969
368k
      int64_t sadCr = distParamSadCr.distFunc(distParamSadCr) * 2;
970
368k
      int64_t satdCr = distParamSatdCr.distFunc(distParamSatdCr);
971
368k
      sad += std::min(sadCr, satdCr);
972
368k
      satdSortedCost[idx] = sad;
973
368k
    }
974
68.2k
    m_numPreselPreds = numKept;
975
976
    // sort the mode based on the cost from small to large.
977
614k
    for (int i = uiMinMode; i <= uiMaxMode - 1; i++)
978
546k
    {
979
2.45M
      for (int j = i + 1; j <= uiMaxMode - 1; j++)
980
1.91M
      {
981
1.91M
        if (satdSortedCost[j] < satdSortedCost[i])
982
114k
        {
983
114k
          std::swap( satdModeList[i],   satdModeList[j]);
984
114k
          std::swap( satdSortedCost[i], satdSortedCost[j]);
985
114k
        }
986
1.91M
      }
987
546k
    }
988
989
341k
    for (int i = 0; i < reducedModeNumber; i++)
990
273k
    {
991
273k
      modeDisable[satdModeList[uiMaxMode - 1 - i]] = true; // disable the last reducedModeNumber modes
992
273k
    }
993
994
68.2k
    int bestLfnstIdx = 0;
995
    // save the dist
996
68.2k
    Distortion baseDist = cs.dist;
997
68.2k
    int32_t bestbdpcmMode = 0;
998
68.2k
    uint32_t numbdpcmModes = ( useBDPCM && CU::bdpcmAllowed(cu, COMP_Cb)
999
45.0k
        && ((partitioner.chType == CH_C) || (cu.ispMode == 0 && cu.lfnstIdx == 0 && cu.firstTU->mtsIdx[COMP_Y] == MTS_SKIP))) ? 2 : 0;
1000
704k
    for (int mode_cur = uiMinMode; mode_cur < (int)(uiMaxMode + numbdpcmModes); mode_cur++)
1001
636k
    {
1002
636k
      int mode = mode_cur;
1003
636k
      if (mode_cur >= uiMaxMode)
1004
90.1k
      {
1005
90.1k
        mode = mode_cur > uiMaxMode ? -1 : -2; //set bdpcm mode
1006
90.1k
        if ((mode == -1) && (saveCS.tus[0]->mtsIdx[COMP_Cb] != MTS_SKIP) && (saveCS.tus[0]->mtsIdx[COMP_Cr] != MTS_SKIP))
1007
45.0k
        {
1008
45.0k
          continue;
1009
45.0k
        }
1010
90.1k
      }
1011
591k
      int chromaIntraMode;
1012
591k
      if (mode < 0)
1013
45.0k
      {
1014
45.0k
        cu.bdpcmM[CH_C] = -mode;
1015
45.0k
        chromaIntraMode = cu.bdpcmM[CH_C] == 2 ? chromaCandModes[1] : chromaCandModes[2];
1016
45.0k
      }
1017
546k
      else
1018
546k
      {
1019
546k
        cu.bdpcmM[CH_C] = 0;
1020
546k
        chromaIntraMode = chromaCandModes[mode];
1021
546k
        if (CU::isLMCMode(chromaIntraMode) && ( !CU::isLMCModeEnabled(cu, chromaIntraMode) || cu.slice->lmChromaCheckDisable ) )
1022
58.7k
        {
1023
58.7k
          continue;
1024
58.7k
        }
1025
487k
        if (modeDisable[chromaIntraMode] && CU::isLMCModeEnabled(cu, chromaIntraMode)) // when CCLM is disable, then MDLM is disable. not use satd checking
1026
194k
        {
1027
194k
          continue;
1028
194k
        }
1029
487k
      }
1030
337k
      cs.dist = baseDist;
1031
      //----- restore context models (still ctxStart's until a mode is coded) -----
1032
337k
      if( ctxCoded )
1033
269k
      {
1034
269k
        m_CABACEstimator->getCtx() = ctxStart;
1035
269k
      }
1036
337k
      ctxCoded = true;
1037
1038
      //----- chroma coding -----
1039
337k
      cu.intraDir[1] = chromaIntraMode;
1040
337k
      m_ispTestedModes[0].IspType = ispType;
1041
337k
      m_ispTestedModes[0].subTuCounter = -1;
1042
      // with transform skip in the SPS the contexts are reset to ctxStart right after it (below, same condition): it need not
1043
      // keep its best ones
1044
337k
      xIntraChromaCodingQT( cs, partitioner, !cs.sps->transformSkip );
1045
337k
      if (lumaUsesISP && cs.dist == MAX_UINT)
1046
0
      {
1047
0
        continue;
1048
0
      }
1049
1050
337k
      if (cs.sps->transformSkip)
1051
337k
      {
1052
337k
        m_CABACEstimator->getCtx() = ctxStart;
1053
337k
      }
1054
337k
      m_ispTestedModes[0].IspType = ispType;
1055
337k
      m_ispTestedModes[0].subTuCounter = -1;
1056
337k
      uint64_t fracBits   = xGetIntraFracBitsQT( cs, partitioner, false );
1057
337k
      Distortion uiDist = cs.dist;
1058
337k
      double    dCost   = m_pcRdCost->calcRdCost( fracBits, uiDist - baseDist );
1059
1060
      //----- compare -----
1061
337k
      if( dCost < dBestCost )
1062
122k
      {
1063
122k
        if (lumaUsesISP && (dCost < bestCostSoFar))
1064
0
        {
1065
0
          bestCostSoFar = dCost;
1066
0
        }
1067
367k
        for( uint32_t i = getFirstComponentOfChannel( CH_C ); i < numberValidComponents; i++ )
1068
245k
        {
1069
245k
          const CompArea& area = cu.blocks[i];
1070
245k
          saveCS.getRecoBuf     ( area ).copyFrom( cs.getRecoBuf   ( area ) );
1071
245k
          cs.picture->getRecoBuf( area ).copyFrom( cs.getRecoBuf   ( area ) );
1072
490k
          for( uint32_t j = 0; j < saveCS.tus.size(); j++ )
1073
245k
          {
1074
245k
            saveCS.tus[j]->copyComponentFrom( *orgTUs[j], area.compID );
1075
245k
          }
1076
245k
        }
1077
122k
        dBestCost    = dCost;
1078
122k
        uiBestDist   = uiDist;
1079
122k
        uiBestMode   = chromaIntraMode;
1080
122k
        bestLfnstIdx = cu.lfnstIdx;
1081
122k
        bestbdpcmMode = cu.bdpcmM[CH_C];
1082
1083
122k
      }
1084
337k
    }
1085
68.2k
    cu.lfnstIdx = bestLfnstIdx;
1086
68.2k
    cu.bdpcmM[CH_C]= bestbdpcmMode;
1087
1088
204k
    for( uint32_t i = getFirstComponentOfChannel( CH_C ); i < numberValidComponents; i++ )
1089
136k
    {
1090
136k
      const CompArea& area = cu.blocks[i];
1091
1092
136k
      cs.getRecoBuf         ( area ).copyFrom( saveCS.getRecoBuf( area ) );
1093
136k
      cs.picture->getRecoBuf( area ).copyFrom( cs.getRecoBuf    ( area ) );
1094
1095
273k
      for( uint32_t j = 0; j < saveCS.tus.size(); j++ )
1096
136k
      {
1097
136k
        orgTUs[ j ]->copyComponentFrom( *saveCS.tus[ j ], area.compID );
1098
136k
      }
1099
136k
    }
1100
68.2k
    m_numPreselPreds = 0;
1101
68.2k
  }
1102
0
  cu.intraDir[1] = uiBestMode;
1103
68.2k
  cs.dist        = uiBestDist;
1104
1105
  //----- restore context models -----
1106
68.2k
  m_CABACEstimator->getCtx() = ctxStart;
1107
68.2k
  if (lumaUsesISP && bestCostSoFar >= maxCostAllowed)
1108
0
  {
1109
0
    cu.ispMode = 0;
1110
0
  }
1111
68.2k
}
1112
1113
void IntraSearch::saveCuAreaCostInSCIPU( Area area, double cost )
1114
0
{
1115
0
  if( m_numCuInSCIPU < NUM_INTER_CU_INFO_SAVE )
1116
0
  {
1117
0
    m_cuAreaInSCIPU[m_numCuInSCIPU] = area;
1118
0
    m_cuCostInSCIPU[m_numCuInSCIPU] = cost;
1119
0
    m_numCuInSCIPU++;
1120
0
  }
1121
0
}
1122
1123
void IntraSearch::initCuAreaCostInSCIPU()
1124
0
{
1125
0
  for( int i = 0; i < NUM_INTER_CU_INFO_SAVE; i++ )
1126
0
  {
1127
0
    m_cuAreaInSCIPU[i] = Area();
1128
0
    m_cuCostInSCIPU[i] = 0;
1129
0
  }
1130
0
  m_numCuInSCIPU = 0;
1131
0
}
1132
// -------------------------------------------------------------------------------------------------------------------
1133
// Intra search
1134
// -------------------------------------------------------------------------------------------------------------------
1135
1136
void IntraSearch::xEncIntraHeader( CodingStructure &cs, Partitioner &partitioner, const bool luma )
1137
548k
{
1138
548k
  CodingUnit &cu = *cs.getCU( partitioner.chType, partitioner.treeType );
1139
1140
548k
  if (luma)
1141
210k
  {
1142
210k
    bool isFirst = cu.ispMode ? m_ispTestedModes[0].subTuCounter == 0 : partitioner.currArea().lumaPos() == cs.area.lumaPos();
1143
1144
    // CU header
1145
210k
    if( isFirst )
1146
205k
    {
1147
205k
      if ((!cs.slice->isIntra() || cs.slice->sps->IBC || cs.slice->sps->PLT) && cu.Y().valid())
1148
205k
      {
1149
205k
        m_CABACEstimator->pred_mode   ( cu );
1150
205k
      }
1151
205k
      m_CABACEstimator->bdpcm_mode  ( cu, ComponentID(partitioner.chType) );
1152
205k
    }
1153
1154
    // luma prediction mode
1155
210k
    if (isFirst)
1156
205k
    {
1157
205k
      if ( !cu.Y().valid())
1158
0
      {
1159
0
        m_CABACEstimator->pred_mode( cu );
1160
0
      }
1161
205k
      const bool searchedCu = m_searchMpmValid && m_searchMpmArea == cu.Y();
1162
205k
#if defined( _DEBUG )
1163
205k
      if( searchedCu )
1164
205k
      {
1165
205k
        unsigned mpmLst[NUM_MOST_PROBABLE_MODES];
1166
205k
        CU::getIntraMPMs( cu, mpmLst );
1167
205k
        CHECK( !std::equal( mpmLst, mpmLst + NUM_MOST_PROBABLE_MODES, m_searchMpmLst ), "MPM list of the searched CU is out of date" );
1168
205k
      }
1169
205k
#endif
1170
205k
      m_CABACEstimator->intra_luma_pred_mode( cu, searchedCu ? m_searchMpmLst : nullptr );
1171
205k
    }
1172
210k
  }
1173
337k
  else //  if (chroma)
1174
337k
  {
1175
337k
    bool isFirst = partitioner.currArea().Cb().valid() && partitioner.currArea().chromaPos() == cs.area.chromaPos();
1176
1177
337k
    if( isFirst )
1178
337k
    {
1179
337k
      m_CABACEstimator->bdpcm_mode(cu, ComponentID(CH_C));
1180
337k
      m_CABACEstimator->intra_chroma_pred_mode(  cu );
1181
337k
    }
1182
337k
  }
1183
548k
}
1184
1185
TransformUnit& IntraSearch::xCurrTU( CodingStructure& cs, Partitioner& partitioner ) const
1186
1.43M
{
1187
1.43M
  if( cs.tus.size() == 1 )
1188
1.42M
  {
1189
1.42M
    return *cs.tus[0];
1190
1.42M
  }
1191
11.5k
  const int subTu = m_ispTestedModes[0].subTuCounter;
1192
11.5k
  if( subTu >= 0 && isLuma( partitioner.chType ) )
1193
11.5k
  {
1194
11.5k
    return *cs.tus[subTu];
1195
11.5k
  }
1196
18.4E
  return *cs.getTU( partitioner.currArea().blocks[partitioner.chType], partitioner.chType );
1197
11.5k
}
1198
1199
void IntraSearch::xEncSubdivCbfQT( CodingStructure &cs, Partitioner &partitioner, const bool luma )
1200
548k
{
1201
548k
  const UnitArea& currArea = partitioner.currArea();
1202
548k
  int subTuCounter = m_ispTestedModes[0].subTuCounter;
1203
548k
  TransformUnit  &currTU   = xCurrTU( cs, partitioner );
1204
548k
  CodingUnit     &currCU   = *currTU.cu;
1205
548k
  const uint32_t currDepth = partitioner.currTrDepth;
1206
548k
  const bool  subdiv = currTU.depth > currDepth;
1207
548k
  ComponentID compID = partitioner.chType == CH_L ? COMP_Y : COMP_Cb;
1208
1209
548k
  if (!luma)
1210
337k
  {
1211
337k
    const bool chromaCbfISP = currArea.blocks[COMP_Cb].valid() && currCU.ispMode && !subdiv;
1212
337k
    if (!currCU.ispMode || chromaCbfISP)
1213
337k
    {
1214
337k
      const uint32_t numberValidComponents = getNumberValidComponents(currArea.chromaFormat);
1215
337k
      const uint32_t cbfDepth = (chromaCbfISP ? currDepth - 1 : currDepth);
1216
1217
1.01M
      for (uint32_t ch = COMP_Cb; ch < numberValidComponents; ch++)
1218
675k
      {
1219
675k
        const ComponentID compID = ComponentID(ch);
1220
675k
        if (currDepth == 0 || TU::getCbfAtDepth(currTU, compID, currDepth - 1) || chromaCbfISP)
1221
675k
        {
1222
675k
          const bool prevCbf = (compID == COMP_Cr ? TU::getCbfAtDepth(currTU, COMP_Cb, currDepth) : false);
1223
675k
          m_CABACEstimator->cbf_comp(currCU, TU::getCbfAtDepth(currTU, compID, currDepth), currArea.blocks[compID], cbfDepth, prevCbf);
1224
675k
        }
1225
675k
      }
1226
337k
    }
1227
337k
  }
1228
1229
548k
  if (subdiv)
1230
0
  {
1231
0
    if (partitioner.canSplit(TU_MAX_TR_SPLIT, cs))
1232
0
    {
1233
0
      partitioner.splitCurrArea(TU_MAX_TR_SPLIT, cs);
1234
0
    }
1235
0
    else if (currCU.ispMode && isLuma(compID))
1236
0
    {
1237
0
      partitioner.splitCurrArea(m_ispTestedModes[0].IspType, cs);
1238
0
    }
1239
0
    else
1240
0
      THROW("Cannot perform an implicit split!");
1241
1242
0
    do
1243
0
    {
1244
0
      xEncSubdivCbfQT(cs, partitioner, luma);   //?
1245
0
      subTuCounter += subTuCounter != -1 ? 1 : 0;
1246
0
    } while (partitioner.nextPart(cs));
1247
1248
0
    partitioner.exitCurrSplit();
1249
0
  }
1250
548k
  else
1251
548k
  {
1252
    //===== Cbfs =====
1253
548k
    if (luma)
1254
210k
    {
1255
210k
      bool previousCbf = false;
1256
210k
      bool lastCbfIsInferred = false;
1257
210k
      if (m_ispTestedModes[0].IspType != TU_NO_ISP)
1258
16.6k
      {
1259
16.6k
        bool     rootCbfSoFar = false;
1260
16.6k
        uint32_t nTus = currCU.ispMode == HOR_INTRA_SUBPARTITIONS ? currCU.lheight() >> floorLog2(currTU.lheight())
1261
16.6k
          : currCU.lwidth() >> floorLog2(currTU.lwidth());
1262
16.6k
        if (subTuCounter == nTus - 1)
1263
1.52k
        {
1264
1.52k
          TransformUnit* tuPointer = currCU.firstTU;
1265
6.09k
          for (int tuIdx = 0; tuIdx < nTus - 1; tuIdx++)
1266
4.57k
          {
1267
4.57k
            rootCbfSoFar |= TU::getCbfAtDepth(*tuPointer, COMP_Y, currDepth);
1268
4.57k
            tuPointer = tuPointer->next;
1269
4.57k
          }
1270
1.52k
          if (!rootCbfSoFar)
1271
0
          {
1272
0
            lastCbfIsInferred = true;
1273
0
          }
1274
1.52k
        }
1275
16.6k
        if (!lastCbfIsInferred)
1276
16.6k
        {
1277
16.6k
          previousCbf = TU::getPrevTuCbfAtDepth(currTU, COMP_Y, partitioner.currTrDepth);
1278
16.6k
        }
1279
16.6k
      }
1280
210k
      if (!lastCbfIsInferred)
1281
210k
      {
1282
210k
        m_CABACEstimator->cbf_comp(currCU, TU::getCbfAtDepth(currTU, COMP_Y, currDepth), currTU.Y(), currTU.depth, previousCbf, currCU.ispMode);
1283
210k
      }
1284
210k
    }
1285
548k
  }
1286
548k
}
1287
void IntraSearch::xEncCoeffQT(CodingStructure& cs, Partitioner& partitioner, const ComponentID compID, CUCtx* cuCtx, const int subTuIdx, const PartSplit ispType)
1288
886k
{
1289
886k
  const UnitArea& currArea  = partitioner.currArea();
1290
1291
886k
  int subTuCounter          = m_ispTestedModes[0].subTuCounter;
1292
886k
  TransformUnit& currTU     = xCurrTU( cs, partitioner );
1293
886k
  uint32_t   currDepth      = partitioner.currTrDepth;
1294
886k
  const bool subdiv         = currTU.depth > currDepth;
1295
1296
886k
  if (subdiv)
1297
0
  {
1298
0
    if (partitioner.canSplit(TU_MAX_TR_SPLIT, cs))
1299
0
    {
1300
0
      partitioner.splitCurrArea(TU_MAX_TR_SPLIT, cs);
1301
0
    }
1302
0
    else if (currTU.cu->ispMode)
1303
0
    {
1304
0
      partitioner.splitCurrArea(m_ispTestedModes[0].IspType, cs);
1305
0
    }
1306
0
    else
1307
0
      THROW("Implicit TU split not available!");
1308
1309
0
    do
1310
0
    {
1311
0
      xEncCoeffQT(cs, partitioner, compID, cuCtx, subTuCounter, m_ispTestedModes[0].IspType);
1312
0
      subTuCounter += subTuCounter != -1 ? 1 : 0;
1313
0
    } while( partitioner.nextPart( cs ) );
1314
1315
0
    partitioner.exitCurrSplit();
1316
0
  }
1317
886k
  else
1318
1319
886k
  if( currArea.blocks[compID].valid() )
1320
886k
  {
1321
886k
    if( compID == COMP_Cr )
1322
337k
    {
1323
337k
      const int cbfMask = ( TU::getCbf( currTU, COMP_Cb ) ? 2 : 0 ) + ( TU::getCbf( currTU, COMP_Cr ) ? 1 : 0 );
1324
337k
      m_CABACEstimator->joint_cb_cr( currTU, cbfMask );
1325
337k
    }
1326
886k
    if( TU::getCbf( currTU, compID ) )
1327
260k
    {
1328
260k
      if( isLuma(compID) )
1329
17.5k
      {
1330
        // kept for the CU's final count (xKeepLumaResiOfTrial): the residual's bits and the flags it sets
1331
17.5k
        const uint64_t bitsBefore = m_CABACEstimator->getEstFracBits();
1332
17.5k
        m_lumaResiCallFlags       = CUCtx();
1333
17.5k
        m_CABACEstimator->residual_coding( currTU, compID, &m_lumaResiCallFlags );
1334
17.5k
        m_lumaResiCallBits        = m_CABACEstimator->getEstFracBits() - bitsBefore;
1335
17.5k
        m_lumaResiCalls++;
1336
17.5k
        if( cuCtx )
1337
14.8k
        {
1338
14.8k
          cuCtx->addResidualFlags( m_lumaResiCallFlags );
1339
14.8k
        }
1340
17.5k
        m_CABACEstimator->mts_idx( *currTU.cu, cuCtx );
1341
17.5k
      }
1342
242k
      else
1343
242k
        m_CABACEstimator->residual_coding( currTU, compID );
1344
260k
    }
1345
886k
  }
1346
886k
}
1347
1348
uint64_t IntraSearch::xGetIntraFracBitsQT( CodingStructure &cs, Partitioner &partitioner, const bool luma, CUCtx *cuCtx )
1349
548k
{
1350
548k
  m_CABACEstimator->resetBits();
1351
1352
548k
  xEncIntraHeader( cs, partitioner, luma );
1353
548k
  xEncSubdivCbfQT( cs, partitioner, luma );
1354
1355
548k
  if( luma )
1356
210k
  {
1357
210k
    m_lumaResiCalls = 0;
1358
210k
    xEncCoeffQT( cs, partitioner, COMP_Y, cuCtx );
1359
1360
210k
    CodingUnit &cu = *cs.cus[0];
1361
210k
    if (cuCtx /*&& CU::isSepTree(cu)*/
1362
128k
      && (!cu.ispMode || (cu.lfnstIdx && m_ispTestedModes[0].subTuCounter == 0)
1363
10.5k
        || (!cu.lfnstIdx
1364
9.16k
          && m_ispTestedModes[0].subTuCounter == m_ispTestedModes[cu.lfnstIdx].numTotalParts[cu.ispMode - 1] - 1)))
1365
119k
    {
1366
119k
      m_CABACEstimator->residual_lfnst_mode( cu, *cuCtx );
1367
119k
    }
1368
210k
  }
1369
337k
  else
1370
337k
  {
1371
337k
    xEncCoeffQT( cs, partitioner, COMP_Cb );
1372
337k
    xEncCoeffQT( cs, partitioner, COMP_Cr );
1373
337k
  }
1374
1375
548k
  uint64_t fracBits = m_CABACEstimator->getEstFracBits();
1376
548k
  return fracBits;
1377
548k
}
1378
1379
uint64_t IntraSearch::xGetIntraFracBitsQTChroma(const TransformUnit& currTU, const ComponentID compID, CUCtx *cuCtx)
1380
2.11M
{
1381
2.11M
  m_CABACEstimator->resetBits();
1382
1383
2.11M
  if ( currTU.jointCbCr )
1384
314k
  {
1385
314k
    const int cbfMask = ( TU::getCbf( currTU, COMP_Cb ) ? 2 : 0 ) + ( TU::getCbf( currTU, COMP_Cr ) ? 1 : 0 );
1386
314k
    m_CABACEstimator->cbf_comp( *currTU.cu, cbfMask>>1, currTU.blocks[ COMP_Cb ], currTU.depth, false );
1387
314k
    m_CABACEstimator->cbf_comp( *currTU.cu, cbfMask &1, currTU.blocks[ COMP_Cr ], currTU.depth, cbfMask>>1 );
1388
314k
    if( cbfMask )
1389
314k
      m_CABACEstimator->joint_cb_cr( currTU, cbfMask );
1390
314k
    if (cbfMask >> 1)
1391
312k
      m_CABACEstimator->residual_coding( currTU, COMP_Cb, cuCtx );
1392
314k
    if (cbfMask & 1)
1393
314k
      m_CABACEstimator->residual_coding( currTU, COMP_Cr, cuCtx );
1394
314k
  }
1395
1.79M
  else
1396
1.79M
  {
1397
1.79M
    if ( compID == COMP_Cb )
1398
899k
      m_CABACEstimator->cbf_comp( *currTU.cu, TU::getCbf( currTU, compID ), currTU.blocks[ compID ], currTU.depth, false );
1399
899k
    else
1400
899k
    {
1401
899k
      const bool cbCbf    = TU::getCbf( currTU, COMP_Cb );
1402
899k
      const bool crCbf    = TU::getCbf( currTU, compID );
1403
899k
      const int  cbfMask  = ( cbCbf ? 2 : 0 ) + ( crCbf ? 1 : 0 );
1404
899k
      m_CABACEstimator->cbf_comp( *currTU.cu, crCbf, currTU.blocks[ compID ], currTU.depth, cbCbf );
1405
899k
      m_CABACEstimator->joint_cb_cr( currTU, cbfMask );
1406
899k
    }
1407
1.79M
  }
1408
1409
2.11M
  if( !currTU.jointCbCr && TU::getCbf( currTU, compID ) )
1410
632k
  {
1411
632k
    m_CABACEstimator->residual_coding( currTU, compID, cuCtx );
1412
632k
  }
1413
1414
2.11M
  uint64_t fracBits = m_CABACEstimator->getEstFracBits();
1415
2.11M
  return fracBits;
1416
2.11M
}
1417
1418
void IntraSearch::xIntraCodingTUBlock(TransformUnit &tu, const ComponentID compID, const bool checkCrossCPrediction, Distortion &ruiDist, uint32_t *numSig, PelUnitBuf *predBuf, const bool loadTr, const QpParam* lumaQP, const bool predKnown, const LfnstPrimary lfnstPrimary)
1419
2.34M
{
1420
2.34M
  if (!tu.blocks[compID].valid())
1421
0
  {
1422
0
    return;
1423
0
  }
1424
1425
2.34M
  CodingStructure &cs             = *tu.cs;
1426
2.34M
  const CompArea      &area       = tu.blocks[compID];
1427
2.34M
  const SPS           &sps        = *cs.sps;
1428
1429
2.34M
  const ChannelType    chType     = toChannelType(compID);
1430
2.34M
  const int            bitDepth   = sps.bitDepths[chType];
1431
1432
2.34M
  CPelBuf        piOrg            = cs.getOrgBuf    (area);
1433
2.34M
  PelBuf         piPred           = cs.getPredBuf   (area);
1434
2.34M
  PelBuf         piResi           = cs.getResiBuf   (area);
1435
2.34M
  PelBuf         piReco           = cs.getRecoBuf   (area);
1436
1437
2.34M
  const CodingUnit& cu            = *tu.cu;
1438
1439
  //===== init availability pattern =====
1440
2.34M
  CHECK( tu.jointCbCr && compID == COMP_Cr, "wrong combination of compID and jointCbCr" );
1441
2.34M
  bool jointCbCr = tu.jointCbCr && compID == COMP_Cb;
1442
1443
2.34M
  if ( isLuma(compID) )
1444
228k
  {
1445
228k
    bool predRegDiffFromTB = CU::isPredRegDiffFromTB(*tu.cu );
1446
228k
    bool firstTBInPredReg  = false;
1447
228k
    CompArea areaPredReg(COMP_Y, tu.chromaFormat, area);
1448
228k
    if (tu.cu->ispMode )
1449
23.0k
    {
1450
23.0k
      firstTBInPredReg = CU::isFirstTBInPredReg(*tu.cu, area);
1451
23.0k
      if (predRegDiffFromTB)
1452
0
      {
1453
0
        if (firstTBInPredReg)
1454
0
        {
1455
0
          CU::adjustPredArea(areaPredReg);
1456
0
          initIntraPatternChTypeISP(*tu.cu, areaPredReg, piReco);
1457
0
        }
1458
0
      }
1459
23.0k
      else
1460
23.0k
        initIntraPatternChTypeISP(*tu.cu, area, piReco);
1461
23.0k
    }
1462
205k
    else if( !predBuf )
1463
34.5k
    {
1464
34.5k
      initIntraPatternChType(*tu.cu, area);
1465
34.5k
    }
1466
1467
    //===== get prediction signal =====
1468
228k
    if (predRegDiffFromTB)
1469
0
    {
1470
0
      if (firstTBInPredReg)
1471
0
      {
1472
0
        PelBuf piPredReg = cs.getPredBuf(areaPredReg);
1473
0
        predIntraAng(compID, piPredReg, cu);
1474
0
      }
1475
0
    }
1476
228k
    else
1477
228k
    {
1478
228k
      if( predKnown )
1479
74.3k
      {
1480
        // this TU's previous transform left it in piPred
1481
74.3k
      }
1482
154k
      else if( predBuf )
1483
102k
      {
1484
102k
        piPred.copyFrom( predBuf->Y() );
1485
102k
      }
1486
51.9k
      else if( CU::isMIP( cu, CH_L ) )
1487
20.4k
      {
1488
20.4k
        initIntraMip( cu );
1489
20.4k
        predIntraMip( piPred, cu );
1490
20.4k
      }
1491
31.5k
      else
1492
31.5k
      {
1493
31.5k
        predIntraAng(compID, piPred, cu);
1494
31.5k
      }
1495
228k
    }
1496
228k
  }
1497
2.34M
  DTRACE( g_trace_ctx, D_PRED, "@(%4d,%4d) [%2dx%2d] IMode=%d\n", tu.lx(), tu.ly(), tu.lwidth(), tu.lheight(), CU::getFinalIntraMode(cu, chType) );
1498
1499
2.34M
  if (isLuma(compID))
1500
228k
  {
1501
    //===== get residual signal =====
1502
228k
    if( lfnstPrimary != LFNST_PRIMARY_KNOWN )
1503
191k
    {
1504
191k
      piResi.subtract( piOrg, piPred );
1505
191k
    }
1506
228k
  }
1507
1508
  //===== transform and quantization =====
1509
  //--- init rate estimation arrays for RDOQ ---
1510
  //--- transform and quantization           ---
1511
2.34M
  TCoeff uiAbsSum = 0;
1512
1513
2.34M
  m_pcTrQuant->selectLambda(compID);
1514
1515
2.34M
  if ( jointCbCr )
1516
318k
  {
1517
    // Lambda is loosened for the joint mode with respect to single modes as the same residual is used for both chroma blocks
1518
318k
    const int    absIct = abs( TU::getICTMode(tu) );
1519
318k
    const double lfact  = ( absIct == 1 || absIct == 3 ? 0.8 : 0.5 );
1520
318k
    m_pcTrQuant->scaleLambda( lfact );
1521
318k
  }
1522
2.34M
  if ( sps.jointCbCr && isChroma(compID) && (tu.cu->cs->slice->sliceQp > 18) )
1523
1.40M
  {
1524
1.40M
    m_pcTrQuant->scaleLambda( 1.3 );
1525
1.40M
  }
1526
1527
2.34M
  if( isLuma(compID) )
1528
228k
  {
1529
228k
    const QpParam cQP = lumaQP ? *lumaQP : QpParam( tu, compID );
1530
228k
    m_pcTrQuant->transformNxN(tu, compID, cQP, uiAbsSum, m_CABACEstimator->getCtx(), loadTr, lfnstPrimary);
1531
1532
228k
    DTRACE( g_trace_ctx, D_TU_ABS_SUM, "%d: comp=%d, abssum=%d\n", DTRACE_GET_COUNTER( g_trace_ctx, D_TU_ABS_SUM ), compID, uiAbsSum );
1533
228k
    if (tu.cu->ispMode && isLuma(compID) && CU::isISPLast(*tu.cu, area, area.compID) && CU::allLumaCBFsAreZero(*tu.cu))
1534
0
    {
1535
      // ISP has to have at least one non-zero CBF
1536
0
      ruiDist = MAX_INT;
1537
0
      return;
1538
0
    }
1539
    //--- inverse transform ---
1540
228k
    if (uiAbsSum > 0)
1541
35.4k
    {
1542
35.4k
      m_pcTrQuant->invTransformNxN(tu, compID, piResi, cQP);
1543
35.4k
    }
1544
193k
    else
1545
193k
    {
1546
193k
      piResi.fill(0);
1547
193k
    }
1548
228k
  }
1549
2.11M
  else // chroma
1550
2.11M
  {
1551
2.11M
    PelBuf          crPred = cs.getPredBuf ( COMP_Cr );
1552
2.11M
    PelBuf          crResi = cs.getResiBuf ( COMP_Cr );
1553
2.11M
    PelBuf          crReco = cs.getRecoBuf ( COMP_Cr );
1554
1555
2.11M
    int         codedCbfMask  = 0;
1556
2.11M
    ComponentID codeCompId    = (tu.jointCbCr ? (tu.jointCbCr >> 1 ? COMP_Cb : COMP_Cr) : compID);
1557
2.11M
    const QpParam qpCbCr(tu, codeCompId);
1558
1559
2.11M
    if( tu.jointCbCr )
1560
318k
    {
1561
318k
      ComponentID otherCompId = ( codeCompId==COMP_Cr ? COMP_Cb : COMP_Cr );
1562
318k
      tu.getCoeffs( otherCompId ).fill(0); // do we need that?
1563
318k
      TU::setCbfAtDepth (tu, otherCompId, tu.depth, false );
1564
318k
    }
1565
2.11M
    PelBuf& codeResi = ( codeCompId == COMP_Cr ? crResi : piResi );
1566
2.11M
    uiAbsSum = 0;
1567
2.11M
    m_pcTrQuant->transformNxN(tu, codeCompId, qpCbCr, uiAbsSum, m_CABACEstimator->getCtx(), loadTr);
1568
2.11M
    DTRACE( g_trace_ctx, D_TU_ABS_SUM, "%d: comp=%d, abssum=%d\n", DTRACE_GET_COUNTER( g_trace_ctx, D_TU_ABS_SUM ), codeCompId, uiAbsSum );
1569
2.11M
    if( uiAbsSum > 0 )
1570
947k
    {
1571
947k
      m_pcTrQuant->invTransformNxN(tu, codeCompId, codeResi, qpCbCr);
1572
947k
      codedCbfMask += ( codeCompId == COMP_Cb ? 2 : 1 );
1573
947k
    }
1574
1.17M
    else
1575
1.17M
    {
1576
1.17M
      codeResi.fill(0);
1577
1.17M
    }
1578
1579
2.11M
    if( tu.jointCbCr )
1580
318k
    {
1581
318k
      if( tu.jointCbCr == 3 && codedCbfMask == 2 )
1582
312k
      {
1583
312k
        codedCbfMask = 3;
1584
312k
        TU::setCbfAtDepth (tu, COMP_Cr, tu.depth, true );
1585
312k
      }
1586
318k
      if( tu.jointCbCr != codedCbfMask )
1587
4.24k
      {
1588
4.24k
        ruiDist = MAX_DISTORTION;
1589
4.24k
        return;
1590
4.24k
      }
1591
314k
      m_pcTrQuant->invTransformICT( tu, piResi, crResi );
1592
314k
      uiAbsSum = codedCbfMask;
1593
314k
    }
1594
1595
    //===== reconstruction =====
1596
2.11M
    if( jointCbCr )
1597
314k
    {
1598
314k
      crReco.reconstruct(crPred, crResi, cs.slice->clpRngs[ COMP_Cr ]);
1599
314k
    }
1600
2.11M
  }
1601
2.34M
  piReco.reconstruct(piPred, piResi, cs.slice->clpRngs[ compID ]);
1602
  
1603
1604
1605
  //===== update distortion =====
1606
2.34M
  ruiDist += m_pcRdCost->getDistPart( piOrg, piReco, bitDepth, compID, DF_SSE );
1607
2.34M
  if( jointCbCr )
1608
314k
  {
1609
314k
    CPelBuf         crOrg  = cs.getOrgBuf  ( COMP_Cr );
1610
314k
    PelBuf          crReco = cs.getRecoBuf ( COMP_Cr );
1611
314k
    ruiDist += m_pcRdCost->getDistPart( crOrg, crReco, bitDepth, COMP_Cr, DF_SSE );
1612
314k
  }
1613
2.34M
}
1614
1615
void IntraSearch::xIntraCodingLumaQT(CodingStructure& cs, Partitioner& partitioner, PelUnitBuf* predBuf, const double bestCostSoFar, int numMode, bool disableMTS, const Ctx& ctxStart)
1616
137k
{
1617
137k
  PROFILER_SCOPE_AND_STAGE_EXT( 0, _TPROF, P_INTRA_RD_SEARCH_LUMA, &cs, partitioner.chType );
1618
137k
  m_trialBestResi.known     = false;
1619
137k
  const UnitArea& currArea  = partitioner.currArea();
1620
137k
  uint32_t        currDepth = partitioner.currTrDepth;
1621
137k
  Distortion singleDistLuma = 0;
1622
137k
  uint32_t   numSig         = 0;
1623
137k
  const SPS &sps            = *cs.sps;
1624
137k
  CodingUnit &cu            = *cs.cus[0];
1625
137k
  bool mtsAllowed = (numMode < 0) || disableMTS ? false : CU::isMTSAllowed(cu, COMP_Y);
1626
137k
  uint64_t singleFracBits   = 0;
1627
137k
  bool   splitCbfLumaSum    = false;
1628
137k
  double bestCostForISP     = bestCostSoFar;
1629
137k
  double dSingleCost        = MAX_DOUBLE;
1630
137k
  int endLfnstIdx           = (partitioner.isSepTree(cs) && partitioner.chType == CH_C && (currArea.lwidth() < 8 || currArea.lheight() < 8))
1631
137k
                           || (currArea.lwidth() > sps.getMaxTbSize() || currArea.lheight() > sps.getMaxTbSize()) || !sps.LFNST || (numMode < 0) ? 0 : 2;
1632
137k
  const bool useTS          = cs.picture->useTS;
1633
137k
  numMode                   = (numMode < 0) ? -numMode : numMode;
1634
1635
137k
  if (cu.mipFlag && !allowLfnstWithMip(cu.lumaSize()))
1636
2.29k
  {
1637
2.29k
    endLfnstIdx = 0;
1638
2.29k
  }
1639
137k
  int bestMTS = 0;
1640
137k
  int EndMTS  = mtsAllowed ? m_pcEncCfg->m_MTSIntraMaxCand : 0;
1641
137k
  if (cu.ispMode && (EndMTS || endLfnstIdx))
1642
6.36k
  {
1643
6.36k
    EndMTS = 0;
1644
6.36k
    if ((m_ispTestedModes[1].numTotalParts[cu.ispMode - 1] == 0)
1645
395
     && (m_ispTestedModes[2].numTotalParts[cu.ispMode - 1] == 0))
1646
395
    {
1647
395
      endLfnstIdx = 0;
1648
395
    }
1649
6.36k
  }
1650
137k
  if (cu.bdpcmM[CH_L])
1651
8.29k
  {
1652
8.29k
    endLfnstIdx = 0;
1653
8.29k
    EndMTS = 0;
1654
8.29k
  }
1655
137k
  bool checkTransformSkip = sps.transformSkip;
1656
1657
137k
  SizeType transformSkipMaxSize = 1 << sps.log2MaxTransformSkipBlockSize;
1658
137k
  bool tsAllowed = useTS  && cu.cs->sps->transformSkip && (!cu.ispMode) && (!cu.bdpcmM[CH_L]) && (!cu.sbtInfo);
1659
137k
  tsAllowed &= cu.blocks[COMP_Y].width <= transformSkipMaxSize && cu.blocks[COMP_Y].height <= transformSkipMaxSize;
1660
137k
  if (tsAllowed)
1661
16.6k
  {
1662
16.6k
    EndMTS += 1;
1663
16.6k
  }
1664
137k
  if (endLfnstIdx || EndMTS)
1665
55.0k
  {
1666
55.0k
    bool       splitCbfLuma  = false;
1667
55.0k
    const PartSplit ispType  = CU::getISPType(cu, COMP_Y);
1668
55.0k
    CUCtx cuCtx;
1669
55.0k
    cuCtx.isDQPCoded         = true;
1670
55.0k
    cuCtx.isChromaQpAdjCoded = true;
1671
55.0k
    cs.cost                  = 0.0;
1672
55.0k
    Distortion       singleDistTmpLuma = 0;
1673
55.0k
    uint64_t         singleTmpFracBits = 0;
1674
55.0k
    double           singleCostTmp     = 0;
1675
55.0k
    CodingStructure &saveCS            = *m_pSaveCS[cu.ispMode?0:1];
1676
55.0k
    TransformUnit *  tmpTU             = nullptr;
1677
55.0k
    int              bestLfnstIdx      = 0;
1678
55.0k
    int              startLfnstIdx     = 0;
1679
    // speedUps LFNST
1680
55.0k
    bool   rapidLFNST                  = false;
1681
55.0k
    bool   rapidDCT                    = false;
1682
55.0k
    double thresholdDCT                = 1;
1683
1684
55.0k
    if (m_pcEncCfg->m_MTS == 2)
1685
0
    {
1686
0
      thresholdDCT += 1.4 / sqrt(cu.lwidth() * cu.lheight());
1687
0
    }
1688
1689
55.0k
    if (m_pcEncCfg->m_LFNST > 1)
1690
0
    {
1691
0
      rapidLFNST = true;
1692
1693
0
      if (m_pcEncCfg->m_LFNST > 2)
1694
0
      {
1695
0
        rapidDCT    = true;
1696
0
        endLfnstIdx = endLfnstIdx ? 1 : 0;
1697
0
      }
1698
0
    }
1699
1700
55.0k
    saveCS.pcv              = cs.pcv;
1701
55.0k
    saveCS.picture          = cs.picture;
1702
55.0k
    saveCS.area.repositionTo( cs.area);
1703
1704
55.0k
    if (cu.ispMode)
1705
5.96k
    {
1706
5.96k
      partitioner.splitCurrArea(ispType, cs);
1707
5.96k
    }
1708
1709
55.0k
    TransformUnit& tu = cs.addTU(CS::getArea(cs, partitioner.currArea(), partitioner.chType, partitioner.treeType), partitioner.chType, cs.cus[0]);
1710
1711
55.0k
    if (cu.ispMode)
1712
5.96k
    {
1713
5.96k
      saveCS.clearTUs();
1714
5.96k
      do
1715
23.8k
      {
1716
23.8k
        saveCS.addTU(
1717
23.8k
          CS::getArea(cs, partitioner.currArea(), partitioner.chType, partitioner.treeType),
1718
23.8k
          partitioner.chType, cs.cus[0]);
1719
23.8k
      } while (partitioner.nextPart(cs));
1720
1721
5.96k
      partitioner.exitCurrSplit();
1722
5.96k
    }
1723
49.1k
    else
1724
49.1k
    {
1725
49.1k
      tmpTU = saveCS.tus.empty() ? &saveCS.addTU( currArea, partitioner.chType, nullptr ) : saveCS.tus.front();
1726
49.1k
      tmpTU->initData();
1727
49.1k
      tmpTU->UnitArea::operator=( currArea );
1728
49.1k
    }
1729
1730
1731
55.0k
    TrModeList trModes{ TrMode(0, true) };
1732
55.0k
    if (tsAllowed)
1733
16.6k
    {
1734
16.6k
      trModes.push_back(TrMode(1, true));
1735
16.6k
    }
1736
55.0k
    double dct2Cost           = MAX_DOUBLE;
1737
55.0k
    double trGrpStopThreshold = 1.001;
1738
55.0k
    double trGrpBestCost      = MAX_DOUBLE;
1739
1740
55.0k
    if (mtsAllowed)
1741
0
    {
1742
0
      if (m_pcEncCfg->m_LFNST)
1743
0
      {
1744
0
        uint32_t uiIntraMode = cs.cus[0]->intraDir[partitioner.chType];
1745
0
        int MTScur           = (uiIntraMode < 34) ? MTS_DST7_DCT8 : MTS_DCT8_DST7;
1746
1747
0
        trModes.push_back(TrMode(     2, true));
1748
0
        trModes.push_back(TrMode(MTScur, true));
1749
1750
0
        MTScur = (uiIntraMode < 34) ? MTS_DCT8_DST7 : MTS_DST7_DCT8;
1751
1752
0
        trModes.push_back(TrMode(MTScur,            true));
1753
0
        trModes.push_back(TrMode(MTS_DST7_DST7 + 3, true));
1754
0
      }
1755
0
      else
1756
0
      {
1757
0
        for (int i = 2; i < 6; i++)
1758
0
        {
1759
0
          trModes.push_back(TrMode(i, true));
1760
0
        }
1761
0
      }
1762
0
    }
1763
1764
55.0k
    if ((EndMTS && !m_pcEncCfg->m_LFNST) || (tsAllowed && !mtsAllowed))
1765
16.6k
    {
1766
16.6k
      xPreCheckMTS(tu, &trModes, m_pcEncCfg->m_MTSIntraMaxCand, predBuf);
1767
16.6k
      if (!mtsAllowed && !trModes[1].second)
1768
3.02k
      {
1769
3.02k
        EndMTS = 0;
1770
3.02k
      }
1771
16.6k
    }
1772
1773
55.0k
    bool NStopMTS = true;
1774
    // All candidates here have the same residual. Without implicit MTS the first one's primary transform is the DCT2 that LFNST
1775
    // works on, otherwise only the second LFNST can use the first one's.
1776
55.0k
    const LfnstPrimary lfnstPrimaryOfDct2 = endLfnstIdx && !sps.getUseImplicitMTS() ? LFNST_PRIMARY_KEEP : LFNST_PRIMARY_NEW;
1777
55.0k
    const QpParam lumaQP( tu, COMP_Y );   // the CU's QP doesn't change in these loops
1778
1779
110k
    for (int modeId = 0; modeId <= EndMTS && NStopMTS; modeId++)
1780
55.0k
    {
1781
55.0k
      if (modeId > 1)
1782
0
      {
1783
0
        trGrpBestCost = MAX_DOUBLE;
1784
0
      }
1785
      // LFNST is only tested with the first transform, and ISP transforms a different block each time
1786
55.0k
      m_pcTrQuant->keepPrimaryCoeffs( modeId == 0 && !cu.ispMode && startLfnstIdx != endLfnstIdx );
1787
196k
      for (int lfnstIdx = startLfnstIdx; lfnstIdx <= endLfnstIdx; lfnstIdx++)
1788
141k
      {
1789
141k
        if (lfnstIdx && modeId)
1790
0
        {
1791
0
          continue;
1792
0
        }
1793
141k
        if (mtsAllowed || tsAllowed)
1794
26.0k
        {
1795
26.0k
          if (m_pcEncCfg->m_TS && bestMTS == MTS_SKIP)
1796
0
          {
1797
0
            break;
1798
0
          }
1799
26.0k
          if (!m_pcEncCfg->m_LFNST && !trModes[modeId].second && mtsAllowed)
1800
0
          {
1801
0
            continue;
1802
0
          }
1803
1804
26.0k
          tu.mtsIdx[COMP_Y] = trModes[modeId].first;
1805
26.0k
        }
1806
1807
141k
        if (cu.ispMode && lfnstIdx)
1808
11.9k
        {
1809
11.9k
          if (m_ispTestedModes[lfnstIdx].numTotalParts[cu.ispMode - 1] == 0)
1810
0
          {
1811
0
            if (lfnstIdx == 2)
1812
0
            {
1813
0
              endLfnstIdx = 1;
1814
0
            }
1815
0
            continue;
1816
0
          }
1817
11.9k
        }
1818
1819
141k
        cu.lfnstIdx                          = lfnstIdx;
1820
141k
        cuCtx.lfnstLastScanPos               = false;
1821
141k
        cuCtx.violatesLfnstConstrained[CH_L] = false;
1822
141k
        cuCtx.violatesLfnstConstrained[CH_C] = false;
1823
141k
        cuCtx.violatesMtsCoeffConstraint     = false;
1824
1825
141k
        if ((lfnstIdx != startLfnstIdx) || (modeId))
1826
86.3k
        {
1827
86.3k
          m_CABACEstimator->getCtx() = ctxStart;
1828
86.3k
        }
1829
1830
141k
        singleDistTmpLuma = 0;
1831
1832
141k
        if (cu.ispMode)
1833
17.8k
        {
1834
17.8k
          splitCbfLuma = false;
1835
1836
17.8k
          partitioner.splitCurrArea(ispType, cs);
1837
1838
17.8k
          singleCostTmp = xTestISP(cs, partitioner, bestCostForISP, ispType, splitCbfLuma, singleTmpFracBits, singleDistTmpLuma, cuCtx);
1839
1840
17.8k
          partitioner.exitCurrSplit();
1841
1842
17.8k
          if (modeId && (singleCostTmp == MAX_DOUBLE))
1843
0
          {
1844
0
            m_ispTestedModes[lfnstIdx].numTotalParts[cu.ispMode - 1] = 0;
1845
0
          }
1846
1847
17.8k
          bool storeCost = (numMode == 1) ? true : false;
1848
1849
17.8k
          if ((m_pcEncCfg->m_ISP >= 2) && (numMode <= 1))
1850
17.8k
          {
1851
17.8k
            storeCost = true;
1852
17.8k
          }
1853
1854
17.8k
          if (storeCost)
1855
17.8k
          {
1856
17.8k
            m_ispTestedModes[0].bestCost[cu.ispMode - 1] = singleCostTmp;
1857
17.8k
          }
1858
17.8k
        }
1859
123k
        else
1860
123k
        {
1861
123k
          bool TrLoad = (EndMTS && !m_pcEncCfg->m_LFNST) || (tsAllowed && !mtsAllowed && (lfnstIdx == 0)) ? true : false;
1862
1863
123k
          const LfnstPrimary lfnstPrimary = lfnstIdx == 0 ? ( modeId == 0 ? lfnstPrimaryOfDct2 : LFNST_PRIMARY_NEW )
1864
123k
                                          : lfnstIdx == 2 || lfnstPrimaryOfDct2 == LFNST_PRIMARY_KEEP ? LFNST_PRIMARY_KNOWN : LFNST_PRIMARY_KEEP;
1865
123k
          xIntraCodingTUBlock(tu, COMP_Y, false, singleDistTmpLuma, &numSig, predBuf, TrLoad, &lumaQP, modeId != 0 || lfnstIdx != 0, lfnstPrimary);
1866
1867
123k
          cuCtx.mtsLastScanPos = false;
1868
          //----- determine rate and r-d cost -----
1869
        // the bits of a later transform are only compared with the best so far, and can't help if its distortion alone doesn't beat that.
1870
123k
        const bool lostOnDist = dSingleCost != MAX_DOUBLE && m_pcRdCost->calcRdCost( 0, singleDistTmpLuma ) >= dSingleCost;
1871
123k
        if (lostOnDist || ((sps.LFNST ? (modeId == EndMTS && modeId != 0 && checkTransformSkip) : (trModes[modeId].first != 0)) && !TU::getCbfAtDepth(tu, COMP_Y, currDepth)))
1872
11.5k
        {
1873
11.5k
          singleCostTmp = MAX_DOUBLE;
1874
11.5k
        }
1875
111k
        else
1876
111k
        {
1877
111k
          m_ispTestedModes[0].IspType      = TU_NO_ISP;
1878
111k
          m_ispTestedModes[0].subTuCounter = -1;
1879
111k
          singleTmpFracBits = xGetIntraFracBitsQT(cs, partitioner, true, &cuCtx);
1880
1881
111k
          if (tu.mtsIdx[COMP_Y] > MTS_SKIP)
1882
0
          {
1883
0
            if (!cuCtx.mtsLastScanPos)
1884
0
            {
1885
0
              singleCostTmp = MAX_DOUBLE;
1886
0
            }
1887
0
            else
1888
0
            {
1889
0
              singleCostTmp = m_pcRdCost->calcRdCost(singleTmpFracBits, singleDistTmpLuma);
1890
0
            }
1891
0
          }
1892
111k
          else
1893
111k
          {
1894
111k
            singleCostTmp = m_pcRdCost->calcRdCost(singleTmpFracBits, singleDistTmpLuma);
1895
111k
          }
1896
111k
        }
1897
1898
123k
          if (((EndMTS && (m_pcEncCfg->m_MTS == 2)) || rapidLFNST) && modeId == 0 && lfnstIdx == 0)
1899
0
          {
1900
0
            if (singleCostTmp > bestCostSoFar * thresholdDCT)
1901
0
            {
1902
0
              EndMTS = 0;
1903
1904
0
              if (rapidDCT)
1905
0
              {
1906
0
                endLfnstIdx = 0;   // break the loop but do not cpy best
1907
0
              }
1908
0
            }
1909
0
          }
1910
1911
123k
          if (lfnstIdx && !cuCtx.lfnstLastScanPos && !cu.ispMode)
1912
73.8k
          {
1913
73.8k
            bool rootCbfL = false;
1914
1915
295k
            for (uint32_t t = 0; t < getNumberValidTBlocks(*cu.cs->pcv); t++)
1916
221k
            {
1917
221k
              rootCbfL |= tu.cbf[t] != 0;
1918
221k
            }
1919
1920
73.8k
            if (rapidLFNST && !rootCbfL)
1921
0
            {
1922
0
              endLfnstIdx = lfnstIdx; // break the loop
1923
0
            }
1924
73.8k
            bool cbfAtZeroDepth = CU::isSepTree(cu)
1925
73.8k
              ? rootCbfL
1926
73.8k
              : (cs.area.chromaFormat != CHROMA_400 && std::min(cu.firstTU->blocks[1].width, cu.firstTU->blocks[1].height) < 4)
1927
1
                ? TU::getCbfAtDepth(tu, COMP_Y, currDepth)
1928
1
                : rootCbfL;
1929
1930
73.8k
            if (cbfAtZeroDepth)
1931
11.8k
            {
1932
11.8k
              singleCostTmp = MAX_DOUBLE;
1933
11.8k
            }
1934
73.8k
          }
1935
123k
        }
1936
1937
141k
        if (singleCostTmp < dSingleCost)
1938
50.6k
        {
1939
50.6k
          trGrpBestCost  = singleCostTmp;
1940
50.6k
          dSingleCost    = singleCostTmp;
1941
50.6k
          singleDistLuma = singleDistTmpLuma;
1942
50.6k
          singleFracBits = singleTmpFracBits;
1943
50.6k
          bestLfnstIdx   = lfnstIdx;
1944
50.6k
          bestMTS        = modeId;
1945
50.6k
          xKeepLumaResiOfTrial( cu, tu );
1946
1947
50.6k
          if (dSingleCost < bestCostForISP)
1948
32.0k
          {
1949
32.0k
            bestCostForISP = dSingleCost;
1950
32.0k
          }
1951
1952
50.6k
          splitCbfLumaSum = splitCbfLuma;
1953
1954
50.6k
          if (lfnstIdx == 0 && modeId == 0 && cu.ispMode == 0)
1955
49.1k
          {
1956
49.1k
            dct2Cost = singleCostTmp;
1957
1958
49.1k
            if (!TU::getCbfAtDepth(tu, COMP_Y, currDepth))
1959
41.6k
            {
1960
41.6k
              if (rapidLFNST)
1961
0
              {
1962
0
                 endLfnstIdx = 0;   // break the loop but do not cpy best
1963
0
              }
1964
1965
41.6k
              EndMTS = 0;
1966
41.6k
            }
1967
49.1k
          }
1968
1969
50.6k
          if (bestLfnstIdx != endLfnstIdx || bestMTS != EndMTS)
1970
38.5k
          {
1971
38.5k
            if (cu.ispMode)
1972
1.14k
            {
1973
1.14k
              saveCS.getRecoBuf(currArea.Y()).copyFrom(cs.getRecoBuf(currArea.Y()));
1974
1975
5.70k
              for (uint32_t j = 0; j < cs.tus.size(); j++)
1976
4.56k
              {
1977
4.56k
                saveCS.tus[j]->copyComponentFrom(*cs.tus[j], COMP_Y);
1978
4.56k
              }
1979
1.14k
            }
1980
37.3k
            else
1981
37.3k
            {
1982
37.3k
              saveCS.getRecoBuf(tu.Y()).copyFrom(cs.getRecoBuf(tu.Y()));
1983
1984
37.3k
              tmpTU->copyComponentFrom(tu, COMP_Y);
1985
37.3k
            }
1986
38.5k
          }
1987
      
1988
50.6k
        }
1989
90.7k
        else
1990
90.7k
        {
1991
90.7k
          if( rapidLFNST )
1992
0
          {
1993
0
            endLfnstIdx = lfnstIdx; // break the loop
1994
0
          }
1995
90.7k
        }
1996
141k
      }
1997
55.0k
      if (m_pcEncCfg->m_LFNST && m_pcEncCfg->m_MTS == 2 && modeId && modeId != EndMTS)
1998
0
      {
1999
0
        NStopMTS = false;
2000
2001
0
        if (bestMTS || bestLfnstIdx)
2002
0
        {
2003
0
          if ((modeId > 1 && bestMTS == modeId) || modeId == 1)
2004
0
          {
2005
0
            NStopMTS = (dct2Cost / trGrpBestCost) < trGrpStopThreshold;
2006
0
          }
2007
0
        }
2008
0
      }
2009
55.0k
    }
2010
55.0k
    m_pcTrQuant->keepPrimaryCoeffs( false );
2011
2012
55.0k
    cu.lfnstIdx = bestLfnstIdx;
2013
55.0k
    if (dSingleCost != MAX_DOUBLE)
2014
50.1k
    {
2015
50.1k
      if (bestLfnstIdx != endLfnstIdx || bestMTS != EndMTS)
2016
38.0k
      {
2017
38.0k
        if (cu.ispMode)
2018
829
        {
2019
829
          const UnitArea& currArea = partitioner.currArea();
2020
829
          cs.getRecoBuf(currArea.Y()).copyFrom(saveCS.getRecoBuf(currArea.Y()));
2021
2022
829
          if (saveCS.tus.size() != cs.tus.size())
2023
0
          {
2024
0
            partitioner.splitCurrArea(ispType, cs);
2025
2026
0
            do
2027
0
            {
2028
0
              partitioner.nextPart(cs);
2029
0
              cs.addTU(CS::getArea(cs, partitioner.currArea(), partitioner.chType, partitioner.treeType),
2030
0
                partitioner.chType, cs.cus[0]);
2031
0
            } while (saveCS.tus.size() != cs.tus.size());
2032
2033
0
            partitioner.exitCurrSplit();
2034
0
          }
2035
2036
4.14k
          for (uint32_t j = 0; j < saveCS.tus.size(); j++)
2037
3.31k
          {
2038
3.31k
            cs.tus[j]->copyComponentFrom(*saveCS.tus[j], COMP_Y);
2039
3.31k
          }
2040
829
        }
2041
37.1k
        else
2042
37.1k
        {
2043
37.1k
          cs.getRecoBuf(tu.Y()).copyFrom(saveCS.getRecoBuf(tu.Y()));
2044
2045
37.1k
          tu.copyComponentFrom(*tmpTU, COMP_Y);
2046
37.1k
        }
2047
38.0k
      }
2048
2049
      // otherwise this would've happened in useSubStructure
2050
50.1k
      cs.picture->getRecoBuf(currArea.Y()).copyFrom(cs.getRecoBuf(currArea.Y()));
2051
50.1k
    }
2052
55.0k
  }
2053
82.3k
  else
2054
82.3k
  {
2055
82.3k
    if (cu.ispMode)
2056
395
    {
2057
395
      const PartSplit ispType = CU::getISPType(cu, COMP_Y);
2058
395
      partitioner.splitCurrArea(ispType, cs);
2059
2060
395
      CUCtx      cuCtx;
2061
395
      dSingleCost = xTestISP(cs, partitioner, bestCostForISP, ispType, splitCbfLumaSum, singleFracBits, singleDistLuma, cuCtx);
2062
395
      partitioner.exitCurrSplit();
2063
395
      bool storeCost = (numMode == 1) ? true : false;
2064
395
      if ((m_pcEncCfg->m_ISP >= 2) && (numMode <= 1))
2065
395
      {
2066
395
        storeCost = true;
2067
395
      }
2068
395
      if (storeCost)
2069
395
      {
2070
395
        m_ispTestedModes[0].bestCost[cu.ispMode - 1] = dSingleCost;
2071
395
      }
2072
395
    }
2073
81.9k
    else
2074
81.9k
    {
2075
81.9k
      TransformUnit& tu =
2076
81.9k
        cs.addTU(CS::getArea(cs, currArea, partitioner.chType, partitioner.treeType), partitioner.chType, cs.cus[0]);
2077
81.9k
      tu.depth = currDepth;
2078
2079
81.9k
      CHECK(!tu.Y().valid(), "Invalid TU");
2080
81.9k
      xIntraCodingTUBlock(tu, COMP_Y, false, singleDistLuma, &numSig, predBuf);
2081
      //----- determine rate and r-d cost -----
2082
81.9k
      m_ispTestedModes[0].IspType = TU_NO_ISP;
2083
81.9k
      m_ispTestedModes[0].subTuCounter = -1;
2084
81.9k
      singleFracBits = xGetIntraFracBitsQT(cs, partitioner, true);
2085
81.9k
      dSingleCost = m_pcRdCost->calcRdCost(singleFracBits, singleDistLuma);
2086
81.9k
      xKeepLumaResiOfTrial( cu, tu );
2087
81.9k
    }
2088
82.3k
  }
2089
2090
137k
  if (cu.ispMode)
2091
6.36k
  { 
2092
6.36k
    for (auto& ptu : cs.tus)
2093
10.1k
    {
2094
10.1k
      if (currArea.Y().contains(ptu->Y()))
2095
10.1k
      {
2096
10.1k
        TU::setCbfAtDepth(*ptu, COMP_Y, currDepth, splitCbfLumaSum ? 1 : 0);
2097
10.1k
      }
2098
10.1k
    }
2099
6.36k
  }
2100
137k
  cs.dist     += singleDistLuma;
2101
137k
  cs.fracBits += singleFracBits;
2102
137k
  cs.cost      = dSingleCost;
2103
2104
137k
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_RD_TESTS][0][!cs.slice->isIntra() + cs.slice->depth] );
2105
137k
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !cs.slice->isIntra(), g_cuCounters2D[CU_RD_TESTS][Log2( cs.area.lheight() )][Log2( cs.area.lwidth() )] );
2106
137k
}
2107
2108
// Called when a luma trial of xIntraCodingLumaQT has just counted its bits and become the best: keeps what its luma
2109
// residual_coding counted, for the CU's final count (takeLumaResiOfSearch). That count repeats the trial's estimate:
2110
// the same coefficients from the same contexts, since every trial starts from the search's start contexts, as the
2111
// final count does, and codes only other contexts before the residual. Kept only for a CU coded as one luma TU with a
2112
// regular residual: not for ISP (its sub-TUs pass contexts on to each other) nor for transform skip and BDPCM (their
2113
// residual contexts are shared with chroma).
2114
void IntraSearch::xKeepLumaResiOfTrial( const CodingUnit& cu, const TransformUnit& tu )
2115
132k
{
2116
132k
  m_trialBestResi.known = m_lumaResiCalls == 1 && !cu.ispMode && !cu.bdpcmM[CH_L] && tu.mtsIdx[COMP_Y] != MTS_SKIP;
2117
132k
  if( m_trialBestResi.known )
2118
9.27k
  {
2119
9.27k
    m_trialBestResi.bits  = m_lumaResiCallBits;
2120
9.27k
    m_trialBestResi.flags = m_lumaResiCallFlags;
2121
    // takes the trial's end contexts without a copy: the estimator's are not read again before the next trial or the
2122
    // mode loop restores the start contexts
2123
9.27k
    m_trialBestResi.ctx.swap( m_CABACEstimator->getCtx() );
2124
9.27k
  }
2125
132k
}
2126
2127
// For EncCu's final count of the CU that estIntraPredLumaQT searched last: when the chosen trial's luma residual count
2128
// can stand in for the final one, sets the estimator's luma residual contexts to what that count left and returns
2129
// its bits and flags (once); nullptr otherwise. Called before the count, which codes nothing that reads these contexts
2130
// before luma's residual; the chroma transform skip flag's context, which the trial did not code, keeps its value.
2131
const IntraSearch::LumaResi* IntraSearch::takeLumaResiOfSearch( const CodingUnit& cu )
2132
30.0k
{
2133
30.0k
  if( !m_modeBestResi.known || cu.firstTU != cu.lastTU || cu.ispMode || cu.colorTransform || cu.bdpcmM[CH_L]
2134
2.15k
      || !TU::getCbf( *cu.firstTU, COMP_Y ) || cu.firstTU->mtsIdx[COMP_Y] == MTS_SKIP )
2135
27.8k
  {
2136
27.8k
    return nullptr;
2137
27.8k
  }
2138
2.15k
  m_modeBestResi.known = false;
2139
2140
  // the contexts luma's residual_coding codes outside transform skip (CoeffCodingContext, ContextModelling.cpp), and
2141
  // its transform skip flag
2142
2.15k
  Ctx& ctx = m_CABACEstimator->getCtx();
2143
2.15k
  for( const CtxSet& set : { Ctx::SigCoeffGroup[CH_L], Ctx::LastX[CH_L], Ctx::LastY[CH_L], Ctx::SigFlag[CH_L],
2144
2.15k
                             Ctx::SigFlag[CH_L + 2], Ctx::SigFlag[CH_L + 4], Ctx::ParFlag[CH_L], Ctx::GtxFlag[CH_L],
2145
2.15k
                             Ctx::GtxFlag[CH_L + 2], Ctx::TransformSkipFlag } )
2146
21.5k
  {
2147
21.5k
    ctx = SubCtx( set, m_modeBestResi.ctx );
2148
21.5k
  }
2149
2.15k
  return &m_modeBestResi;
2150
30.0k
}
2151
2152
// keepBestCtx: leave the best mode's contexts in the estimator; when false the caller overwrites them, so the copies that only
2153
// carry them to the end (the saves after Cr and after the LFNST / joint CbCr candidates) are skipped
2154
ChromaCbfs IntraSearch::xIntraChromaCodingQT(CodingStructure& cs, Partitioner& partitioner, const bool keepBestCtx)
2155
337k
{
2156
337k
  UnitArea    currArea      = partitioner.currArea();
2157
2158
337k
  if( !currArea.Cb().valid() ) 
2159
0
    return ChromaCbfs(false);
2160
2161
337k
  TransformUnit& currTU     = *cs.getTU( currArea.chromaPos(), CH_C );
2162
337k
  const CodingUnit& cu  = *cs.getCU( currArea.chromaPos(), CH_C, TREE_D );
2163
337k
  ChromaCbfs cbfs(false);
2164
337k
  uint32_t   currDepth = partitioner.currTrDepth;
2165
337k
  const bool useTS = cs.picture->useTS;
2166
337k
  if (currDepth == currTU.depth)
2167
337k
  {
2168
337k
    if (!currArea.Cb().valid() || !currArea.Cr().valid())
2169
0
    {
2170
0
      return cbfs;
2171
0
    }
2172
2173
337k
    CodingStructure& saveCS = *m_pSaveCS[1];
2174
337k
    saveCS.pcv = cs.pcv;
2175
337k
    saveCS.picture = cs.picture;
2176
337k
    saveCS.area.repositionTo(cs.area);
2177
2178
337k
    TransformUnit& tmpTU = saveCS.tus.empty() ? saveCS.addTU(currArea, partitioner.chType, nullptr) : *saveCS.tus.front();
2179
337k
    tmpTU.initData();
2180
337k
    tmpTU.UnitArea::operator=(currArea);
2181
337k
    const unsigned      numTBlocks = getNumberValidTBlocks(*cs.pcv);
2182
2183
337k
    CompArea& cbArea = currTU.blocks[COMP_Cb];
2184
337k
    CompArea& crArea = currTU.blocks[COMP_Cr];
2185
337k
    double     bestCostCb = MAX_DOUBLE;
2186
337k
    double     bestCostCr = MAX_DOUBLE;
2187
337k
    Distortion bestDistCb = 0;
2188
337k
    Distortion bestDistCr = 0;
2189
2190
337k
    TempCtx ctxStartTU(m_CtxCache);
2191
337k
    TempCtx ctxStart(m_CtxCache);
2192
337k
    TempCtx ctxBest(m_CtxCache);
2193
2194
337k
    ctxStartTU = m_CABACEstimator->getCtx();
2195
337k
    currTU.jointCbCr = 0;
2196
2197
    // Do predictions here to avoid repeating the "default0Save1Load2" stuff
2198
337k
    int  predMode = cu.bdpcmM[CH_C] ? BDPCM_IDX : CU::getFinalIntraMode(cu, CH_C);
2199
2200
337k
    PelBuf piPredCb = cs.getPredBuf(COMP_Cb);
2201
337k
    PelBuf piPredCr = cs.getPredBuf(COMP_Cr);
2202
2203
    // estIntraPredChromaQT has read the samples around the whole chroma block, and only writes inside the block
2204
337k
    const bool samplesKept = cbArea == cu.Cb();
2205
337k
    if( samplesKept )
2206
337k
    {
2207
337k
      keepIntraPatternChType(*currTU.cu, cbArea);
2208
337k
      keepIntraPatternChType(*currTU.cu, crArea);
2209
337k
    }
2210
0
    else
2211
0
    {
2212
0
      initIntraPatternChType(*currTU.cu, cbArea);
2213
0
      initIntraPatternChType(*currTU.cu, crArea);
2214
0
    }
2215
2216
    // the pre-selection's prediction of this mode, made with the same reference samples, if it kept one
2217
337k
    int keptIdx = -1;
2218
337k
    if( samplesKept && !cu.bdpcmM[CH_C] )
2219
292k
    {
2220
1.04M
      for( int i = 0; i < m_numPreselPreds; i++ )
2221
978k
      {
2222
978k
        if( m_preselPredMode[i] == cu.intraDir[CH_C] )
2223
222k
        {
2224
222k
          keptIdx = i;
2225
222k
          break;
2226
222k
        }
2227
978k
      }
2228
292k
    }
2229
2230
337k
    if( keptIdx >= 0 )
2231
222k
    {
2232
222k
      piPredCb.copyFrom( preselPred( keptIdx, COMP_Cb, cbArea ) );
2233
222k
      piPredCr.copyFrom( preselPred( keptIdx, COMP_Cr, crArea ) );
2234
222k
    }
2235
115k
    else if (CU::isLMCMode(predMode))
2236
24.1k
    {
2237
24.1k
      if( !samplesKept )
2238
0
      {
2239
0
        loadLMLumaRecPels(cu, cbArea);
2240
0
      }
2241
24.1k
      predIntraChromaLM(COMP_Cb, piPredCb, cu, cbArea, predMode);
2242
24.1k
      predIntraChromaLM(COMP_Cr, piPredCr, cu, crArea, predMode);
2243
24.1k
    }
2244
90.9k
    else
2245
90.9k
    {
2246
90.9k
      predIntraAng(COMP_Cb, piPredCb, cu);
2247
90.9k
      predIntraAng(COMP_Cr, piPredCr, cu);
2248
90.9k
    }
2249
2250
    // determination of chroma residuals including reshaping and cross-component prediction
2251
    //----- get chroma residuals -----
2252
337k
    PelBuf resiCb = cs.getResiBuf(COMP_Cb);
2253
337k
    PelBuf resiCr = cs.getResiBuf(COMP_Cr);
2254
337k
    resiCb.subtract(cs.getOrgBuf(COMP_Cb), piPredCb);
2255
337k
    resiCr.subtract(cs.getOrgBuf(COMP_Cr), piPredCr);
2256
2257
    //===== store original residual signals (std and crossCompPred) =====
2258
2.02M
    for( int k = 0; k < 5; k++ )
2259
1.68M
    {
2260
1.68M
      m_orgResiCb[k].compactResize( cbArea );
2261
1.68M
      m_orgResiCr[k].compactResize( crArea );
2262
1.68M
    }
2263
675k
    for (int k = 0; k < 1; k += 4)
2264
337k
    {
2265
337k
      m_orgResiCb[k].copyFrom(resiCb);
2266
337k
      m_orgResiCr[k].copyFrom(resiCr);
2267
337k
    }
2268
2269
337k
    CUCtx cuCtx;
2270
337k
    cuCtx.isDQPCoded = true;
2271
337k
    cuCtx.isChromaQpAdjCoded = true;
2272
337k
    cuCtx.lfnstLastScanPos = false;
2273
2274
337k
    CodingStructure& saveCScur = *m_pSaveCS[2];
2275
2276
337k
    saveCScur.pcv = cs.pcv;
2277
337k
    saveCScur.picture = cs.picture;
2278
337k
    saveCScur.area.repositionTo(cs.area);
2279
2280
337k
    TransformUnit& tmpTUcur = saveCScur.tus.empty() ? saveCScur.addTU(currArea, partitioner.chType, nullptr) : *saveCScur.tus.front();
2281
337k
    tmpTUcur.initData();
2282
337k
    tmpTUcur.UnitArea::operator=(currArea);
2283
2284
337k
    TempCtx ctxBestTUL(m_CtxCache);
2285
2286
337k
    const SPS& sps = *cs.sps;
2287
337k
    double     bestCostCbcur = MAX_DOUBLE;
2288
337k
    double     bestCostCrcur = MAX_DOUBLE;
2289
337k
    Distortion bestDistCbcur = 0;
2290
337k
    Distortion bestDistCrcur = 0;
2291
2292
337k
    int  endLfnstIdx = (partitioner.isSepTree(cs) && partitioner.chType == CH_C && (partitioner.currArea().lwidth() < 8 || partitioner.currArea().lheight() < 8))
2293
323k
      || (partitioner.currArea().lwidth() > sps.getMaxTbSize() || partitioner.currArea().lheight() > sps.getMaxTbSize()) || !sps.LFNST ? 0 : 2;
2294
337k
    int  startLfnstIdx = 0;
2295
337k
    int  bestLfnstIdx = 0;
2296
337k
    bool testLFNST = sps.LFNST;
2297
2298
    // speedUps LFNST
2299
337k
    bool rapidLFNST = false;
2300
337k
    if (m_pcEncCfg->m_LFNST > 1)
2301
0
    {
2302
0
      rapidLFNST = true;
2303
0
      if (m_pcEncCfg->m_LFNST > 2)
2304
0
      {
2305
0
        endLfnstIdx = endLfnstIdx ? 1 : 0;
2306
0
      }
2307
0
    }
2308
337k
    int ts_used = 0;
2309
337k
    bool testTS = false;
2310
337k
    if (partitioner.chType != CH_C)
2311
0
    {
2312
0
      startLfnstIdx = currTU.cu->lfnstIdx;
2313
0
      endLfnstIdx = currTU.cu->lfnstIdx;
2314
0
      bestLfnstIdx = currTU.cu->lfnstIdx;
2315
0
      testLFNST  = false;
2316
0
      rapidLFNST = false;
2317
0
      ts_used = currTU.mtsIdx[COMP_Y];
2318
0
    }
2319
337k
    if (cu.bdpcmM[CH_C])
2320
45.0k
    {
2321
45.0k
      endLfnstIdx = 0;
2322
45.0k
      testLFNST = false;
2323
45.0k
    }
2324
2325
337k
    double dSingleCostAll = MAX_DOUBLE;
2326
337k
    double singleCostTmpAll = 0;
2327
2328
337k
    m_pcTrQuant->keepPrimaryCoeffs( startLfnstIdx != endLfnstIdx );
2329
2330
1.23M
    for (int lfnstIdx = startLfnstIdx; lfnstIdx <= endLfnstIdx; lfnstIdx++)
2331
899k
    {
2332
899k
      if (rapidLFNST && lfnstIdx)
2333
0
      {
2334
0
        if ((lfnstIdx == 2) && (bestLfnstIdx == 0))
2335
0
        {
2336
0
          continue;
2337
0
        }
2338
0
      }
2339
2340
899k
      currTU.cu->lfnstIdx = lfnstIdx;
2341
899k
      if (lfnstIdx)
2342
562k
      {
2343
562k
        m_CABACEstimator->getCtx() = ctxStartTU;
2344
562k
      }
2345
2346
899k
      cuCtx.lfnstLastScanPos = false;
2347
899k
      cuCtx.violatesLfnstConstrained[CH_L] = false;
2348
899k
      cuCtx.violatesLfnstConstrained[CH_C] = false;
2349
2350
2.69M
      for (uint32_t c = COMP_Cb; c < numTBlocks; c++)
2351
1.79M
      {
2352
1.79M
        const ComponentID compID = ComponentID(c);
2353
1.79M
        const CompArea& area = currTU.blocks[compID];
2354
1.79M
        double     dSingleCost = MAX_DOUBLE;
2355
1.79M
        Distortion singleDistCTmp = 0;
2356
1.79M
        double     singleCostTmp = 0;
2357
1.79M
        bool tsAllowed = useTS && TU::isTSAllowed(currTU, compID) && m_pcEncCfg->m_useChromaTS && !currTU.cu->lfnstIdx && !cu.bdpcmM[CH_C];
2358
1.79M
        if ((partitioner.chType == CH_L) && (!ts_used))
2359
0
        {
2360
0
          tsAllowed = false;
2361
0
        }
2362
1.79M
        uint8_t nNumTransformCands = 1 + (tsAllowed ? 1 : 0); // DCT + TS = 2 tests       
2363
1.79M
        TrModeList trModes;
2364
1.79M
        if (nNumTransformCands > 1)
2365
0
        {
2366
0
          trModes.push_back(TrMode(0, true));   // DCT2
2367
0
          trModes.push_back(TrMode(1, true));   // TS
2368
0
          testTS = true;
2369
0
        }
2370
1.79M
        bool cbfDCT2 = true;
2371
18.4E
        const bool isLastMode = testLFNST || cs.sps->jointCbCr ||  tsAllowed ? false : true;
2372
1.79M
        int bestModeId = 0;
2373
1.79M
        if( nNumTransformCands > 1 )   // only the second transform mode restores it
2374
0
        {
2375
0
          ctxStart = m_CABACEstimator->getCtx();
2376
0
        }
2377
3.59M
        for (int modeId = 0; modeId < nNumTransformCands; modeId++)
2378
1.79M
        {
2379
1.79M
          if (lfnstIdx || modeId)
2380
1.12M
          {
2381
1.12M
            resiCb.copyFrom(m_orgResiCb[0]);
2382
1.12M
            resiCr.copyFrom(m_orgResiCr[0]);
2383
1.12M
          }
2384
1.79M
          if (modeId == 0)
2385
1.79M
          {
2386
1.79M
            if ( tsAllowed)
2387
0
            {
2388
0
              xPreCheckMTS(currTU, &trModes, m_pcEncCfg->m_MTSIntraMaxCand, 0, compID);
2389
0
            }
2390
1.79M
          }
2391
2392
1.79M
          currTU.mtsIdx[compID] = currTU.cu->bdpcmM[CH_C] ? MTS_SKIP : modeId;
2393
2394
1.79M
          if (modeId)
2395
0
          {
2396
0
            if (!cbfDCT2 && trModes[modeId].first == MTS_SKIP)
2397
0
            {
2398
0
              break;
2399
0
            }
2400
0
            m_CABACEstimator->getCtx() = ctxStart;
2401
0
          }
2402
1.79M
          singleDistCTmp = 0;
2403
1.79M
          if (tsAllowed)
2404
0
          {
2405
0
            xIntraCodingTUBlock(currTU, compID, false, singleDistCTmp, 0, 0, true);
2406
0
            if ((modeId == 0) && (!trModes[modeId + 1].second))
2407
0
            {
2408
0
              nNumTransformCands = 1;
2409
0
            }
2410
0
          }
2411
1.79M
          else
2412
1.79M
        {
2413
1.79M
          xIntraCodingTUBlock(currTU, compID, false, singleDistCTmp);
2414
1.79M
        }
2415
1.79M
        if (((currTU.mtsIdx[compID] == MTS_SKIP && !currTU.cu->bdpcmM[CH_C])
2416
0
          && !TU::getCbf(currTU, compID)))   // In order not to code TS flag when cbf is zero, the case for TS with
2417
                                             // cbf being zero is forbidden.
2418
0
        {
2419
0
          singleCostTmp = MAX_DOUBLE;
2420
0
        }
2421
1.79M
        else
2422
1.79M
        {
2423
1.79M
          uint64_t fracBitsTmp = xGetIntraFracBitsQTChroma(currTU, compID, &cuCtx);
2424
1.79M
          singleCostTmp = m_pcRdCost->calcRdCost(fracBitsTmp, singleDistCTmp);
2425
1.79M
        }
2426
2427
1.79M
        if (singleCostTmp < dSingleCost)
2428
1.79M
        {
2429
1.79M
          dSingleCost = singleCostTmp;
2430
2431
1.79M
          if (compID == COMP_Cb)
2432
899k
          {
2433
899k
            bestCostCb = singleCostTmp;
2434
899k
            bestDistCb = singleDistCTmp;
2435
899k
          }
2436
899k
          else
2437
899k
          {
2438
899k
            bestCostCr = singleCostTmp;
2439
899k
            bestDistCr = singleDistCTmp;
2440
899k
          }
2441
1.79M
          bestModeId = modeId;
2442
1.79M
          if (currTU.mtsIdx[compID] == MTS_DCT2_DCT2)
2443
1.70M
          {
2444
1.70M
            cbfDCT2 = TU::getCbfAtDepth(currTU, compID, currDepth);
2445
1.70M
          }
2446
1.79M
          if (!isLastMode)
2447
1.79M
          {
2448
1.79M
            saveCS.getRecoBuf(area).copyFrom(cs.getRecoBuf(area));
2449
1.79M
            tmpTU.copyComponentFrom(currTU, compID);
2450
            // The save after Cb is read only after a transform skip test (below), the save after Cr only at the end
2451
1.79M
            if( compID == COMP_Cb ? testTS : keepBestCtx )
2452
0
            {
2453
0
              ctxBest = m_CABACEstimator->getCtx();
2454
0
            }
2455
1.79M
          }
2456
1.79M
        }
2457
1.79M
        }
2458
1.79M
        if (testTS && ((c == COMP_Cb && bestModeId < (nNumTransformCands - 1)) ))
2459
0
        {
2460
0
          m_CABACEstimator->getCtx() = ctxBest;
2461
2462
0
          currTU.copyComponentFrom(tmpTU, COMP_Cb); // Cbf of Cb is needed to estimate cost for Cr Cbf
2463
0
        }
2464
1.79M
      }
2465
2466
899k
      singleCostTmpAll = bestCostCb + bestCostCr;
2467
2468
899k
      bool rootCbfL = false;
2469
899k
      if (testLFNST)
2470
854k
      {
2471
3.41M
        for (uint32_t t = 0; t < getNumberValidTBlocks(*cs.pcv); t++)
2472
2.56M
        {
2473
2.56M
          rootCbfL |= bool(tmpTU.cbf[t]);
2474
2.56M
        }
2475
854k
        if (rapidLFNST && !rootCbfL)
2476
0
        {
2477
0
          endLfnstIdx = lfnstIdx; // end this
2478
0
        }
2479
854k
      }
2480
2481
899k
      if (testLFNST && lfnstIdx && !cuCtx.lfnstLastScanPos)
2482
370k
      {
2483
370k
        bool cbfAtZeroDepth = CU::isSepTree(*currTU.cu)
2484
370k
          ? rootCbfL : (cs.area.chromaFormat != CHROMA_400
2485
0
            && std::min(tmpTU.blocks[1].width, tmpTU.blocks[1].height) < 4)
2486
0
          ? TU::getCbfAtDepth(currTU, COMP_Y, currTU.depth) : rootCbfL;
2487
370k
        if (cbfAtZeroDepth)
2488
2.04k
        {
2489
2.04k
          singleCostTmpAll = MAX_DOUBLE;
2490
2.04k
        }
2491
370k
      }
2492
899k
      if ((testLFNST || testTS) && (singleCostTmpAll < dSingleCostAll))
2493
292k
      {
2494
292k
        bestLfnstIdx = lfnstIdx;
2495
292k
        if ((lfnstIdx != endLfnstIdx) || testTS)
2496
281k
        {
2497
281k
          dSingleCostAll = singleCostTmpAll;
2498
2499
281k
          bestCostCbcur = bestCostCb;
2500
281k
          bestCostCrcur = bestCostCr;
2501
281k
          bestDistCbcur = bestDistCb;
2502
281k
          bestDistCrcur = bestDistCr;
2503
2504
281k
          saveCScur.getRecoBuf(cbArea).copyFrom(saveCS.getRecoBuf(cbArea));
2505
281k
          saveCScur.getRecoBuf(crArea).copyFrom(saveCS.getRecoBuf(crArea));
2506
2507
281k
          tmpTUcur.copyComponentFrom(tmpTU, COMP_Cb);
2508
281k
          tmpTUcur.copyComponentFrom(tmpTU, COMP_Cr);
2509
281k
        }
2510
292k
        if( keepBestCtx )
2511
0
        {
2512
0
          ctxBestTUL = m_CABACEstimator->getCtx();
2513
0
        }
2514
292k
      }
2515
899k
    }
2516
337k
    if ((testLFNST && (bestLfnstIdx != endLfnstIdx)) || testTS)
2517
281k
    {
2518
281k
      bestCostCb = bestCostCbcur;
2519
281k
      bestCostCr = bestCostCrcur;
2520
281k
      bestDistCb = bestDistCbcur;
2521
281k
      bestDistCr = bestDistCrcur;
2522
281k
      currTU.cu->lfnstIdx = bestLfnstIdx;
2523
281k
      if (!cs.sps->jointCbCr)
2524
0
      {
2525
0
        cs.getRecoBuf(cbArea).copyFrom(saveCScur.getRecoBuf(cbArea));
2526
0
        cs.getRecoBuf(crArea).copyFrom(saveCScur.getRecoBuf(crArea));
2527
2528
0
        currTU.copyComponentFrom(tmpTUcur, COMP_Cb);
2529
0
        currTU.copyComponentFrom(tmpTUcur, COMP_Cr);
2530
2531
        // swapped, not copied: ctxBestTUL is not read again without joint CbCr
2532
0
        if( keepBestCtx )
2533
0
        {
2534
0
          m_CABACEstimator->getCtx().swap( ctxBestTUL );
2535
0
        }
2536
0
      }
2537
281k
    }
2538
2539
337k
    Distortion bestDistCbCr = bestDistCb + bestDistCr;
2540
2541
337k
    if (cs.sps->jointCbCr)
2542
337k
    {
2543
337k
      if ((testLFNST && (bestLfnstIdx != endLfnstIdx)) || testTS)
2544
281k
      {
2545
281k
        saveCS.getRecoBuf(cbArea).copyFrom(saveCScur.getRecoBuf(cbArea));
2546
281k
        saveCS.getRecoBuf(crArea).copyFrom(saveCScur.getRecoBuf(crArea));
2547
2548
281k
        tmpTU.copyComponentFrom(tmpTUcur, COMP_Cb);
2549
281k
        tmpTU.copyComponentFrom(tmpTUcur, COMP_Cr);
2550
        // the best contexts go to ctxBest only (swapped, not copied): every joint candidate below starts from ctxStartTU, and
2551
        // when none is coded the contexts are restored from ctxBest at the end
2552
281k
        if( keepBestCtx )
2553
0
        {
2554
0
          static_cast<Ctx&>( ctxBest ).swap( ctxBestTUL );
2555
0
        }
2556
281k
      }
2557
      // Test using joint chroma residual coding
2558
337k
      double     bestCostCbCr = bestCostCb + bestCostCr;
2559
337k
      int        bestJointCbCr = 0;
2560
337k
      bool checkDCTOnly = m_pcEncCfg->m_useChromaTS && ((TU::getCbf(tmpTU, COMP_Cb) && tmpTU.mtsIdx[COMP_Cb] == MTS_DCT2_DCT2 && !TU::getCbf(tmpTU, COMP_Cr)) ||
2561
0
        (TU::getCbf(tmpTU, COMP_Cr) && tmpTU.mtsIdx[COMP_Cr] == MTS_DCT2_DCT2 && !TU::getCbf(tmpTU, COMP_Cb)) ||
2562
0
        (TU::getCbf(tmpTU, COMP_Cb) && tmpTU.mtsIdx[COMP_Cb] == MTS_DCT2_DCT2 && TU::getCbf(tmpTU, COMP_Cr) && tmpTU.mtsIdx[COMP_Cr] == MTS_DCT2_DCT2));
2563
337k
      bool checkTSOnly = m_pcEncCfg->m_useChromaTS && ((TU::getCbf(tmpTU, COMP_Cb) && tmpTU.mtsIdx[COMP_Cb] == MTS_SKIP && !TU::getCbf(tmpTU, COMP_Cr)) ||
2564
0
        (TU::getCbf(tmpTU, COMP_Cr) && tmpTU.mtsIdx[COMP_Cr] == MTS_SKIP && !TU::getCbf(tmpTU, COMP_Cb)) ||
2565
0
        (TU::getCbf(tmpTU, COMP_Cb) && tmpTU.mtsIdx[COMP_Cb] == MTS_SKIP && TU::getCbf(tmpTU, COMP_Cr) && tmpTU.mtsIdx[COMP_Cr] == MTS_SKIP));
2566
337k
      bool       lastIsBest = false;
2567
337k
      bool noLFNST1 = false;
2568
337k
      if (rapidLFNST && (startLfnstIdx != endLfnstIdx))
2569
0
      {
2570
0
        if (bestLfnstIdx == 2)
2571
0
        {
2572
0
          noLFNST1 = true;
2573
0
        }
2574
0
        else
2575
0
        {
2576
0
          endLfnstIdx = 1;
2577
0
        }
2578
0
      }
2579
2580
      // The candidates and their residuals don't depend on the LFNST index, so the rounds after the first don't select again
2581
337k
      std::vector<int> jointCbfCandidates;
2582
337k
      const std::vector<int> noJointCbfCandidates;
2583
337k
      bool jointCbfSelected = false;
2584
2585
1.23M
      for (int lfnstIdxj = startLfnstIdx; lfnstIdxj <= endLfnstIdx; lfnstIdxj++)
2586
899k
      {
2587
899k
        if (rapidLFNST && noLFNST1 && (lfnstIdxj == 1))
2588
0
        {
2589
0
          continue;
2590
0
        }
2591
899k
        currTU.cu->lfnstIdx = lfnstIdxj;
2592
899k
        const bool testJointCbf = TU::getCbf(tmpTU, COMP_Cb) || TU::getCbf(tmpTU, COMP_Cr);
2593
899k
        if( testJointCbf && !jointCbfSelected )
2594
122k
        {
2595
122k
          jointCbfCandidates = m_pcTrQuant->selectICTCandidates(currTU, m_orgResiCb, m_orgResiCr);
2596
122k
          jointCbfSelected   = true;
2597
122k
        }
2598
899k
        const std::vector<int>& jointCbfMasksToTest = testJointCbf ? jointCbfCandidates : noJointCbfCandidates;
2599
899k
        for (int cbfMask : jointCbfMasksToTest)
2600
318k
        {
2601
318k
          currTU.jointCbCr = (uint8_t)cbfMask;
2602
318k
          ComponentID codeCompId = ((currTU.jointCbCr >> 1) ? COMP_Cb : COMP_Cr);
2603
318k
          ComponentID otherCompId = ((codeCompId == COMP_Cb) ? COMP_Cr : COMP_Cb);
2604
318k
          bool tsAllowed = useTS && TU::isTSAllowed(currTU, codeCompId) && (m_pcEncCfg->m_useChromaTS) && !currTU.cu->lfnstIdx && !cu.bdpcmM[CH_C];
2605
318k
          if ((partitioner.chType == CH_L)&& tsAllowed && (currTU.mtsIdx[COMP_Y] != MTS_SKIP))
2606
0
          {
2607
0
            tsAllowed = false;
2608
0
          }
2609
318k
          if (!tsAllowed)
2610
318k
          {
2611
318k
            checkTSOnly = false;
2612
318k
          }
2613
318k
          uint8_t     numTransformCands = 1 + (tsAllowed && !(checkDCTOnly || checkTSOnly)? 1 : 0); // DCT + TS = 2 tests
2614
318k
          TrModeList trModes;
2615
318k
          if (numTransformCands > 1)
2616
0
          {
2617
0
            trModes.push_back(TrMode(0, true)); // DCT2
2618
0
            trModes.push_back(TrMode(1, true));//TS
2619
0
          }
2620
318k
          else
2621
318k
          {
2622
318k
            currTU.mtsIdx[codeCompId] = checkTSOnly || currTU.cu->bdpcmM[CH_C] ? 1 : 0;
2623
318k
          }
2624
2625
637k
          for (int modeId = 0; modeId < numTransformCands; modeId++)
2626
318k
          {
2627
318k
            Distortion distTmp = 0;
2628
318k
            currTU.mtsIdx[codeCompId] = currTU.cu->bdpcmM[CH_C] ? MTS_SKIP : MTS_DCT2_DCT2;
2629
318k
            if (numTransformCands > 1)
2630
0
            {
2631
0
              currTU.mtsIdx[codeCompId] = currTU.cu->bdpcmM[CH_C] ? MTS_SKIP : trModes[modeId].first;
2632
0
            }
2633
318k
            currTU.mtsIdx[otherCompId] = MTS_DCT2_DCT2;
2634
2635
318k
            m_CABACEstimator->getCtx() = ctxStartTU;
2636
2637
318k
            resiCb.copyFrom(m_orgResiCb[cbfMask]);
2638
318k
            resiCr.copyFrom(m_orgResiCr[cbfMask]);
2639
318k
            if ((modeId == 0) && (numTransformCands > 1))
2640
0
            {
2641
0
              xPreCheckMTS(currTU, &trModes, m_pcEncCfg->m_MTSIntraMaxCand, 0, COMP_Cb);
2642
0
              currTU.mtsIdx[codeCompId] = trModes[modeId].first;
2643
0
              currTU.mtsIdx[(codeCompId == COMP_Cr) ? COMP_Cb : COMP_Cr] = MTS_DCT2_DCT2;
2644
0
            }
2645
318k
            cuCtx.lfnstLastScanPos = false;
2646
318k
            cuCtx.violatesLfnstConstrained[CH_L] = false;
2647
318k
            cuCtx.violatesLfnstConstrained[CH_C] = false;
2648
318k
            if (numTransformCands > 1)
2649
0
            {
2650
0
              xIntraCodingTUBlock(currTU, COMP_Cb, false, distTmp, 0, 0, true);
2651
0
              if ((modeId == 0) && !trModes[modeId + 1].second)
2652
0
              {
2653
0
                numTransformCands = 1;
2654
0
              }
2655
0
            }
2656
318k
            else
2657
318k
            {
2658
318k
              xIntraCodingTUBlock(currTU, COMP_Cb, false, distTmp, 0);
2659
318k
            }
2660
2661
318k
            double costTmp = std::numeric_limits<double>::max();
2662
318k
            if (distTmp < MAX_DISTORTION)
2663
314k
            {
2664
314k
              uint64_t bits = xGetIntraFracBitsQTChroma(currTU, COMP_Cb, &cuCtx);
2665
314k
              costTmp = m_pcRdCost->calcRdCost(bits, distTmp);
2666
314k
            }
2667
4.24k
            else if (!currTU.mtsIdx[codeCompId])
2668
4.24k
            {
2669
4.24k
              numTransformCands = 1;
2670
4.24k
            }
2671
318k
            bool rootCbfL = false;
2672
1.27M
            for (uint32_t t = 0; t < getNumberValidTBlocks(*cs.pcv); t++)
2673
955k
            {
2674
955k
              rootCbfL |= bool(tmpTU.cbf[t]);
2675
955k
            }
2676
318k
            if (rapidLFNST && !rootCbfL)
2677
0
            {
2678
0
              endLfnstIdx = lfnstIdxj;
2679
0
            }
2680
318k
            if (testLFNST && currTU.cu->lfnstIdx && !cuCtx.lfnstLastScanPos)
2681
4.21k
            {
2682
4.21k
              bool cbfAtZeroDepth = CU::isSepTree(*currTU.cu) ? rootCbfL
2683
4.21k
                : (cs.area.chromaFormat != CHROMA_400 && std::min(tmpTU.blocks[1].width, tmpTU.blocks[1].height) < 4)
2684
0
                ? TU::getCbfAtDepth(currTU, COMP_Y, currTU.depth) : rootCbfL;
2685
4.21k
              if (cbfAtZeroDepth)
2686
4.21k
              {
2687
4.21k
                costTmp = MAX_DOUBLE;
2688
4.21k
              }
2689
4.21k
            }
2690
318k
            if (costTmp < bestCostCbCr)
2691
119k
            {
2692
119k
              bestCostCbCr = costTmp;
2693
119k
              bestDistCbCr = distTmp;
2694
119k
              bestJointCbCr = currTU.jointCbCr;
2695
2696
              // store data
2697
119k
              bestLfnstIdx = lfnstIdxj;
2698
119k
              if ((cbfMask != jointCbfMasksToTest.back() || (lfnstIdxj != endLfnstIdx)) || (modeId != (numTransformCands - 1)))
2699
97.9k
              {
2700
97.9k
                saveCS.getRecoBuf(cbArea).copyFrom(cs.getRecoBuf(cbArea));
2701
97.9k
                saveCS.getRecoBuf(crArea).copyFrom(cs.getRecoBuf(crArea));
2702
2703
97.9k
                tmpTU.copyComponentFrom(currTU, COMP_Cb);
2704
97.9k
                tmpTU.copyComponentFrom(currTU, COMP_Cr);
2705
2706
97.9k
                if( keepBestCtx )
2707
0
                {
2708
0
                  ctxBest = m_CABACEstimator->getCtx();
2709
0
                }
2710
97.9k
              }
2711
21.7k
              else
2712
21.7k
              {
2713
21.7k
                lastIsBest = true;
2714
21.7k
                cs.cus[0]->lfnstIdx = bestLfnstIdx;
2715
21.7k
              }
2716
119k
            }
2717
318k
          }
2718
318k
        }
2719
2720
        // Retrieve the best CU data (unless it was the very last one tested)
2721
899k
      }
2722
337k
      if (!lastIsBest)
2723
316k
      {
2724
316k
        cs.getRecoBuf(cbArea).copyFrom(saveCS.getRecoBuf(cbArea));
2725
316k
        cs.getRecoBuf(crArea).copyFrom(saveCS.getRecoBuf(crArea));
2726
2727
316k
        cs.cus[0]->lfnstIdx = bestLfnstIdx;
2728
316k
        currTU.copyComponentFrom(tmpTU, COMP_Cb);
2729
316k
        currTU.copyComponentFrom(tmpTU, COMP_Cr);
2730
316k
        if( keepBestCtx )
2731
0
        {
2732
0
          m_CABACEstimator->getCtx().swap( ctxBest );   // ctxBest is not read again
2733
0
        }
2734
316k
      }
2735
337k
      currTU.jointCbCr = (TU::getCbf(currTU, COMP_Cb) || TU::getCbf(currTU, COMP_Cr)) ? bestJointCbCr : 0;
2736
337k
    } // jointCbCr
2737
2738
337k
    m_pcTrQuant->keepPrimaryCoeffs( false );
2739
2740
337k
    cs.dist += bestDistCbCr;
2741
337k
    cuCtx.violatesLfnstConstrained[CH_L] = false;
2742
337k
    cuCtx.violatesLfnstConstrained[CH_C] = false;
2743
337k
    cuCtx.lfnstLastScanPos = false;
2744
337k
    cuCtx.violatesMtsCoeffConstraint = false;
2745
337k
    cuCtx.mtsLastScanPos = false;
2746
337k
    cbfs.cbf(COMP_Cb) = TU::getCbf(currTU, COMP_Cb);
2747
337k
    cbfs.cbf(COMP_Cr) = TU::getCbf(currTU, COMP_Cr);
2748
337k
  }
2749
0
  else
2750
0
  {
2751
0
    unsigned   numValidTBlocks = getNumberValidTBlocks(*cs.pcv);
2752
0
    ChromaCbfs SplitCbfs(false);
2753
2754
0
    if (partitioner.canSplit(TU_MAX_TR_SPLIT, cs))
2755
0
    {
2756
0
      partitioner.splitCurrArea(TU_MAX_TR_SPLIT, cs);
2757
0
    }
2758
0
    else if (currTU.cu->ispMode)
2759
0
    {
2760
0
      partitioner.splitCurrArea(m_ispTestedModes[0].IspType, cs);
2761
0
    }
2762
0
    else
2763
0
      THROW("Implicit TU split not available");
2764
2765
0
    do
2766
0
    {
2767
0
      ChromaCbfs subCbfs = xIntraChromaCodingQT(cs, partitioner, true);   // the next sub-TU starts from these contexts
2768
2769
0
      for (uint32_t ch = COMP_Cb; ch < numValidTBlocks; ch++)
2770
0
      {
2771
0
        const ComponentID compID = ComponentID(ch);
2772
0
        SplitCbfs.cbf(compID) |= subCbfs.cbf(compID);
2773
0
      }
2774
0
    } while (partitioner.nextPart(cs));
2775
2776
0
    partitioner.exitCurrSplit();
2777
2778
    /*if (lumaUsesISP && cs.dist == MAX_UINT) //ahenkel
2779
    {
2780
      return cbfs;
2781
    }*/
2782
0
    {
2783
0
      cbfs.Cb |= SplitCbfs.Cb;
2784
0
      cbfs.Cr |= SplitCbfs.Cr;
2785
2786
0
      if (1)   //(!lumaUsesISP)
2787
0
      {
2788
0
        for (auto& ptu : cs.tus)
2789
0
        {
2790
0
          if (currArea.Cb().contains(ptu->Cb()) || (!ptu->Cb().valid() && currArea.Y().contains(ptu->Y())))
2791
0
          {
2792
0
            TU::setCbfAtDepth(*ptu, COMP_Cb, currDepth, SplitCbfs.Cb);
2793
0
            TU::setCbfAtDepth(*ptu, COMP_Cr, currDepth, SplitCbfs.Cr);
2794
0
          }
2795
0
        }
2796
0
      }
2797
0
    }
2798
0
  }
2799
337k
  return cbfs;
2800
337k
}
2801
2802
uint64_t IntraSearch::xFracModeBitsIntraLuma(const CodingUnit& cu, const unsigned* mpmLst)
2803
1.11M
{
2804
1.11M
  m_CABACEstimator->resetBits();
2805
2806
1.11M
  if (!cu.ciip)
2807
1.11M
  {
2808
1.11M
    m_CABACEstimator->intra_luma_pred_mode(cu, mpmLst);
2809
1.11M
  }
2810
2811
1.11M
  return m_CABACEstimator->getEstFracBits();
2812
1.11M
}
2813
2814
template<typename T, size_t N, int M>
2815
void IntraSearch::xReduceHadCandList(static_vector<T, N>& candModeList, static_vector<double, N>& candCostList, SortedPelUnitBufs<M>& sortedPelBuffer, int& numModesForFullRD, const double thresholdHadCost, const double* mipHadCost, const CodingUnit& cu, const bool fastMip)
2816
22.7k
{
2817
22.7k
  const int maxCandPerType = numModesForFullRD >> 1;
2818
22.7k
  static_vector<ModeInfo, FAST_UDI_MAX_RDMODE_NUM> tempRdModeList;
2819
22.7k
  static_vector<double, FAST_UDI_MAX_RDMODE_NUM> tempCandCostList;
2820
22.7k
  const double minCost = candCostList[0];
2821
22.7k
  bool keepOneMip = candModeList.size() > numModesForFullRD;
2822
22.7k
  const int maxNumConv = 3; 
2823
2824
22.7k
  int numConv = 0;
2825
22.7k
  int numMip = 0;
2826
103k
  for (int idx = 0; idx < candModeList.size() - (keepOneMip?0:1); idx++)
2827
80.3k
  {
2828
80.3k
    bool addMode = false;
2829
80.3k
    const ModeInfo& orgMode = candModeList[idx];
2830
2831
80.3k
    if (!orgMode.mipFlg)
2832
57.5k
    {
2833
57.5k
      addMode = (numConv < maxNumConv);
2834
57.5k
      numConv += addMode ? 1:0;
2835
57.5k
    }
2836
22.7k
    else
2837
22.7k
    {
2838
22.7k
      addMode = ( numMip < maxCandPerType || (candCostList[idx] < thresholdHadCost * minCost) || keepOneMip );
2839
22.7k
      keepOneMip = false;
2840
22.7k
      numMip += addMode ? 1:0;
2841
22.7k
    }
2842
80.3k
    if( addMode )
2843
80.3k
    {
2844
80.3k
      tempRdModeList.push_back(orgMode);
2845
80.3k
      tempCandCostList.push_back(candCostList[idx]);
2846
80.3k
    }
2847
80.3k
  }
2848
2849
  // sort Pel Buffer
2850
22.7k
  int i = -1;
2851
22.7k
  for( auto &m: tempRdModeList)
2852
80.3k
  {
2853
80.3k
    if( ! (m == candModeList.at( ++i )) )
2854
0
    {
2855
0
      for( int j = i; j < (int)candModeList.size()-1; )
2856
0
      {
2857
0
        if( m == candModeList.at( ++j ) )
2858
0
        {
2859
0
          sortedPelBuffer.swap( i, j);
2860
0
          break;
2861
0
        }
2862
0
      }
2863
0
    }
2864
80.3k
  }
2865
22.7k
  sortedPelBuffer.reduceTo( (int)tempRdModeList.size() );
2866
2867
22.7k
  if ((cu.lwidth() > 8 && cu.lheight() > 8))
2868
20.4k
  {
2869
    // Sort MIP candidates by Hadamard cost
2870
20.4k
    const int transpOff = getNumModesMip(cu.Y());
2871
20.4k
    static_vector<uint8_t, FAST_UDI_MAX_RDMODE_NUM> sortedMipModes(0);
2872
20.4k
    static_vector<double, FAST_UDI_MAX_RDMODE_NUM> sortedMipCost(0);
2873
20.4k
    for (uint8_t mode : { 0, 1, 2 })
2874
61.4k
    {
2875
61.4k
      uint8_t candMode = mode + uint8_t((mipHadCost[mode + transpOff] < mipHadCost[mode]) ? transpOff : 0);
2876
61.4k
      updateCandList(candMode, mipHadCost[candMode], sortedMipModes, sortedMipCost, 3);
2877
61.4k
    }
2878
2879
    // Append MIP mode to RD mode list
2880
20.4k
    const int modeListSize = int(tempRdModeList.size());
2881
40.9k
    for (int idx = 0; idx < 3; idx++)
2882
40.9k
    {
2883
40.9k
      const bool     isTransposed = (sortedMipModes[idx] >= transpOff ? true : false);
2884
40.9k
      const uint32_t mipIdx       = (isTransposed ? sortedMipModes[idx] - transpOff : sortedMipModes[idx]);
2885
40.9k
      const ModeInfo mipMode( true, isTransposed, 0, NOT_INTRA_SUBPARTITIONS, mipIdx );
2886
40.9k
      bool alreadyIncluded = false;
2887
163k
      for (int modeListIdx = 0; modeListIdx < modeListSize; modeListIdx++)
2888
143k
      {
2889
143k
        if (tempRdModeList[modeListIdx] == mipMode)
2890
20.4k
        {
2891
20.4k
          alreadyIncluded = true;
2892
20.4k
          break;
2893
20.4k
        }
2894
143k
      }
2895
2896
40.9k
      if (!alreadyIncluded)
2897
20.4k
      {
2898
20.4k
        tempRdModeList.push_back(mipMode);
2899
20.4k
        tempCandCostList.push_back(0);
2900
20.4k
        if( fastMip ) break;
2901
20.4k
      }
2902
40.9k
    }
2903
20.4k
  }
2904
2905
22.7k
  candModeList = tempRdModeList;
2906
22.7k
  candCostList = tempCandCostList;
2907
22.7k
  numModesForFullRD = int(candModeList.size());
2908
22.7k
}
2909
2910
void IntraSearch::xPreCheckMTS(TransformUnit &tu, TrModeList *trModes, const int maxCand, PelUnitBuf *predBuf, const ComponentID& compID)
2911
16.6k
{
2912
16.6k
  if (compID == COMP_Y)
2913
16.6k
  {
2914
16.6k
    CodingStructure&  cs = *tu.cs;
2915
16.6k
    const CompArea& area = tu.blocks[compID];
2916
16.6k
    const CodingUnit& cu = *cs.getCU(area.pos(), CH_L,TREE_D);
2917
16.6k
    PelBuf piPred = cs.getPredBuf(area);
2918
16.6k
    PelBuf piResi = cs.getResiBuf(area);
2919
2920
16.6k
    initIntraPatternChType(*tu.cu, area);
2921
16.6k
    if (predBuf)
2922
14.9k
    {
2923
14.9k
      piPred.copyFrom(predBuf->Y());
2924
14.9k
    }
2925
1.72k
    else if (CU::isMIP(cu, CH_L))
2926
1.69k
    {
2927
1.69k
      initIntraMip(cu);
2928
1.69k
      predIntraMip(piPred, cu);
2929
1.69k
    }
2930
30
    else
2931
30
    {
2932
30
      predIntraAng(COMP_Y, piPred, cu);
2933
30
    }
2934
2935
    //===== get residual signal =====
2936
16.6k
    CPelBuf piOrg = cs.getOrgBuf(COMP_Y);
2937
16.6k
    piResi.subtract(piOrg, piPred);
2938
16.6k
    m_pcTrQuant->checktransformsNxN(tu, trModes, m_pcEncCfg->m_MTSIntraMaxCand, compID);
2939
16.6k
  }
2940
0
  else
2941
0
  {
2942
0
    ComponentID codeCompId = (tu.jointCbCr ? (tu.jointCbCr >> 1 ? COMP_Cb : COMP_Cr) : compID);
2943
0
    m_pcTrQuant->checktransformsNxN(tu, trModes, m_pcEncCfg->m_MTSIntraMaxCand, codeCompId);
2944
0
  }
2945
16.6k
}
2946
2947
double IntraSearch::xTestISP(CodingStructure& cs, Partitioner& subTuPartitioner, double bestCostForISP, PartSplit ispType, bool& splitcbf, uint64_t& singleFracBits, Distortion& singleDistLuma, CUCtx& cuCtx)
2948
18.2k
{
2949
18.2k
  int  subTuCounter = 0;
2950
18.2k
  bool earlySkipISP = false;
2951
18.2k
  bool splitCbfLuma = false;
2952
18.2k
  CodingUnit& cu = *cs.cus[0];
2953
2954
18.2k
  Distortion singleDistTmpLumaSUM = 0;
2955
18.2k
  uint64_t   singleTmpFracBitsSUM = 0;
2956
18.2k
  double     singleCostTmpSUM = 0;
2957
18.2k
  cuCtx.isDQPCoded = true;
2958
18.2k
  cuCtx.isChromaQpAdjCoded = true;
2959
2960
18.2k
  do
2961
23.0k
  {
2962
23.0k
    Distortion singleDistTmpLuma = 0;
2963
23.0k
    uint64_t   singleTmpFracBits = 0;
2964
23.0k
    double     singleCostTmp = 0;
2965
23.0k
    TransformUnit& tmpTUcur = ((cs.tus.size() < (subTuCounter + 1)))
2966
23.0k
      ? cs.addTU(CS::getArea(cs, subTuPartitioner.currArea(), subTuPartitioner.chType,
2967
4.14k
        subTuPartitioner.treeType),
2968
4.14k
        subTuPartitioner.chType, cs.cus[0])
2969
23.0k
      : *cs.tus[subTuCounter];
2970
23.0k
    tmpTUcur.depth = subTuPartitioner.currTrDepth;
2971
2972
    // Encode TU
2973
23.0k
    xIntraCodingTUBlock(tmpTUcur, COMP_Y, false, singleDistTmpLuma, 0);
2974
23.0k
    cuCtx.mtsLastScanPos = false;
2975
2976
23.0k
    if (singleDistTmpLuma == MAX_INT)   // all zero CBF skip
2977
0
    {
2978
0
      earlySkipISP = true;
2979
0
      singleCostTmpSUM = MAX_DOUBLE;
2980
0
      break;
2981
0
    }
2982
2983
23.0k
    if (m_pcRdCost->calcRdCost(singleTmpFracBitsSUM, singleDistTmpLumaSUM + singleDistTmpLuma) > bestCostForISP)
2984
6.39k
    {
2985
6.39k
      earlySkipISP = true;
2986
6.39k
    }
2987
16.6k
    else
2988
16.6k
    {
2989
16.6k
      m_ispTestedModes[0].IspType = ispType;
2990
16.6k
      m_ispTestedModes[0].subTuCounter = subTuCounter;
2991
16.6k
      singleTmpFracBits = xGetIntraFracBitsQT(cs, subTuPartitioner, true, &cuCtx);
2992
16.6k
    }
2993
23.0k
    singleCostTmp = m_pcRdCost->calcRdCost(singleTmpFracBits, singleDistTmpLuma);
2994
2995
23.0k
    singleCostTmpSUM     += singleCostTmp;
2996
23.0k
    singleDistTmpLumaSUM += singleDistTmpLuma;
2997
23.0k
    singleTmpFracBitsSUM += singleTmpFracBits;
2998
2999
23.0k
    subTuCounter++;
3000
3001
23.0k
    splitCbfLuma |= TU::getCbfAtDepth( tmpTUcur, 
3002
23.0k
                                       COMP_Y, subTuPartitioner.currTrDepth);
3003
23.0k
    int nSubPartitions = m_ispTestedModes[cu.lfnstIdx].numTotalParts[cu.ispMode - 1];
3004
23.0k
    bool doStop = (m_pcEncCfg->m_ISP != 1) || (subTuCounter < nSubPartitions);
3005
23.0k
    if (doStop)
3006
23.0k
    {
3007
23.0k
      if (singleCostTmpSUM > bestCostForISP)
3008
15.5k
      {
3009
15.5k
        earlySkipISP = true;
3010
15.5k
        break;
3011
15.5k
      }
3012
7.45k
      if (subTuCounter < nSubPartitions)
3013
5.93k
      {
3014
5.93k
        double threshold = nSubPartitions == 2 ? 0.95 : subTuCounter == 1 ? 0.83 : 0.91;
3015
5.93k
        if (singleCostTmpSUM > bestCostForISP * threshold)
3016
1.17k
        {
3017
1.17k
          earlySkipISP = true;
3018
1.17k
          break;
3019
1.17k
        }
3020
5.93k
      }
3021
7.45k
    }
3022
23.0k
  } while (subTuPartitioner.nextPart(cs));
3023
18.2k
  singleDistLuma = singleDistTmpLumaSUM;
3024
18.2k
  singleFracBits = singleTmpFracBitsSUM;
3025
3026
18.2k
  splitcbf = splitCbfLuma;
3027
18.2k
  return earlySkipISP ? MAX_DOUBLE : singleCostTmpSUM;
3028
18.2k
}
3029
3030
int IntraSearch::xSpeedUpISP(int speed, bool& testISP, int mode, int& noISP, int& endISP, CodingUnit& cu, static_vector<ModeInfo, FAST_UDI_MAX_RDMODE_NUM>& RdModeList, const ModeInfo& bestPUMode, int bestISP, int bestLfnstIdx)
3031
16.6k
{
3032
16.6k
  if (speed)
3033
6.73k
  {
3034
6.73k
    if (mode >= 1)
3035
3.54k
    {
3036
3.54k
      if (m_ispTestedModes[0].splitIsFinished[1] && m_ispTestedModes[0].splitIsFinished[0])
3037
0
      {
3038
0
        testISP = false;
3039
0
        endISP = 0;
3040
0
      }
3041
3.54k
      else
3042
3.54k
      {
3043
3.54k
        if (m_pcEncCfg->m_ISP >= 2)
3044
3.54k
        {
3045
3.54k
          if (mode == 1) //best Hor||Ver
3046
3.18k
          {
3047
3.18k
            int bestDir = 0;
3048
9.56k
            for (int d = 0; d < 2; d++)
3049
6.37k
            {
3050
6.37k
              int d2 = d ? 0 : 1;
3051
6.37k
              if ((m_ispTestedModes[0].bestCost[d] <= m_ispTestedModes[0].bestCost[d2])
3052
6.01k
                && (m_ispTestedModes[0].bestCost[d] != MAX_DOUBLE))
3053
356
              {
3054
356
                bestDir = d + 1;
3055
356
                m_ispTestedModes[0].splitIsFinished[d2] = true;
3056
356
              }
3057
6.37k
            }
3058
3.18k
            m_ispTestedModes[0].bestModeSoFar = bestDir;
3059
3.18k
            if (m_ispTestedModes[0].bestModeSoFar <= 0)
3060
2.83k
            {
3061
2.83k
              m_ispTestedModes[0].splitIsFinished[1] = true;
3062
2.83k
              m_ispTestedModes[0].splitIsFinished[0] = true;
3063
2.83k
              testISP = false;
3064
2.83k
              endISP = 0;
3065
2.83k
            }
3066
3.18k
          }
3067
3.54k
          if (m_ispTestedModes[0].bestModeSoFar == 2)
3068
96
          {
3069
96
            noISP = 1;
3070
96
          }
3071
3.44k
          else
3072
3.44k
          {
3073
3.44k
            endISP = 1;
3074
3.44k
          }
3075
3.54k
        }
3076
3.54k
      }
3077
3.54k
    }
3078
6.73k
    if (testISP)
3079
3.89k
    {
3080
3.89k
      if (mode == 2)
3081
356
      {
3082
1.06k
        for (int d = 0; d < 2; d++)
3083
712
        {
3084
712
          int d2 = d ? 0 : 1;
3085
712
          if (m_ispTestedModes[0].bestCost[d] == MAX_DOUBLE)
3086
329
          {
3087
329
            m_ispTestedModes[0].splitIsFinished[d] = true;
3088
329
          }
3089
712
          if ((m_ispTestedModes[0].bestCost[d2] < 1.3 * m_ispTestedModes[0].bestCost[d])
3090
383
            && (int(m_ispTestedModes[0].bestSplitSoFar) != (d + 1)))
3091
283
          {
3092
283
            if (d)
3093
235
            {
3094
235
              endISP = 1;
3095
235
            }
3096
48
            else
3097
48
            {
3098
48
              noISP = 1;
3099
48
            }
3100
283
            m_ispTestedModes[0].splitIsFinished[d] = true;
3101
283
          }
3102
712
        }
3103
356
      }
3104
3.54k
      else
3105
3.54k
      {
3106
3.54k
        if (m_ispTestedModes[0].splitIsFinished[0])
3107
48
        {
3108
48
          noISP = 1;
3109
48
        }
3110
3.54k
        if (m_ispTestedModes[0].splitIsFinished[1])
3111
308
        {
3112
308
          endISP = 1;
3113
308
        }
3114
3.54k
      }
3115
3.89k
    }
3116
6.73k
    if ((noISP == 1) && (endISP == 1))
3117
27
    {
3118
27
      endISP = 0;
3119
27
    }
3120
6.73k
  }
3121
9.88k
  else
3122
9.88k
  {
3123
9.88k
    bool stopFound = false;
3124
9.88k
    if (m_pcEncCfg->m_ISP >= 3)
3125
9.88k
    {
3126
9.88k
      if (mode)
3127
3.51k
      {
3128
3.51k
        if ((bestISP == 0) || ((bestPUMode.modeId != RdModeList[mode - 1].modeId)
3129
127
          && (bestPUMode.modeId != RdModeList[mode].modeId)))
3130
2.50k
        {
3131
2.50k
          stopFound = true;
3132
2.50k
        }
3133
3.51k
      }
3134
9.88k
    }
3135
9.88k
    if (cu.mipFlag || cu.multiRefIdx)
3136
204
    {
3137
204
      cu.mipFlag = false;
3138
204
      cu.multiRefIdx = 0;
3139
204
      if (!stopFound)
3140
0
      {
3141
0
        for (int k = 0; k < mode; k++)
3142
0
        {
3143
0
          if (cu.intraDir[CH_L] == RdModeList[k].modeId)
3144
0
          {
3145
0
            stopFound = true;
3146
0
            break;
3147
0
          }
3148
0
        }
3149
0
      }
3150
204
    }
3151
9.88k
    if (stopFound)
3152
2.50k
    {
3153
2.50k
      testISP = false;
3154
2.50k
      endISP = 0;
3155
2.50k
      return 1;
3156
2.50k
    }
3157
7.37k
    if (!stopFound && (m_pcEncCfg->m_ISP >= 2) && (cu.intraDir[CH_L] == DC_IDX))
3158
1.01k
    {
3159
1.01k
      stopFound = true;
3160
1.01k
      endISP = 0;
3161
1.01k
      return 1;
3162
1.01k
    }
3163
7.37k
  }
3164
13.0k
  return 0;
3165
16.6k
}
3166
3167
void IntraSearch::xSpeedUpIntra(double bestcost, int& EndMode, int& speedIntra, CodingUnit& cu)
3168
30.0k
{
3169
30.0k
  int bestIdxbefore = m_ispTestedModes[0].bestIntraMode;
3170
30.0k
  if (m_ispTestedModes[0].isIntra)
3171
0
  {
3172
0
    if (bestIdxbefore == 1)//ISP
3173
0
    {
3174
0
      speedIntra = 14;
3175
0
    }
3176
0
    if (bestIdxbefore == 4)//MTS
3177
0
    {
3178
0
      speedIntra = 3;
3179
0
    }
3180
0
  }
3181
30.0k
  else if (!cu.cs->slice->isIntra())
3182
0
  {
3183
0
    if (bestcost != MAX_DOUBLE)
3184
0
    {
3185
0
      speedIntra = 10;
3186
0
    }
3187
0
  }
3188
30.0k
  if (m_ispTestedModes[0].bestBefore[0] == -1)
3189
26.8k
  {
3190
26.8k
    speedIntra |= 7;
3191
26.8k
    if (m_pcEncCfg->m_FastIntraTools == 2)
3192
0
    {
3193
0
      EndMode = 1;
3194
0
    }
3195
26.8k
  }
3196
30.0k
  if (!cu.cs->slice->isIntra())
3197
0
  {
3198
0
    if ((m_ispTestedModes[0].bestBefore[1] == 1) || (m_ispTestedModes[0].bestBefore[2] == 1))
3199
0
    {
3200
0
      speedIntra |= 2;
3201
0
    }
3202
0
    if ((m_ispTestedModes[0].bestBefore[1] == 4) || (m_ispTestedModes[0].bestBefore[2] == 4))
3203
0
    {
3204
0
      speedIntra |= 3;
3205
0
    }
3206
0
    if ((m_ispTestedModes[0].bestBefore[1] == 2) || (m_ispTestedModes[0].bestBefore[2] == 2))
3207
0
    {
3208
0
      speedIntra |= 1;
3209
0
    }
3210
0
  }
3211
30.0k
}
3212
3213
} // namespace vvenc
3214
3215
//! \}
3216