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/InterSearch.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 inter search class
46
 */
47
48
#include "InterSearch.h"
49
#include "EncModeCtrl.h"
50
#include "EncLib.h"
51
#include "CommonLib/CommonDef.h"
52
#include "CommonLib/Rom.h"
53
#include "CommonLib/MotionInfo.h"
54
#include "CommonLib/Picture.h"
55
#include "CommonLib/UnitTools.h"
56
#include "CommonLib/dtrace_next.h"
57
#include "CommonLib/dtrace_buffer.h"
58
#include "CommonLib/TimeProfiler.h"
59
60
#include <algorithm>
61
#include <math.h>
62
63
 //! \ingroup EncoderLib
64
 //! \{
65
66
namespace vvenc {
67
68
static const Mv s_acMvRefineH[9] =
69
{
70
  Mv(  0,  0 ), // 0
71
  Mv(  0, -1 ), // 1
72
  Mv(  0,  1 ), // 2
73
  Mv( -1,  0 ), // 3
74
  Mv(  1,  0 ), // 4
75
  Mv( -1, -1 ), // 5
76
  Mv(  1, -1 ), // 6
77
  Mv( -1,  1 ), // 7
78
  Mv(  1,  1 )  // 8
79
};
80
81
static const Mv s_acMvRefineQ[9] =
82
{
83
  Mv(  0,  0 ), // 0
84
  Mv(  0, -1 ), // 1
85
  Mv(  0,  1 ), // 2
86
  Mv( -1, -1 ), // 5
87
  Mv(  1, -1 ), // 6
88
  Mv( -1,  0 ), // 3
89
  Mv(  1,  0 ), // 4
90
  Mv( -1,  1 ), // 7
91
  Mv(  1,  1 )  // 8
92
};
93
94
static const bool s_skipQpelPosition[ 42 ][ 9 ] =
95
{
96
  { false, true,  true,  true,  true,  true,  true,  true,  true  },
97
  { true,  true,  true,  true,  true,  false, true,  true,  true  },
98
  { true,  true,  true,  true,  true,  true,  false, true,  true  },
99
  { true,  false, true,  true,  true,  true,  true,  true,  true  },
100
  { true,  false, true,  false, true,  false, true,  true,  true  },
101
  { true,  false, true,  true,  false, true,  false, true,  true  },
102
  { true,  true,  false, true,  true,  true,  true,  true,  true  },
103
  { true,  true,  false, true,  true,  false, true,  false, true  },
104
  { true,  true,  false, true,  true,  true,  false, true,  false },
105
  { true,  true,  false, true,  true,  true,  true,  false, false },
106
  { true,  true,  true,  true,  true,  false, true,  true,  true  },
107
  { true,  true,  false, true,  true,  false, true,  false, true  },
108
  { true,  true,  true,  true,  true,  true,  false, true,  true  },
109
  { true,  true,  false, true,  true,  true,  false, true,  false },
110
  { true,  false, true,  false, false, true,  true,  true,  true  },
111
  { true,  true,  true,  true,  true,  false, true,  true,  true  },
112
  { true,  false, true,  false, true,  false, true,  true,  true  },
113
  { true,  true,  true,  true,  true,  true,  false, true,  true  },
114
  { true,  false, true,  true,  false, true,  false, true,  true  },
115
  { true,  true,  true,  true,  false, true,  false, true,  false },
116
  { true,  false, true,  true,  true,  true,  true,  true,  true  },
117
  { true,  false, true,  true,  false, true,  false, true,  true  },
118
  { true,  true,  false, true,  true,  true,  true,  true,  true  },
119
  { true,  true,  false, true,  true,  true,  false, true,  false },
120
  { true,  true,  true,  false, true,  false, true,  false, true  },
121
  { true,  false, true,  true,  true,  true,  true,  true,  true  },
122
  { true,  false, true,  false, true,  false, true,  true,  true  },
123
  { true,  true,  false, true,  true,  true,  true,  true,  true  },
124
  { true,  true,  false, true,  true,  false, true,  false, true  },
125
  { true,  true,  true,  true,  true,  true,  false, true,  true  },
126
  { true,  true,  false, true,  true,  true,  true,  true,  true  },
127
  { true,  true,  false, true,  true,  true,  false, true,  false },
128
  { true,  true,  true,  true,  true,  false, true,  true,  true  },
129
  { true,  true,  false, true,  true,  true,  true,  true,  true  },
130
  { true,  true,  false, true,  true,  false, true,  false, true  },
131
  { true,  true,  true,  true,  true,  true,  false, true,  true  },
132
  { true,  false, true,  true,  true,  true,  true,  true,  true  },
133
  { true,  false, true,  true,  false, true,  false, true,  true  },
134
  { true,  true,  true,  true,  true,  false, true,  true,  true  },
135
  { true,  false, true,  true,  true,  true,  true,  true,  true  },
136
  { true,  false, true,  false, true,  false, true,  true,  true  },
137
  { false, false, false, false, false, false, false, false, false },
138
};
139
140
//   1,0    3,0    0,1    1,1    2,1    3,1    1,2    3,2    0,3    1,3    2,3    3,3    H1,0   H3,0
141
static const bool s_doInterpQ[ 42 ][ 14 ] =
142
{
143
  { false, false, false, false, false, false, false, false, false, false, false, false, false, false },
144
  { false, false, false, false, false, false, false, false, true,  false, false, false, false, true  },
145
  { false, false, true,  false, false, false, false, false, false, false, false, false, true,  false },
146
  { false, true,  false, false, false, false, false, false, false, false, false, false, false, false },
147
  { false, true,  false, false, false, false, false, false, true,  false, false, true,  false, true  },
148
  { false, true,  true,  false, false, true,  false, false, false, false, false, false, true,  false },
149
  { true,  false, false, false, false, false, false, false, false, false, false, false, false, false },
150
  { true,  false, false, false, false, false, false, false, true,  true,  false, false, false, true  },
151
  { true,  false, true,  true,  false, false, false, false, false, false, false, false, true,  false },
152
  { false, true,  false, false, false, true,  false, false, false, false, false, true,  true,  true  },
153
  { false, false, false, false, false, false, false, false, false, false, true,  false, false, true  },
154
  { false, true,  false, false, false, false, false, false, false, false, true,  true,  false, true  },
155
  { false, false, false, false, true,  false, false, false, false, false, false, false, true,  false },
156
  { false, true,  false, false, true,  true,  false, false, false, false, false, false, true,  false },
157
  { true,  false, false, true,  false, false, false, false, false, true,  false, false, true,  true  },
158
  { false, false, false, false, false, false, false, false, false, false, true,  false, false, true  },
159
  { true,  false, false, false, false, false, false, false, false, true,  true,  false, false, true  },
160
  { false, false, false, false, true,  false, false, false, false, false, false, false, true,  false },
161
  { true,  false, false, true,  true,  false, false, false, false, false, false, false, true,  false },
162
  { false, false, false, false, false, false, false, false, true,  true,  false, true,  false, true  },
163
  { false, false, false, false, false, false, false, true,  false, false, false, false, false, false },
164
  { false, false, false, false, false, false, false, true,  true,  false, false, true,  false, true  },
165
  { false, false, false, false, false, false, true,  false, false, false, false, false, false, false },
166
  { false, false, false, false, false, false, true,  false, true,  true,  false, false, false, true  },
167
  { false, false, true,  true,  false, true,  false, false, false, false, false, false, true,  false },
168
  { false, false, false, false, false, false, false, true,  false, false, false, false, false, false },
169
  { false, false, true,  false, false, true,  false, true,  false, false, false, false, true,  false },
170
  { false, false, false, false, false, false, true,  false, false, false, false, false, false, false },
171
  { false, false, true,  true,  false, false, true,  false, false, false, false, false, true,  false },
172
  { false, false, false, false, false, false, false, false, false, false, true,  false, false, true  },
173
  { false, false, false, false, false, false, false, true,  false, false, false, false, false, false },
174
  { false, false, false, false, false, false, false, true,  false, false, true,  true,  false, true  },
175
  { false, false, false, false, true,  false, false, false, false, false, false, false, true,  false },
176
  { false, false, false, false, false, false, false, true,  false, false, false, false, false, false },
177
  { false, false, false, false, true,  true,  false, true,  false, false, false, false, true,  false },
178
  { false, false, false, false, false, false, false, false, false, false, true,  false, false, true  },
179
  { false, false, false, false, false, false, true,  false, false, false, false, false, false, false },
180
  { false, false, false, false, false, false, true,  false, false, true,  true,  false, false, true  },
181
  { false, false, false, false, true,  false, false, false, false, false, false, false, true,  false },
182
  { false, false, false, false, false, false, true,  false, false, false, false, false, false, false },
183
  { false, false, false, true,  true,  false, true,  false, false, false, false, false, true,  false },
184
  { true,  true,  true,  true,  true,  true,  true,  true,  true,  true,  true,  true,  true,  true  },
185
};
186
187
const int BlkUniMvInfoBuffer::m_uniMvListMaxSize;
188
189
InterSearch::InterSearch()
190
5.72k
  : m_modeCtrl                    (nullptr)
191
5.72k
  , m_defaultCachedBvs            (nullptr)
192
5.72k
  , m_pcEncCfg                    (nullptr)
193
5.72k
  , m_pcTrQuant                   (nullptr)
194
5.72k
  , m_iSearchRange                (0)
195
5.72k
  , m_bipredSearchRange           (0)
196
5.72k
  , m_motionEstimationSearchMethod(VVENC_MESEARCH_FULL)
197
5.72k
  , m_motionEstimationSearchMethodSCC( 0 )
198
5.72k
  , m_CABACEstimator              (nullptr)
199
5.72k
  , m_CtxCache                    (nullptr)
200
5.72k
  , m_pTempPel                    (nullptr)
201
5.72k
{
202
17.1k
  for (int i=0; i<MAX_NUM_REF_LIST_ADAPT_SR; i++)
203
11.4k
  {
204
11.4k
    memset (m_aaiAdaptSR[i], 0, MAX_IDX_ADAPT_SR * sizeof (int));
205
11.4k
  }
206
22.9k
  for (int i=0; i<AMVP_MAX_NUM_CANDS+1; i++)
207
17.1k
  {
208
17.1k
    memset (m_auiMVPIdxCost[i], 0, (AMVP_MAX_NUM_CANDS+1) * sizeof (uint32_t) );
209
17.1k
  }
210
5.72k
}
211
212
213
InterSearch::~InterSearch()
214
5.72k
{
215
5.72k
  destroy();
216
5.72k
}
217
218
// residual_coding, outside transform skip, changes only these contexts of its channel type and its transform skip flag. They lie back to
219
// back (checked in InterSearch::init in debug builds).
220
static CtxSet coeffCtxSpan()
221
301k
{
222
301k
  return CtxSet( Ctx::SigCoeffGroup[0].Offset, Ctx::LastY[1].Offset + Ctx::LastY[1].Size - Ctx::SigCoeffGroup[0].Offset );
223
301k
}
224
225
static void saveCoeffCtx( Ctx& dst, const Ctx& src )
226
27.0k
{
227
27.0k
  dst = SubCtx( coeffCtxSpan(), src );
228
27.0k
  dst = SubCtx( Ctx::TransformSkipFlag, src );
229
27.0k
}
230
231
void InterSearch::init( const VVEncCfg& encCfg, TrQuant* pTrQuant, RdCost* pRdCost, EncModeCtrl* pModeCtrl, CodingStructure **pSaveCS )
232
5.72k
{
233
5.72k
#if _DEBUG
234
5.72k
  for( const CtxSet* set : { &Ctx::SigCoeffGroup[1], &Ctx::SigFlag[0], &Ctx::SigFlag[1], &Ctx::SigFlag[2], &Ctx::SigFlag[3], &Ctx::SigFlag[4], &Ctx::SigFlag[5],
235
5.72k
                             &Ctx::ParFlag[0], &Ctx::ParFlag[1], &Ctx::GtxFlag[0], &Ctx::GtxFlag[1], &Ctx::GtxFlag[2], &Ctx::GtxFlag[3], &Ctx::LastX[0], &Ctx::LastX[1], &Ctx::LastY[0] } )
236
91.6k
  {
237
91.6k
    CHECKD( set->Offset < coeffCtxSpan().Offset || set->Offset + set->Size > coeffCtxSpan().Offset + coeffCtxSpan().Size, "a coefficient context lies outside the span" );
238
91.6k
  }
239
5.72k
#endif
240
241
5.72k
  InterPrediction::init( pRdCost, encCfg.m_internChromaFormat, encCfg.m_CTUSize, encCfg.m_ifpLines );
242
5.72k
  m_numBVs                       = 0;
243
5.72k
  m_pcEncCfg                     = &encCfg;
244
5.72k
  m_pcTrQuant                    = pTrQuant;
245
5.72k
  m_pcRdCost                     = pRdCost;
246
5.72k
  m_modeCtrl                     = pModeCtrl;
247
5.72k
  m_pSaveCS                      = pSaveCS;
248
249
5.72k
  m_iSearchRange                    = encCfg.m_SearchRange;
250
5.72k
  m_bipredSearchRange               = encCfg.m_bipredSearchRange;
251
5.72k
  m_motionEstimationSearchMethod    = vvencMESearchMethod( encCfg.m_motionEstimationSearchMethod );
252
5.72k
  m_motionEstimationSearchMethodSCC = encCfg.m_motionEstimationSearchMethodSCC;
253
254
17.1k
  for( uint32_t iDir = 0; iDir < MAX_NUM_REF_LIST_ADAPT_SR; iDir++ )
255
11.4k
  {
256
80.1k
    for( uint32_t iRefIdx = 0; iRefIdx < MAX_IDX_ADAPT_SR; iRefIdx++ )
257
68.7k
    {
258
68.7k
      m_aaiAdaptSR[iDir][iRefIdx] = m_iSearchRange;
259
68.7k
    }
260
11.4k
  }
261
262
  // initialize motion cost
263
22.9k
  for( int iNum = 0; iNum < AMVP_MAX_NUM_CANDS + 1; iNum++ )
264
17.1k
  {
265
51.5k
    for( int iIdx = 0; iIdx < AMVP_MAX_NUM_CANDS; iIdx++ )
266
34.3k
    {
267
34.3k
      if( iIdx < iNum )
268
17.1k
      {
269
17.1k
        m_auiMVPIdxCost[iIdx][iNum] = xGetMvpIdxBits( iIdx, iNum );
270
17.1k
      }
271
17.1k
      else
272
17.1k
      {
273
17.1k
        m_auiMVPIdxCost[iIdx][iNum] = MAX_UINT;
274
17.1k
      }
275
34.3k
    }
276
17.1k
  }
277
278
5.72k
  const ChromaFormat cform   = encCfg.m_internChromaFormat;
279
5.72k
  const int          ctuSize = encCfg.m_CTUSize;
280
17.1k
  for (uint32_t i = 0; i < NUM_REF_PIC_LIST_01; i++)
281
11.4k
  {
282
11.4k
    m_tmpPredStorage[i].create( UnitArea( cform, Area( 0, 0, ctuSize, ctuSize ) ) );
283
11.4k
  }
284
5.72k
  m_symStartPredB.create( CHROMA_400, Area( 0, 0, ctuSize, ctuSize ) );
285
5.72k
  m_tmpStorageLCU.create( UnitArea( cform, Area( 0, 0, ctuSize, ctuSize ) ) );
286
  // The zero residual of the distortion checks: nothing writes to it, so clearing it here is enough.
287
5.72k
  m_pTempPel = new Pel[ctuSize * ctuSize]();
288
5.72k
  m_tmpAffiStorage.create(UnitArea(cform, Area(0, 0, ctuSize, ctuSize + 2)));  // allow overread by 2 samples
289
5.72k
  m_tmpAffiError = new Pel[ctuSize * ctuSize];
290
5.72k
  m_tmpAffiDeri[0] = new Pel[ctuSize * ctuSize];
291
5.72k
  m_tmpAffiDeri[1] = new Pel[ctuSize * ctuSize];
292
293
5.72k
  CompArea chromaArea( COMP_Cb, cform, Area( 0, 0, encCfg.m_CTUSize, encCfg.m_CTUSize ), true );
294
28.6k
  for( int i = 0; i < 4; i++ )
295
22.9k
  {
296
22.9k
    m_orgResiCb[i].create( chromaArea );
297
22.9k
    m_orgResiCr[i].create( chromaArea );
298
22.9k
  }
299
5.72k
}
300
301
void InterSearch::destroy()
302
5.72k
{
303
5.72k
  if ( m_pTempPel )
304
5.72k
  {
305
5.72k
    delete [] m_pTempPel;
306
5.72k
    m_pTempPel = nullptr;
307
5.72k
  }
308
309
17.1k
  for( int i = 0; i < NUM_REF_PIC_LIST_01; i++ )
310
11.4k
  {
311
11.4k
    m_tmpPredStorage[i].destroy();
312
11.4k
  }
313
5.72k
  m_symStartPredB.destroy();
314
5.72k
  m_tmpStorageLCU.destroy();
315
5.72k
  m_tmpAffiStorage.destroy();
316
5.72k
  if (m_tmpAffiError != NULL)
317
5.72k
  {
318
5.72k
    delete[] m_tmpAffiError;
319
5.72k
    m_tmpAffiError = nullptr;
320
5.72k
  }
321
5.72k
  if (m_tmpAffiDeri[0] != NULL)
322
5.72k
  {
323
5.72k
    delete[] m_tmpAffiDeri[0];
324
5.72k
    m_tmpAffiDeri[0] = nullptr;
325
5.72k
  }
326
5.72k
  if (m_tmpAffiDeri[1] != NULL)
327
5.72k
  {
328
5.72k
    delete[] m_tmpAffiDeri[1];
329
5.72k
    m_tmpAffiDeri[1] = nullptr;
330
5.72k
  }
331
332
5.72k
  m_pSaveCS  = nullptr;
333
5.72k
}
334
335
void InterSearch::setCtuEncRsrc( CABACWriter* cabacEstimator, CtxCache* ctxCache, ReuseUniMv* pReuseUniMv, BlkUniMvInfoBuffer* pBlkUniMvInfoBuffer, AffineProfList* pAffineProfList, IbcBvCand* pCachedBvs )
336
4.65k
{
337
4.65k
  m_CABACEstimator     = cabacEstimator;
338
4.65k
  m_CtxCache           = ctxCache;
339
4.65k
  m_ReuseUniMv         = pReuseUniMv;
340
4.65k
  m_BlkUniMvInfoBuffer = pBlkUniMvInfoBuffer;
341
4.65k
  m_AffineProfList     = pAffineProfList;
342
4.65k
  m_defaultCachedBvs   = pCachedBvs;
343
4.65k
}
344
345
ReuseUniMv::ReuseUniMv()
346
10.2k
{
347
10.2k
  const int numPos     = MAX_CU_SIZE >> MIN_CU_LOG2;
348
10.2k
  const int maxSizeIdx = MAX_CU_SIZE_IDX-2;
349
71.6k
  for( int wIdx = 0; wIdx < maxSizeIdx; wIdx++ )
350
61.4k
  {
351
429k
    for( int hIdx = 0; hIdx < maxSizeIdx; hIdx++ )
352
368k
    {
353
12.1M
      for( int y = 0; y < numPos; y++ )
354
11.7M
      {
355
389M
        for( int x = 0; x < numPos; x++ )
356
377M
        {
357
377M
          m_reusedUniMVs[ wIdx ][ hIdx ][ x ][ y ] = nullptr;
358
377M
        }
359
11.7M
      }
360
368k
    }
361
61.4k
  }
362
10.2k
}
363
364
ReuseUniMv::~ReuseUniMv()
365
10.2k
{
366
10.2k
  resetReusedUniMvs();
367
10.2k
}
368
369
void ReuseUniMv::resetReusedUniMvs()
370
15.3k
{
371
15.3k
  const int numPos     = MAX_CU_SIZE >> MIN_CU_LOG2;
372
15.3k
  const int maxSizeIdx = MAX_CU_SIZE_IDX-2;
373
107k
  for ( int wIdx = 0; wIdx < maxSizeIdx; wIdx++ )
374
92.1k
  {
375
644k
    for ( int hIdx = 0; hIdx < maxSizeIdx; hIdx++ )
376
552k
    {
377
18.2M
      for ( int y = 0; y < numPos; y++ )
378
17.6M
      {
379
583M
        for ( int x = 0; x < numPos; x++ )
380
566M
        {
381
566M
          if ( m_reusedUniMVs[ wIdx ][ hIdx ][ x ][ y ] )
382
0
          {
383
0
            delete [] m_reusedUniMVs[ wIdx ][ hIdx ][ x ][ y ];
384
0
            m_reusedUniMVs[ wIdx ][ hIdx ][ x ][ y ] = nullptr;
385
0
          }
386
566M
        }
387
17.6M
      }
388
552k
    }
389
92.1k
  }
390
15.3k
}
391
392
void InterSearch::loadGlobalUniMvs( const Area& lumaArea, const PreCalcValues& pcv)
393
0
{
394
0
  unsigned idx1, idx2, idx3, idx4;
395
0
  getAreaIdxNew(lumaArea, pcv, idx1, idx2, idx3, idx4);
396
0
  if( m_ReuseUniMv->m_reusedUniMVs[idx1][idx2][idx3][idx4])
397
0
  {
398
//    DTRACE( g_trace_ctx, D_TMP, "%d unimv load %d %d %d %d \n", g_trace_ctx->getChannelCounter(D_TMP), idx3,idx4,idx1,idx2 );
399
0
    m_BlkUniMvInfoBuffer->insertUniMvCands(lumaArea, m_ReuseUniMv->m_reusedUniMVs[idx1][idx2][idx3][idx4]);
400
0
  }
401
0
}
402
403
void InterSearch::getBestSbt( CodingStructure* tempCS, CodingUnit* cu, uint8_t& histBestSbt, Distortion& curPuSse, uint8_t sbtAllowed, bool doPreAnalyzeResi, bool mtsAllowed )
404
0
{
405
0
  m_estMinDistSbt[NUMBER_SBT_MODE] = MAX_DISTORTION;
406
0
  m_skipSbtAll = false;
407
408
0
  if( doPreAnalyzeResi )
409
0
  {
410
0
    xCalcMinDistSbt( *tempCS, *cu, sbtAllowed );
411
0
  }
412
413
0
  curPuSse = getEstDistSbt( NUMBER_SBT_MODE );
414
415
0
  if( doPreAnalyzeResi )
416
0
  {
417
0
    if( m_skipSbtAll && !mtsAllowed )
418
0
    {
419
0
      histBestSbt = 0; //try DCT2
420
0
    }
421
0
    else
422
0
    {
423
0
      int  slShift = 4 + std::min( Log2( cu->lwidth() * cu->lheight() ), 9 );
424
0
      assert( curPuSse != MAX_DISTORTION );
425
0
      histBestSbt = m_modeCtrl->findBestSbt( cu->cs->area, (uint32_t)( curPuSse >> slShift ) );
426
0
      if( m_skipSbtAll && CU::isSbtMode( histBestSbt ) ) //special case, skip SBT when loading SBT
427
0
      {
428
0
        histBestSbt = 0; //try DCT2
429
0
      }
430
0
    }
431
0
  }
432
0
}
433
434
435
// The integer start positions of a motion search. Different MVs often round to one position, and its second test cannot
436
// win: the costs are compared strictly, and the best cost only falls. A SAD that stops early is above the best cost too.
437
// So a repeat is not searched for: the search costs more than the SADs of the repeats.
438
struct InterSearch::StartPositions
439
{
440
  Mv  positions[BlkUniMvInfoBuffer::m_uniMvListMaxSize + 2];   // room for the search's start, zero and the whole list
441
  int size = 0;
442
443
0
  void add( const Mv& position ) { positions[size++] = position; }
444
};
445
446
// xClipMvSearch for one block, with its bounds worked out once. The clip is a clamp per component, so the bounds are the
447
// clip of the extremes, and clamping to them is the same clip for every MV, also when a block's bounds cross.
448
struct InterSearch::BlockMvClip
449
{
450
  Mv lo, hi;
451
452
  BlockMvClip( InterSearch& search, const CodingUnit& cu, const int ifpLines )
453
0
    : lo( std::numeric_limits<int>::min(), std::numeric_limits<int>::min() )
454
0
    , hi( std::numeric_limits<int>::max(), std::numeric_limits<int>::max() )
455
0
  {
456
0
    search.xClipMvSearch( lo, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv, ifpLines );
457
0
    search.xClipMvSearch( hi, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv, ifpLines );
458
0
  }
459
460
  Mv operator()( const Mv& mv ) const
461
0
  {
462
0
    return Mv( std::min( hi.hor, std::max( lo.hor, mv.hor ) ), std::min( hi.ver, std::max( lo.ver, mv.ver ) ) );
463
0
  }
464
};
465
466
// Passes the cost of each position from first on, in list order. Two or more positions take a four-position SAD call,
467
// padded with the last position, which costs less than separate calls.
468
template<typename OnCost>
469
void InterSearch::xCostsOfStartPositions( const StartPositions& startPositions, const int first, const TZSearchStruct& cStruct, OnCost&& onCost )
470
0
{
471
0
  const auto refOf  = [&]( const Mv& position ) { return cStruct.piRefY + position.ver * cStruct.iRefStride + position.hor; };
Unexecuted instantiation: InterSearch.cpp:vvenc::InterSearch::xCostsOfStartPositions<vvenc::InterSearch::xMotionEstimation(vvenc::CodingUnit&, vvenc::UnitBuf<short const>&, vvenc::RefPicList, vvenc::Mv&, int, vvenc::Mv&, int&, unsigned int&, unsigned long&, vvenc::AMVPInfo const&, bool)::$_2>(vvenc::InterSearch::StartPositions const&, int, vvenc::InterSearch::TZSearchStruct const&, vvenc::InterSearch::xMotionEstimation(vvenc::CodingUnit&, vvenc::UnitBuf<short const>&, vvenc::RefPicList, vvenc::Mv&, int, vvenc::Mv&, int&, unsigned int&, unsigned long&, vvenc::AMVPInfo const&, bool)::$_2&&)::{lambda(vvenc::Mv const&)#1}::operator()(vvenc::Mv const&) const
Unexecuted instantiation: InterSearch.cpp:vvenc::InterSearch::xCostsOfStartPositions<vvenc::InterSearch::xTZSearch(vvenc::CodingUnit const&, vvenc::RefPicList, int, vvenc::InterSearch::TZSearchStruct&, vvenc::Mv&, unsigned long&, bool, bool)::$_1>(vvenc::InterSearch::StartPositions const&, int, vvenc::InterSearch::TZSearchStruct const&, vvenc::InterSearch::xTZSearch(vvenc::CodingUnit const&, vvenc::RefPicList, int, vvenc::InterSearch::TZSearchStruct&, vvenc::Mv&, unsigned long&, bool, bool)::$_1&&)::{lambda(vvenc::Mv const&)#1}::operator()(vvenc::Mv const&) const
472
0
  const auto costOf = [&]( const Mv& position, const Distortion sad ) { return sad + m_pcRdCost->getCostOfVectorWithPredictor( position.hor, position.ver, cStruct.imvShift ); };
Unexecuted instantiation: InterSearch.cpp:vvenc::InterSearch::xCostsOfStartPositions<vvenc::InterSearch::xMotionEstimation(vvenc::CodingUnit&, vvenc::UnitBuf<short const>&, vvenc::RefPicList, vvenc::Mv&, int, vvenc::Mv&, int&, unsigned int&, unsigned long&, vvenc::AMVPInfo const&, bool)::$_2>(vvenc::InterSearch::StartPositions const&, int, vvenc::InterSearch::TZSearchStruct const&, vvenc::InterSearch::xMotionEstimation(vvenc::CodingUnit&, vvenc::UnitBuf<short const>&, vvenc::RefPicList, vvenc::Mv&, int, vvenc::Mv&, int&, unsigned int&, unsigned long&, vvenc::AMVPInfo const&, bool)::$_2&&)::{lambda(vvenc::Mv const&, unsigned long)#1}::operator()(vvenc::Mv const&, unsigned long) const
Unexecuted instantiation: InterSearch.cpp:vvenc::InterSearch::xCostsOfStartPositions<vvenc::InterSearch::xTZSearch(vvenc::CodingUnit const&, vvenc::RefPicList, int, vvenc::InterSearch::TZSearchStruct&, vvenc::Mv&, unsigned long&, bool, bool)::$_1>(vvenc::InterSearch::StartPositions const&, int, vvenc::InterSearch::TZSearchStruct const&, vvenc::InterSearch::xTZSearch(vvenc::CodingUnit const&, vvenc::RefPicList, int, vvenc::InterSearch::TZSearchStruct&, vvenc::Mv&, unsigned long&, bool, bool)::$_1&&)::{lambda(vvenc::Mv const&, unsigned long)#1}::operator()(vvenc::Mv const&, unsigned long) const
473
474
0
  const Mv*  positions = startPositions.positions;
475
0
  const int  size      = startPositions.size;
476
0
  int        index     = first;
477
0
  if( m_cDistParam.sadFourPositions )
478
0
  {
479
0
    while( size - index >= 2 )
480
0
    {
481
0
      const int  count = std::min( size - index, 4 );
482
0
      const Pel* refs[4];
483
0
      for( int k = 0; k < 4; k++ )
484
0
      {
485
0
        refs[k] = refOf( positions[index + std::min( k, count - 1 )] );
486
0
      }
487
0
      Distortion sads[4];
488
0
      m_cDistParam.sadFourPositions( m_cDistParam, refs, sads );
489
0
      for( int k = 0; k < count; k++, index++ )
490
0
      {
491
0
        onCost( index, costOf( positions[index], sads[k] ) );
492
0
      }
493
0
    }
494
0
  }
495
0
  for( ; index < size; index++ )
496
0
  {
497
0
    m_cDistParam.cur.buf = refOf( positions[index] );
498
0
    onCost( index, costOf( positions[index], m_cDistParam.distFunc( m_cDistParam ) ) );
499
0
  }
500
0
}
Unexecuted instantiation: InterSearch.cpp:void vvenc::InterSearch::xCostsOfStartPositions<vvenc::InterSearch::xMotionEstimation(vvenc::CodingUnit&, vvenc::UnitBuf<short const>&, vvenc::RefPicList, vvenc::Mv&, int, vvenc::Mv&, int&, unsigned int&, unsigned long&, vvenc::AMVPInfo const&, bool)::$_2>(vvenc::InterSearch::StartPositions const&, int, vvenc::InterSearch::TZSearchStruct const&, vvenc::InterSearch::xMotionEstimation(vvenc::CodingUnit&, vvenc::UnitBuf<short const>&, vvenc::RefPicList, vvenc::Mv&, int, vvenc::Mv&, int&, unsigned int&, unsigned long&, vvenc::AMVPInfo const&, bool)::$_2&&)
Unexecuted instantiation: InterSearch.cpp:void vvenc::InterSearch::xCostsOfStartPositions<vvenc::InterSearch::xTZSearch(vvenc::CodingUnit const&, vvenc::RefPicList, int, vvenc::InterSearch::TZSearchStruct&, vvenc::Mv&, unsigned long&, bool, bool)::$_1>(vvenc::InterSearch::StartPositions const&, int, vvenc::InterSearch::TZSearchStruct const&, vvenc::InterSearch::xTZSearch(vvenc::CodingUnit const&, vvenc::RefPicList, int, vvenc::InterSearch::TZSearchStruct&, vvenc::Mv&, unsigned long&, bool, bool)::$_1&&)
501
502
inline void InterSearch::xTZSearchHelp( TZSearchStruct& rcStruct, const int iSearchX, const int iSearchY, const uint8_t ucPointNr, const uint32_t uiDistance )
503
0
{
504
  // Check the MV cost first: a point whose MV cost alone reaches the best cost cannot win, whatever its SAD.
505
0
  const Distortion mvCost = m_pcRdCost->getCostOfVectorWithPredictor( iSearchX, iSearchY, rcStruct.imvShift );
506
0
  if( mvCost >= rcStruct.uiBestSad )
507
0
  {
508
0
    return;
509
0
  }
510
511
0
  m_cDistParam.cur.buf = rcStruct.piRefY + iSearchY * rcStruct.iRefStride + iSearchX;
512
513
0
  const TZCandidate candidate{ iSearchX, iSearchY, mvCost, uiDistance, ucPointNr };
514
0
  xTZAcceptIfBetter( rcStruct, candidate, m_cDistParam.distFunc( m_cDistParam ) );
515
0
}
516
517
inline void InterSearch::xTZAcceptIfBetter( TZSearchStruct& rcStruct, const TZCandidate& candidate, const Distortion sad )
518
0
{
519
0
  const Distortion cost = sad + candidate.mvCost;
520
0
  if( cost < rcStruct.uiBestSad )
521
0
  {
522
0
    rcStruct.uiBestSad      = cost;
523
0
    rcStruct.iBestX         = candidate.x;
524
0
    rcStruct.iBestY         = candidate.y;
525
0
    rcStruct.uiBestDistance = candidate.distance;
526
0
    rcStruct.uiBestRound    = 0;
527
0
    rcStruct.ucPointNr      = candidate.pointNr;
528
0
    m_cDistParam.maximumDistortionForEarlyExit = cost;
529
0
  }
530
0
}
531
532
// As xTZSearchHelp, but with a four-position kernel the SADs wait until four candidates are queued. The results are the
533
// same: the candidates are compared in their original order, and one that the MV cost check would have rejected against
534
// a better cost found meanwhile cannot win that comparison either.
535
inline void InterSearch::xTZSearchQueued( TZSearchStruct& rcStruct, const int iSearchX, const int iSearchY, const uint8_t ucPointNr, const uint32_t uiDistance )
536
0
{
537
0
  if( !m_cDistParam.sadFourPositions )
538
0
  {
539
0
    xTZSearchHelp( rcStruct, iSearchX, iSearchY, ucPointNr, uiDistance );
540
0
    return;
541
0
  }
542
543
0
  const Distortion mvCost = m_pcRdCost->getCostOfVectorWithPredictor( iSearchX, iSearchY, rcStruct.imvShift );
544
0
  if( mvCost < rcStruct.uiBestSad )
545
0
  {
546
0
    TZCandidate& candidate = m_tzQueue[m_tzQueued++];
547
0
    candidate.x        = iSearchX;
548
0
    candidate.y        = iSearchY;
549
0
    candidate.mvCost   = mvCost;
550
0
    candidate.distance = uiDistance;
551
0
    candidate.pointNr  = ucPointNr;
552
0
    if( m_tzQueued == 4 )
553
0
    {
554
0
      xTZSearchFlush( rcStruct );
555
0
    }
556
0
  }
557
0
}
558
559
inline void InterSearch::xTZSearchFlush( TZSearchStruct& rcStruct )
560
0
{
561
0
  const auto refOf = [&]( const TZCandidate& c ) { return rcStruct.piRefY + c.y * rcStruct.iRefStride + c.x; };
562
0
  if( m_tzQueued == 4 )
563
0
  {
564
0
    Distortion sads[4];
565
0
    const Pel* const refs[4] = { refOf( m_tzQueue[0] ), refOf( m_tzQueue[1] ), refOf( m_tzQueue[2] ), refOf( m_tzQueue[3] ) };
566
0
    m_cDistParam.sadFourPositions( m_cDistParam, refs, sads );
567
0
    for( int k = 0; k < 4; k++ )
568
0
    {
569
0
      xTZAcceptIfBetter( rcStruct, m_tzQueue[k], sads[k] );
570
0
    }
571
0
  }
572
0
  else
573
0
  {
574
0
    for( int k = 0; k < m_tzQueued; k++ )
575
0
    {
576
0
      if( m_tzQueue[k].mvCost < rcStruct.uiBestSad )
577
0
      {
578
0
        m_cDistParam.cur.buf = refOf( m_tzQueue[k] );
579
0
        xTZAcceptIfBetter( rcStruct, m_tzQueue[k], m_cDistParam.distFunc( m_cDistParam ) );
580
0
      }
581
0
    }
582
0
  }
583
0
  m_tzQueued = 0;
584
0
}
585
586
587
588
inline void InterSearch::xTZ2PointSearch( TZSearchStruct& rcStruct )
589
0
{
590
0
  const SearchRange& sr = rcStruct.searchRange;
591
592
0
  static const int xOffset[2][9] = { {  0, -1, -1,  0, -1, +1, -1, -1, +1 }, {  0,  0, +1, +1, -1, +1,  0, +1,  0 } };
593
0
  static const int yOffset[2][9] = { {  0,  0, -1, -1, +1, -1,  0, +1,  0 }, {  0, -1, -1,  0, -1, +1, +1, +1, +1 } };
594
595
  // 2 point search,                   //   1 2 3
596
  // check only the 2 untested points  //   4 0 5
597
  // around the start point            //   6 7 8
598
0
  const int iX1 = rcStruct.iBestX + xOffset[0][rcStruct.ucPointNr];
599
0
  const int iX2 = rcStruct.iBestX + xOffset[1][rcStruct.ucPointNr];
600
601
0
  const int iY1 = rcStruct.iBestY + yOffset[0][rcStruct.ucPointNr];
602
0
  const int iY2 = rcStruct.iBestY + yOffset[1][rcStruct.ucPointNr];
603
604
0
  if( iX1 >= sr.left && iX1 <= sr.right && iY1 >= sr.top && iY1 <= sr.bottom )
605
0
  {
606
0
    xTZSearchHelp( rcStruct, iX1, iY1, 0, 2 );
607
0
  }
608
609
0
  if( iX2 >= sr.left && iX2 <= sr.right && iY2 >= sr.top && iY2 <= sr.bottom )
610
0
  {
611
0
    xTZSearchHelp( rcStruct, iX2, iY2, 0, 2 );
612
0
  }
613
0
}
614
615
inline void InterSearch::xTZ4PointSquareSearch( TZSearchStruct & rcStruct, const int iStartX, const int iStartY, const int iDist )
616
0
{
617
0
  const SearchRange& sr = rcStruct.searchRange;
618
0
  CHECK( iDist == 0 || iDist > 2, "Invalid distance" );
619
  // 4 point search,                   //     1 2 3
620
  // search around the start point     //     4 0 5
621
  // with the required  distance       //     6 7 8
622
0
  const int iTop = iStartY - iDist;
623
0
  const int iBottom = iStartY + iDist;
624
0
  const int iLeft = iStartX - iDist;
625
0
  const int iRight = iStartX + iDist;
626
0
  rcStruct.uiBestRound += 1;
627
628
0
  if ( iTop >= sr.top )
629
0
  {
630
0
    if ( iLeft >= sr.left ) // check top left
631
0
    {
632
0
      xTZSearchQueued( rcStruct, iLeft, iTop, 1, iDist );
633
0
    }
634
0
    if ( iRight <= sr.right ) // check top right
635
0
    {
636
0
      xTZSearchQueued( rcStruct, iRight, iTop, 3, iDist );
637
0
    }
638
0
  }
639
0
  if ( iBottom <= sr.bottom )
640
0
  {
641
0
    if ( iLeft >= sr.left ) // check bottom left
642
0
    {
643
0
      xTZSearchQueued( rcStruct, iLeft, iBottom, 6, iDist );
644
0
    }
645
0
    if ( iRight <= sr.right ) // check bottom right
646
0
    {
647
0
      xTZSearchQueued( rcStruct, iRight, iBottom, 8, iDist );
648
0
    }
649
0
  }
650
0
  xTZSearchFlush( rcStruct );
651
0
}
652
653
inline void InterSearch::xTZ8PointSquareSearch( TZSearchStruct& rcStruct, const int iStartX, const int iStartY, const int iDist )
654
0
{
655
0
  const SearchRange& sr = rcStruct.searchRange;
656
0
  // 8 point search,                   //   1 2 3
657
0
  // search around the start point     //   4 0 5
658
0
  // with the required  distance       //   6 7 8
659
0
  CHECK( iDist == 0 , "Invalid distance");
660
0
  const int iTop        = iStartY - iDist;
661
0
  const int iBottom     = iStartY + iDist;
662
0
  const int iLeft       = iStartX - iDist;
663
0
  const int iRight      = iStartX + iDist;
664
0
  rcStruct.uiBestRound += 1;
665
0
666
0
  if ( iTop >= sr.top ) // check top
667
0
  {
668
0
    if ( iLeft >= sr.left ) // check top left
669
0
    {
670
0
      xTZSearchQueued( rcStruct, iLeft, iTop, 1, iDist );
671
0
    }
672
0
    // top middle
673
0
    xTZSearchQueued( rcStruct, iStartX, iTop, 2, iDist );
674
0
675
0
    if ( iRight <= sr.right ) // check top right
676
0
    {
677
0
      xTZSearchQueued( rcStruct, iRight, iTop, 3, iDist );
678
0
    }
679
0
  } // check top
680
0
  if ( iLeft >= sr.left ) // check middle left
681
0
  {
682
0
    xTZSearchQueued( rcStruct, iLeft, iStartY, 4, iDist );
683
0
  }
684
0
  if ( iRight <= sr.right ) // check middle right
685
0
  {
686
0
    xTZSearchQueued( rcStruct, iRight, iStartY, 5, iDist );
687
0
  }
688
0
  if ( iBottom <= sr.bottom ) // check bottom
689
0
  {
690
0
    if ( iLeft >= sr.left ) // check bottom left
691
0
    {
692
0
      xTZSearchQueued( rcStruct, iLeft, iBottom, 6, iDist );
693
0
    }
694
0
    // check bottom middle
695
0
    xTZSearchQueued( rcStruct, iStartX, iBottom, 7, iDist );
696
0
697
0
    if ( iRight <= sr.right ) // check bottom right
698
0
    {
699
0
      xTZSearchQueued( rcStruct, iRight, iBottom, 8, iDist );
700
0
    }
701
0
  } // check bottom
702
0
  xTZSearchFlush( rcStruct );
703
0
}
704
705
inline void InterSearch::xTZ8PointDiamondSearch( TZSearchStruct& rcStruct,
706
                                                 const int iStartX,
707
                                                 const int iStartY,
708
                                                 const int iDist,
709
                                                 const bool bCheckCornersAtDist1 )
710
0
{
711
0
  const SearchRange& sr = rcStruct.searchRange;
712
  // 8 point search,                   //   1 2 3
713
  // search around the start point     //   4 0 5
714
  // with the required  distance       //   6 7 8
715
0
  CHECK( iDist == 0, "Invalid distance" );
716
0
  const int iTop        = iStartY - iDist;
717
0
  const int iBottom     = iStartY + iDist;
718
0
  const int iLeft       = iStartX - iDist;
719
0
  const int iRight      = iStartX + iDist;
720
0
  rcStruct.uiBestRound += 1;
721
722
0
  if ( iDist == 1 )
723
0
  {
724
0
    if ( iTop >= sr.top ) // check top
725
0
    {
726
0
      if (bCheckCornersAtDist1)
727
0
      {
728
0
        if ( iLeft >= sr.left) // check top-left
729
0
        {
730
0
          xTZSearchQueued( rcStruct, iLeft, iTop, 1, iDist );
731
0
        }
732
0
        xTZSearchQueued( rcStruct, iStartX, iTop, 2, iDist );
733
0
        if ( iRight <= sr.right ) // check middle right
734
0
        {
735
0
          xTZSearchQueued( rcStruct, iRight, iTop, 3, iDist );
736
0
        }
737
0
      }
738
0
      else
739
0
      {
740
0
        xTZSearchQueued( rcStruct, iStartX, iTop, 2, iDist );
741
0
      }
742
0
    }
743
0
    if ( iLeft >= sr.left ) // check middle left
744
0
    {
745
0
      xTZSearchQueued( rcStruct, iLeft, iStartY, 4, iDist );
746
0
    }
747
0
    if ( iRight <= sr.right ) // check middle right
748
0
    {
749
0
      xTZSearchQueued( rcStruct, iRight, iStartY, 5, iDist );
750
0
    }
751
0
    if ( iBottom <= sr.bottom ) // check bottom
752
0
    {
753
0
      if (bCheckCornersAtDist1)
754
0
      {
755
0
        if ( iLeft >= sr.left) // check top-left
756
0
        {
757
0
          xTZSearchQueued( rcStruct, iLeft, iBottom, 6, iDist );
758
0
        }
759
0
        xTZSearchQueued( rcStruct, iStartX, iBottom, 7, iDist );
760
0
        if ( iRight <= sr.right ) // check middle right
761
0
        {
762
0
          xTZSearchQueued( rcStruct, iRight, iBottom, 8, iDist );
763
0
        }
764
0
      }
765
0
      else
766
0
      {
767
0
        xTZSearchQueued( rcStruct, iStartX, iBottom, 7, iDist );
768
0
      }
769
0
    }
770
0
  }
771
0
  else
772
0
  {
773
0
    if ( iDist <= 8 )
774
0
    {
775
0
      const int iTop_2      = iStartY - (iDist>>1);
776
0
      const int iBottom_2   = iStartY + (iDist>>1);
777
0
      const int iLeft_2     = iStartX - (iDist>>1);
778
0
      const int iRight_2    = iStartX + (iDist>>1);
779
780
0
      if (  iTop >= sr.top && iLeft >= sr.left &&
781
0
           iRight <= sr.right && iBottom <= sr.bottom ) // check border
782
0
      {
783
0
        xTZSearchQueued( rcStruct, iStartX,  iTop,      2, iDist    );
784
0
        xTZSearchQueued( rcStruct, iLeft_2,  iTop_2,    1, iDist>>1 );
785
0
        xTZSearchQueued( rcStruct, iRight_2, iTop_2,    3, iDist>>1 );
786
0
        xTZSearchQueued( rcStruct, iLeft,    iStartY,   4, iDist    );
787
0
        xTZSearchQueued( rcStruct, iRight,   iStartY,   5, iDist    );
788
0
        xTZSearchQueued( rcStruct, iLeft_2,  iBottom_2, 6, iDist>>1 );
789
0
        xTZSearchQueued( rcStruct, iRight_2, iBottom_2, 8, iDist>>1 );
790
0
        xTZSearchQueued( rcStruct, iStartX,  iBottom,   7, iDist    );
791
0
      }
792
0
      else // check border
793
0
      {
794
0
        if ( iTop >= sr.top ) // check top
795
0
        {
796
0
          xTZSearchQueued( rcStruct, iStartX, iTop, 2, iDist );
797
0
        }
798
0
        if ( iTop_2 >= sr.top ) // check half top
799
0
        {
800
0
          if ( iLeft_2 >= sr.left ) // check half left
801
0
          {
802
0
            xTZSearchQueued( rcStruct, iLeft_2, iTop_2, 1, (iDist>>1) );
803
0
          }
804
0
          if ( iRight_2 <= sr.right ) // check half right
805
0
          {
806
0
            xTZSearchQueued( rcStruct, iRight_2, iTop_2, 3, (iDist>>1) );
807
0
          }
808
0
        } // check half top
809
0
        if ( iLeft >= sr.left ) // check left
810
0
        {
811
0
          xTZSearchQueued( rcStruct, iLeft, iStartY, 4, iDist );
812
0
        }
813
0
        if ( iRight <= sr.right ) // check right
814
0
        {
815
0
          xTZSearchQueued( rcStruct, iRight, iStartY, 5, iDist );
816
0
        }
817
0
        if ( iBottom_2 <= sr.bottom ) // check half bottom
818
0
        {
819
0
          if ( iLeft_2 >= sr.left ) // check half left
820
0
          {
821
0
            xTZSearchQueued( rcStruct, iLeft_2, iBottom_2, 6, (iDist>>1) );
822
0
          }
823
0
          if ( iRight_2 <= sr.right ) // check half right
824
0
          {
825
0
            xTZSearchQueued( rcStruct, iRight_2, iBottom_2, 8, (iDist>>1) );
826
0
          }
827
0
        } // check half bottom
828
0
        if ( iBottom <= sr.bottom ) // check bottom
829
0
        {
830
0
          xTZSearchQueued( rcStruct, iStartX, iBottom, 7, iDist );
831
0
        }
832
0
      } // check border
833
0
    }
834
0
    else // iDist > 8
835
0
    {
836
0
      if ( iTop >= sr.top && iLeft >= sr.left &&
837
0
           iRight <= sr.right && iBottom <= sr.bottom ) // check border
838
0
      {
839
0
        xTZSearchQueued( rcStruct, iStartX, iTop,    0, iDist );
840
0
        xTZSearchQueued( rcStruct, iLeft,   iStartY, 0, iDist );
841
0
        xTZSearchQueued( rcStruct, iRight,  iStartY, 0, iDist );
842
0
        xTZSearchQueued( rcStruct, iStartX, iBottom, 0, iDist );
843
0
        for ( int index = 1; index < 4; index++ )
844
0
        {
845
0
          const int iPosYT = iTop    + ((iDist>>2) * index);
846
0
          const int iPosYB = iBottom - ((iDist>>2) * index);
847
0
          const int iPosXL = iStartX - ((iDist>>2) * index);
848
0
          const int iPosXR = iStartX + ((iDist>>2) * index);
849
0
          xTZSearchQueued( rcStruct, iPosXL, iPosYT, 0, iDist );
850
0
          xTZSearchQueued( rcStruct, iPosXR, iPosYT, 0, iDist );
851
0
          xTZSearchQueued( rcStruct, iPosXL, iPosYB, 0, iDist );
852
0
          xTZSearchQueued( rcStruct, iPosXR, iPosYB, 0, iDist );
853
0
        }
854
0
      }
855
0
      else // check border
856
0
      {
857
0
        if ( iTop >= sr.top ) // check top
858
0
        {
859
0
          xTZSearchQueued( rcStruct, iStartX, iTop, 0, iDist );
860
0
        }
861
0
        if ( iLeft >= sr.left ) // check left
862
0
        {
863
0
          xTZSearchQueued( rcStruct, iLeft, iStartY, 0, iDist );
864
0
        }
865
0
        if ( iRight <= sr.right ) // check right
866
0
        {
867
0
          xTZSearchQueued( rcStruct, iRight, iStartY, 0, iDist );
868
0
        }
869
0
        if ( iBottom <= sr.bottom ) // check bottom
870
0
        {
871
0
          xTZSearchQueued( rcStruct, iStartX, iBottom, 0, iDist );
872
0
        }
873
0
        for ( int index = 1; index < 4; index++ )
874
0
        {
875
0
          const int iPosYT = iTop    + ((iDist>>2) * index);
876
0
          const int iPosYB = iBottom - ((iDist>>2) * index);
877
0
          const int iPosXL = iStartX - ((iDist>>2) * index);
878
0
          const int iPosXR = iStartX + ((iDist>>2) * index);
879
880
0
          if ( iPosYT >= sr.top ) // check top
881
0
          {
882
0
            if ( iPosXL >= sr.left ) // check left
883
0
            {
884
0
              xTZSearchQueued( rcStruct, iPosXL, iPosYT, 0, iDist );
885
0
            }
886
0
            if ( iPosXR <= sr.right ) // check right
887
0
            {
888
0
              xTZSearchQueued( rcStruct, iPosXR, iPosYT, 0, iDist );
889
0
            }
890
0
          } // check top
891
0
          if ( iPosYB <= sr.bottom ) // check bottom
892
0
          {
893
0
            if ( iPosXL >= sr.left ) // check left
894
0
            {
895
0
              xTZSearchQueued( rcStruct, iPosXL, iPosYB, 0, iDist );
896
0
            }
897
0
            if ( iPosXR <= sr.right ) // check right
898
0
            {
899
0
              xTZSearchQueued( rcStruct, iPosXR, iPosYB, 0, iDist );
900
0
            }
901
0
          } // check bottom
902
0
        } // for ...
903
0
      } // check border
904
0
    } // iDist <= 8
905
0
  } // iDist == 1
906
0
  xTZSearchFlush( rcStruct );
907
0
}
908
909
// The stride of the buffers of the fractional search, which hold a block and the extra column of its half-pel positions. At widths 4 and 8 it
910
// is twice the width, so that one filter call on the kernel of the next width can fill block and column (see columnInFirstCall).
911
static inline int fracSearchStride( const int width )
912
0
{
913
0
  return width <= 8 ? 2 * width : width + 1;
914
0
}
915
916
Distortion InterSearch::xPatternRefinement( const CPelBuf* pcPatternKey,
917
                                            Mv baseRefMv,
918
                                            int iFrac, Mv& rcMvFrac,
919
                                            Distortion& uiDistBest,
920
                                            int& patternId,
921
                                            CPelBuf* pattern,
922
                                            bool useAltHpelIf,
923
                                            Distortion centreDistNoMv,
924
                                            Distortion& bestDistNoMv )
925
0
{
926
0
  Distortion  uiDist;
927
0
  uiDistBest = m_pcEncCfg->m_fastSubPel == 1 ? uiDistBest : MAX_DISTORTION;
928
0
  bestDistNoMv = MAX_DISTORTION;
929
0
  uint32_t        uiDirecBest = 0;
930
0
  const int reduceTap = m_pcEncCfg->m_meReduceTap;
931
932
0
  const Pel* piRefPos;
933
0
  int iRefStride = fracSearchStride( pcPatternKey->width );
934
0
  m_pcRdCost->setDistParam( m_cDistParam, *pcPatternKey, m_filteredBlock[0][0][0], iRefStride, m_lumaClpRng.bd, COMP_Y, 0, m_pcEncCfg->m_bUseHADME ? ( m_pcEncCfg->m_fastHad ? 2 : 1 ) : 0 );
935
936
0
  const ClpRng& clpRng = m_lumaClpRng;
937
0
  int width = pattern->width;
938
0
  int height = pattern->height;
939
0
  int srcStride = pattern->stride;
940
941
0
  int intStride = fracSearchStride( width );
942
0
  int dstStride = fracSearchStride( width );
943
  // At widths 4 and 8 the stride has room for the block and its extra column, and one call at the whole stride fills both on the
944
  // kernel of the next width. Wider blocks keep the column as a second call, as a rounded width would leave their kernel.
945
0
  const bool columnInFirstCall = intStride > width + 1;
946
0
  const int  firstCallWidth    = columnInFirstCall ? intStride : width;
947
0
  Pel* intPtr;
948
0
  Pel* dstPtr;
949
0
  int filterSize     = useAltHpelIf ? ( reduceTap >= 1 ? NTAPS_AFFINE : NTAPS_LUMA )
950
0
                                    : ( reduceTap == 1 ? NTAPS_AFFINE
951
0
                                                       : ( reduceTap == 0 ? NTAPS_LUMA : NTAPS_CHROMA ) );
952
0
  int halfFilterSize = ( filterSize >> 1 );
953
0
  const Pel* srcPtr  = pattern->buf - halfFilterSize*srcStride - 1;
954
955
0
  const ChromaFormat chFmt = m_currChromaFormat;
956
957
0
  Distortion distH[ 9 ] = { uiDistBest, uiDistBest, uiDistBest, uiDistBest, uiDistBest, uiDistBest, uiDistBest, uiDistBest, uiDistBest };
958
0
  const int TH = 17, TL = 15, shift = 4;
959
960
0
  const Mv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
961
0
  for (uint32_t i = 0; i < 9; i++)
962
0
  {
963
0
    if( m_pcEncCfg->m_fastSubPel == 1 )
964
0
    {
965
0
      if( s_skipQpelPosition[ patternId ][ i ] )
966
0
      {
967
0
        continue;
968
0
      }
969
970
0
      if( 2 == iFrac )
971
0
      {
972
0
        if ( ( 5 == i && 0 == uiDirecBest ) || ( 7 == i && 1 == uiDirecBest ) || ( 8 == i && ( 1 == uiDirecBest || 3 == uiDirecBest || 5 == uiDirecBest ) ) )
973
0
        {
974
0
          break;
975
0
        }
976
977
0
        if( 0 == i )
978
0
        {
979
          // the integer position needs no interpolation: its SAD reads the reference itself (see piRefPos below)
980
981
0
          m_if.filterHor( COMP_Y, srcPtr, srcStride, m_filteredBlockTmp[ 2 ][ 0 ], intStride, firstCallWidth, height + filterSize, 2 << MV_FRACTIONAL_BITS_DIFF, false, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
982
0
          if( !columnInFirstCall )
983
0
          {
984
0
            m_if.filterHor( COMP_Y, srcPtr + width, srcStride, m_filteredBlockTmp[ 2 ][ 0 ] + width, intStride, 1, height + filterSize, 2 << MV_FRACTIONAL_BITS_DIFF, false, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
985
0
          }
986
0
        }
987
0
        else if( 1 == i )
988
0
        {
989
          // vertical-only position: filtered straight from the reference (isFirst), see xFilterVerFromReference
990
0
          dstPtr = m_filteredBlock[ 2 ][ 0 ][ 0 ];
991
0
          xFilterVerFromReference( pattern, -1, dstPtr, dstStride, height + 1, 2, useAltHpelIf );
992
0
        }
993
0
        else if( 3 == i )
994
0
        {
995
0
          intPtr = m_filteredBlockTmp[ 2 ][ 0 ] + halfFilterSize * intStride;
996
0
          dstPtr = m_filteredBlock[ 0 ][ 2 ][ 0 ];
997
          // The rows follow each other in both buffers, so all of them are one long row. It copies the block and its extra column.
998
0
          m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, intStride * height, 1, 0 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
999
0
        }
1000
0
        else if( 5 == i )
1001
0
        {
1002
0
          intPtr = m_filteredBlockTmp[ 2 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
1003
0
          dstPtr = m_filteredBlock[ 2 ][ 2 ][ 0 ];
1004
0
          m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, firstCallWidth, height + 1, 2 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
1005
0
          if( !columnInFirstCall )
1006
0
          {
1007
0
            m_if.filterVer( COMP_Y, intPtr + width, intStride, dstPtr + width, dstStride, 1, height + 1, 2 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
1008
0
          }
1009
0
        }
1010
0
      }
1011
0
    }
1012
0
    Mv cMvTest = pcMvRefine[ i ];
1013
0
    cMvTest += baseRefMv;
1014
1015
0
    int horVal = cMvTest.hor * iFrac;
1016
0
    int verVal = cMvTest.ver * iFrac;
1017
    // the integer position is the reference itself, with the reference's stride; the others are interpolated blocks
1018
0
    const bool integerPos = ( verVal & 3 ) == 0 && ( horVal & 3 ) == 0;
1019
0
    piRefPos = integerPos ? pattern->buf : m_filteredBlock[verVal & 3][horVal & 3][0];
1020
1021
0
    if ( horVal == 2 && ( verVal & 1 ) == 0 )
1022
0
    {
1023
0
      piRefPos += 1;
1024
0
    }
1025
0
    if ( ( horVal & 1 ) == 0 && verVal == 2 )
1026
0
    {
1027
0
      piRefPos += iRefStride;
1028
0
    }
1029
0
    cMvTest = pcMvRefine[i];
1030
0
    cMvTest += rcMvFrac;
1031
1032
1033
0
    Distortion distNoMv;
1034
0
    if( 0 == i && centreDistNoMv != MAX_DISTORTION )
1035
0
    {
1036
      // the centre is the previous stage's winner: the same block of the same filtered buffer (the quarter-pel
1037
      // up-sampling writes only the quarter positions), measured in full there (a winner never exits early)
1038
0
      distNoMv = centreDistNoMv;
1039
0
    }
1040
0
    else
1041
0
    {
1042
0
      m_cDistParam.cur.buf    = piRefPos;
1043
0
      m_cDistParam.cur.stride = integerPos ? pattern->stride : iRefStride;
1044
0
      distNoMv = m_cDistParam.distFunc( m_cDistParam );
1045
0
    }
1046
0
    uiDist = distNoMv + m_pcRdCost->getCostOfVectorWithPredictor( cMvTest.hor, cMvTest.ver, 0 );
1047
1048
0
    distH[ i ] = uiDist;
1049
0
    if ( uiDist < uiDistBest )
1050
0
    {
1051
0
      uiDistBest   = uiDist;
1052
0
      uiDirecBest  = i;
1053
0
      bestDistNoMv = distNoMv;
1054
0
      m_cDistParam.maximumDistortionForEarlyExit = uiDist;
1055
0
    }
1056
0
  }
1057
1058
0
  rcMvFrac = pcMvRefine[uiDirecBest];
1059
1060
0
  if( m_pcEncCfg->m_fastSubPel == 1 && iFrac == 2 )
1061
0
  {
1062
0
    switch ( uiDirecBest )
1063
0
    {
1064
0
    case 0:
1065
      // hor
1066
0
      distH[ 3 ] <<= shift;
1067
0
      patternId += ( distH[ 3 ] > TH * distH[ 4 ] ? 2 : ( distH[ 3 ] < TL * distH[ 4 ] ? 1 : 0 ) );
1068
      // ver
1069
0
      distH[ 1 ] <<= shift;
1070
0
      patternId += ( distH[ 1 ] > TH * distH[ 2 ] ? 6 : ( distH[ 1 ] < TL * distH[ 2 ] ? 3 : 0 ) );
1071
0
      break;
1072
0
    case 1:
1073
      // hor
1074
0
      distH[ 5 ] <<= shift;
1075
0
      patternId += ( distH[ 5 ] > TH * distH[ 6 ] ? 4 : ( distH[ 5 ] < TL * distH[ 6 ] ? 2 : 0 ) );
1076
      // ver
1077
0
      patternId += ( distH[ 2 ] - distH[ 0 ] > distH[ 0 ] - distH[ 1 ] ? 1 : 0 );
1078
1079
0
      patternId += ( 41 == patternId ? 0 : 8 );
1080
0
      break;
1081
0
    case 2:
1082
      // hor
1083
0
      distH[ 7 ] <<= shift;
1084
0
      patternId += ( distH[ 7 ] > TH * distH[ 8 ] ? 4 : ( distH[ 7 ] < TL * distH[ 8 ] ? 2 : 0 ) );
1085
      // ver
1086
0
      patternId += ( distH[ 1 ] - distH[ 0 ] > distH[ 0 ] - distH[ 2 ] ? 1 : 0 );
1087
1088
0
      patternId += ( 41 == patternId ? 0 : 13 );
1089
0
      break;
1090
0
    case 3:
1091
      // hor
1092
0
      patternId += ( distH[ 4 ] - distH[ 0 ] > distH[ 0 ] - distH[ 3 ] ? 1 : 0 );
1093
      // ver
1094
0
      distH[ 5 ] <<= shift;
1095
0
      patternId += ( distH[ 5 ] > TH * distH[ 7 ] ? 4 : ( distH[ 5 ] < TL * distH[ 7 ] ? 2 : 0 ) );
1096
1097
0
      patternId += ( 41 == patternId ? 0 : 18 );
1098
0
      break;
1099
0
    case 4:
1100
      // hor
1101
0
      patternId += ( distH[ 3 ] - distH[ 0 ] > distH[ 0 ] - distH[ 4 ] ? 1 : 0 );
1102
      // ver
1103
0
      distH[ 6 ] <<= shift;
1104
0
      patternId += ( distH[ 6 ] > TH * distH[ 8 ] ? 4 : ( distH[ 6 ] < TL * distH[ 8 ] ? 2 : 0 ) );
1105
1106
0
      patternId += ( 41 == patternId ? 0 : 23 );
1107
0
      break;
1108
0
    case 5:
1109
      // hor
1110
0
      patternId += ( distH[ 6 ] - distH[ 1 ] > distH[ 1 ] - distH[ 5 ] ? 1 : 0 );
1111
      // ver
1112
0
      patternId += ( distH[ 7 ] - distH[ 3 ] > distH[ 3 ] - distH[ 5 ] ? 2 : 0 );
1113
1114
0
      patternId += ( 41 == patternId ? 0 : 28 );
1115
0
      break;
1116
0
    case 6:
1117
      // hor
1118
0
      patternId += ( distH[ 5 ] - distH[ 1 ] > distH[ 1 ] - distH[ 6 ] ? 1 : 0 );
1119
      // ver
1120
0
      patternId += ( distH[ 8 ] - distH[ 4 ] > distH[ 4 ] - distH[ 6 ] ? 2 : 0 );
1121
1122
0
      patternId += ( 41 == patternId ? 0 : 31 );
1123
0
      break;
1124
0
    case 7:
1125
      // hor
1126
0
      patternId += ( distH[ 8 ] - distH[ 2 ] > distH[ 2 ] - distH[ 7 ] ? 1 : 0 );
1127
      // ver
1128
0
      patternId += ( distH[ 5 ] - distH[ 3 ] > distH[ 3 ] - distH[ 7 ] ? 2 : 0 );
1129
1130
0
      patternId += ( 41 == patternId ? 0 : 34 );
1131
0
      break;
1132
0
    case 8:
1133
      // hor
1134
0
      patternId += ( distH[ 7 ] - distH[ 2 ] > distH[ 2 ] - distH[ 8 ] ? 1 : 0 );
1135
      // ver
1136
0
      patternId += ( distH[ 6 ] - distH[ 4 ] > distH[ 4 ] - distH[ 8 ] ? 2 : 0 );
1137
1138
0
      patternId += ( 41 == patternId ? 0 : 37 );
1139
0
      break;
1140
0
    default:
1141
0
      break;
1142
0
    }
1143
0
  }
1144
1145
0
  return uiDistBest;
1146
0
}
1147
1148
//! search of the best candidate for inter prediction
1149
bool InterSearch::predInterSearch(CodingUnit& cu, Partitioner& partitioner, double& bestCostInter)
1150
0
{
1151
0
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTER_MVD_SEARCH, cu.cs, partitioner.chType );
1152
0
  CodingStructure& cs = *cu.cs;
1153
1154
0
  AMVPInfo     amvp[2];
1155
0
  Mv           cMvSrchRngLT;
1156
0
  Mv           cMvSrchRngRB;
1157
0
  Mv           cMvZero;
1158
0
  Mv           cMv[2];
1159
0
  Mv           cMvBi[2];
1160
0
  Mv           cMvTemp[2][MAX_REF_PICS];
1161
0
  Mv           cMvHevcTemp[2][MAX_REF_PICS];
1162
0
  int          iNumPredDir = cs.slice->isInterP() ? 1 : 2;
1163
1164
0
  Mv           cMvPred[2][MAX_REF_PICS];
1165
1166
0
  Mv           cMvPredBi[2][MAX_REF_PICS];
1167
0
  int          aaiMvpIdxBi[2][MAX_REF_PICS];
1168
1169
0
  int          aaiMvpIdx[2][MAX_REF_PICS];
1170
0
  int          aaiMvpNum[2][MAX_REF_PICS];
1171
1172
0
  AMVPInfo     aacAMVPInfo[2][MAX_REF_PICS];
1173
1174
0
  int          iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
1175
0
  int          iRefIdxBi[2] = { -1, -1 };
1176
1177
0
  uint32_t     uiMbBits[3] = {1, 1, 0};
1178
1179
0
  uint32_t     uiLastMode = 0;
1180
0
  int          iRefStart, iRefEnd;
1181
1182
0
  int          symMode = 0;
1183
1184
0
  int          bestBiPRefIdxL1 = 0;
1185
0
  int          bestBiPMvpL1    = 0;
1186
0
  Distortion   biPDistTemp     = MAX_DISTORTION;
1187
1188
0
  uint8_t      BcwIdx          = (cu.cs->slice->isInterB() ? cu.BcwIdx : BCW_DEFAULT);
1189
0
  bool         enforceBcwPred = false;
1190
1191
  // Loop over Prediction Units
1192
0
  uint32_t     puIdx = 0;
1193
0
  uint32_t     uiLastModeTemp = 0;
1194
0
  Distortion   uiAffineCost = MAX_DISTORTION;
1195
0
  Distortion   uiHevcCost = MAX_DISTORTION;
1196
0
  bool checkAffine = (cu.imv == IMV_OFF);
1197
0
  if (cu.cs->bestParent != nullptr && cu.cs->bestParent->getCU(CH_L,TREE_D) != nullptr && cu.cs->bestParent->getCU(CH_L,TREE_D)->affine == false)
1198
0
  {
1199
0
    m_skipPROF = true;
1200
0
  }
1201
1202
0
  m_encOnly = true;
1203
0
  {
1204
0
    CU::spanMotionInfo( cu );
1205
0
    Distortion   uiCost[2] = { MAX_DISTORTION, MAX_DISTORTION };
1206
0
    Distortion   uiCostBi  =   MAX_DISTORTION;
1207
0
    Distortion   uiCostTemp;
1208
1209
0
    uint32_t         uiBits[3];
1210
0
    uint32_t         uiBitsTemp;
1211
0
    Distortion   bestBiPDist = MAX_DISTORTION;
1212
1213
0
    Distortion   uiCostTempL0[MAX_NUM_REF];
1214
0
    for (int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
1215
0
    {
1216
0
      uiCostTempL0[iNumRef] = MAX_DISTORTION;
1217
0
    }
1218
0
    uint32_t         uiBitsTempL0[MAX_NUM_REF];
1219
1220
0
    Mv           mvValidList1;
1221
0
    int          refIdxValidList1 = 0;
1222
0
    uint32_t         bitsValidList1   = MAX_UINT;
1223
0
    Distortion   costValidList1   = MAX_DISTORTION;
1224
1225
0
    CPelUnitBuf origBuf = static_cast<const CodingStructure*>( cu.cs )->getOrgBuf(); // const overload: no conversion from PelUnitBuf
1226
1227
0
    xGetBlkBits( cs.slice->isInterP(), puIdx, uiLastMode, uiMbBits );
1228
1229
0
    m_pcRdCost->selectMotionLambda();
1230
1231
0
    unsigned imvShift = cu.imv == IMV_HPEL ? 1 : (cu.imv << 1);
1232
1233
    //  Uni-directional prediction
1234
0
    for ( int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
1235
0
    {
1236
0
      RefPicList  refPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1237
0
      for (int iRefIdxTemp = 0; iRefIdxTemp < cs.slice->numRefIdx[ refPicList ]; iRefIdxTemp++)
1238
0
      {
1239
0
        uiBitsTemp = uiMbBits[iRefList];
1240
0
        if ( cs.slice->numRefIdx[ refPicList ] > 1 )
1241
0
        {
1242
0
          uiBitsTemp += iRefIdxTemp+1;
1243
0
          if ( iRefIdxTemp == cs.slice->numRefIdx[ refPicList ]-1 )
1244
0
          {
1245
0
            uiBitsTemp--;
1246
0
          }
1247
0
        }
1248
0
        xEstimateMvPredAMVP( cu, origBuf, refPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], amvp[refPicList], biPDistTemp);
1249
1250
0
        aaiMvpIdx[iRefList][iRefIdxTemp] = cu.mvpIdx[refPicList];
1251
0
        aaiMvpNum[iRefList][iRefIdxTemp] = cu.mvpNum[refPicList];
1252
1253
0
        if(cs.picHeader->mvdL1Zero && iRefList==1 && biPDistTemp < bestBiPDist)
1254
0
        {
1255
0
          bestBiPDist = biPDistTemp;
1256
0
          bestBiPMvpL1 = aaiMvpIdx[iRefList][iRefIdxTemp];
1257
0
          bestBiPRefIdxL1 = iRefIdxTemp;
1258
0
        }
1259
1260
0
        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
1261
1262
0
        if ( m_pcEncCfg->m_bFastMEForGenBLowDelayEnabled && iRefList == 1 )    // list 1
1263
0
        {
1264
0
          if ( cs.slice->list1IdxToList0Idx[ iRefIdxTemp ] >= 0 )
1265
0
          {
1266
0
            cMvTemp[1][iRefIdxTemp] = cMvTemp[0][cs.slice->list1IdxToList0Idx[iRefIdxTemp ]];
1267
0
            uiCostTemp = uiCostTempL0[cs.slice->list1IdxToList0Idx[ iRefIdxTemp ]];
1268
            /*first subtract the bit-rate part of the cost of the other list*/
1269
0
            uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[cs.slice->list1IdxToList0Idx[ iRefIdxTemp ]] );
1270
            /*correct the bit-rate part of the current ref*/
1271
0
            m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
1272
0
            uiBitsTemp += m_pcRdCost->getBitsOfVectorWithPredictor( cMvTemp[1][iRefIdxTemp].hor, cMvTemp[1][iRefIdxTemp].ver, imvShift + MV_FRACTIONAL_BITS_DIFF );
1273
            /*calculate the correct cost*/
1274
0
            uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
1275
0
          }
1276
0
          else
1277
0
          {
1278
0
            xMotionEstimation( cu, origBuf, refPicList, cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, amvp[refPicList] );
1279
0
          }
1280
0
        }
1281
0
        else
1282
0
        {
1283
0
          xMotionEstimation( cu, origBuf, refPicList, cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, amvp[refPicList] );
1284
0
        }
1285
          
1286
0
        if( cs.slice->sps->BCW && cu.BcwIdx == BCW_DEFAULT && cs.slice->isInterB() )
1287
0
        {
1288
0
          m_uniMotions.setReadMode( true, (uint32_t)iRefList, (uint32_t)iRefIdxTemp) ;
1289
0
          m_uniMotions.copyFrom( cMvTemp[iRefList][iRefIdxTemp], uiCostTemp - m_pcRdCost->getCost(uiBitsTemp), (uint32_t)iRefList, (uint32_t)iRefIdxTemp );
1290
0
        }
1291
1292
0
        xCopyAMVPInfo( &amvp[refPicList], &aacAMVPInfo[iRefList][iRefIdxTemp]); // must always be done ( also when AMVP_MODE = AM_NONE )
1293
0
        xCheckBestMVP( refPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], amvp[refPicList], uiBitsTemp, uiCostTemp, cu.imv );
1294
1295
0
        if ( iRefList == 0 )
1296
0
        {
1297
0
          uiCostTempL0[iRefIdxTemp] = uiCostTemp;
1298
0
          uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
1299
0
        }
1300
0
        if ( uiCostTemp < uiCost[iRefList] )
1301
0
        {
1302
0
          uiCost[iRefList] = uiCostTemp;
1303
0
          uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
1304
1305
          // set motion
1306
0
          cMv    [iRefList] = cMvTemp[iRefList][iRefIdxTemp];
1307
0
          iRefIdx[iRefList] = iRefIdxTemp;
1308
0
        }
1309
1310
0
        if ( iRefList == 1 && uiCostTemp < costValidList1 && cs.slice->list1IdxToList0Idx[ iRefIdxTemp ] < 0 )
1311
0
        {
1312
0
          costValidList1 = uiCostTemp;
1313
0
          bitsValidList1 = uiBitsTemp;
1314
1315
          // set motion
1316
0
          mvValidList1     = cMvTemp[iRefList][iRefIdxTemp];
1317
0
          refIdxValidList1 = iRefIdxTemp;
1318
0
        }
1319
0
      }
1320
0
    }
1321
1322
0
    ::memcpy(cMvHevcTemp, cMvTemp, sizeof(cMvTemp));
1323
0
    if (cu.imv == IMV_OFF && (!cu.slice->sps->BCW || BcwIdx == BCW_DEFAULT))
1324
0
    {
1325
0
      m_BlkUniMvInfoBuffer->insertUniMvCands(cu.Y(), &cMvTemp[0][0]);
1326
1327
0
      unsigned idx1, idx2, idx3, idx4;
1328
0
      getAreaIdxNew(cu.Y(), *cs.pcv, idx1, idx2, idx3, idx4);
1329
0
      if( ! m_ReuseUniMv->m_reusedUniMVs[idx1][idx2][idx3][idx4] )
1330
0
      {
1331
0
        m_ReuseUniMv->m_reusedUniMVs[idx1][idx2][idx3][idx4] = new Mv[ 2 * MAX_REF_PICS ];
1332
//          DTRACE( g_trace_ctx, D_TMP, "%d unimv first reuse %d %d %d %d \n", g_trace_ctx->getChannelCounter(D_TMP), idx3,idx4,idx1,idx2 );
1333
0
      }
1334
0
      ::memcpy(m_ReuseUniMv->m_reusedUniMVs[idx1][idx2][idx3][idx4], cMvTemp, 2 * MAX_REF_PICS * sizeof(Mv));
1335
0
    }
1336
0
    if (bestCostInter != MAX_DOUBLE)
1337
0
    {
1338
0
      int L = (cu.slice->TLayer <= 2) ? 0 : (cu.slice->TLayer - 2);
1339
0
      double besCostMerge = bestCostInter;
1340
0
      bestCostInter = (uiCost[0] < uiCost[1]) ? uiCost[0] : uiCost[1];
1341
0
      if ((cu.slice->TLayer > (m_pcEncCfg->m_maxTLayer - (m_pcEncCfg->m_FastInferMerge & 7))) && bestCostInter > MRG_FAST_RATIOMYV[L] * besCostMerge)
1342
0
      {
1343
0
        m_skipPROF = false;
1344
0
        m_encOnly = false;
1345
0
        return true;
1346
0
      }
1347
0
    }
1348
    //  Bi-predictive Motion estimation
1349
0
    if( cs.slice->isInterB() && !CU::isBipredRestriction( cu ) && (cu.slice->checkLDC || BcwIdx == BCW_DEFAULT  || !m_affineModeSelected || m_pcEncCfg->m_BCW != 2 ) )
1350
0
    {
1351
0
      PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTER_MVD_SEARCH_B, &cs, partitioner.chType );
1352
0
      bool doBiPred = true;
1353
0
      cMvBi[0] = cMv[0];
1354
0
      cMvBi[1] = cMv[1];
1355
0
      iRefIdxBi[0] = iRefIdx[0];
1356
0
      iRefIdxBi[1] = iRefIdx[1];
1357
1358
0
      ::memcpy( cMvPredBi,   cMvPred,   sizeof( cMvPred   ) );
1359
0
      ::memcpy( aaiMvpIdxBi, aaiMvpIdx, sizeof( aaiMvpIdx ) );
1360
1361
0
      uint32_t uiMotBits[2];
1362
1363
0
      if(cs.picHeader->mvdL1Zero)
1364
0
      {
1365
        // case: no mvd for L1
1366
        // note: mv = mvp + mvd
1367
        // mv for L1 is equal to mvp(L1) and the mvd search is only performed for L0
1368
0
        xCopyAMVPInfo(&aacAMVPInfo[1][bestBiPRefIdxL1], &amvp[REF_PIC_LIST_1]);
1369
0
        aaiMvpIdxBi[1][bestBiPRefIdxL1] = bestBiPMvpL1;
1370
0
        cMvPredBi  [1][bestBiPRefIdxL1] = amvp[REF_PIC_LIST_1].mvCand[bestBiPMvpL1];
1371
0
        if( m_pcEncCfg->m_ifpLines && !CU::isMvInRangeFPP( cu.ly(), cu.lheight(), cMvPredBi[1][bestBiPRefIdxL1].ver, m_pcEncCfg->m_ifpLines, *cu.cs->pcv ) )
1372
0
        {
1373
          // this mvp cannot be used for mv, skip Bi-pred
1374
0
          uiCostBi = std::numeric_limits<Distortion>::max();
1375
0
          doBiPred = false;
1376
0
        }
1377
1378
0
        if( doBiPred )
1379
0
        {
1380
0
          cMvBi[1] = cMvPredBi[1][bestBiPRefIdxL1];
1381
0
          iRefIdxBi[1] = bestBiPRefIdxL1;
1382
0
          cu.mv[REF_PIC_LIST_1][0] = cMvBi[1];
1383
0
          cu.refIdx[REF_PIC_LIST_1] = iRefIdxBi[1];
1384
0
          cu.mvpIdx[REF_PIC_LIST_1] = bestBiPMvpL1;
1385
0
          PelUnitBuf predBufTmp = m_tmpPredStorage[REF_PIC_LIST_1].getCompactBuf( cu );
1386
0
          xPredOtherListLuma( cu, predBufTmp, REF_PIC_LIST_1 );
1387
1388
0
          uiMotBits[0] = uiBits[0] - uiMbBits[0];
1389
0
          uiMotBits[1] = uiMbBits[1];
1390
1391
0
          if(cs.slice->numRefIdx[REF_PIC_LIST_1] > 1)
1392
0
          {
1393
0
            uiMotBits[1] += bestBiPRefIdxL1 + 1;
1394
0
            if(bestBiPRefIdxL1 == cs.slice->numRefIdx[REF_PIC_LIST_1] - 1)
1395
0
            {
1396
0
              uiMotBits[1]--;
1397
0
            }
1398
0
          }
1399
1400
0
          uiMotBits[1] += m_auiMVPIdxCost[aaiMvpIdxBi[1][bestBiPRefIdxL1]][AMVP_MAX_NUM_CANDS];
1401
1402
0
          uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
1403
1404
0
          cMvTemp[1][bestBiPRefIdxL1] = cMvBi[1];
1405
0
        }
1406
0
      }
1407
0
      else
1408
0
      {
1409
0
        uiMotBits[0] = uiBits[0] - uiMbBits[0];
1410
0
        uiMotBits[1] = uiBits[1] - uiMbBits[1];
1411
0
        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
1412
0
      }
1413
1414
0
      if( doBiPred )
1415
0
      {
1416
        // 4-times iteration (default)
1417
0
        int iNumIter = 4;
1418
1419
        // fast encoder setting: only one iteration
1420
0
        if ( m_pcEncCfg->m_fastInterSearchMode==VVENC_FASTINTERSEARCH_MODE3 || m_pcEncCfg->m_fastInterSearchMode==VVENC_FASTINTERSEARCH_MODE2 || cs.picHeader->mvdL1Zero )
1421
0
        {
1422
0
          iNumIter = 1;
1423
0
        }
1424
1425
0
        enforceBcwPred = (BcwIdx != BCW_DEFAULT);
1426
1427
0
        for ( int iIter = 0; iIter < iNumIter; iIter++ )
1428
0
        {
1429
0
          int         iRefList    = iIter % 2;
1430
1431
0
          if ( m_pcEncCfg->m_fastInterSearchMode==VVENC_FASTINTERSEARCH_MODE3 || m_pcEncCfg->m_fastInterSearchMode==VVENC_FASTINTERSEARCH_MODE2 )
1432
0
          {
1433
0
            if( uiCost[0] <= uiCost[1] )
1434
0
            {
1435
0
              iRefList = 1;
1436
0
            }
1437
0
            else
1438
0
            {
1439
0
              iRefList = 0;
1440
0
            }
1441
0
          }
1442
0
          else if ( iIter == 0 )
1443
0
          {
1444
0
            iRefList = 0;
1445
0
          }
1446
0
          if ( iIter == 0 && !cs.picHeader->mvdL1Zero)
1447
0
          {
1448
0
            cu.mv    [1 - iRefList][0] = cMv    [1 - iRefList];
1449
0
            cu.refIdx[1 - iRefList]    = iRefIdx[1 - iRefList];
1450
1451
0
            PelUnitBuf predBufTmp = m_tmpPredStorage[1 - iRefList].getCompactBuf( cu );
1452
0
            xPredOtherListLuma( cu, predBufTmp, RefPicList(1 - iRefList) );
1453
0
          }
1454
1455
0
          RefPicList  refPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
1456
1457
0
          if(cs.picHeader->mvdL1Zero)
1458
0
          {
1459
0
            iRefList = 0;
1460
0
            refPicList = REF_PIC_LIST_0;
1461
0
          }
1462
1463
0
          bool bChanged = false;
1464
1465
0
          iRefStart = 0;
1466
0
          iRefEnd   = cs.slice->numRefIdx[ refPicList ]-1;
1467
0
          for (int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++)
1468
0
          {
1469
0
            uiBitsTemp = uiMbBits[2] + uiMotBits[1-iRefList];
1470
0
            uiBitsTemp += ( (cs.slice->sps->BCW == true) ? getWeightIdxBits(BcwIdx) : 0 );
1471
0
            if ( cs.slice->numRefIdx[ refPicList ] > 1 )
1472
0
            {
1473
0
              uiBitsTemp += iRefIdxTemp+1;
1474
0
              if ( iRefIdxTemp == cs.slice->numRefIdx[ refPicList ]-1 )
1475
0
              {
1476
0
                uiBitsTemp--;
1477
0
              }
1478
0
            }
1479
0
            uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
1480
0
            if ( cs.slice->biDirPred )
1481
0
            {
1482
0
              uiBitsTemp += 1; // add one bit for symmetrical MVD mode
1483
0
            }
1484
            // call ME
1485
0
            xCopyAMVPInfo(&aacAMVPInfo[iRefList][iRefIdxTemp], &amvp[refPicList] );
1486
0
            xMotionEstimation ( cu, origBuf, refPicList, cMvPredBi[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, amvp[refPicList], true );
1487
0
            xCheckBestMVP( refPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPredBi[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], amvp[refPicList], uiBitsTemp, uiCostTemp, cu.imv);
1488
0
            if ( uiCostTemp < uiCostBi )
1489
0
            {
1490
0
              bChanged = true;
1491
1492
0
              cMvBi[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
1493
0
              iRefIdxBi[iRefList] = iRefIdxTemp;
1494
1495
0
              uiCostBi            = uiCostTemp;
1496
0
              uiMotBits[iRefList] = uiBitsTemp - uiMbBits[2] - uiMotBits[1-iRefList];
1497
0
              uiMotBits[iRefList] -= ( (cs.slice->sps->BCW == true) ? getWeightIdxBits(BcwIdx) : 0 );
1498
0
              uiBits[2]           = uiBitsTemp;
1499
1500
0
              if(iNumIter!=1)
1501
0
              {
1502
                //  Set motion
1503
0
                cu.mv    [refPicList][0] = cMvBi    [iRefList];
1504
0
                cu.refIdx[refPicList]    = iRefIdxBi[iRefList];
1505
1506
0
                PelUnitBuf predBufTmp = m_tmpPredStorage[iRefList].getCompactBuf( cu );
1507
0
                xPredOtherListLuma( cu, predBufTmp, refPicList );
1508
0
              }
1509
0
            }
1510
0
          } // for loop-iRefIdxTemp
1511
1512
0
          if( !bChanged )
1513
0
          {
1514
0
            if ((uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1]) || enforceBcwPred)
1515
0
            {
1516
0
              xCopyAMVPInfo(&aacAMVPInfo[0][iRefIdxBi[0]], &amvp[REF_PIC_LIST_0]);
1517
0
              xCheckBestMVP( REF_PIC_LIST_0, cMvBi[0], cMvPredBi[0][iRefIdxBi[0]], aaiMvpIdxBi[0][iRefIdxBi[0]], amvp[REF_PIC_LIST_0], uiBits[2], uiCostBi, cu.imv);
1518
0
              if(!cs.picHeader->mvdL1Zero)
1519
0
              {
1520
0
                xCopyAMVPInfo(&aacAMVPInfo[1][iRefIdxBi[1]], &amvp[REF_PIC_LIST_1]);
1521
0
                xCheckBestMVP( REF_PIC_LIST_1, cMvBi[1], cMvPredBi[1][iRefIdxBi[1]], aaiMvpIdxBi[1][iRefIdxBi[1]], amvp[REF_PIC_LIST_1], uiBits[2], uiCostBi, cu.imv);
1522
0
              }
1523
0
            }
1524
0
            break;
1525
0
          }
1526
0
        } // for loop-iter
1527
0
      }
1528
1529
      // SMVD
1530
0
      if( cs.slice->biDirPred )
1531
0
      {
1532
0
        double th1 = 1.02;
1533
0
        bool testSME = true;
1534
0
        int numStartCand = m_pcEncCfg->m_SMVD > 1 ? 1 : 5;
1535
0
        Distortion symCost;
1536
0
        Mv cMvPredSym[2];
1537
0
        int mvpIdxSym[2];
1538
1539
0
        int curRefList = REF_PIC_LIST_0;
1540
0
        int tarRefList = 1 - curRefList;
1541
0
        RefPicList eCurRefList = (curRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
1542
0
        RefPicList eTarRefList = (tarRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
1543
0
        int refIdxCur = cs.slice->symRefIdx[ curRefList ];
1544
0
        int refIdxTar = cs.slice->symRefIdx[ tarRefList ];
1545
0
        if( aacAMVPInfo[ curRefList ][ refIdxCur ].mvCand[ 0 ] == aacAMVPInfo[ curRefList ][ refIdxCur ].mvCand[ 1 ] )
1546
0
        {
1547
0
          aacAMVPInfo[ curRefList ][ refIdxCur ].numCand = 1;
1548
0
        }
1549
0
        if( aacAMVPInfo[ tarRefList ][ refIdxTar ].mvCand[ 0 ] == aacAMVPInfo[ tarRefList ][ refIdxTar ].mvCand[ 1 ] )
1550
0
        {
1551
0
          aacAMVPInfo[ tarRefList ][ refIdxTar ].numCand = 1;
1552
0
        }
1553
1554
        // The cost of a candidate pair (i, j) needs the list-A prediction of candidate i with its high-frequency buffer, and
1555
        // the list-B prediction of candidate j. Each is made once: list B first (the last target candidate into the list's
1556
        // usual buffer m_tmpPredStorage, an earlier one into m_symStartPredB), then list A per i.
1557
0
        static_assert( AMVP_MAX_NUM_CANDS == 2, "m_symStartPredB holds the one list-B prediction before the last" );
1558
0
        const int numCandCur = aacAMVPInfo[curRefList][refIdxCur].numCand;
1559
0
        const int numCandTar = aacAMVPInfo[tarRefList][refIdxTar].numCand;
1560
0
        MvField   cCurMvField, cTarMvField;
1561
0
        CPelBuf   predBufB[AMVP_MAX_NUM_CANDS];
1562
0
        for ( int j = 0; j < numCandTar; j++ )
1563
0
        {
1564
          GCC_WARNING_DISABLE_array_bounds // probably a bug in gcc-10 static analyzer: It thinks the indices are -1 and therefore triggers -Werror=array-bounds
1565
0
          cTarMvField.setMvField( aacAMVPInfo[tarRefList][refIdxTar].mvCand[j], refIdxTar );
1566
0
          GCC_WARNING_RESET
1567
0
          if( m_pcEncCfg->m_ifpLines )
1568
0
          {
1569
0
            xCheckAndClipMvToFppLine( cTarMvField.mv, cu.ly(), cu.lheight(), m_pcEncCfg->m_ifpLines, *cu.cs->pcv );
1570
0
          }
1571
0
          PelUnitBuf predStorageB = j + 1 < numCandTar ? m_symStartPredB.getCompactBuf( cu ) : m_tmpPredStorage[tarRefList].getCompactBuf( cu );
1572
0
          predBufB[j]             = xSymPred( cu, eTarRefList, cTarMvField, predStorageB );
1573
0
        }
1574
0
        Distortion costStart = MAX_DISTORTION;
1575
0
        for ( int i = 0; i < numCandCur; i++ )
1576
0
        {
1577
          GCC_WARNING_DISABLE_array_bounds // probably a bug in gcc-10 static analyzer: It thinks the indices are -1 and therefore triggers -Werror=array-bounds
1578
0
          cCurMvField.setMvField( aacAMVPInfo[curRefList][refIdxCur].mvCand[i], refIdxCur );
1579
0
          GCC_WARNING_RESET
1580
0
          if( m_pcEncCfg->m_ifpLines )
1581
0
          {
1582
0
            xCheckAndClipMvToFppLine( cCurMvField.mv, cu.ly(), cu.lheight(), m_pcEncCfg->m_ifpLines, *cu.cs->pcv );
1583
0
          }
1584
0
          PelUnitBuf    predStorageA = m_tmpPredStorage[curRefList].getCompactBuf( cu );
1585
0
          const CPelBuf highFreqA    = xSymHighFreq( cu, origBuf, xSymPred( cu, eCurRefList, cCurMvField, predStorageA ) );
1586
0
          for ( int j = 0; j < numCandTar; j++ )
1587
0
          {
1588
0
            Distortion cost = xSymHadCost( cu, highFreqA, predBufB[j], eTarRefList );
1589
0
            if ( cost < costStart )
1590
0
            {
1591
0
              costStart = cost;
1592
0
              cMvPredSym[curRefList] = aacAMVPInfo[curRefList][refIdxCur].mvCand[i];
1593
0
              cMvPredSym[tarRefList] = aacAMVPInfo[tarRefList][refIdxTar].mvCand[j];
1594
0
              mvpIdxSym[curRefList] = i;
1595
0
              mvpIdxSym[tarRefList] = j;
1596
0
            }
1597
0
          }
1598
0
        }
1599
0
        cCurMvField.mv = cMvPredSym[curRefList];
1600
0
        cTarMvField.mv = cMvPredSym[tarRefList];
1601
1602
0
        m_pcRdCost->setCostScale(0);
1603
0
        Mv pred = cMvPredSym[curRefList];
1604
0
        pred.changeTransPrecInternal2Amvr(cu.imv);
1605
0
        m_pcRdCost->setPredictor(pred);
1606
0
        Mv mv = cCurMvField.mv;
1607
0
        mv.changeTransPrecInternal2Amvr(cu.imv);
1608
0
        uint32_t bits = m_pcRdCost->getBitsOfVectorWithPredictor(mv.hor, mv.ver, 0);
1609
0
        bits += m_auiMVPIdxCost[mvpIdxSym[curRefList]][AMVP_MAX_NUM_CANDS];
1610
0
        bits += m_auiMVPIdxCost[mvpIdxSym[tarRefList]][AMVP_MAX_NUM_CANDS];
1611
0
        costStart += m_pcRdCost->getCost(bits);
1612
1613
0
        std::vector<Mv> symmvdCands;
1614
0
        auto smmvdCandsGen = [&](Mv mvCand, bool mvPrecAdj)
1615
0
        {
1616
0
          if (mvPrecAdj && cu.imv)
1617
0
          {
1618
0
            mvCand.roundTransPrecInternal2Amvr(cu.imv);
1619
0
          }
1620
1621
0
          bool toAddMvCand = true;
1622
0
          for (std::vector<Mv>::iterator pos = symmvdCands.begin(); pos != symmvdCands.end(); pos++)
1623
0
          {
1624
0
            if (*pos == mvCand)
1625
0
            {
1626
0
              toAddMvCand = false;
1627
0
              break;
1628
0
            }
1629
0
          }
1630
1631
0
          if (toAddMvCand)
1632
0
          {
1633
0
            symmvdCands.push_back(mvCand);
1634
0
          }
1635
0
        };
1636
1637
0
        smmvdCandsGen(cMvHevcTemp[curRefList][refIdxCur], false);
1638
0
        smmvdCandsGen(cMvTemp[curRefList][refIdxCur], false);
1639
0
        if (iRefIdxBi[curRefList] == refIdxCur)
1640
0
        {
1641
0
          smmvdCandsGen(cMvBi[curRefList], false);
1642
0
        }
1643
0
        for (int i = 0; i < m_BlkUniMvInfoBuffer->m_uniMvListSize; i++)
1644
0
        {
1645
0
          if( symmvdCands.size() >= numStartCand )
1646
0
          {
1647
0
            break;
1648
0
          }
1649
0
          BlkUniMvInfo* curMvInfo = m_BlkUniMvInfoBuffer->getBlkUniMvInfo(i);
1650
0
          smmvdCandsGen(curMvInfo->uniMvs[curRefList][refIdxCur], true);
1651
0
        }
1652
1653
0
        for (auto mvStart : symmvdCands)
1654
0
        {
1655
0
          bool checked = false; //if it has been checkin in the mvPred.
1656
0
          for (int i = 0; i < aacAMVPInfo[curRefList][refIdxCur].numCand && !checked; i++)
1657
0
          {
1658
0
            checked |= (mvStart == aacAMVPInfo[curRefList][refIdxCur].mvCand[i]);
1659
0
          }
1660
0
          if (checked)
1661
0
          {
1662
0
            continue;
1663
0
          }
1664
1665
0
          Distortion bestCost = costStart;
1666
0
          xSymMvdCheckBestMvp(cu, origBuf, mvStart, (RefPicList)curRefList, aacAMVPInfo, BcwIdx, cMvPredSym, mvpIdxSym, costStart, false);
1667
0
          if (costStart < bestCost)
1668
0
          {
1669
0
            cCurMvField.setMvField(mvStart, refIdxCur);
1670
0
            cTarMvField.setMvField(mvStart.getSymmvdMv(cMvPredSym[curRefList], cMvPredSym[tarRefList]), refIdxTar);
1671
0
          }
1672
0
        }
1673
0
        Mv startPtMv = cCurMvField.mv;
1674
1675
0
        Distortion mvpCost = m_pcRdCost->getCost(m_auiMVPIdxCost[mvpIdxSym[curRefList]][AMVP_MAX_NUM_CANDS] + m_auiMVPIdxCost[mvpIdxSym[tarRefList]][AMVP_MAX_NUM_CANDS]);
1676
0
        symCost = costStart - mvpCost;
1677
1678
        // ME
1679
0
        testSME = m_pcEncCfg->m_SMVD <= 2 || ( symCost < uiCostBi * th1 && uiCostBi < uiCost[ 0 ] && uiCostBi < uiCost[ 1 ] );
1680
0
        if( testSME )
1681
0
        {
1682
0
          xSymMotionEstimation( cu, origBuf, cMvPredSym[ curRefList ], cMvPredSym[ tarRefList ], eCurRefList, cCurMvField, cTarMvField, symCost, BcwIdx );
1683
0
        }
1684
1685
0
        symCost += mvpCost;
1686
1687
0
        if (startPtMv != cCurMvField.mv)
1688
0
        { // if ME change MV, run a final check for best MVP.
1689
0
          xSymMvdCheckBestMvp(cu, origBuf, cCurMvField.mv, (RefPicList)curRefList, aacAMVPInfo, BcwIdx, cMvPredSym, mvpIdxSym, symCost, true);
1690
0
        }
1691
1692
0
        bits = uiMbBits[2];
1693
0
        bits += 1; // add one bit for #symmetrical MVD mode
1694
0
        bits += ( (cs.slice->sps->BCW == true) ? getWeightIdxBits(BcwIdx) : 0 );
1695
0
        symCost += m_pcRdCost->getCost(bits);
1696
0
        cTarMvField.setMvField(cCurMvField.mv.getSymmvdMv(cMvPredSym[curRefList], cMvPredSym[tarRefList]), refIdxTar);
1697
1698
        // save results
1699
0
        if ( symCost < uiCostBi  
1700
0
          && ( !m_pcEncCfg->m_ifpLines || 
1701
0
          ( CU::isMvInRangeFPP( cu.ly(), cu.lheight(), cCurMvField.mv.ver, m_pcEncCfg->m_ifpLines, *cu.cs->pcv ) &&
1702
0
            CU::isMvInRangeFPP( cu.ly(), cu.lheight(), cTarMvField.mv.ver, m_pcEncCfg->m_ifpLines, *cu.cs->pcv ) ) )          
1703
0
          )
1704
0
        {
1705
0
          uiCostBi = symCost;
1706
0
          symMode = 1 + curRefList;
1707
1708
0
          cMvBi[curRefList] = cCurMvField.mv;
1709
0
          iRefIdxBi[curRefList] = cCurMvField.refIdx;
1710
0
          aaiMvpIdxBi[curRefList][cCurMvField.refIdx] = mvpIdxSym[curRefList];
1711
0
          cMvPredBi[curRefList][iRefIdxBi[curRefList]] = cMvPredSym[curRefList];
1712
1713
0
          cMvBi[tarRefList] = cTarMvField.mv;
1714
0
          iRefIdxBi[tarRefList] = cTarMvField.refIdx;
1715
0
          aaiMvpIdxBi[tarRefList][cTarMvField.refIdx] = mvpIdxSym[tarRefList];
1716
0
          cMvPredBi[tarRefList][iRefIdxBi[tarRefList]] = cMvPredSym[tarRefList];
1717
0
        }
1718
0
      }
1719
0
    } // if (B_SLICE)
1720
1721
      //  Clear Motion Field
1722
0
    cu.mv [REF_PIC_LIST_0][0] = Mv();
1723
0
    cu.mv [REF_PIC_LIST_1][0] = Mv();
1724
0
    cu.mvd[REF_PIC_LIST_0][0] = cMvZero;
1725
0
    cu.mvd[REF_PIC_LIST_1][0] = cMvZero;
1726
0
    cu.refIdx[REF_PIC_LIST_0] = NOT_VALID;
1727
0
    cu.refIdx[REF_PIC_LIST_1] = NOT_VALID;
1728
0
    cu.mvpIdx[REF_PIC_LIST_0] = NOT_VALID;
1729
0
    cu.mvpIdx[REF_PIC_LIST_1] = NOT_VALID;
1730
0
    cu.mvpNum[REF_PIC_LIST_0] = NOT_VALID;
1731
0
    cu.mvpNum[REF_PIC_LIST_1] = NOT_VALID;
1732
1733
    // Set Motion Field
1734
0
    cMv    [1] = mvValidList1;
1735
0
    iRefIdx[1] = refIdxValidList1;
1736
0
    uiBits [1] = bitsValidList1;
1737
0
    uiCost [1] = costValidList1;
1738
0
    if( enforceBcwPred )
1739
0
    {
1740
0
      uiCost[0] = uiCost[1] = MAX_UINT;
1741
0
    }
1742
1743
0
    uiLastModeTemp = uiLastMode;
1744
0
    if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1])
1745
0
    {
1746
0
      bestCostInter = uiCostBi;
1747
0
      uiLastMode = 2;
1748
0
      cu.mv [REF_PIC_LIST_0][0] = cMvBi[0];
1749
0
      cu.mv [REF_PIC_LIST_1][0] = cMvBi[1];
1750
0
      cu.mvd[REF_PIC_LIST_0][0] = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
1751
0
      cu.mvd[REF_PIC_LIST_1][0] = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
1752
0
      cu.refIdx[REF_PIC_LIST_0] = iRefIdxBi[0];
1753
0
      cu.refIdx[REF_PIC_LIST_1] = iRefIdxBi[1];
1754
0
      cu.mvpIdx[REF_PIC_LIST_0] = aaiMvpIdxBi[0][iRefIdxBi[0]];
1755
0
      cu.mvpIdx[REF_PIC_LIST_1] = aaiMvpIdxBi[1][iRefIdxBi[1]];
1756
0
      cu.mvpNum[REF_PIC_LIST_0] = aaiMvpNum[0][iRefIdxBi[0]];
1757
0
      cu.mvpNum[REF_PIC_LIST_1] = aaiMvpNum[1][iRefIdxBi[1]];
1758
0
      cu.interDir = 3;
1759
1760
0
      cu.smvdMode = symMode;
1761
0
    }
1762
0
    else if ( uiCost[0] <= uiCost[1] )
1763
0
    {
1764
0
      bestCostInter = uiCost[0];
1765
0
      uiLastMode = 0;
1766
0
      cu.mv [REF_PIC_LIST_0][0] = cMv[0];
1767
0
      cu.mvd[REF_PIC_LIST_0][0] = cMv[0] - cMvPred[0][iRefIdx[0]];
1768
0
      cu.refIdx[REF_PIC_LIST_0] = iRefIdx[0];
1769
0
      cu.mvpIdx[REF_PIC_LIST_0] = aaiMvpIdx[0][iRefIdx[0]];
1770
0
      cu.mvpNum[REF_PIC_LIST_0] = aaiMvpNum[0][iRefIdx[0]];
1771
0
      cu.interDir = 1;
1772
0
    }
1773
0
    else
1774
0
    {
1775
0
      bestCostInter = uiCost[1];
1776
0
      uiLastMode = 1;
1777
0
      cu.mv [REF_PIC_LIST_1][0] = cMv[1];
1778
0
      cu.mvd[REF_PIC_LIST_1][0] = cMv[1] - cMvPred[1][iRefIdx[1]];
1779
0
      cu.refIdx[REF_PIC_LIST_1] = iRefIdx[1];
1780
0
      cu.mvpIdx[REF_PIC_LIST_1] = aaiMvpIdx[1][iRefIdx[1]];
1781
0
      cu.mvpNum[REF_PIC_LIST_1] = aaiMvpNum[1][iRefIdx[1]];
1782
0
      cu.interDir = 2;
1783
0
    }
1784
1785
0
    if( BcwIdx != BCW_DEFAULT )
1786
0
    {
1787
0
      cu.BcwIdx = BCW_DEFAULT; // Reset to default for the Non-NormalMC modes.
1788
0
    }
1789
0
    uiHevcCost = (uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1]) ? uiCostBi : ((uiCost[0] <= uiCost[1]) ? uiCost[0] : uiCost[1]);
1790
0
    if (m_pcEncCfg->m_Affine > 2)
1791
0
    {
1792
0
      if (cu.slice->TLayer > 3)
1793
0
      {
1794
0
        checkAffine = false;
1795
0
      }
1796
0
      else
1797
0
      {
1798
0
        if( m_pcEncCfg->m_Affine >= 4 && cu.slice->TLayer >= 2 )
1799
0
        {
1800
0
          checkAffine = m_modeCtrl->comprCUCtx->bestCU ? (checkAffine && m_modeCtrl->comprCUCtx->bestCU->affine) : checkAffine;
1801
0
        }
1802
0
      }
1803
0
    }
1804
0
    if( checkAffine && cu.Y().width > 8 && cu.Y().height > 8 && m_pcEncCfg->m_Affine > 0 )
1805
0
    {
1806
      // Based on:
1807
      // H. Pejman*, S. Coulombe*, C. Vazquez*, M. Jamali° and A. Vakili°
1808
      // *École de technologie supérieure, °Summit Tech Multimedia
1809
      // "An Adjustable Fast Decision Method for Affine Motion Estimation in VVC,"
1810
      // ICIP, Kuala Lumpur, Malaysia, 2023, pp. 2695-2699, doi: 10.1109/ICIP49359.2023.10222750.
1811
      // https://ieeexplore.ieee.org/document/10222750
1812
1813
0
      static const double affine_thr_coffs[3] = { 2.534229853866437, 0.05173246 ,0.87650414 };
1814
0
      static const double affine_thr_param[5] = { 1, 1, 1, 1.3, 2.3 }; // TODO: Adapt if extending m_Affine range!
1815
0
      const int qp         = cu.qp;
1816
0
      const int blk_area   = cu.Y().area();
1817
0
      const double threshold  = affine_thr_param[m_pcEncCfg->m_Affine - 1];
1818
1819
      //Multiple linear regression (MLR):
1820
      //Y = b0 + b1*(QP) + b2*(LOG2(BLK_AREA))
1821
0
      double log_affine_thr =
1822
0
        affine_thr_coffs[0] +
1823
0
        qp * affine_thr_coffs[1] +
1824
0
        log2(blk_area) * affine_thr_coffs[2];
1825
1826
      //log_affine_thr is LOG 2 of estimated thr
1827
0
      double affine_thr = pow(2, log_affine_thr) * threshold;
1828
1829
0
      double scaled_uiHevcCost = (double)uiHevcCost;
1830
1831
      //The trained coefficients are based on the cost of internal 10 BitDepth. So, the cost should be scaled if the internal BitDepth is not 10.
1832
0
      if (m_pcEncCfg->m_internalBitDepth[0] !=10)
1833
0
      {
1834
        //Based on the CTC documnet to convert 8 bit to 10 bit video or vice versa, the VTM only multiply (8 to 10 bits) or divide (10 to 8 bits) pixel values to 4.
1835
        //In this case, the cost values are approximately scaled by 4.
1836
        //The trained data acquired from internal 10 bit data. So, if internal bit depth is 8, the conversion into 10-bit cost can be done as follows:
1837
0
        scaled_uiHevcCost = uiHevcCost * (pow(2.0, 10-m_pcEncCfg->m_internalBitDepth[0]));
1838
0
      }
1839
0
      if( scaled_uiHevcCost < affine_thr )
1840
0
      {
1841
0
        checkAffine = false;
1842
0
      }
1843
0
    }
1844
0
    if (cu.Y().width > 8 && cu.Y().height > 8 && cu.slice->sps->Affine && checkAffine)
1845
0
    {
1846
0
      PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTER_MVD_SEARCH_AFFINE, &cs, partitioner.chType );
1847
0
      m_hevcCost = uiHevcCost;
1848
      // save normal hevc result
1849
0
      uint32_t uiMRGIndex = cu.mergeIdx;
1850
0
      bool bMergeFlag = cu.mergeFlag;
1851
0
      uint32_t uiInterDir = cu.interDir;
1852
0
      int  iSymMode = cu.smvdMode;
1853
1854
0
      Mv cMvd[2];
1855
0
      uint32_t uiMvpIdx[2], uiMvpNum[2];
1856
0
      uiMvpIdx[0] = cu.mvpIdx[REF_PIC_LIST_0];
1857
0
      uiMvpIdx[1] = cu.mvpIdx[REF_PIC_LIST_1];
1858
0
      uiMvpNum[0] = cu.mvpNum[REF_PIC_LIST_0];
1859
0
      uiMvpNum[1] = cu.mvpNum[REF_PIC_LIST_1];
1860
0
      cMvd[0] = cu.mvd[REF_PIC_LIST_0][0];
1861
0
      cMvd[1] = cu.mvd[REF_PIC_LIST_1][0];
1862
1863
0
      MvField cHevcMvField[2];
1864
0
      cHevcMvField[0].setMvField(cu.mv[REF_PIC_LIST_0][0], cu.refIdx[REF_PIC_LIST_0]);
1865
0
      cHevcMvField[1].setMvField(cu.mv[REF_PIC_LIST_1][0], cu.refIdx[REF_PIC_LIST_1]);
1866
1867
      // do affine ME & Merge
1868
0
      cu.affineType = AFFINEMODEL_4PARAM;
1869
0
      Mv acMvAffine4Para[2][MAX_REF_PICS][3];
1870
0
      int refIdx4Para[2] = { -1, -1 };
1871
1872
0
      xPredAffineInterSearch(cu, origBuf, puIdx, uiLastModeTemp, uiAffineCost, cMvHevcTemp, acMvAffine4Para, refIdx4Para, BcwIdx, enforceBcwPred, (cs.slice->sps->BCW == true) ? getWeightIdxBits(BcwIdx) : 0 );
1873
1874
0
      if (cu.imv == IMV_OFF)
1875
0
      {
1876
0
        storeAffineMotion(cu.mv, cu.refIdx, AFFINEMODEL_4PARAM, BcwIdx);
1877
0
      }
1878
0
      if (cu.slice->sps->AffineType && uiAffineCost != MAX_DISTORTION)
1879
0
      {
1880
0
        if (uiAffineCost < uiHevcCost * 1.05) ///< condition for 6 parameter affine ME
1881
0
        {
1882
          // save 4 parameter results
1883
0
          Mv bestMv[2][3], bestMvd[2][3];
1884
0
          int bestMvpIdx[2], bestMvpNum[2], bestRefIdx[2];
1885
0
          uint8_t bestInterDir;
1886
1887
0
          bestInterDir = cu.interDir;
1888
0
          bestRefIdx[0] = cu.refIdx[0];
1889
0
          bestRefIdx[1] = cu.refIdx[1];
1890
0
          bestMvpIdx[0] = cu.mvpIdx[0];
1891
0
          bestMvpIdx[1] = cu.mvpIdx[1];
1892
0
          bestMvpNum[0] = cu.mvpNum[0];
1893
0
          bestMvpNum[1] = cu.mvpNum[1];
1894
1895
0
          for (int refList = 0; refList < 2; refList++)
1896
0
          {
1897
0
            bestMv[refList][0] = cu.mv[refList][0];
1898
0
            bestMv[refList][1] = cu.mv[refList][1];
1899
0
            bestMv[refList][2] = cu.mv[refList][2];
1900
0
            bestMvd[refList][0] = cu.mvd[refList][0];
1901
0
            bestMvd[refList][1] = cu.mvd[refList][1];
1902
0
            bestMvd[refList][2] = cu.mvd[refList][2];
1903
0
          }
1904
1905
0
          refIdx4Para[0] = bestRefIdx[0];
1906
0
          refIdx4Para[1] = bestRefIdx[1];
1907
1908
0
          Distortion uiAffine6Cost = MAX_DISTORTION;
1909
0
          cu.affineType = AFFINEMODEL_6PARAM;
1910
0
          xPredAffineInterSearch(cu, origBuf, puIdx, uiLastModeTemp, uiAffine6Cost, cMvHevcTemp, acMvAffine4Para, refIdx4Para, BcwIdx, enforceBcwPred, (cs.slice->sps->BCW == true) ? getWeightIdxBits(BcwIdx) : 0 );
1911
1912
0
          if (cu.imv == IMV_OFF)
1913
0
          {
1914
0
            storeAffineMotion(cu.mv, cu.refIdx, AFFINEMODEL_6PARAM, BcwIdx);
1915
0
          }
1916
1917
          // reset to 4 parameter affine inter mode
1918
0
          if (uiAffineCost <= uiAffine6Cost)
1919
0
          {
1920
0
            cu.affineType = AFFINEMODEL_4PARAM;
1921
0
            cu.interDir = bestInterDir;
1922
0
            cu.refIdx[0] = bestRefIdx[0];
1923
0
            cu.refIdx[1] = bestRefIdx[1];
1924
0
            cu.mvpIdx[0] = bestMvpIdx[0];
1925
0
            cu.mvpIdx[1] = bestMvpIdx[1];
1926
0
            cu.mvpNum[0] = bestMvpNum[0];
1927
0
            cu.mvpNum[1] = bestMvpNum[1];
1928
1929
0
            for (int verIdx = 0; verIdx < 3; verIdx++)
1930
0
            {
1931
0
              cu.mvd[REF_PIC_LIST_0][verIdx] = bestMvd[0][verIdx];
1932
0
              cu.mvd[REF_PIC_LIST_1][verIdx] = bestMvd[1][verIdx];
1933
0
            }
1934
1935
0
            CU::setAllAffineMv(cu, bestMv[0][0], bestMv[0][1], bestMv[0][2], REF_PIC_LIST_0);
1936
0
            CU::setAllAffineMv(cu, bestMv[1][0], bestMv[1][1], bestMv[1][2], REF_PIC_LIST_1);
1937
0
          }
1938
0
          else
1939
0
          {
1940
0
            uiAffineCost = uiAffine6Cost;
1941
0
          }
1942
0
        }
1943
1944
0
        uiAffineCost += m_pcRdCost->getCost(1); // add one bit for affine_type
1945
0
      }
1946
1947
0
      if (uiHevcCost <= uiAffineCost)
1948
0
      {
1949
        // set hevc me result
1950
0
        cu.affine = false;
1951
0
        cu.mergeFlag = bMergeFlag;
1952
0
        cu.mergeIdx = uiMRGIndex;
1953
0
        cu.interDir = uiInterDir;
1954
0
        cu.smvdMode = iSymMode;
1955
0
        cu.mv[REF_PIC_LIST_0][0]  = cHevcMvField[0].mv;
1956
0
        cu.refIdx[REF_PIC_LIST_0] = cHevcMvField[0].refIdx;
1957
0
        cu.mv[REF_PIC_LIST_1][0]  = cHevcMvField[1].mv;
1958
0
        cu.refIdx[REF_PIC_LIST_1] = cHevcMvField[1].refIdx;
1959
0
        cu.mvpIdx[REF_PIC_LIST_0] = uiMvpIdx[0];
1960
0
        cu.mvpIdx[REF_PIC_LIST_1] = uiMvpIdx[1];
1961
0
        cu.mvpNum[REF_PIC_LIST_0] = uiMvpNum[0];
1962
0
        cu.mvpNum[REF_PIC_LIST_1] = uiMvpNum[1];
1963
0
        cu.mvd[REF_PIC_LIST_0][0] = cMvd[0];
1964
0
        cu.mvd[REF_PIC_LIST_1][0] = cMvd[1];
1965
0
      }
1966
0
      else
1967
0
      {
1968
0
        cu.smvdMode = 0;
1969
0
        CHECK(!cu.affine, "Wrong.");
1970
0
        uiLastMode = uiLastModeTemp;
1971
0
      }
1972
0
    }
1973
1974
0
    if( cu.interDir == 3 && !cu.mergeFlag )
1975
0
    {
1976
0
      if (BcwIdx != BCW_DEFAULT)
1977
0
      {
1978
0
        cu.BcwIdx = BcwIdx;
1979
0
      }
1980
0
    }
1981
1982
0
    CU::spanMotionInfo( cu );
1983
1984
0
    m_skipPROF = false;
1985
0
    m_encOnly  = false;
1986
    //  MC
1987
0
    PelUnitBuf predBuf = cu.cs->getPredBuf();
1988
0
    motionCompensation( cu, predBuf, REF_PIC_LIST_X );
1989
0
    puIdx++;
1990
0
  }
1991
1992
0
  return false;
1993
0
}
1994
1995
// AMVP
1996
void InterSearch::xEstimateMvPredAMVP( CodingUnit& cu, CPelUnitBuf& origBuf, RefPicList refPicList, int iRefIdx, Mv& rcMvPred, AMVPInfo& rAMVPInfo, Distortion& distBiP )
1997
0
{
1998
0
  Mv         cBestMv;
1999
0
  int        iBestIdx   = 0;
2000
0
  Distortion uiBestCost = MAX_DISTORTION;
2001
0
  int        i;
2002
2003
0
  AMVPInfo*  pcAMVPInfo = &rAMVPInfo;
2004
2005
0
  AmvpResult& known = m_amvpResults[cu.imv][refPicList][iRefIdx];
2006
0
  if( known.modeTestId == m_modeTestId )
2007
0
  {
2008
0
    rAMVPInfo             = known.info;
2009
0
    rcMvPred              = known.mvPred;
2010
0
    distBiP               = known.dist;
2011
0
    cu.mvpIdx[refPicList] = known.mvpIdx;
2012
0
    cu.mvpNum[refPicList] = known.info.numCand;
2013
0
    return;
2014
0
  }
2015
2016
  // Fill the MV Candidates
2017
0
  CU::fillMvpCand( cu, refPicList, iRefIdx, *pcAMVPInfo );
2018
2019
  // initialize Mvp index & Mvp
2020
0
  iBestIdx = 0;
2021
0
  cBestMv  = pcAMVPInfo->mvCand[0];
2022
2023
0
  PelUnitBuf predBuf = m_tmpStorageLCU.getCompactBuf( cu );
2024
2025
  //-- Check Minimum Cost.
2026
0
  for( i = 0 ; i < pcAMVPInfo->numCand; i++)
2027
0
  {
2028
0
    Mv mvCand = pcAMVPInfo->mvCand[i];
2029
0
    if( m_pcEncCfg->m_ifpLines )
2030
0
      xClipMvSearch( mvCand, cu.lumaPos(), cu.lumaSize(),*cu.cs->pcv, true );
2031
2032
0
    Distortion uiTmpCost = xGetTemplateCost( cu, origBuf, predBuf, mvCand, i, AMVP_MAX_NUM_CANDS, refPicList, iRefIdx );
2033
0
    if( uiBestCost > uiTmpCost )
2034
0
    {
2035
0
      uiBestCost  = uiTmpCost;
2036
0
      cBestMv     = pcAMVPInfo->mvCand[i];
2037
0
      iBestIdx    = i;
2038
0
      distBiP     = uiTmpCost;
2039
0
    }
2040
0
  }
2041
2042
  // Setting Best MVP
2043
0
  rcMvPred = cBestMv;
2044
0
  cu.mvpIdx[refPicList] = iBestIdx;
2045
0
  cu.mvpNum[refPicList] = pcAMVPInfo->numCand;
2046
2047
0
  known.modeTestId = m_modeTestId;
2048
0
  known.info       = rAMVPInfo;
2049
0
  known.mvPred     = rcMvPred;
2050
0
  known.dist       = distBiP;
2051
0
  known.mvpIdx     = iBestIdx;
2052
2053
0
  return;
2054
0
}
2055
2056
uint32_t InterSearch::xGetMvpIdxBits(int iIdx, int iNum)
2057
17.1k
{
2058
17.1k
  CHECK(iIdx < 0 || iNum < 0 || iIdx >= iNum, "Invalid parameters");
2059
2060
17.1k
  if (iNum == 1)
2061
5.72k
  {
2062
5.72k
    return 0;
2063
5.72k
  }
2064
2065
11.4k
  uint32_t uiLength = 1;
2066
11.4k
  int iTemp = iIdx;
2067
11.4k
  if ( iTemp == 0 )
2068
5.72k
  {
2069
5.72k
    return uiLength;
2070
5.72k
  }
2071
2072
5.72k
  bool bCodeLast = ( iNum-1 > iTemp );
2073
2074
5.72k
  uiLength += (iTemp-1);
2075
2076
5.72k
  if( bCodeLast )
2077
0
  {
2078
0
    uiLength++;
2079
0
  }
2080
2081
5.72k
  return uiLength;
2082
11.4k
}
2083
2084
void InterSearch::xGetBlkBits( bool bPSlice, int iPartIdx, uint32_t uiLastMode, uint32_t uiBlkBit[3])
2085
0
{
2086
0
  uiBlkBit[0] = (! bPSlice) ? 3 : 1;
2087
0
  uiBlkBit[1] = 3;
2088
0
  uiBlkBit[2] = 5;
2089
0
}
2090
2091
void InterSearch::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
2092
0
{
2093
0
  pDst->numCand = pSrc->numCand;
2094
0
  for (int i = 0; i < pSrc->numCand; i++)
2095
0
  {
2096
0
    pDst->mvCand[i] = pSrc->mvCand[i];
2097
0
  }
2098
0
}
2099
2100
void InterSearch::xCheckBestMVP ( RefPicList refPicList, const Mv& cMv, Mv& rcMvPred, int& riMVPIdx, AMVPInfo& amvpInfo, uint32_t& ruiBits, Distortion& ruiCost, const uint8_t imv )
2101
0
{
2102
0
  if ( imv > 0 && imv < 3 )
2103
0
  {
2104
0
    return;
2105
0
  }
2106
2107
0
  AMVPInfo* pcAMVPInfo = &amvpInfo;
2108
2109
0
  CHECK(pcAMVPInfo->mvCand[riMVPIdx] != rcMvPred, "Invalid MV prediction candidate");
2110
2111
0
  if (pcAMVPInfo->numCand < 2)
2112
0
  {
2113
0
    return;
2114
0
  }
2115
2116
0
  m_pcRdCost->setCostScale ( 0    );
2117
2118
0
  int iBestMVPIdx = riMVPIdx;
2119
2120
0
  Mv pred = rcMvPred;
2121
0
  pred.changeTransPrecInternal2Amvr(imv);
2122
0
  m_pcRdCost->setPredictor( pred );
2123
0
  Mv mv = cMv;
2124
0
  mv.changeTransPrecInternal2Amvr(imv);
2125
0
  int iOrgMvBits = m_pcRdCost->getBitsOfVectorWithPredictor(mv.hor, mv.ver, 0);
2126
0
  iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
2127
0
  int iBestMvBits = iOrgMvBits;
2128
2129
0
  for (int iMVPIdx = 0; iMVPIdx < pcAMVPInfo->numCand; iMVPIdx++)
2130
0
  {
2131
0
    if (iMVPIdx == riMVPIdx)
2132
0
    {
2133
0
      continue;
2134
0
    }
2135
2136
0
    pred = pcAMVPInfo->mvCand[iMVPIdx];
2137
0
    pred.changeTransPrecInternal2Amvr(imv);
2138
0
    m_pcRdCost->setPredictor( pred );
2139
0
    int iMvBits = m_pcRdCost->getBitsOfVectorWithPredictor(mv.hor, mv.ver, 0);
2140
0
    iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
2141
2142
0
    if (iMvBits < iBestMvBits)
2143
0
    {
2144
0
      iBestMvBits = iMvBits;
2145
0
      iBestMVPIdx = iMVPIdx;
2146
0
    }
2147
0
  }
2148
2149
0
  if (iBestMVPIdx != riMVPIdx)  //if changed
2150
0
  {
2151
0
    rcMvPred = pcAMVPInfo->mvCand[iBestMVPIdx];
2152
2153
0
    riMVPIdx = iBestMVPIdx;
2154
0
    uint32_t uiOrgBits = ruiBits;
2155
0
    ruiBits = uiOrgBits - iOrgMvBits + iBestMvBits;
2156
0
    ruiCost = (ruiCost - m_pcRdCost->getCost( uiOrgBits ))  + m_pcRdCost->getCost( ruiBits );
2157
0
  }
2158
0
}
2159
2160
2161
Distortion InterSearch::xGetTemplateCost( const CodingUnit& cu,
2162
                                          CPelUnitBuf& origBuf,
2163
                                          PelUnitBuf&  predBuf,
2164
                                          Mv           cMvCand,
2165
                                          int          iMVPIdx,
2166
                                          int          iMVPNum,
2167
                                          RefPicList   refPicList,
2168
                                          int          iRefIdx
2169
)
2170
0
{
2171
0
  Distortion uiCost = MAX_DISTORTION;
2172
2173
0
  const Picture* picRef = cu.slice->getRefPic( refPicList, iRefIdx );
2174
0
  clipMv( cMvCand, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv );
2175
2176
  // prediction pattern
2177
0
  const CPelBuf pred = xPredLumaReadOnly( cu, picRef, cMvCand, predBuf );
2178
2179
  // calc distortion
2180
2181
0
  uiCost = m_pcRdCost->getDistPart(origBuf.Y(), pred, cu.cs->sps->bitDepths[ CH_L ], COMP_Y, DF_SAD);
2182
0
  uiCost += m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
2183
2184
0
  return uiCost;
2185
0
}
2186
2187
void InterSearch::xMotionEstimation(CodingUnit& cu, CPelUnitBuf& origBuf, RefPicList refPicList, Mv& rcMvPred, int iRefIdxPred, Mv& rcMv, int& riMVPIdx, uint32_t& ruiBits, Distortion& ruiCost, const AMVPInfo& amvpInfo, bool bBi)
2188
0
{
2189
0
  if( cu.cs->sps->BCW && cu.BcwIdx != BCW_DEFAULT && !bBi && xReadBufferedUniMv( cu, refPicList, iRefIdxPred, rcMvPred, rcMv, ruiBits, ruiCost ) )
2190
0
  {
2191
0
    return;
2192
0
  }
2193
2194
0
  Mv cMvHalf, cMvQter;
2195
2196
0
  CHECK(refPicList >= MAX_NUM_REF_LIST_ADAPT_SR || iRefIdxPred>=int(MAX_IDX_ADAPT_SR), "Invalid reference picture list");
2197
0
  m_iSearchRange = m_aaiAdaptSR[refPicList][iRefIdxPred];
2198
2199
0
  int    iSrchRng   = (bBi ? m_bipredSearchRange : m_iSearchRange);
2200
0
  double fWeight    = 1.0;
2201
2202
  //  Search key pattern initialization
2203
0
  CPelBuf  tmpPattern   = origBuf.Y();
2204
2205
0
  if(bBi) // Bi-predictive ME
2206
0
  {
2207
0
    PelUnitBuf  origBufTmp = m_tmpStorageLCU.getCompactBuf( cu );
2208
    // NOTE: Other buf contains predicted signal from another direction
2209
0
    PelUnitBuf otherBuf = m_tmpPredStorage[1 - (int)refPicList].getCompactBuf( cu );
2210
0
    origBufTmp.removeHighFreq( origBuf, otherBuf, m_pcEncCfg->m_bClipForBiPredMeEnabled, cu.slice->clpRngs );
2211
   
2212
0
    tmpPattern     = origBufTmp.Y();
2213
0
    fWeight        = xGetMEDistortionWeight( cu.BcwIdx, refPicList );
2214
0
  }
2215
2216
0
  CPelBuf* pcPatternKey = &tmpPattern;
2217
2218
0
  m_lumaClpRng = cu.cs->slice->clpRngs[ COMP_Y ];
2219
2220
0
  const Picture* refPic = cu.slice->getRefPic(refPicList, iRefIdxPred);
2221
0
  CPelBuf buf = refPic->getRecoBuf(cu.blocks[COMP_Y]);
2222
2223
0
  TZSearchStruct cStruct;
2224
0
  cStruct.pcPatternKey  = pcPatternKey;
2225
0
  cStruct.iRefStride    = buf.stride;
2226
0
  cStruct.piRefY        = buf.buf;
2227
0
  cStruct.imvShift      = cu.imv == IMV_HPEL ? 1 : (cu.imv << 1);
2228
0
  cStruct.useAltHpelIf  = cu.imv == IMV_HPEL;
2229
0
  cStruct.zeroMV        = false;
2230
0
  cStruct.uiBestSad     = MAX_DISTORTION;
2231
2232
2233
0
  CodedCUInfo &relatedCU = m_modeCtrl->getBlkInfo( cu );
2234
2235
0
  bool bQTBTMV = false;
2236
0
  Mv cIntMv;
2237
0
  if( !bBi )
2238
0
  {
2239
0
    bool bValid = relatedCU.getMv( refPicList, iRefIdxPred, cIntMv );
2240
0
    if( bValid )
2241
0
    {
2242
0
      bQTBTMV = true;
2243
0
      cIntMv.changePrecision( MV_PRECISION_INT, MV_PRECISION_INTERNAL);
2244
0
    }
2245
0
  }
2246
2247
0
  Mv predQuarter = rcMvPred;
2248
0
  predQuarter.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_QUARTER);
2249
0
  m_pcRdCost->setPredictor( predQuarter );
2250
0
  m_pcRdCost->setCostScale(2);
2251
2252
  //  Do integer search
2253
0
  if( m_motionEstimationSearchMethod == VVENC_MESEARCH_FULL || bBi )
2254
0
  {
2255
0
    cStruct.subShiftMode = m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE1 || m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE3 ? 1 : 0;
2256
0
    m_pcRdCost->setDistParam( m_cDistParam, *cStruct.pcPatternKey, cStruct.piRefY, cStruct.iRefStride, m_lumaClpRng.bd, COMP_Y, cStruct.subShiftMode );
2257
2258
    // The search range is centred on the start candidate of the lowest cost.
2259
0
    StartPositions startPositions;
2260
0
    Mv             startMvs[BlkUniMvInfoBuffer::m_uniMvListMaxSize + 1];
2261
0
    const BlockMvClip clip( *this, cu, m_pcEncCfg->m_ifpLines );
2262
0
    const auto addStartMv = [&]( const Mv& mv )
2263
0
    {
2264
0
      Mv cTmpMv = clip( mv );
2265
0
      cTmpMv.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_INT);
2266
0
      startMvs[startPositions.size] = mv;
2267
0
      startPositions.add( cTmpMv );
2268
0
    };
2269
2270
0
    addStartMv( bBi ? rcMv : rcMvPred );
2271
0
    m_BlkUniMvInfoBuffer->forEachNewestFirst( [&]( const BlkUniMvInfo& info ) { addStartMv( info.uniMvs[refPicList][iRefIdxPred] ); } );
2272
2273
0
    Mv         bestInitMv, bestStartPosition;
2274
0
    Distortion uiBestSad = MAX_DISTORTION;
2275
0
    xCostsOfStartPositions( startPositions, 0, cStruct, [&]( const int index, const Distortion cost )
2276
0
    {
2277
0
      if( cost < uiBestSad )
2278
0
      {
2279
0
        uiBestSad  = cost;
2280
0
        bestInitMv = startMvs[index];
2281
0
        bestStartPosition = startPositions.positions[index];
2282
0
        m_cDistParam.maximumDistortionForEarlyExit = cost;
2283
0
      }
2284
0
    } );
2285
2286
0
    xSetSearchRange( cu, bestInitMv, iSrchRng, cStruct.searchRange );
2287
0
    xPatternSearch ( cStruct, rcMv, ruiCost, bestStartPosition, uiBestSad );
2288
0
  }
2289
0
  else if( bQTBTMV )
2290
0
  {
2291
0
    rcMv = cIntMv;
2292
0
    cStruct.subShiftMode = ( m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE1 || m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE3 ) ? 1 : 0;
2293
0
    xTZSearch( cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiCost, false, true );
2294
0
  }
2295
0
  else
2296
0
  {
2297
0
    cStruct.subShiftMode = ( m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE1 || m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE3 ) ? 1 : 0;
2298
0
    rcMv = rcMvPred;
2299
0
    xPatternSearchFast(cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiCost );
2300
0
    relatedCU.setMv( refPicList, iRefIdxPred, rcMv );
2301
0
  }
2302
2303
0
  DTRACE( g_trace_ctx, D_ME, "%d %d %d :MECostFPel<L%d,%d>: %d,%d,%dx%d, %d", DTRACE_GET_COUNTER( g_trace_ctx, D_ME ), cu.slice->poc, 0, ( int ) refPicList, ( int ) bBi, cu.Y().x, cu.Y().y, cu.Y().width, cu.Y().height, ruiCost );
2304
  // sub-pel refinement for sub-pel resolution
2305
0
  if ( cu.imv == IMV_OFF || cu.imv == IMV_HPEL )
2306
0
  {
2307
0
    if ( m_pcEncCfg->m_fastSubPel != 2 )
2308
0
    {
2309
0
      xPatternSearchFracDIF( cu, refPicList, iRefIdxPred, cStruct, rcMv, cMvHalf, cMvQter, ruiCost );
2310
0
    }
2311
0
    m_pcRdCost->setCostScale( 0 );
2312
0
    rcMv <<= 2;
2313
0
    rcMv  += ( cMvHalf <<= 1 );
2314
0
    rcMv  += cMvQter;
2315
0
    uint32_t uiMvBits = m_pcRdCost->getBitsOfVectorWithPredictor( rcMv.hor, rcMv.ver, cStruct.imvShift );
2316
0
    ruiBits += uiMvBits;
2317
0
    ruiCost = ( Distortion ) ( floor( fWeight * ( ( double ) ruiCost - ( double ) m_pcRdCost->getCost( uiMvBits ) ) ) + ( double ) m_pcRdCost->getCost( ruiBits ) );
2318
0
    rcMv.changePrecision(MV_PRECISION_QUARTER, MV_PRECISION_INTERNAL);
2319
0
  }
2320
0
  else // integer refinement for integer-pel and 4-pel resolution
2321
0
  {
2322
0
    rcMv.changePrecision(MV_PRECISION_INT, MV_PRECISION_INTERNAL);
2323
0
    xPatternSearchIntRefine( cu, cStruct, rcMv, rcMvPred, riMVPIdx, ruiBits, ruiCost, amvpInfo, fWeight);
2324
0
  }
2325
0
  DTRACE(g_trace_ctx, D_ME, "   MECost<L%d,%d>: %6d (%d)  MV:%d,%d\n", (int)refPicList, (int)bBi, ruiCost, ruiBits, rcMv.hor << 2, rcMv.ver << 2);
2326
0
}
2327
2328
void InterSearch::xClipMvSearch( Mv& rcMv, const Position& pos, const struct Size& size, const PreCalcValues& pcv, const int ifpLines )
2329
0
{
2330
0
  int iMvShift = MV_FRACTIONAL_BITS_INTERNAL;
2331
0
  int iOffset = 8;
2332
0
  int iHorMax = ( pcv.lumaWidth + iOffset - ( int ) pos.x - 1 ) << iMvShift;
2333
0
  int iHorMin = ( -( int ) pcv.maxCUSize   - iOffset - ( int ) pos.x + 1 ) * (1 << iMvShift);
2334
2335
0
  int maxLumaHeight = ifpLines && ((pos.y >> pcv.maxCUSizeLog2) + ifpLines + 1 < pcv.heightInCtus) ? 
2336
    
2337
0
    (((pos.y >> pcv.maxCUSizeLog2) + ifpLines + 1) << pcv.maxCUSizeLog2 ) - size.height - 4  // 4 samples from DCTIF vertical bottom part
2338
2339
0
    : pcv.lumaHeight + iOffset;
2340
2341
0
  int iVerMax = ( maxLumaHeight - ( int ) pos.y - 1 ) << iMvShift;
2342
0
  int iVerMin = ( -( int ) pcv.maxCUSize   - iOffset - ( int ) pos.y + 1 ) * (1 << iMvShift);
2343
2344
0
  rcMv.hor = ( std::min( iHorMax, std::max( iHorMin, rcMv.hor ) ) );
2345
0
  rcMv.ver = ( std::min( iVerMax, std::max( iVerMin, rcMv.ver ) ) );
2346
0
}
2347
2348
void InterSearch::xClipMvToFppLine( Mv& mv, const int yB, const int nH, const int ifpLines, const PreCalcValues& pcv )
2349
0
{
2350
0
  const int yCompScale = 0;
2351
0
  const int mvPrecShift = MV_FRACTIONAL_BITS_INTERNAL;
2352
0
  const int ctuLogScale = pcv.maxCUSizeLog2 - yCompScale;
2353
0
  const int yRefMax     = ( ( ( yB >> ctuLogScale ) + ifpLines + 1 ) << ctuLogScale ) - 1;
2354
0
  const int yRefMv      = yB + nH + ( 4 >> yCompScale ) + (mv.ver >> mvPrecShift) - 1;
2355
0
  CHECKD( yRefMv <= yRefMax, "Not expected" );
2356
0
  mv.ver -= ( yRefMv - yRefMax ) << mvPrecShift;
2357
0
}
2358
2359
void InterSearch::xCheckAndClipMvToFppLine( Mv& mv, const int yB, const int nH, const int ifpLines, const PreCalcValues& pcv )
2360
0
{
2361
0
  const int yCompScale  = 0;
2362
0
  const int mvPrecShift = MV_FRACTIONAL_BITS_INTERNAL;
2363
0
  const int ctuLogScale = pcv.maxCUSizeLog2 - yCompScale;
2364
0
  const int yBMax       = ( pcv.heightInCtus - 1 - ifpLines ) << ctuLogScale;
2365
0
  if( yB < yBMax )
2366
0
  {
2367
0
    const int yRefMax = ( ( ( yB >> ctuLogScale ) + ifpLines + 1 ) << ctuLogScale ) - 1;
2368
0
    const int yRefMv  = yB + nH + ( 4 >> yCompScale ) + (mv.ver >> mvPrecShift) - 1;
2369
0
    if( yRefMv > yRefMax )
2370
0
    {
2371
      // clip MV
2372
0
      mv.ver -= (yRefMv - yRefMax) << mvPrecShift;
2373
0
    }
2374
0
  }
2375
0
}
2376
2377
void InterSearch::xSetSearchRange ( const CodingUnit& cu,
2378
                                    const Mv& cMvPred,
2379
                                    const int iSrchRng,
2380
                                    SearchRange& sr )
2381
0
{
2382
0
  const PreCalcValues& pcv = *cu.cs->pcv;
2383
0
  const int iMvShift = MV_FRACTIONAL_BITS_INTERNAL;
2384
0
  Mv cFPMvPred = cMvPred;
2385
0
  clipMv( cFPMvPred, cu.lumaPos(), cu.lumaSize(), pcv );
2386
2387
0
  Mv mvTL(cFPMvPred.hor - (iSrchRng << iMvShift), cFPMvPred.ver - (iSrchRng << iMvShift));
2388
0
  Mv mvBR(cFPMvPred.hor + (iSrchRng << iMvShift), cFPMvPred.ver + (iSrchRng << iMvShift));
2389
2390
0
  clipMv( mvTL, cu.lumaPos(), cu.lumaSize(), pcv);
2391
0
  xClipMvSearch( mvBR, cu.lumaPos(), cu.lumaSize(), pcv, m_pcEncCfg->m_ifpLines );
2392
2393
0
  mvTL.divideByPowerOf2( iMvShift );
2394
0
  mvBR.divideByPowerOf2( iMvShift );
2395
2396
0
  sr.left   = mvTL.hor;
2397
0
  sr.top    = mvTL.ver;
2398
0
  sr.right  = mvBR.hor;
2399
0
  sr.bottom = mvBR.ver;
2400
0
}
2401
2402
2403
void InterSearch::xPatternSearch( TZSearchStruct&  cStruct,
2404
                                  Mv&                 rcMv,
2405
                                  Distortion&         ruiSAD,
2406
                                  const Mv&           knownPosition,
2407
                                  const Distortion    knownCost )
2408
0
{
2409
0
  Distortion  uiSad;
2410
0
  Distortion  uiSadBest = MAX_DISTORTION;
2411
0
  int         iBestX = 0;
2412
0
  int         iBestY = 0;
2413
2414
  //-- jclee for using the SAD function pointer
2415
0
  m_pcRdCost->setDistParam( m_cDistParam, *cStruct.pcPatternKey, cStruct.piRefY, cStruct.iRefStride, m_lumaClpRng.bd, COMP_Y, cStruct.subShiftMode );
2416
2417
0
  const SearchRange& sr = cStruct.searchRange;
2418
2419
  // A position in the range whose cost is known bounds the result, so a position above that cost can stop its SAD at
2420
  // once and cannot be taken. The first position that reaches the lowest cost still wins, as in a scan without a bound.
2421
0
  if( knownPosition.hor >= sr.left && knownPosition.hor <= sr.right && knownPosition.ver >= sr.top && knownPosition.ver <= sr.bottom )
2422
0
  {
2423
0
    uiSadBest = knownCost + 1;
2424
0
    m_cDistParam.maximumDistortionForEarlyExit = knownCost;
2425
0
  }
2426
2427
  // The motion vector bits are the sum of a horizontal and a vertical part: the horizontal part of every column once
2428
  // per search, the vertical part once per row (the cost is getCostOfVectorWithPredictor's on the same sum).
2429
0
  m_mvBitsHor.resize( std::max<size_t>( m_mvBitsHor.size(), sr.right - sr.left + 1 ) );
2430
0
  for( int x = sr.left; x <= sr.right; x++ )
2431
0
  {
2432
0
    m_mvBitsHor[x - sr.left] = m_pcRdCost->getBitsOfVectorHor( x, cStruct.imvShift );
2433
0
  }
2434
2435
0
  const FpSadFourPositions sadFourPositions = m_cDistParam.sadFourPositions;
2436
2437
0
  const Pel* piRef = cStruct.piRefY + (sr.top * cStruct.iRefStride);
2438
0
  for ( int y = sr.top; y <= sr.bottom; y++ )
2439
0
  {
2440
0
    const uint32_t bitsVer = m_pcRdCost->getBitsOfVectorVer( y, cStruct.imvShift );
2441
2442
    //  find min. distortion position
2443
0
    const auto checkPosition = [&]( const int x, const Distortion sad )
2444
0
    {
2445
      // motion cost
2446
0
      uiSad = sad + m_pcRdCost->getCost( m_mvBitsHor[x - sr.left] + bitsVer );
2447
2448
0
      if ( uiSad < uiSadBest )
2449
0
      {
2450
0
        uiSadBest = uiSad;
2451
0
        iBestX    = x;
2452
0
        iBestY    = y;
2453
0
        m_cDistParam.maximumDistortionForEarlyExit = uiSad;
2454
0
      }
2455
0
    };
2456
2457
0
    int x = sr.left;
2458
0
    if( sadFourPositions )
2459
0
    {
2460
0
      for( ; x + 3 <= sr.right; x += 4 )
2461
0
      {
2462
0
        Distortion sads[4];
2463
0
        const Pel* const refs[4] = { piRef + x, piRef + x + 1, piRef + x + 2, piRef + x + 3 };
2464
0
        sadFourPositions( m_cDistParam, refs, sads );
2465
0
        for( int k = 0; k < 4; k++ )
2466
0
        {
2467
0
          checkPosition( x + k, sads[k] );
2468
0
        }
2469
0
      }
2470
0
    }
2471
0
    for( ; x <= sr.right; x++ )
2472
0
    {
2473
0
      m_cDistParam.cur.buf = piRef + x;
2474
0
      checkPosition( x, m_cDistParam.distFunc( m_cDistParam ) );
2475
0
    }
2476
0
    piRef += cStruct.iRefStride;
2477
0
  }
2478
0
  rcMv.set( iBestX, iBestY );
2479
2480
0
  cStruct.uiBestSad = uiSadBest; // th for testing
2481
0
  ruiSAD = uiSadBest - m_pcRdCost->getCostOfVectorWithPredictor( iBestX, iBestY, cStruct.imvShift );
2482
0
  return;
2483
0
}
2484
2485
2486
void InterSearch::xPatternSearchFast( const CodingUnit& cu,
2487
                                      RefPicList            refPicList,
2488
                                      int                   iRefIdxPred,
2489
                                      TZSearchStruct&       cStruct,
2490
                                      Mv&                   rcMv,
2491
                                      Distortion&           ruiSAD )
2492
0
{
2493
0
  if( cu.cs->picture->useME )
2494
0
  {
2495
0
    switch ( m_motionEstimationSearchMethodSCC )
2496
0
    {
2497
0
      case 3: //VVENC_MESEARCH_DIAMOND_FAST:
2498
0
        xTZSearch( cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiSAD, true, true );
2499
0
        break;
2500
0
      case 2: //VVENC_MESEARCH_DIAMOND:
2501
0
        xTZSearch( cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiSAD, true );
2502
0
        break;
2503
0
      default:
2504
0
        THROW("shouldn't get here");
2505
0
        break;
2506
0
    }
2507
0
    return;
2508
0
  }
2509
2510
0
  switch ( m_motionEstimationSearchMethod )
2511
0
  {
2512
0
    case VVENC_MESEARCH_DIAMOND_FAST:
2513
0
      xTZSearch         ( cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiSAD, false, true );
2514
0
      break;
2515
0
    case VVENC_MESEARCH_DIAMOND:
2516
0
      xTZSearch         ( cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiSAD, false );
2517
0
      break;
2518
0
    case VVENC_MESEARCH_DIAMOND_ENHANCED:
2519
0
      xTZSearch         ( cu, refPicList, iRefIdxPred, cStruct, rcMv, ruiSAD, true );
2520
0
      break;
2521
0
    case VVENC_MESEARCH_FULL:
2522
0
    default:
2523
0
      THROW("shouldn't get here");
2524
0
      break;
2525
0
  }
2526
0
}
2527
2528
2529
void InterSearch::xTZSearch( const CodingUnit& cu,
2530
                             RefPicList            refPicList,
2531
                             int                   iRefIdxPred,
2532
                             TZSearchStruct&       cStruct,
2533
                             Mv&                   rcMv,
2534
                             Distortion&           ruiSAD,
2535
                             const bool            bExtendedSettings,
2536
                             const bool            bFastSettings)
2537
0
{
2538
0
  const bool bUseRasterInFastMode                    = true; //toggle this to further reduce runtime
2539
0
  const bool bUseAdaptiveRaster                      = bExtendedSettings;
2540
0
  const int  iRaster                                 = (bFastSettings && bUseRasterInFastMode) ? 8 : 5;
2541
0
  const bool bTestZeroVector                         = true && !bFastSettings;
2542
0
  const bool bTestZeroVectorStart                    = bExtendedSettings;
2543
0
  const bool bTestZeroVectorStop                     = false;
2544
0
  const bool bFirstSearchDiamond                     = true;  // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
2545
0
  const bool bFirstCornersForDiamondDist1            = bExtendedSettings;
2546
0
  const bool bFirstSearchStop                        = m_pcEncCfg->m_bFastMEAssumingSmootherMVEnabled;
2547
0
  const uint32_t uiFirstSearchRounds                 = bFastSettings ? (bUseRasterInFastMode?3:2) : 3;     // first search stop X rounds after best match (must be >=1)
2548
0
  const bool bEnableRasterSearch                     = bFastSettings ? bUseRasterInFastMode : true;
2549
0
  const bool bAlwaysRasterSearch                     = bExtendedSettings;  // true: BETTER but factor 2 slower
2550
0
  const bool bRasterRefinementEnable                 = false; // enable either raster refinement or star refinement
2551
0
  const bool bRasterRefinementDiamond                = false; // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
2552
0
  const bool bRasterRefinementCornersForDiamondDist1 = bExtendedSettings;
2553
0
  const bool bStarRefinementEnable                   = true;  // enable either star refinement or raster refinement
2554
0
  const bool bStarRefinementDiamond                  = true;  // 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch
2555
0
  const bool bStarRefinementCornersForDiamondDist1   = bExtendedSettings;
2556
0
  const bool bStarRefinementStop                     = bFastSettings;
2557
0
  const uint32_t uiStarRefinementRounds              = 2;  // star refinement stop X rounds after best match (must be >=1)
2558
0
  const bool bNewZeroNeighbourhoodTest               = bExtendedSettings;
2559
2560
0
  int iSearchRange = m_iSearchRange;
2561
0
  xClipMvSearch( rcMv, cu.lumaPos(), cu.lumaSize(),*cu.cs->pcv, m_pcEncCfg->m_ifpLines );
2562
0
  rcMv.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_QUARTER);
2563
0
  rcMv.divideByPowerOf2(2);
2564
2565
  //
2566
0
  m_cDistParam.maximumDistortionForEarlyExit = cStruct.uiBestSad;
2567
0
  m_pcRdCost->setDistParam( m_cDistParam, *cStruct.pcPatternKey, cStruct.piRefY, cStruct.iRefStride, m_lumaClpRng.bd, COMP_Y, cStruct.subShiftMode );
2568
2569
  // set rcMv (Median predictor) as start point and as best point
2570
0
  xTZSearchHelp( cStruct, rcMv.hor, rcMv.ver, 0, 0 );
2571
2572
  // test whether zero Mv is better start point than Median predictor
2573
0
  if ( bTestZeroVector )
2574
0
  {
2575
0
    if( ( rcMv.hor != 0 || rcMv.ver != 0 ) && ( 0 != cStruct.iBestX || 0 != cStruct.iBestY ) )
2576
0
    {
2577
      // only test 0-vector if not obviously previously tested.
2578
0
      xTZSearchHelp( cStruct, 0, 0, 0, 0 );
2579
0
    }
2580
0
  }
2581
2582
0
  SearchRange& sr = cStruct.searchRange;
2583
2584
  // The start and the zero vector had their tests above, or found out that they cannot win.
2585
0
  StartPositions startPositions;
2586
0
  startPositions.add( Mv( rcMv.hor, rcMv.ver ) );
2587
0
  if( bTestZeroVector )
2588
0
  {
2589
0
    startPositions.add( Mv( 0, 0 ) );
2590
0
  }
2591
0
  const int numTested = startPositions.size;
2592
0
  const BlockMvClip clip( *this, cu, m_pcEncCfg->m_ifpLines );
2593
0
  m_BlkUniMvInfoBuffer->forEachNewestFirst( [&]( const BlkUniMvInfo& info )
2594
0
  {
2595
0
    Mv cTmpMv = clip( info.uniMvs[refPicList][iRefIdxPred] );
2596
0
    cTmpMv.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_INT);
2597
0
    startPositions.add( cTmpMv );
2598
0
  } );
2599
2600
0
  xCostsOfStartPositions( startPositions, numTested, cStruct, [&]( const int index, const Distortion cost )
2601
0
  {
2602
0
    if( cost < cStruct.uiBestSad )
2603
0
    {
2604
0
      cStruct.uiBestSad = cost;
2605
0
      cStruct.iBestX = startPositions.positions[index].hor;
2606
0
      cStruct.iBestY = startPositions.positions[index].ver;
2607
0
      m_cDistParam.maximumDistortionForEarlyExit = cost;
2608
0
    }
2609
0
  } );
2610
2611
0
  {
2612
    // set search range
2613
0
    Mv currBestMv(cStruct.iBestX, cStruct.iBestY );
2614
0
    currBestMv <<= MV_FRACTIONAL_BITS_INTERNAL;
2615
0
    xSetSearchRange(cu, currBestMv, m_iSearchRange >> (bFastSettings ? 1 : 0), sr );
2616
0
  }
2617
2618
  // starting point after initial examination
2619
0
  int  iDist = 0;
2620
0
  int  iStartX = cStruct.iBestX;
2621
0
  int  iStartY = cStruct.iBestY;
2622
2623
  // Early termination of motion search after selection of starting candidate
2624
0
  if( m_pcEncCfg->m_bIntegerET )
2625
0
  {
2626
0
    bool isLargeBlock = cu.lumaSize().area() > 64;
2627
0
    xTZ8PointDiamondSearch( cStruct, iStartX, iStartY, 1, false ); // 4-point small diamond search
2628
0
    if ( cStruct.iBestX == iStartX && cStruct.iBestY == iStartY )
2629
0
    {
2630
0
      if ( isLargeBlock )
2631
0
      {
2632
0
        xTZ4PointSquareSearch( cStruct, iStartX, iStartY, 1 );
2633
0
        if ( cStruct.iBestX == iStartX && cStruct.iBestY == iStartY )
2634
0
        {
2635
          // write out best match
2636
0
          rcMv.set( cStruct.iBestX, cStruct.iBestY );
2637
0
          ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCostOfVectorWithPredictor( cStruct.iBestX, cStruct.iBestY, cStruct.imvShift );
2638
0
          return;
2639
0
        }
2640
0
      }
2641
0
      else
2642
0
      {
2643
        // write out best match
2644
0
        rcMv.set( cStruct.iBestX, cStruct.iBestY );
2645
0
        ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCostOfVectorWithPredictor( cStruct.iBestX, cStruct.iBestY, cStruct.imvShift );
2646
0
        return;
2647
0
      }
2648
0
    }
2649
0
  }
2650
2651
  // start search
2652
0
  iDist = 0;
2653
0
  iStartX = cStruct.iBestX;
2654
0
  iStartY = cStruct.iBestY;
2655
2656
0
  const bool bBestCandidateZero = ( cStruct.iBestX == 0 ) && ( cStruct.iBestY == 0 );
2657
2658
  // first search around best position up to now.
2659
  // The following works as a "subsampled/log" window search around the best candidate
2660
0
  for( iDist = 1; iDist <= iSearchRange; iDist *= 2 )
2661
0
  {
2662
0
    if( bFirstSearchDiamond == 1 )
2663
0
    {
2664
0
      xTZ8PointDiamondSearch( cStruct, iStartX, iStartY, iDist, bFirstCornersForDiamondDist1 );
2665
0
    }
2666
0
    else
2667
0
    {
2668
0
      xTZ8PointSquareSearch( cStruct, iStartX, iStartY, iDist );
2669
0
    }
2670
2671
0
    if( bFirstSearchStop && ( cStruct.uiBestRound >= uiFirstSearchRounds ) ) // stop criterion
2672
0
    {
2673
0
      break;
2674
0
    }
2675
0
  }
2676
2677
0
  if( bNewZeroNeighbourhoodTest )
2678
0
  {
2679
0
    if( bTestZeroVectorStart && !bBestCandidateZero )
2680
0
    {
2681
0
      for( iDist = 1; iDist <= ( iSearchRange >> 1 ); iDist *= 2 )
2682
0
      {
2683
0
        xTZ8PointDiamondSearch( cStruct, 0, 0, iDist, false );
2684
0
        if( bTestZeroVectorStop && ( cStruct.uiBestRound > 2 ) ) // stop criterion
2685
0
        {
2686
0
          break;
2687
0
        }
2688
0
      }
2689
0
    }
2690
0
  }
2691
2692
  // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
2693
0
  if ( cStruct.uiBestDistance == 1 )
2694
0
  {
2695
0
    cStruct.uiBestDistance = 0;
2696
0
    xTZ2PointSearch( cStruct );
2697
0
  }
2698
2699
  // raster search if distance is too big
2700
0
  if( bUseAdaptiveRaster )
2701
0
  {
2702
0
    int iWindowSize     = iRaster;
2703
0
    SearchRange localsr = sr;
2704
2705
0
    if( !( bEnableRasterSearch && ( ( ( int ) ( cStruct.uiBestDistance ) >= iRaster ) ) ) )
2706
0
    {
2707
0
      iWindowSize++;
2708
0
      localsr.left    /= 2;
2709
0
      localsr.right   /= 2;
2710
0
      localsr.top     /= 2;
2711
0
      localsr.bottom  /= 2;
2712
0
    }
2713
2714
0
    cStruct.uiBestDistance = iWindowSize;
2715
2716
0
    for( iStartY = localsr.top; iStartY <= localsr.bottom; iStartY += iWindowSize )
2717
0
    {
2718
0
      for( iStartX = localsr.left; iStartX <= localsr.right; iStartX += iWindowSize )
2719
0
      {
2720
0
        xTZSearchQueued( cStruct, iStartX, iStartY, 0, iWindowSize );
2721
0
      }
2722
0
    }
2723
0
    xTZSearchFlush( cStruct );
2724
0
  }
2725
0
  else
2726
0
  {
2727
0
    if( bEnableRasterSearch && ( ( ( int ) ( cStruct.uiBestDistance ) >= iRaster ) || bAlwaysRasterSearch ) )
2728
0
    {
2729
0
      cStruct.uiBestDistance = iRaster;
2730
2731
0
      for( iStartY = sr.top; iStartY <= sr.bottom; iStartY += iRaster )
2732
0
      {
2733
0
        for( iStartX = sr.left; iStartX <= sr.right; iStartX += iRaster )
2734
0
        {
2735
0
          xTZSearchQueued( cStruct, iStartX, iStartY, 0, iRaster );
2736
0
        }
2737
0
      }
2738
0
      xTZSearchFlush( cStruct );
2739
0
    }
2740
0
  }
2741
2742
  // raster refinement
2743
2744
0
  if ( bRasterRefinementEnable && cStruct.uiBestDistance > 0 )
2745
0
  {
2746
0
    while ( cStruct.uiBestDistance > 0 )
2747
0
    {
2748
0
      iStartX = cStruct.iBestX;
2749
0
      iStartY = cStruct.iBestY;
2750
0
      if ( cStruct.uiBestDistance > 1 )
2751
0
      {
2752
0
        iDist = cStruct.uiBestDistance >>= 1;
2753
0
        if ( bRasterRefinementDiamond == 1 )
2754
0
        {
2755
0
          xTZ8PointDiamondSearch ( cStruct, iStartX, iStartY, iDist, bRasterRefinementCornersForDiamondDist1 );
2756
0
        }
2757
0
        else
2758
0
        {
2759
0
          xTZ8PointSquareSearch  ( cStruct, iStartX, iStartY, iDist );
2760
0
        }
2761
0
      }
2762
2763
      // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
2764
0
      if ( cStruct.uiBestDistance == 1 )
2765
0
      {
2766
0
        cStruct.uiBestDistance = 0;
2767
0
        if ( cStruct.ucPointNr != 0 )
2768
0
        {
2769
0
          xTZ2PointSearch( cStruct );
2770
0
        }
2771
0
      }
2772
0
    }
2773
0
  }
2774
2775
  // star refinement
2776
0
  if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
2777
0
  {
2778
0
    while ( cStruct.uiBestDistance > 0 )
2779
0
    {
2780
0
      iStartX = cStruct.iBestX;
2781
0
      iStartY = cStruct.iBestY;
2782
0
      cStruct.uiBestDistance = 0;
2783
0
      cStruct.ucPointNr = 0;
2784
0
      for ( iDist = 1; iDist < iSearchRange + 1; iDist*=2 )
2785
0
      {
2786
0
        if ( bStarRefinementDiamond == 1 )
2787
0
        {
2788
0
          xTZ8PointDiamondSearch ( cStruct, iStartX, iStartY, iDist, bStarRefinementCornersForDiamondDist1 );
2789
0
        }
2790
0
        else
2791
0
        {
2792
0
          xTZ8PointSquareSearch  ( cStruct, iStartX, iStartY, iDist );
2793
0
        }
2794
0
        if ( bStarRefinementStop && (cStruct.uiBestRound >= uiStarRefinementRounds) ) // stop criterion
2795
0
        {
2796
0
          break;
2797
0
        }
2798
0
      }
2799
2800
      // calculate only 2 missing points instead 8 points if cStrukt.uiBestDistance == 1
2801
0
      if ( cStruct.uiBestDistance == 1 )
2802
0
      {
2803
0
        cStruct.uiBestDistance = 0;
2804
0
        if ( cStruct.ucPointNr != 0 )
2805
0
        {
2806
0
          xTZ2PointSearch( cStruct );
2807
0
        }
2808
0
      }
2809
0
    }
2810
0
  }
2811
2812
  // write out best match
2813
0
  rcMv.set( cStruct.iBestX, cStruct.iBestY );
2814
0
  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCostOfVectorWithPredictor( cStruct.iBestX, cStruct.iBestY, cStruct.imvShift );
2815
0
}
2816
2817
void InterSearch::xPatternSearchIntRefine(CodingUnit& cu, TZSearchStruct&  cStruct, Mv& rcMv, Mv& rcMvPred, int& riMVPIdx, uint32_t& ruiBits, Distortion& ruiCost, const AMVPInfo& amvpInfo, double fWeight)
2818
0
{
2819
2820
0
  CHECK( cu.imv == IMV_OFF || cu.imv == IMV_HPEL , "xPatternSearchIntRefine(): Sub-pel MV used.");
2821
0
  CHECK( amvpInfo.mvCand[riMVPIdx] != rcMvPred, "xPatternSearchIntRefine(): MvPred issue.");
2822
2823
0
  m_pcRdCost->setDistParam(m_cDistParam, *cStruct.pcPatternKey, cStruct.piRefY, cStruct.iRefStride, m_lumaClpRng.bd, COMP_Y, 0, m_pcEncCfg->m_bUseHADME ? ( m_pcEncCfg->m_fastHad ? 2 : 1 ) : 0 );
2824
2825
  // -> set MV scale for cost calculation to QPEL (0)
2826
0
  m_pcRdCost->setCostScale ( 0 );
2827
2828
0
  Distortion  uiDist, uiSATD = 0;
2829
0
  Distortion  uiBestDist  = MAX_DISTORTION;
2830
  // subtract old MVP costs because costs for all newly tested MVPs are added in here
2831
0
  ruiBits -= m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
2832
2833
0
  Mv cBestMv = rcMv;
2834
0
  Mv cBaseMvd[2];
2835
0
  int iBestBits = 0;
2836
0
  int iBestMVPIdx = riMVPIdx;
2837
0
  Mv testPos[9] = { { 0, 0}, { -1, -1},{ -1, 0},{ -1, 1},{ 0, -1},{ 0, 1},{ 1, -1},{ 1, 0},{ 1, 1} };
2838
2839
2840
0
  cBaseMvd[0] = (rcMv - amvpInfo.mvCand[0]);
2841
0
  cBaseMvd[1] = (rcMv - amvpInfo.mvCand[1]);
2842
0
  CHECK( (cBaseMvd[0].hor & 0x03) != 0 || (cBaseMvd[0].ver & 0x03) != 0 , "xPatternSearchIntRefine(): AMVP cand 0 Mvd issue.");
2843
0
  CHECK( (cBaseMvd[1].hor & 0x03) != 0 || (cBaseMvd[1].ver & 0x03) != 0 , "xPatternSearchIntRefine(): AMVP cand 1 Mvd issue.");
2844
2845
0
  cBaseMvd[0].roundTransPrecInternal2Amvr(cu.imv);
2846
0
  cBaseMvd[1].roundTransPrecInternal2Amvr(cu.imv);
2847
2848
  // test best integer position and all 8 neighboring positions
2849
0
  for (int pos = 0; pos < 9; pos ++)
2850
0
  {
2851
0
    Mv cTestMv[2];
2852
    // test both AMVP candidates for each position
2853
0
    for (int iMVPIdx = 0; iMVPIdx < amvpInfo.numCand; iMVPIdx++)
2854
0
    {
2855
0
      cTestMv[iMVPIdx] = testPos[pos];
2856
0
      cTestMv[iMVPIdx].changeTransPrecAmvr2Internal(cu.imv);
2857
0
      cTestMv[iMVPIdx] += cBaseMvd[iMVPIdx];
2858
0
      cTestMv[iMVPIdx] += amvpInfo.mvCand[iMVPIdx];
2859
2860
0
      if( m_pcEncCfg->m_ifpLines && !CU::isMvInRangeFPP( cu.ly(), cu.lheight(), cTestMv[iMVPIdx].ver, m_pcEncCfg->m_ifpLines, *cu.cs->pcv ) )
2861
0
      {
2862
0
        xClipMvToFppLine( cTestMv[iMVPIdx], cu.ly(), cu.lheight(), m_pcEncCfg->m_ifpLines, *cu.cs->pcv );
2863
0
        cTestMv[iMVPIdx].roundTransPrecInternal2AmvrVertical(cu.imv);
2864
0
      }
2865
2866
0
      if ( iMVPIdx == 0 || cTestMv[0] != cTestMv[1])
2867
0
      {
2868
0
        Mv cTempMV = cTestMv[iMVPIdx];
2869
0
        clipMv(cTempMV, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
2870
0
        m_cDistParam.cur.buf = cStruct.piRefY  + cStruct.iRefStride * (cTempMV.ver >>  MV_FRACTIONAL_BITS_INTERNAL) + (cTempMV.hor >> MV_FRACTIONAL_BITS_INTERNAL);
2871
0
        uiDist = uiSATD = (Distortion) (m_cDistParam.distFunc( m_cDistParam ) * fWeight);
2872
0
      }
2873
0
      else
2874
0
      {
2875
0
        uiDist = uiSATD;
2876
0
      }
2877
2878
0
      int iMvBits = m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
2879
0
      Mv pred = amvpInfo.mvCand[iMVPIdx];
2880
0
      pred.changeTransPrecInternal2Amvr(cu.imv);
2881
0
      m_pcRdCost->setPredictor( pred );
2882
0
      Mv mv = cTestMv[iMVPIdx];
2883
0
      mv.changeTransPrecInternal2Amvr(cu.imv);
2884
0
      iMvBits += m_pcRdCost->getBitsOfVectorWithPredictor( mv.hor, mv.ver, 0 );
2885
0
      uiDist += m_pcRdCost->getCost(iMvBits);
2886
2887
0
      if (uiDist < uiBestDist)
2888
0
      {
2889
0
        uiBestDist = uiDist;
2890
0
        cBestMv = cTestMv[iMVPIdx];
2891
0
        iBestMVPIdx = iMVPIdx;
2892
0
        iBestBits = iMvBits;
2893
0
      }
2894
0
    }
2895
0
  }
2896
0
  if( uiBestDist == MAX_DISTORTION )
2897
0
  {
2898
0
    ruiCost = MAX_DISTORTION;
2899
0
    return;
2900
0
  }
2901
2902
0
  rcMv = cBestMv;
2903
0
  rcMvPred = amvpInfo.mvCand[iBestMVPIdx];
2904
0
  riMVPIdx = iBestMVPIdx;
2905
0
  m_pcRdCost->setPredictor( rcMvPred );
2906
2907
0
  ruiBits += iBestBits;
2908
  // taken from JEM 5.0
2909
  // verify since it makes no sence to subtract Lamda*(Rmvd+Rmvpidx) from D+Lamda(Rmvd)
2910
  // this would take the rate for the MVP idx out of the cost calculation
2911
  // however this rate is always 1 so impact is small
2912
0
  ruiCost = uiBestDist - m_pcRdCost->getCost(iBestBits) + m_pcRdCost->getCost(ruiBits);
2913
  // taken from JEM 5.0
2914
  // verify since it makes no sense to add rate for MVDs twicce
2915
2916
0
  return;
2917
0
}
2918
2919
void InterSearch::xPatternSearchFracDIF(
2920
  const CodingUnit& cu,
2921
  RefPicList            refPicList,
2922
  int                   iRefIdx,
2923
  TZSearchStruct&    cStruct,
2924
  const Mv&             rcMvInt,
2925
  Mv&                   rcMvHalf,
2926
  Mv&                   rcMvQter,
2927
  Distortion&           ruiCost
2928
)
2929
0
{
2930
0
  PROFILER_SCOPE_AND_STAGE( 0, _TPROF, P_FRAC_PEL );
2931
2932
  //  Reference pattern initialization (integer scale)
2933
0
  int         iOffset    = rcMvInt.hor + rcMvInt.ver * cStruct.iRefStride;
2934
0
  CPelBuf cPatternRoi(cStruct.piRefY + iOffset, cStruct.iRefStride, *cStruct.pcPatternKey);
2935
2936
  //  Half-pel refinement
2937
0
  m_pcRdCost->setCostScale(1);
2938
0
  if( 0 == m_pcEncCfg->m_fastSubPel )
2939
0
  {
2940
0
    xExtDIFUpSamplingH( &cPatternRoi, cStruct.useAltHpelIf );
2941
0
  }
2942
2943
0
  rcMvHalf = rcMvInt;   rcMvHalf <<= 1;    // for mv-cost
2944
0
  Mv baseRefMv(0, 0);
2945
0
  Distortion  uiDistBest = MAX_DISTORTION;
2946
0
  int patternId = 41;
2947
0
  Distortion halfPelBestDistNoMv;
2948
0
  ruiCost = xPatternRefinement( cStruct.pcPatternKey, baseRefMv, 2, rcMvHalf, uiDistBest, patternId, &cPatternRoi, cStruct.useAltHpelIf,
2949
0
                                MAX_DISTORTION, halfPelBestDistNoMv );
2950
0
  patternId -= ( m_pcEncCfg->m_fastSubPel == 1 ? 41 : 0 );
2951
2952
2953
  //  quarter-pel refinement
2954
0
  if( cStruct.imvShift == IMV_OFF && 0 != patternId )
2955
0
  {
2956
0
    PROFILER_SCOPE_AND_STAGE( 0, _TPROF, P_QPEL );
2957
0
    m_pcRdCost->setCostScale( 0 );
2958
0
    xExtDIFUpSamplingQ( &cPatternRoi, rcMvHalf, patternId );
2959
0
    baseRefMv = rcMvHalf;
2960
0
    baseRefMv <<= 1;
2961
2962
0
    rcMvQter = rcMvInt;    rcMvQter <<= 1;    // for mv-cost
2963
0
    rcMvQter += rcMvHalf;  rcMvQter <<= 1;
2964
    // the quarter-pel centre is the half-pel winner, already measured
2965
0
    Distortion quarterPelBestDistNoMv;
2966
0
    ruiCost = xPatternRefinement( cStruct.pcPatternKey, baseRefMv, 1, rcMvQter, uiDistBest, patternId, &cPatternRoi, cStruct.useAltHpelIf,
2967
0
                                  halfPelBestDistNoMv, quarterPelBestDistNoMv );
2968
0
  }
2969
2970
0
}
2971
2972
void InterSearch::xPredOtherListLuma( CodingUnit& cu, PelUnitBuf& pred, const RefPicList list )
2973
0
{
2974
0
  const uint8_t mcControl = cu.mcControl;
2975
0
  cu.mcControl = 2;
2976
0
  motionCompensation( cu, pred, list );
2977
0
  cu.mcControl = mcControl;
2978
0
}
2979
2980
// The luma prediction of the symmetric MVD search for an already clipped MV. Not read in place with IFP and a fast inter
2981
// search mode below 2: there the affine bi-prediction search can skip its first prediction (an MV outside the IFP lines)
2982
// and then read a prediction buffer it did not write, so the buffer has to hold what this function would have written.
2983
CPelBuf InterSearch::xPredSymLuma( const CodingUnit& cu, const Picture* refPic, const Mv& mv, PelUnitBuf& predBuf )
2984
0
{
2985
0
  const bool bufferMayBeReadLater = m_pcEncCfg->m_ifpLines && m_pcEncCfg->m_fastInterSearchMode < VVENC_FASTINTERSEARCH_MODE2;
2986
0
  if( bufferMayBeReadLater )
2987
0
  {
2988
0
    xPredInterBlk( COMP_Y, cu, refPic, mv, predBuf, false, cu.slice->clpRngs[ COMP_Y ], false, false );
2989
0
    return predBuf.Y();
2990
0
  }
2991
0
  return xPredLumaReadOnly( cu, refPic, mv, predBuf );
2992
0
}
2993
2994
// A luma prediction for an already clipped MV that the caller only reads. At an integer MV the prediction is a plain copy
2995
// of the reference block (xPredInterBlk: filterHor with fraction 0 and isLast), so the reference picture is read in place.
2996
CPelBuf InterSearch::xPredLumaReadOnly( const CodingUnit& cu, const Picture* refPic, const Mv& mv, PelUnitBuf& predBuf )
2997
0
{
2998
0
  static constexpr int FRAC_MASK = ( 1 << MV_FRACTIONAL_BITS_INTERNAL ) - 1;
2999
0
  const bool integerMv = ( mv.hor & FRAC_MASK ) == 0 && ( mv.ver & FRAC_MASK ) == 0;
3000
0
  if( integerMv )
3001
0
  {
3002
    // the block xPredInterBlk would copy: the CU's position moved by the integer MV, in the picture's own stride
3003
0
    const int  stride = refPic->getRecoBufStride( COMP_Y );
3004
0
    const Pel* ref    = refPic->getRecoBufPtr( COMP_Y ) + cu.lumaPos().x + ( mv.hor >> MV_FRACTIONAL_BITS_INTERNAL )
3005
0
                        + ( cu.lumaPos().y + ( mv.ver >> MV_FRACTIONAL_BITS_INTERNAL ) ) * stride;
3006
0
    CHECKD( m_ifpLines && cu.cs->picture != refPic && !CU::isMvInRangeFPP( cu.lumaPos().y, cu.lumaSize().height, mv.ver, m_ifpLines, *cu.cs->pcv ),
3007
0
            "xPredLumaReadOnly: CTU line-wise FPP MV restriction failed!\n" );   // as xPredInterBlk checks it
3008
0
    return CPelBuf( ref, stride, cu.lumaSize() );
3009
0
  }
3010
0
  xPredInterBlk( COMP_Y, cu, refPic, mv, predBuf, false, cu.slice->clpRngs[ COMP_Y ], false, false );
3011
0
  return predBuf.Y();
3012
0
}
3013
3014
Distortion InterSearch::xGetSymCost( const CodingUnit& cu, CPelUnitBuf& origBuf, RefPicList eCurRefPicList, const MvField& cCurMvField, MvField& cTarMvField, int BcwIdx )
3015
0
{
3016
0
  const RefPicList eTarRefPicList = (RefPicList)(1 - (int)eCurRefPicList);
3017
0
  PelUnitBuf       predStorageA   = m_tmpPredStorage[eCurRefPicList].getCompactBuf( cu );
3018
0
  const CPelBuf    predBufA       = xSymPred( cu, eCurRefPicList, cCurMvField, predStorageA );
3019
0
  PelUnitBuf       predStorageB   = m_tmpPredStorage[eTarRefPicList].getCompactBuf( cu );
3020
0
  const CPelBuf    predBufB       = xSymPred( cu, eTarRefPicList, cTarMvField, predStorageB );
3021
0
  return xSymHadCost( cu, xSymHighFreq( cu, origBuf, predBufA ), predBufB, eTarRefPicList );
3022
0
}
3023
3024
// The luma prediction of one list of the symmetric MVD search, its MV clipped to the picture.
3025
CPelBuf InterSearch::xSymPred( const CodingUnit& cu, RefPicList refList, const MvField& mvField, PelUnitBuf& predStorage )
3026
0
{
3027
0
  const Picture* refPic = cu.slice->getRefPic( refList, mvField.refIdx );
3028
0
  Mv mv = mvField.mv;
3029
0
  clipMv( mv, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv );
3030
0
  return xPredSymLuma( cu, refPic, mv, predStorage );
3031
0
}
3032
3033
// Twice the original minus the list-A prediction (removeHighFreq), into m_tmpStorageLCU: the target the list-B prediction is
3034
// compared with, since the bi-prediction averages the two lists.
3035
CPelBuf InterSearch::xSymHighFreq( const CodingUnit& cu, CPelUnitBuf& origBuf, const CPelBuf& predBufA )
3036
0
{
3037
0
  PelBuf bufTmp = m_tmpStorageLCU.getCompactBuf( cu.Y() );
3038
0
  bufTmp.removeHighFreq( origBuf.Y(), predBufA, m_pcEncCfg->m_bClipForBiPredMeEnabled, cu.slice->clpRngs[ COMP_Y ]/*, getBcwWeight( cu.BcwIdx, eTarRefPicList )*/ );
3039
0
  return bufTmp;
3040
0
}
3041
3042
// The symmetric MVD cost of a pair: the weighted HAD of the list-B prediction against the list-A high-frequency buffer.
3043
Distortion InterSearch::xSymHadCost( const CodingUnit& cu, const CPelBuf& highFreqA, const CPelBuf& predBufB, RefPicList eTarRefPicList )
3044
0
{
3045
0
  const double fWeight = xGetMEDistortionWeight( cu.BcwIdx, eTarRefPicList );
3046
0
  return ( Distortion ) floor( fWeight * ( double ) m_pcRdCost->getDistPart( highFreqA, predBufB, cu.cs->sps->bitDepths[ CH_L ], COMP_Y, DF_HAD ) );
3047
0
}
3048
3049
Distortion InterSearch::xSymRefineMvSearch( CodingUnit& cu, CPelUnitBuf& origBuf, Mv& rcMvCurPred, Mv& rcMvTarPred, RefPicList refPicList, MvField& rCurMvField, 
3050
                                            MvField& rTarMvField, Distortion uiMinCost, int SearchPattern, int nSearchStepShift, uint32_t uiMaxSearchRounds, int BcwIdx )
3051
0
{
3052
0
  const Mv mvSearchOffsetCross[4] = { Mv( 0 , 1 ) , Mv( 1 , 0 ) , Mv( 0 , -1 ) , Mv( -1 ,  0 ) };
3053
0
  const Mv mvSearchOffsetSquare[8] = { Mv( -1 , 1 ) , Mv( 0 , 1 ) , Mv( 1 ,  1 ) , Mv( 1 ,  0 ) , Mv( 1 , -1 ) , Mv( 0 , -1 ) , Mv( -1 , -1 ) , Mv( -1 , 0 ) };
3054
0
  const Mv mvSearchOffsetDiamond[8] = { Mv( 0 , 2 ) , Mv( 1 , 1 ) , Mv( 2 ,  0 ) , Mv( 1 , -1 ) , Mv( 0 , -2 ) , Mv( -1 , -1 ) , Mv( -2 ,  0 ) , Mv( -1 , 1 ) };
3055
0
  const Mv mvSearchOffsetHexagon[6] = { Mv( 2 , 0 ) , Mv( 1 , 2 ) , Mv( -1 ,  2 ) , Mv( -2 ,  0 ) , Mv( -1 , -2 ) , Mv( 1 , -2 ) };
3056
3057
0
  int nDirectStart = 0, nDirectEnd = 0, nDirectRounding = 0, nDirectMask = 0;
3058
0
  const Mv * pSearchOffset;
3059
0
  if ( SearchPattern == 0 )
3060
0
  {
3061
0
    nDirectEnd = 3;
3062
0
    nDirectRounding = 4;
3063
0
    nDirectMask = 0x03;
3064
0
    pSearchOffset = mvSearchOffsetCross;
3065
0
  }
3066
0
  else if ( SearchPattern == 1 )
3067
0
  {
3068
0
    nDirectEnd = 7;
3069
0
    nDirectRounding = 8;
3070
0
    nDirectMask = 0x07;
3071
0
    pSearchOffset = mvSearchOffsetSquare;
3072
0
  }
3073
0
  else if ( SearchPattern == 2 )
3074
0
  {
3075
0
    nDirectEnd = 7;
3076
0
    nDirectRounding = 8;
3077
0
    nDirectMask = 0x07;
3078
0
    pSearchOffset = mvSearchOffsetDiamond;
3079
0
  }
3080
0
  else if ( SearchPattern == 3 )
3081
0
  {
3082
0
    nDirectEnd = 5;
3083
0
    pSearchOffset = mvSearchOffsetHexagon;
3084
0
  }
3085
0
  else
3086
0
  {
3087
0
    THROW( "Invalid search pattern" );
3088
0
  }
3089
3090
0
  int nBestDirect;
3091
0
  for ( uint32_t uiRound = 0; uiRound < uiMaxSearchRounds; uiRound++ )
3092
0
  {
3093
0
    Distortion roundZeroBestCost = MAX_DISTORTION;
3094
0
    const int positionLut[ 8 ] = { 0, 2, 4, 6, 1, 3, 5, 7 };
3095
0
    nBestDirect = -1;
3096
0
    MvField mvCurCenter = rCurMvField;
3097
0
    for ( int nIdx = nDirectStart; nIdx <= nDirectEnd; nIdx++ )
3098
0
    {
3099
      // terminate the search if none of the first four tested points hasn't provided improvement
3100
0
      if( m_pcEncCfg->m_SMVD > 1 && 2 == SearchPattern && 0 == uiRound && 4 == nIdx && roundZeroBestCost > uiMinCost )
3101
0
      {
3102
0
        break;
3103
0
      }
3104
0
      int nDirect;
3105
0
      if ( SearchPattern == 3 )
3106
0
      {
3107
0
        nDirect = nIdx < 0 ? nIdx + 6 : nIdx >= 6 ? nIdx - 6 : nIdx;
3108
0
      }
3109
0
      else
3110
0
      {
3111
0
        if( m_pcEncCfg->m_SMVD > 1 && 2 == SearchPattern && 0 == uiRound )
3112
0
        {
3113
0
          nDirect = positionLut[ ( nIdx + nDirectRounding ) & nDirectMask ];
3114
0
        }
3115
0
        else
3116
0
        {
3117
0
          nDirect = ( nIdx + nDirectRounding ) & nDirectMask;
3118
0
        }
3119
0
      }
3120
3121
0
      Mv mvOffset = pSearchOffset[nDirect];
3122
0
      mvOffset <<= nSearchStepShift;
3123
0
      MvField mvCand = mvCurCenter, mvPair;
3124
0
      mvCand.mv += mvOffset;
3125
0
      if( m_pcEncCfg->m_ifpLines && !CU::isMvInRangeFPP( cu.ly(), cu.lheight(), mvCand.mv.ver, m_pcEncCfg->m_ifpLines, *cu.cs->pcv ) )
3126
0
      {
3127
0
        continue; // Skip this pos
3128
0
      }
3129
3130
      // get MVD cost
3131
0
      Mv pred = rcMvCurPred;
3132
0
      pred.changeTransPrecInternal2Amvr(cu.imv);
3133
0
      m_pcRdCost->setPredictor( pred );
3134
0
      m_pcRdCost->setCostScale( 0 );
3135
0
      Mv mv = mvCand.mv;
3136
0
      mv.changeTransPrecInternal2Amvr(cu.imv);
3137
0
      uint32_t uiMvBits = m_pcRdCost->getBitsOfVectorWithPredictor( mv.hor, mv.ver, 0 );
3138
0
      Distortion uiCost = m_pcRdCost->getCost( uiMvBits );
3139
3140
      // get MVD pair and set target MV
3141
0
      mvPair.refIdx = rTarMvField.refIdx;
3142
0
      mvPair.mv.set( rcMvTarPred.hor - (mvCand.mv.hor - rcMvCurPred.hor), rcMvTarPred.ver - (mvCand.mv.ver - rcMvCurPred.ver) );
3143
3144
0
      if( m_pcEncCfg->m_ifpLines && !CU::isMvInRangeFPP( cu.ly(), cu.lheight(), mvPair.mv.ver, m_pcEncCfg->m_ifpLines, *cu.cs->pcv ) )
3145
0
      {
3146
0
        continue; // Skip this pos
3147
0
      }
3148
3149
0
      uiCost += xGetSymCost( cu, origBuf, refPicList, mvCand, mvPair, BcwIdx );
3150
0
      if ( uiCost < uiMinCost )
3151
0
      {
3152
0
        uiMinCost = uiCost;
3153
0
        rCurMvField = mvCand;
3154
0
        rTarMvField = mvPair;
3155
0
        nBestDirect = nDirect;
3156
0
      }
3157
0
      if ( m_pcEncCfg->m_SMVD > 1 && 2 == SearchPattern && 0 == uiRound && 4 > nIdx && uiCost < roundZeroBestCost)
3158
0
      {
3159
0
        roundZeroBestCost = uiCost;
3160
0
      }
3161
0
    }
3162
3163
0
    if ( nBestDirect == -1 )
3164
0
    {
3165
0
      break;
3166
0
    }
3167
0
    int nStep = 1;
3168
0
    if( (SearchPattern == 1 || SearchPattern == 2) && m_pcEncCfg->m_SMVD <= 1 )
3169
0
    {
3170
      // test at most 3 points in fast presets
3171
0
      nStep = 2 - ( nBestDirect & 0x01 );
3172
0
    }
3173
0
    nDirectStart = nBestDirect - nStep;
3174
0
    nDirectEnd = nBestDirect + nStep;
3175
0
  }
3176
3177
0
  return(uiMinCost);
3178
0
}
3179
3180
3181
void InterSearch::xSymMotionEstimation( CodingUnit& cu, CPelUnitBuf& origBuf, Mv& rcMvCurPred, Mv& rcMvTarPred, RefPicList refPicList, MvField& rCurMvField, MvField& rTarMvField, Distortion& ruiCost, int BcwIdx )
3182
0
{
3183
  // Refine Search
3184
0
  int nSearchStepShift = MV_FRACTIONAL_BITS_DIFF;
3185
0
  int nDiamondRound = 8;
3186
0
  int nCrossRound = 1;
3187
3188
0
  nSearchStepShift += cu.imv == IMV_HPEL ? 1 : (cu.imv << 1);
3189
0
  nDiamondRound >>= cu.imv;
3190
3191
0
  ruiCost = xSymRefineMvSearch( cu, origBuf, rcMvCurPred, rcMvTarPred, refPicList, rCurMvField, rTarMvField, ruiCost, 2, nSearchStepShift, nDiamondRound, BcwIdx );
3192
0
  if( m_pcEncCfg->m_SMVD < 3 )
3193
0
  {
3194
0
    ruiCost = xSymRefineMvSearch( cu, origBuf, rcMvCurPred, rcMvTarPred, refPicList, rCurMvField, rTarMvField, ruiCost, 0, nSearchStepShift, nCrossRound, BcwIdx );
3195
0
  }
3196
0
}
3197
3198
3199
// A vertical-only sub-pel position of the ME (fraction quarterFrac / 4 vertically, 0 horizontally), filtered from the
3200
// reference rows starting at rowOffset relative to the pattern. Before, these positions were filtered from a frac-0
3201
// "horizontal" pass, ( x << h ) - IF_INTERNAL_OFFS in m_filteredBlockTmp[ 0 ][ 0 ], with isFirst = false. Because the
3202
// taps sum to 64, ( sum c * ( ( x << h ) - IF_INTERNAL_OFFS ) + IF_INTERNAL_OFFS * 64 + 2^(5+h) ) >> ( 6 + h ) equals
3203
// ( sum c * x + 32 ) >> 6, the isFirst = true filter of the reference, with the same clip: identical samples, without
3204
// the copy, for every luma filter the ME uses and both internal bit depths (8 and 10).
3205
void InterSearch::xFilterVerFromReference( const CPelBuf* pattern, int rowOffset, Pel* dst, int dstStride, int height, int quarterFrac, bool useAltHpelIf )
3206
0
{
3207
0
  m_if.filterVer( COMP_Y, pattern->buf + rowOffset * pattern->stride, pattern->stride, dst, dstStride, pattern->width, height,
3208
0
                  quarterFrac << MV_FRACTIONAL_BITS_DIFF, true, true, m_currChromaFormat, m_lumaClpRng, useAltHpelIf, 0, m_pcEncCfg->m_meReduceTap );
3209
0
}
3210
3211
/**
3212
* \brief Generate half-sample interpolated block
3213
*
3214
* \param pattern Reference picture ROI
3215
* \param biPred    Flag indicating whether block is for biprediction
3216
*/
3217
void InterSearch::xExtDIFUpSamplingH(CPelBuf* pattern, bool useAltHpelIf)
3218
0
{
3219
0
  PROFILER_SCOPE_AND_STAGE( 0, _TPROF, P_HPEL_INTERP );
3220
0
  const ClpRng& clpRng = m_lumaClpRng;
3221
0
  int width            = pattern->width;
3222
0
  int height           = pattern->height;
3223
0
  int srcStride        = pattern->stride;
3224
0
  const int reduceTap = m_pcEncCfg->m_meReduceTap;
3225
3226
0
  int intStride = fracSearchStride( width );
3227
0
  int dstStride = fracSearchStride( width );
3228
  // At widths 4 and 8 the stride has room for the block and its extra column, and one call at the whole stride fills both on the
3229
  // kernel of the next width. Wider blocks keep the column as a second call, as a rounded width would leave their kernel.
3230
0
  const bool columnInFirstCall = intStride > width + 1;
3231
0
  const int  firstCallWidth    = columnInFirstCall ? intStride : width;
3232
0
  Pel* intPtr;
3233
0
  Pel* dstPtr;
3234
0
  int filterSize     = useAltHpelIf ? ( reduceTap >= 1 ? NTAPS_AFFINE : NTAPS_LUMA )
3235
0
                                    : ( reduceTap == 1 ? NTAPS_AFFINE
3236
0
                                                       : ( reduceTap == 0 ? NTAPS_LUMA : NTAPS_CHROMA ) );
3237
0
  int halfFilterSize = ( filterSize >> 1 );
3238
0
  const Pel *srcPtr  = pattern->buf - halfFilterSize * srcStride - 1;
3239
3240
0
  const ChromaFormat chFmt = m_currChromaFormat;
3241
3242
  // the integer position needs no interpolation: xPatternRefinement's SAD reads the reference itself
3243
3244
0
  m_if.filterHor( COMP_Y, srcPtr, srcStride, m_filteredBlockTmp[2][0], intStride, firstCallWidth, height + filterSize, 2 << MV_FRACTIONAL_BITS_DIFF, false, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
3245
0
  if( !columnInFirstCall )
3246
0
  {
3247
0
    m_if.filterHor( COMP_Y, srcPtr + width, srcStride, m_filteredBlockTmp[2][0] + width, intStride,     1, height + filterSize, 2 << MV_FRACTIONAL_BITS_DIFF, false, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
3248
0
  }
3249
3250
0
  dstPtr = m_filteredBlock[2][0][0];
3251
0
  xFilterVerFromReference( pattern, -1, dstPtr, dstStride, height + 1, 2, useAltHpelIf );
3252
3253
0
  intPtr = m_filteredBlockTmp[2][0] + halfFilterSize * intStride;
3254
0
  dstPtr = m_filteredBlock[0][2][0];
3255
  // The rows follow each other in both buffers, so all of them are one long row. It copies the block and its extra column.
3256
0
  m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, intStride * height, 1, 0 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
3257
3258
0
  intPtr = m_filteredBlockTmp[2][0] + (halfFilterSize - 1) * intStride;
3259
0
  dstPtr = m_filteredBlock[2][2][0];
3260
0
  m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, firstCallWidth, height + 1, 2 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
3261
0
  if( !columnInFirstCall )
3262
0
  {
3263
0
    m_if.filterVer( COMP_Y, intPtr + width, intStride, dstPtr + width, dstStride,     1, height + 1, 2 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, useAltHpelIf, 0, reduceTap );
3264
0
  }
3265
0
}
3266
3267
3268
3269
3270
3271
/**
3272
* \brief Generate quarter-sample interpolated blocks
3273
*
3274
* \param pattern    Reference picture ROI
3275
* \param halfPelRef Half-pel mv
3276
* \param biPred     Flag indicating whether block is for biprediction
3277
*/
3278
void InterSearch::xExtDIFUpSamplingQ( CPelBuf* pattern, Mv halfPelRef, int& patternId )
3279
0
{
3280
0
  PROFILER_SCOPE_AND_STAGE( 0, _TPROF, P_QPEL_INTERP );
3281
0
  const ClpRng& clpRng = m_lumaClpRng;
3282
0
  int width      = pattern->width;
3283
0
  int height     = pattern->height;
3284
0
  int srcStride  = pattern->stride;
3285
0
  const int reduceTap = m_pcEncCfg->m_meReduceTap;
3286
3287
0
  Pel const* srcPtr;
3288
0
  int intStride = fracSearchStride( width );
3289
0
  int dstStride = fracSearchStride( width );
3290
0
  Pel* intPtr;
3291
0
  Pel* dstPtr;
3292
3293
0
  int filterSize     = reduceTap == 1 ? NTAPS_AFFINE
3294
0
                   : ( reduceTap == 0 ? NTAPS_LUMA : NTAPS_CHROMA );
3295
3296
0
  int halfFilterSize = (filterSize>>1);
3297
3298
0
  int extHeight = (halfPelRef.ver == 0) ? height + filterSize : height + filterSize-1;
3299
3300
0
  const ChromaFormat chFmt = m_currChromaFormat;
3301
3302
0
  if( s_doInterpQ[ patternId ][ 12 ] )
3303
0
  {
3304
    // Horizontal filter 1/4
3305
0
    srcPtr = pattern->buf - halfFilterSize * srcStride - 1;
3306
0
    intPtr = m_filteredBlockTmp[ 1 ][ 0 ];
3307
0
    if( halfPelRef.ver > 0 )
3308
0
    {
3309
0
      srcPtr += srcStride;
3310
0
    }
3311
0
    if( halfPelRef.hor >= 0 )
3312
0
    {
3313
0
      srcPtr += 1;
3314
0
    }
3315
0
    m_if.filterHor( COMP_Y, srcPtr, srcStride, intPtr, intStride, width, extHeight, 1 << MV_FRACTIONAL_BITS_DIFF, false, chFmt, clpRng, false, 0, reduceTap );
3316
0
  }
3317
3318
0
  if( s_doInterpQ[ patternId ][ 13 ] )
3319
0
  {
3320
    // Horizontal filter 3/4
3321
0
    srcPtr = pattern->buf - halfFilterSize*srcStride - 1;
3322
0
    intPtr = m_filteredBlockTmp[ 3 ][ 0 ];
3323
0
    if( halfPelRef.ver > 0 )
3324
0
    {
3325
0
      srcPtr += srcStride;
3326
0
    }
3327
0
    if( halfPelRef.hor > 0 )
3328
0
    {
3329
0
      srcPtr += 1;
3330
0
    }
3331
0
    m_if.filterHor( COMP_Y, srcPtr, srcStride, intPtr, intStride, width, extHeight, 3 << MV_FRACTIONAL_BITS_DIFF, false, chFmt, clpRng, false, 0, reduceTap );
3332
0
  }
3333
3334
0
  if( s_doInterpQ[ patternId ][ 3 ] )
3335
0
  {
3336
    // Generate @ 1,1
3337
0
    intPtr = m_filteredBlockTmp[ 1 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3338
0
    dstPtr = m_filteredBlock[ 1 ][ 1 ][ 0 ];
3339
0
    if( halfPelRef.ver == 0 )
3340
0
    {
3341
0
      intPtr += intStride;
3342
0
    }
3343
0
    m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3344
0
  }
3345
3346
0
  if( s_doInterpQ[ patternId ][ 11 ] )
3347
0
  {
3348
    // Generate @ 3,3
3349
0
    intPtr = m_filteredBlockTmp[ 3 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3350
0
    dstPtr = m_filteredBlock[ 3 ][ 3 ][ 0 ];
3351
0
    m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3352
0
  }
3353
3354
0
  if( s_doInterpQ[ patternId ][ 5 ] )
3355
0
  {
3356
    // Generate @ 3,1
3357
0
    intPtr = m_filteredBlockTmp[ 1 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3358
0
    dstPtr = m_filteredBlock[ 3 ][ 1 ][ 0 ];
3359
0
    m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3360
0
  }
3361
3362
0
  if( s_doInterpQ[ patternId ][ 9 ] )
3363
0
  {
3364
    // Generate @ 1,3
3365
0
    intPtr = m_filteredBlockTmp[ 3 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3366
0
    dstPtr = m_filteredBlock[ 1 ][ 3 ][ 0 ];
3367
0
    if( halfPelRef.ver == 0 )
3368
0
    {
3369
0
      intPtr += intStride;
3370
0
    }
3371
0
    m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3372
0
  }
3373
3374
0
  if (halfPelRef.ver != 0)
3375
0
  {
3376
0
    if( s_doInterpQ[ patternId ][ 4 ] )
3377
0
    {
3378
      // Generate @ 2,1
3379
0
      intPtr = m_filteredBlockTmp[ 1 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3380
0
      dstPtr = m_filteredBlock[ 2 ][ 1 ][ 0 ];
3381
0
      if( halfPelRef.ver == 0 )
3382
0
      {
3383
0
        intPtr += intStride;
3384
0
      }
3385
0
      m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 2 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3386
0
    }
3387
3388
0
    if( s_doInterpQ[ patternId ][ 10 ] )
3389
0
    {
3390
      // Generate @ 2,3
3391
0
      intPtr = m_filteredBlockTmp[ 3 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3392
0
      dstPtr = m_filteredBlock[ 2 ][ 3 ][ 0 ];
3393
0
      if( halfPelRef.ver == 0 )
3394
0
      {
3395
0
        intPtr += intStride;
3396
0
      }
3397
0
      m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 2 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3398
0
    }
3399
0
  }
3400
0
  else
3401
0
  {
3402
0
    if( s_doInterpQ[ patternId ][ 2 ] )
3403
0
    {
3404
      // Generate @ 0,1
3405
0
      intPtr = m_filteredBlockTmp[ 1 ][ 0 ] + halfFilterSize * intStride;
3406
0
      dstPtr = m_filteredBlock[ 0 ][ 1 ][ 0 ];
3407
0
      m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 0 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3408
0
    }
3409
3410
0
    if( s_doInterpQ[ patternId ][ 8 ] )
3411
0
    {
3412
      // Generate @ 0,3
3413
0
      intPtr = m_filteredBlockTmp[ 3 ][ 0 ] + halfFilterSize * intStride;
3414
0
      dstPtr = m_filteredBlock[ 0 ][ 3 ][ 0 ];
3415
0
      m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 0 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3416
0
    }
3417
0
  }
3418
3419
0
  if (halfPelRef.hor != 0)
3420
0
  {
3421
0
    if( s_doInterpQ[ patternId ][ 6 ] )
3422
0
    {
3423
      // Generate @ 1,2
3424
0
      intPtr = m_filteredBlockTmp[ 2 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3425
0
      dstPtr = m_filteredBlock[ 1 ][ 2 ][ 0 ];
3426
0
      if( halfPelRef.hor > 0 )
3427
0
      {
3428
0
        intPtr += 1;
3429
0
      }
3430
0
      if( halfPelRef.ver >= 0 )
3431
0
      {
3432
0
        intPtr += intStride;
3433
0
      }
3434
0
      m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3435
0
    }
3436
3437
0
    if( s_doInterpQ[ patternId ][ 7 ] )
3438
0
    {
3439
      // Generate @ 3,2
3440
0
      intPtr = m_filteredBlockTmp[ 2 ][ 0 ] + ( halfFilterSize - 1 ) * intStride;
3441
0
      dstPtr = m_filteredBlock[ 3 ][ 2 ][ 0 ];
3442
0
      if( halfPelRef.hor > 0 )
3443
0
      {
3444
0
        intPtr += 1;
3445
0
      }
3446
0
      if( halfPelRef.ver > 0 )
3447
0
      {
3448
0
        intPtr += intStride;
3449
0
      }
3450
0
      m_if.filterVer( COMP_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3 << MV_FRACTIONAL_BITS_DIFF, false, true, chFmt, clpRng, false, 0, reduceTap );
3451
0
    }
3452
0
  }
3453
0
  else
3454
0
  {
3455
0
    if( s_doInterpQ[ patternId ][ 0 ] )
3456
0
    {
3457
      // Generate @ 1,0
3458
0
      dstPtr = m_filteredBlock[ 1 ][ 0 ][ 0 ];
3459
0
      xFilterVerFromReference( pattern, halfPelRef.ver >= 0 ? 0 : -1, dstPtr, dstStride, height, 1, false );
3460
0
    }
3461
3462
0
    if( s_doInterpQ[ patternId ][ 1 ] )
3463
0
    {
3464
      // Generate @ 3,0
3465
0
      dstPtr = m_filteredBlock[ 3 ][ 0 ][ 0 ];
3466
0
      xFilterVerFromReference( pattern, halfPelRef.ver > 0 ? 0 : -1, dstPtr, dstStride, height, 3, false );
3467
0
    }
3468
0
  }
3469
0
}
3470
3471
3472
void InterSearch::xEncodeInterResidualQT(CodingStructure &cs, Partitioner &partitioner, const ComponentID compID)
3473
0
{
3474
0
  const UnitArea& currArea    = partitioner.currArea();
3475
0
  const TransformUnit& currTU = *cs.getTU(isLuma(partitioner.chType) ? currArea.lumaPos() : currArea.chromaPos(), partitioner.chType);
3476
0
  const CodingUnit &cu        = *currTU.cu;
3477
0
  const unsigned currDepth    = partitioner.currTrDepth;
3478
3479
0
  const bool bSubdiv          = currDepth != currTU.depth;
3480
3481
0
  if (compID == MAX_NUM_TBLOCKS)  // we are not processing a channel, instead we always recurse and code the CBFs
3482
0
  {
3483
0
    if( partitioner.canSplit( TU_MAX_TR_SPLIT, cs ) )
3484
0
    {
3485
0
      CHECK( !bSubdiv, "Not performing the implicit TU split" );
3486
0
    }
3487
0
    else if( cu.sbtInfo && partitioner.canSplit( CU::getSbtTuSplit( cu.sbtInfo ), cs ) )
3488
0
    {
3489
0
      CHECK( !bSubdiv, "Not performing the implicit TU split - sbt" );
3490
0
    }
3491
0
    else
3492
0
    {
3493
0
      CHECK( bSubdiv, "transformsplit not supported" );
3494
0
    }
3495
3496
0
    CHECK(CU::isIntra(cu), "Inter search provided with intra CU");
3497
3498
0
    if( cu.chromaFormat != CHROMA_400
3499
0
      && (!CU::isSepTree(cu) || isChroma(partitioner.chType))
3500
0
      )
3501
0
    {
3502
0
      {
3503
0
        {
3504
0
          const bool  chroma_cbf = TU::getCbfAtDepth( currTU, COMP_Cb, currDepth );
3505
0
          if (!(cu.sbtInfo && (currDepth == 0 || (currDepth == 1 && currTU.noResidual))))
3506
0
          m_CABACEstimator->cbf_comp( cu, chroma_cbf, currArea.blocks[COMP_Cb], currDepth );
3507
0
        }
3508
0
        {
3509
0
          const bool  chroma_cbf = TU::getCbfAtDepth( currTU, COMP_Cr, currDepth );
3510
0
          if (!(cu.sbtInfo && (currDepth == 0 || (currDepth == 1 && currTU.noResidual))))
3511
0
          m_CABACEstimator->cbf_comp( cu, chroma_cbf, currArea.blocks[COMP_Cr], currDepth, TU::getCbfAtDepth( currTU, COMP_Cb, currDepth ) );
3512
0
        }
3513
0
      }
3514
0
    }
3515
3516
0
    if( !bSubdiv && !( cu.sbtInfo && currTU.noResidual )
3517
0
      && !isChroma(partitioner.chType)
3518
0
      )
3519
0
    {
3520
0
      m_CABACEstimator->cbf_comp( cu, TU::getCbfAtDepth( currTU, COMP_Y, currDepth ), currArea.Y(), currDepth );
3521
0
    }
3522
0
  }
3523
3524
0
  if (!bSubdiv)
3525
0
  {
3526
0
    if (compID != MAX_NUM_TBLOCKS) // we have already coded the CBFs, so now we code coefficients
3527
0
    {
3528
0
      if( currArea.blocks[compID].valid() )
3529
0
      {
3530
0
        if( compID == COMP_Cr )
3531
0
        {
3532
0
          const int cbfMask = ( TU::getCbf( currTU, COMP_Cb ) ? 2 : 0) + ( TU::getCbf( currTU, COMP_Cr ) ? 1 : 0 );
3533
0
          m_CABACEstimator->joint_cb_cr( currTU, cbfMask );
3534
0
        }
3535
0
        if( TU::getCbf( currTU, compID ) )
3536
0
        {
3537
0
          if( cu.sbtInfo && compID == COMP_Y )
3538
0
          {
3539
0
            m_CABACEstimator->addEstFracBits( m_tuResiBits[COMP_Y] );
3540
0
          }
3541
0
          else
3542
0
          {
3543
0
            const uint64_t bitsBeforeResi = m_CABACEstimator->getEstFracBits();
3544
0
            m_CABACEstimator->residual_coding( currTU, compID );
3545
0
            if( cu.sbtInfo )
3546
0
            {
3547
0
              m_tuResiBits[compID] = m_CABACEstimator->getEstFracBits() - bitsBeforeResi;
3548
0
            }
3549
0
          }
3550
0
        }
3551
0
      }
3552
0
    }
3553
0
  }
3554
0
  else
3555
0
  {
3556
0
    if( compID == MAX_NUM_TBLOCKS || TU::getCbfAtDepth( currTU, compID, currDepth ) )
3557
0
    {
3558
0
      if( partitioner.canSplit( TU_MAX_TR_SPLIT, cs ) )
3559
0
      {
3560
0
        partitioner.splitCurrArea( TU_MAX_TR_SPLIT, cs );
3561
0
      }
3562
0
      else if( cu.sbtInfo && partitioner.canSplit( CU::getSbtTuSplit( cu.sbtInfo ), cs ) )
3563
0
      {
3564
0
        partitioner.splitCurrArea( CU::getSbtTuSplit( cu.sbtInfo ), cs );
3565
0
      }
3566
0
      else
3567
0
        THROW( "Implicit TU split not available!" );
3568
3569
0
      do
3570
0
      {
3571
0
        xEncodeInterResidualQT( cs, partitioner, compID );
3572
0
      } while( partitioner.nextPart( cs ) );
3573
3574
0
      partitioner.exitCurrSplit();
3575
0
    }
3576
0
  }
3577
0
}
3578
3579
void InterSearch::xCalcMinDistSbt( CodingStructure &cs, const CodingUnit& cu, const uint8_t sbtAllowed )
3580
0
{
3581
0
  if( !sbtAllowed )
3582
0
  {
3583
0
    m_estMinDistSbt[NUMBER_SBT_MODE] = 0;
3584
0
    for( int comp = 0; comp < getNumberValidTBlocks( *cs.pcv ); comp++ )
3585
0
    {
3586
0
      const ComponentID compID = ComponentID( comp );
3587
0
      CPelBuf pred = cs.getPredBuf( compID );
3588
0
      CPelBuf org  = cs.getOrgBuf( compID );
3589
0
      m_estMinDistSbt[NUMBER_SBT_MODE] += m_pcRdCost->getDistPart( org, pred, cs.sps->bitDepths[ toChannelType( compID ) ], compID, DF_SSE );
3590
0
    }
3591
0
    return;
3592
0
  }
3593
3594
  //SBT fast algorithm 2.1 : estimate a minimum RD cost of a SBT mode based on the luma distortion of uncoded part and coded part (assuming distorted can be reduced to 1/16);
3595
  //                         if this cost is larger than the best cost, no need to try a specific SBT mode
3596
0
  int cuWidth  = cu.lwidth();
3597
0
  int cuHeight = cu.lheight();
3598
0
  int numPartX = cuWidth  >= 16 ? 4 : ( cuWidth  == 4 ? 1 : 2 );
3599
0
  int numPartY = cuHeight >= 16 ? 4 : ( cuHeight == 4 ? 1 : 2 );
3600
0
  Distortion dist[4][4];
3601
0
  memset( dist, 0, sizeof( Distortion ) * 16 );
3602
0
  const double chromaWeight = m_pcRdCost->getChromaWeight();
3603
3604
0
  for( uint32_t c = 0; c < getNumberValidTBlocks( *cs.pcv ); c++ )
3605
0
  {
3606
0
    const ComponentID compID   = ComponentID( c );
3607
0
    const CompArea&   compArea = cu.blocks[compID];
3608
    // the structure holds this CU alone
3609
0
    CHECKD( compArea.pos() != cs.area.blocks[compID].pos() || compArea.size() != cs.area.blocks[compID].size(), "not the whole structure" );
3610
0
    const CPelBuf orgPel  = cs.getOrgBuf( compID );
3611
0
    const CPelBuf predPel = cs.getPredBuf( compID );
3612
0
    int lengthX = compArea.width / numPartX;
3613
0
    int lengthY = compArea.height / numPartY;
3614
0
    static_assert( DISTORTION_PRECISION_ADJUSTMENT( 2 ) == 0, "the squared errors of the sub parts are not scaled" );
3615
3616
    //calc distY of 16 sub parts
3617
0
    uint32_t sums[4][4];
3618
0
    g_pelBufOP.sumSquaredErrorParts( orgPel.buf, orgPel.stride, predPel.buf, predPel.stride, lengthX, lengthY, numPartX, numPartY, sums );
3619
0
    for( int j = 0; j < numPartY; j++ )
3620
0
    {
3621
0
      for( int i = 0; i < numPartX; i++ )
3622
0
      {
3623
        // each chroma part is weighted and rounded for itself
3624
0
        dist[j][i] += isChroma( compID ) ? (Distortion)( sums[j][i] * chromaWeight ) : (Distortion) sums[j][i];
3625
0
      }
3626
0
    }
3627
0
  }
3628
3629
  //SSE of a CU
3630
0
  m_estMinDistSbt[NUMBER_SBT_MODE] = 0;
3631
0
  for( int j = 0; j < numPartY; j++ )
3632
0
  {
3633
0
    for( int i = 0; i < numPartX; i++ )
3634
0
    {
3635
0
      m_estMinDistSbt[NUMBER_SBT_MODE] += dist[j][i];
3636
0
    }
3637
0
  }
3638
  //init per-mode dist
3639
0
  for( int i = SBT_VER_H0; i < NUMBER_SBT_MODE; i++ )
3640
0
  {
3641
0
    m_estMinDistSbt[i] = MAX_DISTORTION;
3642
0
  }
3643
3644
  //SBT fast algorithm 1: not try SBT if the residual is too small to compensate bits for encoding residual info
3645
0
  uint64_t minNonZeroResiFracBits = 12 << SCALE_BITS;
3646
0
  if( m_pcRdCost->calcRdCost( 0, m_estMinDistSbt[NUMBER_SBT_MODE] ) < m_pcRdCost->calcRdCost( minNonZeroResiFracBits, 0 ) )
3647
0
  {
3648
0
    m_skipSbtAll = true;
3649
0
    return;
3650
0
  }
3651
3652
  //derive estimated minDist of SBT = zero-residual part distortion + non-zero residual part distortion / 16
3653
0
  int shift = 5;
3654
0
  Distortion distResiPart = 0, distNoResiPart = 0;
3655
3656
0
  if( CU::targetSbtAllowed( SBT_VER_HALF, sbtAllowed ) )
3657
0
  {
3658
0
    int offsetResiPart = 0;
3659
0
    int offsetNoResiPart = numPartX / 2;
3660
0
    distResiPart = distNoResiPart = 0;
3661
0
    assert( numPartX >= 2 );
3662
0
    for( int j = 0; j < numPartY; j++ )
3663
0
    {
3664
0
      for( int i = 0; i < numPartX / 2; i++ )
3665
0
      {
3666
0
        distResiPart   += dist[j][i + offsetResiPart];
3667
0
        distNoResiPart += dist[j][i + offsetNoResiPart];
3668
0
      }
3669
0
    }
3670
0
    m_estMinDistSbt[SBT_VER_H0] = ( distResiPart >> shift ) + distNoResiPart;
3671
0
    m_estMinDistSbt[SBT_VER_H1] = ( distNoResiPart >> shift ) + distResiPart;
3672
0
  }
3673
3674
0
  if( CU::targetSbtAllowed( SBT_HOR_HALF, sbtAllowed ) )
3675
0
  {
3676
0
    int offsetResiPart = 0;
3677
0
    int offsetNoResiPart = numPartY / 2;
3678
0
    assert( numPartY >= 2 );
3679
0
    distResiPart = distNoResiPart = 0;
3680
0
    for( int j = 0; j < numPartY / 2; j++ )
3681
0
    {
3682
0
      for( int i = 0; i < numPartX; i++ )
3683
0
      {
3684
0
        distResiPart   += dist[j + offsetResiPart][i];
3685
0
        distNoResiPart += dist[j + offsetNoResiPart][i];
3686
0
      }
3687
0
    }
3688
0
    m_estMinDistSbt[SBT_HOR_H0] = ( distResiPart >> shift ) + distNoResiPart;
3689
0
    m_estMinDistSbt[SBT_HOR_H1] = ( distNoResiPart >> shift ) + distResiPart;
3690
0
  }
3691
3692
0
  if( CU::targetSbtAllowed( SBT_VER_QUAD, sbtAllowed ) )
3693
0
  {
3694
0
    assert( numPartX == 4 );
3695
0
    m_estMinDistSbt[SBT_VER_Q0] = m_estMinDistSbt[SBT_VER_Q1] = 0;
3696
0
    for( int j = 0; j < numPartY; j++ )
3697
0
    {
3698
0
      m_estMinDistSbt[SBT_VER_Q0] += dist[j][0] + ( ( dist[j][1] + dist[j][2] + dist[j][3] ) << shift );
3699
0
      m_estMinDistSbt[SBT_VER_Q1] += dist[j][3] + ( ( dist[j][0] + dist[j][1] + dist[j][2] ) << shift );
3700
0
    }
3701
0
    m_estMinDistSbt[SBT_VER_Q0] = m_estMinDistSbt[SBT_VER_Q0] >> shift;
3702
0
    m_estMinDistSbt[SBT_VER_Q1] = m_estMinDistSbt[SBT_VER_Q1] >> shift;
3703
0
  }
3704
3705
0
  if( CU::targetSbtAllowed( SBT_HOR_QUAD, sbtAllowed ) )
3706
0
  {
3707
0
    assert( numPartY == 4 );
3708
0
    m_estMinDistSbt[SBT_HOR_Q0] = m_estMinDistSbt[SBT_HOR_Q1] = 0;
3709
0
    for( int i = 0; i < numPartX; i++ )
3710
0
    {
3711
0
      m_estMinDistSbt[SBT_HOR_Q0] += dist[0][i] + ( ( dist[1][i] + dist[2][i] + dist[3][i] ) << shift );
3712
0
      m_estMinDistSbt[SBT_HOR_Q1] += dist[3][i] + ( ( dist[0][i] + dist[1][i] + dist[2][i] ) << shift );
3713
0
    }
3714
0
    m_estMinDistSbt[SBT_HOR_Q0] = m_estMinDistSbt[SBT_HOR_Q0] >> shift;
3715
0
    m_estMinDistSbt[SBT_HOR_Q1] = m_estMinDistSbt[SBT_HOR_Q1] >> shift;
3716
0
  }
3717
3718
  //SBT fast algorithm 5: try N SBT modes with the lowest distortion
3719
0
  Distortion temp[NUMBER_SBT_MODE];
3720
0
  memcpy( temp, m_estMinDistSbt, sizeof( Distortion ) * NUMBER_SBT_MODE );
3721
0
  memset( m_sbtRdoOrder, 255, NUMBER_SBT_MODE );
3722
0
  int startIdx = 0, numRDO;
3723
0
  numRDO = CU::targetSbtAllowed( SBT_VER_HALF, sbtAllowed ) + CU::targetSbtAllowed( SBT_HOR_HALF, sbtAllowed );
3724
0
  numRDO = std::min( ( numRDO << 1 ), SBT_NUM_RDO );
3725
0
  for( int i = startIdx; i < startIdx + numRDO; i++ )
3726
0
  {
3727
0
    Distortion minDist = MAX_DISTORTION;
3728
0
    for( int n = SBT_VER_H0; n <= SBT_HOR_H1; n++ )
3729
0
    {
3730
0
      if( temp[n] < minDist )
3731
0
      {
3732
0
        minDist = temp[n];
3733
0
        m_sbtRdoOrder[i] = n;
3734
0
      }
3735
0
    }
3736
0
    temp[m_sbtRdoOrder[i]] = MAX_DISTORTION;
3737
0
  }
3738
3739
0
  startIdx += numRDO;
3740
0
  numRDO = CU::targetSbtAllowed( SBT_VER_QUAD, sbtAllowed ) + CU::targetSbtAllowed( SBT_HOR_QUAD, sbtAllowed );
3741
0
  numRDO = std::min( ( numRDO << 1 ), SBT_NUM_RDO );
3742
0
  for( int i = startIdx; i < startIdx + numRDO; i++ )
3743
0
  {
3744
0
    Distortion minDist = MAX_DISTORTION;
3745
0
    for( int n = SBT_VER_Q0; n <= SBT_HOR_Q1; n++ )
3746
0
    {
3747
0
      if( temp[n] < minDist )
3748
0
      {
3749
0
        minDist = temp[n];
3750
0
        m_sbtRdoOrder[i] = n;
3751
0
      }
3752
0
    }
3753
0
    temp[m_sbtRdoOrder[i]] = MAX_DISTORTION;
3754
0
  }
3755
0
}
3756
3757
uint8_t InterSearch::skipSbtByRDCost( int width, int height, int mtDepth, uint8_t sbtIdx, uint8_t sbtPos, double bestCost, Distortion distSbtOff, double costSbtOff, bool rootCbfSbtOff )
3758
0
{
3759
0
  int sbtMode = CU::getSbtMode( sbtIdx, sbtPos );
3760
3761
  //SBT fast algorithm 2.2 : estimate a minimum RD cost of a SBT mode based on the luma distortion of uncoded part and coded part (assuming distorted can be reduced to 1/16);
3762
  //                         if this cost is larger than the best cost, no need to try a specific SBT mode
3763
0
  if( m_pcRdCost->calcRdCost( 11 << SCALE_BITS, m_estMinDistSbt[sbtMode] ) > bestCost )
3764
0
  {
3765
0
    return 0; //early skip type 0
3766
0
  }
3767
3768
0
  if( costSbtOff != MAX_DOUBLE )
3769
0
  {
3770
0
    if( !rootCbfSbtOff )
3771
0
    {
3772
      //SBT fast algorithm 3: skip SBT when the residual is too small (estCost is more accurate than fast algorithm 1, counting PU mode bits)
3773
0
      uint64_t minNonZeroResiFracBits = 10 << SCALE_BITS;
3774
0
      Distortion distResiPart;
3775
0
      if( sbtIdx == SBT_VER_HALF || sbtIdx == SBT_HOR_HALF )
3776
0
      {
3777
0
        distResiPart = (Distortion)( ( ( m_estMinDistSbt[NUMBER_SBT_MODE] - m_estMinDistSbt[sbtMode] ) * 9 ) >> 4 );
3778
0
      }
3779
0
      else
3780
0
      {
3781
0
        distResiPart = (Distortion)( ( ( m_estMinDistSbt[NUMBER_SBT_MODE] - m_estMinDistSbt[sbtMode] ) * 3 ) >> 3 );
3782
0
      }
3783
3784
0
      double estCost = ( costSbtOff - m_pcRdCost->calcRdCost( 0 << SCALE_BITS, distSbtOff ) ) + m_pcRdCost->calcRdCost( minNonZeroResiFracBits, m_estMinDistSbt[sbtMode] + distResiPart );
3785
0
      if( estCost > costSbtOff )
3786
0
      {
3787
0
        return 1;
3788
0
      }
3789
0
      if( estCost > bestCost )
3790
0
      {
3791
0
        return 2;
3792
0
      }
3793
0
    }
3794
0
    else
3795
0
    {
3796
      //SBT fast algorithm 4: skip SBT when an estimated RD cost is larger than the bestCost
3797
0
      double weight = sbtMode > SBT_HOR_H1 ? 0.4 : 0.6;
3798
0
      double estCost = ( ( costSbtOff - m_pcRdCost->calcRdCost( 0 << SCALE_BITS, distSbtOff ) ) * weight ) + m_pcRdCost->calcRdCost( 0 << SCALE_BITS, m_estMinDistSbt[sbtMode] );
3799
0
      if( estCost > bestCost )
3800
0
      {
3801
0
        return 3;
3802
0
      }
3803
0
    }
3804
0
  }
3805
0
  return MAX_UCHAR;
3806
0
}
3807
3808
// ctxStart: a copy of the estimator's contexts on entry (the callers save them right before the call); every test starts from it
3809
void InterSearch::xEstimateInterResidualQT(CodingStructure &cs, Partitioner &partitioner, const Ctx& ctxStart, Distortion *puiZeroDist /*= NULL*/)
3810
26.8k
{
3811
26.8k
  const UnitArea& currArea = partitioner.currArea();
3812
26.8k
  const SPS &sps           = *cs.sps;
3813
3814
26.8k
  const uint32_t numValidComp  = getNumberValidComponents( sps.chromaFormatIdc );
3815
26.8k
  const uint32_t numTBlocks    = getNumberValidTBlocks   ( *cs.pcv );
3816
26.8k
  CodingUnit& cu               = *cs.getCU(partitioner.chType, partitioner.treeType);
3817
26.8k
  const unsigned currDepth = partitioner.currTrDepth;
3818
26.8k
  const bool useTS = cs.picture->useTS;
3819
3820
26.8k
  bool bCheckFull  = !partitioner.canSplit( TU_MAX_TR_SPLIT, cs );
3821
26.8k
  if( cu.sbtInfo && partitioner.canSplit( CU::getSbtTuSplit( cu.sbtInfo ), cs ) )
3822
0
  {
3823
0
    bCheckFull = false;
3824
0
  }
3825
26.8k
  bool bCheckSplit = !bCheckFull;
3826
3827
  // get temporary data
3828
26.8k
  CodingStructure *csSplit = nullptr;
3829
26.8k
  CodingStructure *csFull  = nullptr;
3830
26.8k
  if (bCheckSplit)
3831
0
  {
3832
0
    csSplit = &cs;
3833
0
  }
3834
26.8k
  else if (bCheckFull)
3835
26.8k
  {
3836
26.8k
    csFull = &cs;
3837
26.8k
  }
3838
3839
26.8k
  Distortion uiSingleDist         = 0;
3840
26.8k
  Distortion uiSingleDistComp [3] = { 0, 0, 0 };
3841
3842
26.8k
  TempCtx       ctxBest   ( m_CtxCache );
3843
3844
26.8k
  if (bCheckFull)
3845
26.8k
  {
3846
    // Only this branch reads the saved residual; a split saves its own in each sub-block.
3847
26.8k
    PelUnitBuf orgResiBuf = m_tmpStorageLCU.getCompactBuf( currArea );
3848
26.8k
    orgResiBuf.copyFrom(cs.getResiBuf(currArea));
3849
3850
26.8k
    TransformUnit& tu = csFull->addTU(CS::getArea(cs, currArea, partitioner.chType, partitioner.treeType), partitioner.chType, &cu);
3851
26.8k
    tu.depth          = currDepth;
3852
26.8k
    tu.mtsIdx[COMP_Y] = MTS_DCT2_DCT2;
3853
26.8k
    tu.checkTuNoResidual( partitioner.currPartIdx() );
3854
3855
26.8k
    double minCost [MAX_NUM_TBLOCKS];
3856
26.8k
    uint64_t resiBits = 0, bestLumaResiBits = 0;
3857
3858
26.8k
    m_CABACEstimator->resetBits();
3859
3860
107k
    for (uint32_t i = 0; i < numTBlocks; i++)
3861
80.5k
    {
3862
80.5k
      minCost[i] = MAX_DOUBLE;
3863
80.5k
    }
3864
3865
26.8k
    CodingStructure &saveCS = *m_pSaveCS[1];
3866
26.8k
    saveCS.pcv     = cs.pcv;
3867
26.8k
    saveCS.picture = cs.picture;
3868
26.8k
    saveCS.area.repositionTo( currArea );
3869
3870
26.8k
    TransformUnit& bestTU = saveCS.tus.empty() ? saveCS.addTU( currArea, partitioner.chType, nullptr ) : *saveCS.tus.front();
3871
26.8k
    bestTU.initData();
3872
26.8k
    bestTU.UnitArea::operator=( currArea );
3873
3874
    // What the estimator coded since it last held ctxStart's contexts (at entry it does): nothing, only the zero cbf of one
3875
    // component (its QtCbf contexts), or more. A restore puts back only what changed.
3876
26.8k
    enum class CtxChange { NONE, ZERO_CBF, ANY };
3877
26.8k
    CtxChange   ctxChange   = CtxChange::NONE;
3878
26.8k
    ComponentID zeroCbfComp = COMP_Y;   // read only in the ZERO_CBF state
3879
26.8k
    auto restoreCtxStart = [&]()
3880
57.2k
    {
3881
57.2k
      if( ctxChange == CtxChange::ANY )
3882
205
      {
3883
205
        m_CABACEstimator->getCtx() = ctxStart;
3884
205
      }
3885
57.0k
      else if( ctxChange == CtxChange::ZERO_CBF )
3886
30.1k
      {
3887
30.1k
        m_CABACEstimator->getCtx() = SubCtx( Ctx::QtCbf[zeroCbfComp], ctxStart );
3888
30.1k
      }
3889
57.2k
      ctxChange = CtxChange::NONE;
3890
57.2k
    };
3891
3892
107k
    for( uint32_t c = 0; c < numTBlocks; c++ )
3893
80.5k
    {
3894
80.5k
      const ComponentID compID    = ComponentID(c);
3895
80.5k
      const CompArea&   compArea  = tu.blocks[compID];
3896
80.5k
      const int channelBitDepth   = sps.bitDepths[toChannelType(compID)];
3897
3898
80.5k
      if( !tu.blocks[compID].valid() )
3899
53.7k
      {
3900
53.7k
        continue;
3901
53.7k
      }
3902
26.8k
      bool tsAllowed = useTS && TU::isTSAllowed(tu, compID) && (isLuma(compID) || (isChroma(compID) && m_pcEncCfg->m_useChromaTS));
3903
26.8k
      if (isChroma(compID) && tsAllowed && (tu.mtsIdx[COMP_Y] != MTS_SKIP))
3904
0
      {
3905
0
        tsAllowed = false;
3906
0
      }
3907
26.8k
      uint8_t nNumTransformCands = 1 + (tsAllowed ? 1 : 0); // DCT + TS = 2 tests
3908
26.8k
      TrModeList trModes;
3909
3910
26.8k
      if (nNumTransformCands > 1)
3911
3.51k
      {
3912
3.51k
        trModes.push_back(TrMode(0, true)); //DCT2
3913
        //for a SBT-no-residual TU, the RDO process should be called once, in order to get the RD cost
3914
3.51k
        if ( !tu.noResidual )
3915
3.51k
        {
3916
3.51k
          trModes.push_back(TrMode(1, true));
3917
3.51k
        }
3918
0
        else
3919
0
        {
3920
0
          nNumTransformCands--;
3921
0
        }
3922
3.51k
      }
3923
26.8k
      bool isLast = true;
3924
57.0k
      for (int transformMode = 0; transformMode < nNumTransformCands; transformMode++)
3925
30.1k
      {
3926
30.1k
        const bool isFirstMode = transformMode == 0;
3927
3928
        // copy the original residual into the residual buffer; before the first mode it still holds that residual
3929
30.1k
        if( !isFirstMode )
3930
3.32k
        {
3931
3.32k
          csFull->getResiBuf(compArea).copyFrom(orgResiBuf.get(compID));
3932
3.32k
        }
3933
3934
3935
30.1k
        restoreCtxStart();
3936
30.1k
        m_CABACEstimator->resetBits();
3937
3938
30.1k
        if (bestTU.mtsIdx[compID] == MTS_SKIP && m_pcEncCfg->m_TS)
3939
0
        {
3940
0
          continue;
3941
0
        }
3942
30.1k
        tu.mtsIdx[compID] = transformMode ? trModes[transformMode].first : 0;
3943
3944
30.1k
        const QpParam cQP(tu, compID);  // note: uses tu.transformSkip[compID]
3945
30.1k
        m_pcTrQuant->selectLambda(compID);
3946
3947
30.1k
        if ( sps.jointCbCr && isChroma( compID ) && ( tu.cu->cs->slice->sliceQp > 18 ) )
3948
0
        {
3949
0
          m_pcTrQuant->scaleLambda( 1.05 );
3950
0
        }
3951
30.1k
        TCoeff     currAbsSum = 0;
3952
30.1k
        uint64_t   currCompFracBits = 0;
3953
30.1k
        Distortion currCompDist = 0;
3954
30.1k
        double     currCompCost = 0;
3955
30.1k
        uint64_t   nonCoeffFracBits = 0;
3956
30.1k
        Distortion nonCoeffDist = 0;
3957
30.1k
        double     nonCoeffCost = 0;
3958
3959
30.1k
        if (nNumTransformCands > 1)
3960
6.83k
        {
3961
6.83k
          if (transformMode == 0)
3962
3.51k
          {
3963
3.51k
            m_pcTrQuant->checktransformsNxN(tu, &trModes, 2, compID);
3964
3.51k
            tu.mtsIdx[compID] = trModes[0].first;
3965
3.51k
            if (!trModes[transformMode + 1].second)
3966
191
            {
3967
191
              nNumTransformCands = 1;
3968
191
            }
3969
3.51k
          }
3970
6.83k
          m_pcTrQuant->transformNxN(tu, compID, cQP, currAbsSum, m_CABACEstimator->getCtx(), true);
3971
6.83k
        }
3972
23.3k
        else
3973
23.3k
        {
3974
23.3k
          m_pcTrQuant->transformNxN(tu, compID, cQP, currAbsSum, m_CABACEstimator->getCtx());
3975
23.3k
        }
3976
30.1k
        if (isFirstMode || (currAbsSum == 0))
3977
30.1k
        {
3978
30.1k
          const CPelBuf zeroBuf(m_pTempPel, compArea);
3979
30.1k
          const CPelBuf& orgResi = orgResiBuf.get(compID);
3980
3981
30.1k
          nonCoeffDist = m_pcRdCost->getDistPart(zeroBuf, orgResi, channelBitDepth, compID, DF_SSE); // initialized with zero residual distortion
3982
3983
30.1k
          if (!tu.noResidual)
3984
30.1k
          {
3985
30.1k
            const bool prevCbf = (compID == COMP_Cr ? tu.cbf[COMP_Cb] : false);
3986
30.1k
            m_CABACEstimator->cbf_comp(*tu.cu, false, compArea, currDepth, prevCbf);
3987
            // the only bin coded since restoreCtxStart at the top of this mode
3988
30.1k
            ctxChange   = CtxChange::ZERO_CBF;
3989
30.1k
            zeroCbfComp = compID;
3990
30.1k
          }
3991
3992
30.1k
          nonCoeffFracBits = m_CABACEstimator->getEstFracBits();
3993
30.1k
          nonCoeffCost = m_pcRdCost->calcRdCost(nonCoeffFracBits, nonCoeffDist, !m_pcEncCfg->m_lumaLevelToDeltaQPEnabled);
3994
30.1k
        }
3995
3996
30.1k
        if ((puiZeroDist != NULL) && isFirstMode)
3997
26.8k
        {
3998
26.8k
          *puiZeroDist += nonCoeffDist; // initialized with zero residual distortion
3999
26.8k
        }
4000
4001
30.1k
        if (currAbsSum > 0) //if non-zero coefficients are present, a residual needs to be derived for further prediction
4002
205
        {
4003
205
          if (isFirstMode)
4004
205
          {
4005
            // since restoreCtxStart above only the zero cbf was coded (checktransformsNxN and transformNxN only read the
4006
            // contexts)
4007
205
            restoreCtxStart();
4008
205
            m_CABACEstimator->resetBits();
4009
205
          }
4010
4011
205
          ctxChange = CtxChange::ANY;
4012
205
          const bool prevCbf = ( compID == COMP_Cr ? tu.cbf[COMP_Cb] : false );
4013
205
          m_CABACEstimator->cbf_comp( *tu.cu, true, compArea, currDepth, prevCbf );
4014
205
          if( compID == COMP_Cr )
4015
0
          {
4016
0
            const int cbfMask = ( tu.cbf[COMP_Cb] ? 2 : 0 ) + 1;
4017
0
            m_CABACEstimator->joint_cb_cr( tu, cbfMask );
4018
0
          }
4019
205
          CUCtx cuCtx;
4020
205
          cuCtx.isDQPCoded = true;
4021
205
          cuCtx.isChromaQpAdjCoded = true;
4022
205
          const uint64_t bitsBeforeResi = m_CABACEstimator->getEstFracBits();
4023
205
          m_CABACEstimator->residual_coding(tu, compID, &cuCtx);
4024
205
          resiBits = m_CABACEstimator->getEstFracBits() - bitsBeforeResi;
4025
205
          m_CABACEstimator->mts_idx(cu, &cuCtx);
4026
4027
205
          currCompFracBits = m_CABACEstimator->getEstFracBits();
4028
4029
205
          PelBuf resiBuf  = csFull->getResiBuf(compArea);
4030
205
          CPelBuf orgResi = orgResiBuf.get(compID);
4031
4032
205
          m_pcTrQuant->invTransformNxN(tu, compID, resiBuf, cQP);
4033
205
          currCompDist = m_pcRdCost->getDistPart(orgResi, resiBuf, channelBitDepth, compID, DF_SSE);
4034
205
          currCompCost = m_pcRdCost->calcRdCost(currCompFracBits, currCompDist, false);
4035
205
        }
4036
29.9k
        else if (transformMode > 0)
4037
3.32k
        {
4038
3.32k
          currCompCost = MAX_DOUBLE;
4039
3.32k
        }
4040
26.6k
        else
4041
26.6k
        {
4042
26.6k
          currCompFracBits = nonCoeffFracBits;
4043
26.6k
          currCompDist     = nonCoeffDist;
4044
26.6k
          currCompCost     = nonCoeffCost;
4045
4046
26.6k
          tu.cbf[compID] = 0;
4047
26.6k
        }
4048
4049
        // evaluate
4050
30.1k
        if ((currCompCost < minCost[compID]) || (transformMode == 1 && currCompCost == minCost[compID]))
4051
26.8k
        {
4052
          // copy component
4053
26.8k
          if (isFirstMode && ((nonCoeffCost < currCompCost) || (currAbsSum == 0))) // check for forced null
4054
26.7k
          {
4055
26.7k
            tu.cbf[compID]   = 0;
4056
4057
26.7k
            currAbsSum       = 0;
4058
26.7k
            currCompFracBits = nonCoeffFracBits;
4059
26.7k
            currCompDist     = nonCoeffDist;
4060
26.7k
            currCompCost     = nonCoeffCost;
4061
26.7k
          }
4062
4063
26.8k
          uiSingleDistComp[compID] = currCompDist;
4064
26.8k
          minCost[compID]          = currCompCost;
4065
26.8k
          if( compID == COMP_Y )
4066
26.8k
          {
4067
26.8k
            bestLumaResiBits = resiBits;
4068
26.8k
            if( currDepth == 0 && !cu.sbtInfo && currAbsSum > 0 )
4069
139
            {
4070
139
              saveCoeffCtx( m_tuLumaCtx, m_CABACEstimator->getCtx() );
4071
139
            }
4072
26.8k
          }
4073
26.8k
          if (transformMode != (nNumTransformCands - 1))
4074
3.32k
          {
4075
3.32k
            bestTU.copyComponentFrom(tu, compID);
4076
3.32k
            saveCS.getResiBuf(compArea).copyFrom(csFull->getResiBuf(compArea));
4077
3.32k
          }
4078
23.5k
          else
4079
23.5k
          {
4080
23.5k
            isLast = false;
4081
23.5k
          }
4082
26.8k
        }
4083
30.1k
        if( tu.noResidual )
4084
0
        {
4085
0
          CHECK( currCompFracBits > 0 || currAbsSum, "currCompFracBits > 0 when tu noResidual" );
4086
0
        }
4087
30.1k
      }
4088
26.8k
      if (isLast)
4089
3.32k
      {
4090
3.32k
        tu.copyComponentFrom(bestTU, compID);
4091
3.32k
        csFull->getResiBuf(compArea).copyFrom(saveCS.getResiBuf(compArea));
4092
3.32k
      }
4093
26.8k
    } // component loop
4094
4095
26.8k
    if ( tu.blocks.size()>2 && tu.blocks[COMP_Cb].valid() )
4096
0
    {
4097
0
      const CompArea& cbArea = tu.blocks[COMP_Cb];
4098
0
      const CompArea& crArea = tu.blocks[COMP_Cr];
4099
0
      bool checkJointCbCr = (sps.jointCbCr) && (!tu.noResidual) && (TU::getCbf(tu, COMP_Cb) || TU::getCbf(tu, COMP_Cr));
4100
0
      const int channelBitDepth = sps.bitDepths[toChannelType(COMP_Cb)];
4101
0
      double minCostCbCr = minCost[COMP_Cb] + minCost[COMP_Cr];
4102
0
      bool   isLastBest  = false;
4103
4104
0
      bool checkDCTOnly = m_pcEncCfg->m_useChromaTS && ((TU::getCbf(tu, COMP_Cb) && tu.mtsIdx[COMP_Cb] == MTS_DCT2_DCT2 && !TU::getCbf(tu, COMP_Cr)) ||
4105
0
        (TU::getCbf(tu, COMP_Cr) && tu.mtsIdx[COMP_Cr] == MTS_DCT2_DCT2 && !TU::getCbf(tu, COMP_Cb)) ||
4106
0
        (TU::getCbf(tu, COMP_Cb) && tu.mtsIdx[COMP_Cb] == MTS_DCT2_DCT2 && TU::getCbf(tu, COMP_Cr) && tu.mtsIdx[COMP_Cr] == MTS_DCT2_DCT2));
4107
0
      bool checkTSOnly = m_pcEncCfg->m_useChromaTS && ((TU::getCbf(tu, COMP_Cb) && tu.mtsIdx[COMP_Cb] == MTS_SKIP && !TU::getCbf(tu, COMP_Cr)) ||
4108
0
        (TU::getCbf(tu, COMP_Cr) && tu.mtsIdx[COMP_Cr] == MTS_SKIP && !TU::getCbf(tu, COMP_Cb)) ||
4109
0
        (TU::getCbf(tu, COMP_Cb) && tu.mtsIdx[COMP_Cb] == MTS_SKIP && TU::getCbf(tu, COMP_Cr) && tu.mtsIdx[COMP_Cr] == MTS_SKIP));
4110
4111
0
      std::vector<int> jointCbfMasksToTest;
4112
0
      if ( checkJointCbCr )
4113
0
      {
4114
0
        for( int i = 0; i < 4; i++ )
4115
0
        {
4116
0
          m_orgResiCb[i].compactResize(cbArea);
4117
0
          m_orgResiCr[i].compactResize(crArea);
4118
0
        }
4119
0
        m_orgResiCb[0].copyFrom(orgResiBuf.Cb());
4120
0
        m_orgResiCr[0].copyFrom(orgResiBuf.Cr());
4121
4122
0
        jointCbfMasksToTest = m_pcTrQuant->selectICTCandidates(tu, m_orgResiCb, m_orgResiCr);
4123
4124
0
        bestTU.copyComponentFrom(tu, COMP_Cb);
4125
0
        bestTU.copyComponentFrom(tu, COMP_Cr);
4126
0
        saveCS.getResiBuf(cbArea).copyFrom(csFull->getResiBuf(cbArea));
4127
0
        saveCS.getResiBuf(crArea).copyFrom(csFull->getResiBuf(crArea));
4128
0
      }
4129
4130
0
      for (int cbfMask: jointCbfMasksToTest)
4131
0
      {
4132
0
        ComponentID codeCompId = (cbfMask >> 1 ? COMP_Cb : COMP_Cr);
4133
0
        ComponentID otherCompId = (codeCompId == COMP_Cr ? COMP_Cb : COMP_Cr);
4134
0
        bool tsAllowed = useTS && TU::isTSAllowed(tu, codeCompId) && (m_pcEncCfg->m_useChromaTS);
4135
0
        if (tsAllowed && (tu.mtsIdx[COMP_Y] != MTS_SKIP))
4136
0
        {
4137
0
          tsAllowed = false;
4138
0
        }
4139
0
        if (!tsAllowed)
4140
0
        {
4141
0
          checkTSOnly = false;
4142
0
        }
4143
0
        uint8_t     numTransformCands = 1 + (tsAllowed && (!(checkDCTOnly || checkTSOnly)) ? 1 : 0); // DCT + TS = 2 tests
4144
0
        TrModeList trModes;
4145
0
        if (numTransformCands > 1)
4146
0
        {
4147
0
          trModes.push_back(TrMode(0, true)); // DCT2
4148
0
          trModes.push_back(TrMode(1, true));//TS
4149
0
        }
4150
0
        else
4151
0
        {
4152
0
          tu.mtsIdx[codeCompId] = checkTSOnly ? 1 : 0;
4153
0
        }
4154
0
        for (int modeId = 0; modeId < numTransformCands; modeId++)
4155
0
        {
4156
0
          TCoeff     currAbsSum = 0;
4157
0
          uint64_t   currCompFracBits = 0;
4158
0
          Distortion currCompDistCb = 0;
4159
0
          Distortion currCompDistCr = 0;
4160
0
          double     currCompCost = 0;
4161
4162
0
          tu.jointCbCr = (uint8_t)cbfMask;
4163
0
          if (numTransformCands > 1)
4164
0
          {
4165
0
            tu.mtsIdx[codeCompId] = trModes[modeId].first;
4166
0
          }
4167
0
          tu.mtsIdx[otherCompId] = MTS_DCT2_DCT2;
4168
0
          m_pcTrQuant->selectLambda(COMP_Cb);
4169
4170
          // Lambda is loosened for the joint mode with respect to single modes as the same residual is used for both chroma blocks
4171
0
          const int    absIct = abs(TU::getICTMode(tu));
4172
0
          const double lfact = (absIct == 1 || absIct == 3 ? 0.8 : 0.5);
4173
0
          m_pcTrQuant->scaleLambda(lfact);
4174
0
          if (checkJointCbCr && (tu.cu->cs->slice->sliceQp > 18))
4175
0
          {
4176
0
            m_pcTrQuant->scaleLambda(1.05);
4177
0
          }
4178
4179
0
          restoreCtxStart();
4180
0
          m_CABACEstimator->resetBits();
4181
4182
0
          PelBuf cbResi = csFull->getResiBuf(cbArea);
4183
0
          PelBuf crResi = csFull->getResiBuf(crArea);
4184
0
          cbResi.copyFrom(m_orgResiCb[cbfMask]);
4185
0
          crResi.copyFrom(m_orgResiCr[cbfMask]);
4186
4187
0
          int         codedCbfMask = 0;
4188
0
          ComponentID codeCompId = (tu.jointCbCr >> 1 ? COMP_Cb : COMP_Cr);
4189
0
          ComponentID otherCompId = (codeCompId == COMP_Cr ? COMP_Cb : COMP_Cr);
4190
0
          const QpParam qpCbCr(tu, codeCompId);
4191
4192
0
          tu.getCoeffs(otherCompId).fill(0);   // do we need that?
4193
0
          TU::setCbfAtDepth(tu, otherCompId, tu.depth, false);
4194
4195
0
          PelBuf& codeResi = (codeCompId == COMP_Cr ? crResi : cbResi);
4196
0
          TCoeff  compAbsSum = 0;
4197
0
          if (numTransformCands > 1)
4198
0
          {
4199
0
            if (modeId == 0)
4200
0
            {
4201
0
              m_pcTrQuant->checktransformsNxN(tu, &trModes, 2, codeCompId);
4202
0
              tu.mtsIdx[codeCompId] = trModes[modeId].first;
4203
0
              tu.mtsIdx[otherCompId] = MTS_DCT2_DCT2;
4204
0
              if (!trModes[modeId + 1].second)
4205
0
              {
4206
0
                numTransformCands = 1;
4207
0
              }
4208
0
            }
4209
0
            m_pcTrQuant->transformNxN(tu, codeCompId, qpCbCr, compAbsSum, m_CABACEstimator->getCtx(), true);
4210
0
          }
4211
0
          else
4212
0
          {
4213
0
            m_pcTrQuant->transformNxN(tu, codeCompId, qpCbCr, compAbsSum, m_CABACEstimator->getCtx());
4214
0
          }
4215
0
          if (compAbsSum > 0)
4216
0
          {
4217
0
            m_pcTrQuant->invTransformNxN(tu, codeCompId, codeResi, qpCbCr);
4218
0
            codedCbfMask += (codeCompId == COMP_Cb ? 2 : 1);
4219
0
          }
4220
0
          else
4221
0
          {
4222
0
            codeResi.fill(0);
4223
0
          }
4224
4225
0
          if (tu.jointCbCr == 3 && codedCbfMask == 2)
4226
0
          {
4227
0
            codedCbfMask = 3;
4228
0
            TU::setCbfAtDepth(tu, COMP_Cr, tu.depth, true);
4229
0
          }
4230
0
          if (codedCbfMask && tu.jointCbCr != codedCbfMask)
4231
0
          {
4232
0
            codedCbfMask = 0;
4233
0
          }
4234
0
          currAbsSum = codedCbfMask;
4235
0
          if (!tu.mtsIdx[codeCompId])
4236
0
          {
4237
0
            numTransformCands = (currAbsSum <= 0) ? 1 : numTransformCands;
4238
0
          }
4239
0
          if (currAbsSum > 0)
4240
0
          {
4241
0
            ctxChange = CtxChange::ANY;
4242
0
            m_CABACEstimator->cbf_comp(*tu.cu, codedCbfMask >> 1, cbArea, currDepth, false);
4243
0
            m_CABACEstimator->cbf_comp(*tu.cu, codedCbfMask & 1, crArea, currDepth, codedCbfMask >> 1);
4244
0
            m_CABACEstimator->joint_cb_cr(tu, codedCbfMask);
4245
0
            if (codedCbfMask >> 1)
4246
0
              m_CABACEstimator->residual_coding(tu, COMP_Cb);
4247
0
            if (codedCbfMask & 1)
4248
0
              m_CABACEstimator->residual_coding(tu, COMP_Cr);
4249
0
            currCompFracBits = m_CABACEstimator->getEstFracBits();
4250
4251
0
            m_pcTrQuant->invTransformICT(tu, cbResi, crResi);
4252
4253
0
            currCompDistCb = m_pcRdCost->getDistPart(orgResiBuf.Cb(), cbResi, channelBitDepth, COMP_Cb, DF_SSE);
4254
0
            currCompDistCr = m_pcRdCost->getDistPart(orgResiBuf.Cr(), crResi, channelBitDepth, COMP_Cr, DF_SSE);
4255
0
            currCompCost = m_pcRdCost->calcRdCost(currCompFracBits, currCompDistCr + currCompDistCb, false);
4256
0
          }
4257
0
          else
4258
0
            currCompCost = MAX_DOUBLE;
4259
4260
          // evaluate
4261
0
          if (currCompCost < minCostCbCr)
4262
0
          {
4263
0
            uiSingleDistComp[COMP_Cb] = currCompDistCb;
4264
0
            uiSingleDistComp[COMP_Cr] = currCompDistCr;
4265
0
            minCostCbCr = currCompCost;
4266
0
            isLastBest = (cbfMask == jointCbfMasksToTest.back()) && (modeId == (numTransformCands - 1));
4267
0
            if (!isLastBest)
4268
0
            {
4269
0
              bestTU.copyComponentFrom(tu, COMP_Cb);
4270
0
              bestTU.copyComponentFrom(tu, COMP_Cr);
4271
0
              saveCS.getResiBuf(cbArea).copyFrom(csFull->getResiBuf(cbArea));
4272
0
              saveCS.getResiBuf(crArea).copyFrom(csFull->getResiBuf(crArea));
4273
0
            }
4274
0
          }
4275
0
        }
4276
4277
0
        if( !isLastBest )
4278
0
        {
4279
          // copy component
4280
0
          tu.copyComponentFrom( bestTU, COMP_Cb );
4281
0
          tu.copyComponentFrom( bestTU, COMP_Cr );
4282
0
          csFull->getResiBuf( cbArea ).copyFrom( saveCS.getResiBuf( cbArea ) );
4283
0
          csFull->getResiBuf( crArea ).copyFrom( saveCS.getResiBuf( crArea ) );
4284
0
        }
4285
0
      }
4286
0
    }
4287
4288
    // The bits of the TU. Luma's coefficients were coded above from the same contexts, and chroma's share none with them unless in
4289
    // transform skip. Only a TU at depth 0 can skip them: a following TU would start from the contexts they leave behind, and here the
4290
    // caller goes back to ctxStart.
4291
26.8k
    const bool reuseLumaBits = currDepth == 0 && !cu.sbtInfo && tu.mtsIdx[COMP_Y] != MTS_SKIP;
4292
    // The TU of an SBT CU: the caller codes the bits of the whole CU again after its TUs, and the other TU codes nothing, so these bits
4293
    // and the contexts they leave behind are never read. The caller takes luma's coefficients from here: they start from ctxStart in both
4294
    // places, and the cbfs before them there use other contexts. An SBT TU has no transform skip.
4295
26.8k
    const bool bitsUnused = cu.sbtInfo && currDepth > 0;
4296
26.8k
    if( bitsUnused && !tu.noResidual )
4297
0
    {
4298
0
      m_tuResiBits[COMP_Y] = bestLumaResiBits;
4299
0
    }
4300
26.8k
    restoreCtxStart();
4301
26.8k
    m_CABACEstimator->resetBits();
4302
26.8k
    if( !tu.noResidual && !bitsUnused )
4303
26.8k
    {
4304
26.8k
      static const ComponentID cbf_getComp[3] = { COMP_Cb, COMP_Cr, COMP_Y };
4305
107k
      for( unsigned c = 0; c < numTBlocks; c++)
4306
80.5k
      {
4307
80.5k
        const ComponentID compID = numTBlocks>1 ? cbf_getComp[c] : COMP_Y;
4308
80.5k
        if( tu.blocks[compID].valid() )
4309
26.8k
        {
4310
26.8k
          const bool prevCbf = ( compID == COMP_Cr ? TU::getCbfAtDepth( tu, COMP_Cb, currDepth ) : false );
4311
26.8k
          m_CABACEstimator->cbf_comp( *tu.cu, TU::getCbfAtDepth( tu, compID, currDepth ), tu.blocks[compID], currDepth, prevCbf );
4312
26.8k
        }
4313
80.5k
      }
4314
26.8k
    }
4315
4316
107k
    for (uint32_t ch = 0; ch < numValidComp; ch++)
4317
80.5k
    {
4318
80.5k
      const ComponentID compID = ComponentID(ch);
4319
80.5k
      if (tu.blocks[compID].valid())
4320
26.8k
      {
4321
26.8k
        if( compID == COMP_Cr && !bitsUnused )
4322
0
        {
4323
0
          const int cbfMask = ( TU::getCbf( tu, COMP_Cb ) ? 2 : 0 ) + ( TU::getCbf( tu, COMP_Cr ) ? 1 : 0 );
4324
0
          m_CABACEstimator->joint_cb_cr(tu, cbfMask);
4325
0
        }
4326
26.8k
        if( TU::getCbf( tu, compID ) && !bitsUnused )
4327
139
        {
4328
139
          if( reuseLumaBits && compID == COMP_Y )
4329
139
          {
4330
139
            m_CABACEstimator->addEstFracBits( bestLumaResiBits );
4331
139
            m_tuResiBits[COMP_Y] = bestLumaResiBits;
4332
139
          }
4333
0
          else
4334
0
          {
4335
0
            const uint64_t bitsBeforeResi = m_CABACEstimator->getEstFracBits();
4336
0
            m_CABACEstimator->residual_coding( tu, compID );
4337
0
            m_tuResiBits[compID] = m_CABACEstimator->getEstFracBits() - bitsBeforeResi;
4338
0
          }
4339
139
        }
4340
26.8k
        uiSingleDist += uiSingleDistComp[compID];
4341
26.8k
      }
4342
80.5k
    }
4343
26.8k
    if( tu.noResidual )
4344
0
    {
4345
0
      CHECK( m_CABACEstimator->getEstFracBits() > 0, "no residual TU's bits shall be 0" );
4346
0
    }
4347
26.8k
    m_tuResiBitsValid = reuseLumaBits;
4348
26.8k
    if( reuseLumaBits )
4349
26.8k
    {
4350
26.8k
      saveCoeffCtx( m_tuChromaCtx, m_CABACEstimator->getCtx() );
4351
26.8k
    }
4352
4353
26.8k
    csFull->fracBits += m_CABACEstimator->getEstFracBits();
4354
26.8k
    csFull->dist     += uiSingleDist;
4355
26.8k
    csFull->cost      = m_pcRdCost->calcRdCost(csFull->fracBits, csFull->dist, !m_pcEncCfg->m_lumaLevelToDeltaQPEnabled);
4356
26.8k
  } // check full
4357
4358
  // code sub-blocks
4359
26.8k
  if( bCheckSplit )
4360
0
  {
4361
0
    if( bCheckFull )
4362
0
    {
4363
0
      m_CABACEstimator->getCtx() = ctxStart;
4364
0
    }
4365
4366
0
    if( partitioner.canSplit( TU_MAX_TR_SPLIT, cs ) )
4367
0
    {
4368
0
      partitioner.splitCurrArea( TU_MAX_TR_SPLIT, cs );
4369
0
    }
4370
0
    else if( cu.sbtInfo && partitioner.canSplit( CU::getSbtTuSplit( cu.sbtInfo ), cs ) )
4371
0
    {
4372
0
      partitioner.splitCurrArea( CU::getSbtTuSplit( cu.sbtInfo ), cs );
4373
0
    }
4374
0
    else
4375
0
      THROW( "Implicit TU split not available!" );
4376
4377
0
    do
4378
0
    {
4379
0
      const TempCtx ctxSubStart( m_CtxCache, m_CABACEstimator->getCtx() );
4380
0
      xEstimateInterResidualQT(*csSplit, partitioner, ctxSubStart, bCheckFull ? nullptr : puiZeroDist );
4381
4382
0
      csSplit->cost = m_pcRdCost->calcRdCost( csSplit->fracBits, csSplit->dist );
4383
0
    } while( partitioner.nextPart( *csSplit ) );
4384
4385
0
    partitioner.exitCurrSplit();
4386
4387
0
    unsigned        compCbf[3]  = { 0, 0, 0 };
4388
4389
0
    if( !bCheckFull )
4390
0
    {
4391
0
      for( auto &currTU : csSplit->traverseTUs( currArea, partitioner.chType ) )
4392
0
      {
4393
0
        for( unsigned ch = 0; ch < numTBlocks; ch++ )
4394
0
        {
4395
0
          compCbf[ ch ] |= ( TU::getCbfAtDepth( currTU, ComponentID(ch), currDepth + 1 ) ? 1 : 0 );
4396
0
        }
4397
0
      }
4398
4399
0
      for( auto &currTU : csSplit->traverseTUs( currArea, partitioner.chType ) )
4400
0
      {
4401
0
        TU::setCbfAtDepth   ( currTU, COMP_Y,  currDepth, compCbf[ COMP_Y  ] );
4402
0
        if( currArea.chromaFormat != CHROMA_400 )
4403
0
        {
4404
0
          TU::setCbfAtDepth ( currTU, COMP_Cb, currDepth, compCbf[ COMP_Cb ] );
4405
0
          TU::setCbfAtDepth ( currTU, COMP_Cr, currDepth, compCbf[ COMP_Cr ] );
4406
0
        }
4407
0
      }
4408
4409
0
      m_CABACEstimator->getCtx() = ctxStart;
4410
0
      m_CABACEstimator->resetBits();
4411
4412
      // when compID isn't a channel, code Cbfs:
4413
0
      xEncodeInterResidualQT( *csSplit, partitioner, MAX_NUM_TBLOCKS );
4414
4415
0
      for (uint32_t ch = 0; ch < numValidComp; ch++)
4416
0
      {
4417
0
        const ComponentID compID = ComponentID(ch);
4418
0
        xEncodeInterResidualQT( *csSplit, partitioner, compID );
4419
0
      }
4420
4421
0
      csSplit->fracBits = m_CABACEstimator->getEstFracBits();
4422
0
      csSplit->cost     = m_pcRdCost->calcRdCost(csSplit->fracBits, csSplit->dist);
4423
0
      m_tuResiBitsValid = cu.sbtInfo != 0;   // only one TU has coefficients, and what it coded above is what the CU will code
4424
0
    }
4425
0
  }
4426
26.8k
}
4427
4428
void InterSearch::encodeResAndCalcRdInterCU(CodingStructure &cs, Partitioner &partitioner, const bool skipResidual, const double bestCost )
4429
26.8k
{
4430
26.8k
  CodingUnit &cu = *cs.getCU( partitioner.chType, partitioner.treeType );
4431
26.8k
  bool luma      = true;
4432
26.8k
  bool chroma    = cs.pcv->chrFormat != VVENC_CHROMA_400;
4433
26.8k
  if( cu.predMode == MODE_IBC )
4434
26.8k
  {
4435
26.8k
    luma    = !cu.mccNoLuma  ();
4436
26.8k
    chroma &= !cu.mccNoChroma();
4437
26.8k
  }
4438
26.8k
  if( cu.predMode == MODE_INTER )
4439
26.8k
    CHECK( CU::isSepTree(cu), "CU with Inter mode must be in single tree" );
4440
4441
26.8k
  const ChromaFormat format      = cs.area.chromaFormat;;
4442
26.8k
  const int  numValidComponents  = getNumberValidComponents(format);
4443
26.8k
  const SPS &sps                 = *cs.sps;
4444
4445
26.8k
  if( skipResidual ) //  No residual coding : SKIP mode
4446
0
  {
4447
0
    cu.skip    = true;
4448
0
    cu.rootCbf = false;
4449
0
    CHECK( cu.sbtInfo != 0, "sbtInfo shall be 0 if CU has no residual" );
4450
0
    cs.getRecoBuf().copyFrom(cs.getPredBuf() );
4451
4452
    // add new "empty" TU(s) spanning the whole CU
4453
0
    cs.addEmptyTUs( partitioner, &cu );
4454
0
    Distortion distortion = 0;
4455
4456
0
    for (int comp = 0; comp < numValidComponents; comp++)
4457
0
    {
4458
0
      const ComponentID compID = ComponentID(comp);
4459
0
      if (compID == COMP_Y && !luma)
4460
0
        continue;
4461
0
      if (compID != COMP_Y && !chroma)
4462
0
        continue;
4463
0
      CPelBuf reco = cs.getRecoBuf (compID);
4464
0
      CPelBuf org  = cs.getOrgBuf  (compID);
4465
4466
0
      distortion  += m_pcRdCost->getDistPart( org, reco, sps.bitDepths[ toChannelType( compID ) ], compID, DF_SSE );
4467
0
    }
4468
4469
0
    CodingUnit& cu = *cs.getCU(partitioner.chType, TREE_D);
4470
0
    m_CABACEstimator->resetBits();
4471
0
    m_CABACEstimator->cu_skip_flag  ( cu );
4472
0
    m_CABACEstimator->merge_data(cu);
4473
0
    cs.fracBits = m_CABACEstimator->getEstFracBits();
4474
0
    cs.dist     = distortion;
4475
0
    cs.cost     = m_pcRdCost->calcRdCost(cs.fracBits, cs.dist);
4476
4477
0
    return;
4478
0
  }
4479
4480
  //  Residual coding.
4481
26.8k
  if (luma)
4482
26.8k
  {
4483
26.8k
    cs.getResiBuf(COMP_Y).subtract(cs.getOrgBuf(COMP_Y), cs.getPredBuf(COMP_Y));
4484
26.8k
  }
4485
26.8k
  if (chroma)
4486
0
  {
4487
0
    cs.getResiBuf(COMP_Cb).subtract(cs.getOrgBuf(COMP_Cb), cs.getPredBuf(COMP_Cb));
4488
0
    cs.getResiBuf(COMP_Cr).subtract(cs.getOrgBuf(COMP_Cr), cs.getPredBuf(COMP_Cr));
4489
0
  }
4490
4491
26.8k
  Distortion zeroDistortion = 0;
4492
4493
26.8k
  const TempCtx ctxStart( m_CtxCache, m_CABACEstimator->getCtx() );
4494
4495
26.8k
  m_tuResiBitsValid = false;
4496
26.8k
  xEstimateInterResidualQT(cs, partitioner, ctxStart, &zeroDistortion );
4497
26.8k
  TransformUnit& firstTU = *cs.getTU( partitioner.chType );
4498
4499
26.8k
  cu.rootCbf = false;
4500
26.8k
  m_CABACEstimator->resetBits();
4501
26.8k
  m_CABACEstimator->rqt_root_cbf( cu );
4502
26.8k
  const uint64_t  zeroFracBits = m_CABACEstimator->getEstFracBits();
4503
26.8k
  double zeroCost = m_pcRdCost->calcRdCost( zeroFracBits, zeroDistortion, !m_pcEncCfg->m_lumaLevelToDeltaQPEnabled );
4504
4505
26.8k
  const int  numValidTBlocks   = getNumberValidTBlocks( *cs.pcv );
4506
107k
  for (uint32_t i = 0; i < numValidTBlocks; i++)
4507
80.5k
  {
4508
80.5k
    cu.rootCbf |= TU::getCbfAtDepth(firstTU, ComponentID(i), 0);
4509
80.5k
  }
4510
4511
  // -------------------------------------------------------
4512
  // If a block full of 0's is efficient, then just use 0's.
4513
  // The costs at this point do not include header bits.
4514
4515
26.8k
  if (zeroCost < cs.cost || !cu.rootCbf)
4516
26.7k
  {
4517
26.7k
    cu.sbtInfo = 0;
4518
26.7k
    cu.rootCbf = false;
4519
4520
26.7k
    cs.clearTUs();
4521
4522
    // add a new "empty" TU spanning the whole CU
4523
26.7k
    cs.addEmptyTUs( partitioner, &cu );
4524
26.7k
  }
4525
4526
  // all decisions now made. Fully encode the CU, including the headers:
4527
26.8k
  m_CABACEstimator->getCtx() = ctxStart;
4528
4529
  // The headers before the residuals use other contexts, and with no transform skip (see reuseLumaBits) chroma shares none with luma, so the
4530
  // residuals cost the bits they did in xEstimateInterResidualQT. mts_idx would read what residual_coding leaves in CUCtx.
4531
26.8k
  const bool useTuResiBits = m_tuResiBitsValid && cu.rootCbf && !CU::isMTSAllowed( cu, COMP_Y );
4532
26.8k
  m_CABACEstimator->setTuResiBits( useTuResiBits ? m_tuResiBits : nullptr );
4533
26.8k
  uint64_t finalFracBits = xGetSymbolFracBitsInter( cs, partitioner );
4534
26.8k
  m_CABACEstimator->setTuResiBits( nullptr );
4535
  // we've now encoded the CU, and so have a valid bit cost
4536
26.8k
  if (!cu.rootCbf)
4537
26.7k
  {
4538
    // Without residual the reconstruction is the prediction, which is already within the clip range.
4539
26.7k
    cs.getRecoBuf().copyFrom( cs.getPredBuf(), luma, chroma );
4540
26.7k
  }
4541
139
  else
4542
139
  {
4543
    // Block by block: a block without a residual (a zero cbf, unless joint CbCr codes the chroma) reconstructs to the
4544
    // prediction. Its residual buffer is stale (the search does not clear it), so it is not added.
4545
556
    for( int comp = 0; comp < numValidComponents; comp++ )
4546
417
    {
4547
417
      const ComponentID compID = ComponentID( comp );
4548
417
      if( !( isLuma( compID ) ? luma : chroma ) )
4549
278
      {
4550
278
        continue;
4551
278
      }
4552
139
      PelBuf         reco   = cs.getRecoBuf( compID );
4553
139
      const CPelBuf  pred   = cs.getPredBuf( compID );
4554
139
      const CPelBuf  resi   = cs.getResiBuf( compID );
4555
139
      const Position origin = cs.area.blocks[compID].pos();
4556
139
      for( const TransformUnit* tu : cs.tus )
4557
139
      {
4558
139
        const CompArea& blk = tu->blocks[compID];
4559
139
        if( !blk.valid() )
4560
0
        {
4561
0
          continue;
4562
0
        }
4563
417
        const auto inBlock = [&]( auto buf ) { return buf.subBuf( blk.x - origin.x, blk.y - origin.y, blk.width, blk.height ); };
InterSearch.cpp:auto vvenc::InterSearch::encodeResAndCalcRdInterCU(vvenc::CodingStructure&, vvenc::Partitioner&, bool, double)::$_0::operator()<vvenc::AreaBuf<short> >(vvenc::AreaBuf<short>) const
Line
Count
Source
4563
139
        const auto inBlock = [&]( auto buf ) { return buf.subBuf( blk.x - origin.x, blk.y - origin.y, blk.width, blk.height ); };
InterSearch.cpp:auto vvenc::InterSearch::encodeResAndCalcRdInterCU(vvenc::CodingStructure&, vvenc::Partitioner&, bool, double)::$_0::operator()<vvenc::AreaBuf<short const> >(vvenc::AreaBuf<short const>) const
Line
Count
Source
4563
278
        const auto inBlock = [&]( auto buf ) { return buf.subBuf( blk.x - origin.x, blk.y - origin.y, blk.width, blk.height ); };
4564
139
        if( TU::getCbf( *tu, compID ) || ( isChroma( compID ) && tu->jointCbCr ) )
4565
139
        {
4566
139
          inBlock( reco ).reconstruct( inBlock( pred ), inBlock( resi ), cs.slice->clpRngs[compID] );
4567
139
        }
4568
0
        else
4569
0
        {
4570
0
          inBlock( reco ).copyFrom( inBlock( pred ) );
4571
0
        }
4572
139
      }
4573
139
    }
4574
139
  }
4575
  // update with clipped distortion and cost (previously unclipped reconstruction values were used)
4576
26.8k
  Distortion finalDistortion = 0;
4577
4578
107k
  for (int comp = 0; comp < numValidComponents; comp++)
4579
80.5k
  {
4580
80.5k
    const ComponentID compID = ComponentID(comp);
4581
80.5k
    if (compID == COMP_Y && !luma)
4582
0
      continue;
4583
80.5k
    if (compID != COMP_Y && !chroma)
4584
53.7k
      continue;
4585
26.8k
    CPelBuf reco = cs.getRecoBuf (compID);
4586
26.8k
    CPelBuf org  = cs.getOrgBuf  (compID);
4587
4588
26.8k
    finalDistortion += m_pcRdCost->getDistPart( org, reco, sps.bitDepths[toChannelType(compID)], compID, DF_SSE );
4589
26.8k
  }
4590
4591
26.8k
  cs.dist     = finalDistortion;
4592
26.8k
  cs.fracBits = finalFracBits;
4593
26.8k
  cs.cost     = m_pcRdCost->calcRdCost(cs.fracBits, cs.dist);
4594
4595
  // The contexts after the CU are only kept if it wins, and the bits still to come can't lower its cost.
4596
26.8k
  if( useTuResiBits && cs.cost < bestCost )
4597
139
  {
4598
139
    const TransformUnit& firstTU = *cs.tus.front();
4599
139
    const bool chromaCbf = numValidComponents > 1 && ( TU::getCbf( firstTU, COMP_Cb ) || TU::getCbf( firstTU, COMP_Cr ) );
4600
    // The one TU of a CU without SBT coded them from these same contexts in xEstimateInterResidualQT: luma's, and then chroma's after it,
4601
    // which share none. In transform skip chroma uses other contexts.
4602
139
    if( !cu.sbtInfo && ( !chromaCbf || ( firstTU.mtsIdx[COMP_Cb] != MTS_SKIP && firstTU.mtsIdx[COMP_Cr] != MTS_SKIP ) ) )
4603
139
    {
4604
139
      Ctx& ctx = m_CABACEstimator->getCtx();
4605
139
      if( chromaCbf )
4606
0
      {
4607
0
        ctx = SubCtx( coeffCtxSpan(), m_tuChromaCtx );
4608
0
        ctx = SubCtx( CtxSet( Ctx::TransformSkipFlag.Offset + 1, 1 ), m_tuChromaCtx );
4609
0
      }
4610
139
      if( TU::getCbf( firstTU, COMP_Y ) )
4611
139
      {
4612
        // luma's sets: SigFlag and GtxFlag take turns between the channel types (luma at the even indices), the others are [ ChannelType ]
4613
139
        for( const CtxSet* set : { &Ctx::SigCoeffGroup[0], &Ctx::SigFlag[0], &Ctx::SigFlag[2], &Ctx::SigFlag[4], &Ctx::ParFlag[0], &Ctx::GtxFlag[0], &Ctx::GtxFlag[2], &Ctx::LastX[0], &Ctx::LastY[0] } )
4614
1.25k
        {
4615
1.25k
          ctx = SubCtx( *set, m_tuLumaCtx );
4616
1.25k
        }
4617
139
        ctx = SubCtx( CtxSet( Ctx::TransformSkipFlag.Offset, 1 ), m_tuLumaCtx );
4618
139
      }
4619
139
    }
4620
0
    else
4621
0
    {
4622
0
      for( const TransformUnit* tu : cs.tus )
4623
0
      {
4624
0
        for( uint32_t ch = 0; ch < numValidComponents; ch++ )
4625
0
        {
4626
0
          if( TU::getCbf( *tu, ComponentID( ch ) ) )
4627
0
          {
4628
0
            m_CABACEstimator->residual_coding( *tu, ComponentID( ch ) );
4629
0
          }
4630
0
        }
4631
0
      }
4632
0
    }
4633
139
  }
4634
4635
26.8k
  CHECK(cs.tus.size() == 0, "No TUs present");
4636
26.8k
}
4637
4638
uint64_t InterSearch::xGetSymbolFracBitsInter(CodingStructure &cs, Partitioner &partitioner)
4639
26.8k
{
4640
26.8k
  uint64_t fracBits   = 0;
4641
26.8k
  CodingUnit &cu    = *cs.getCU( partitioner.chType, partitioner.treeType );
4642
4643
26.8k
  m_CABACEstimator->resetBits();
4644
4645
26.8k
  if( cu.mergeFlag && !cu.rootCbf )
4646
0
  {
4647
0
    cu.skip = true;
4648
4649
0
    m_CABACEstimator->cu_skip_flag  ( cu );
4650
0
    if (!cu.ciip)
4651
0
    {
4652
0
      m_CABACEstimator->merge_data(cu);
4653
0
    }
4654
0
    fracBits   += m_CABACEstimator->getEstFracBits();
4655
0
  }
4656
26.8k
  else
4657
26.8k
  {
4658
26.8k
    CHECK( cu.skip, "Skip flag has to be off at this point!" );
4659
4660
26.8k
    if (cu.Y().valid())
4661
26.8k
    m_CABACEstimator->cu_skip_flag( cu );
4662
26.8k
    m_CABACEstimator->pred_mode   ( cu );
4663
26.8k
    m_CABACEstimator->cu_pred_data( cu );
4664
26.8k
    CUCtx cuCtx;
4665
26.8k
    cuCtx.isDQPCoded = true;
4666
26.8k
    cuCtx.isChromaQpAdjCoded = true;
4667
26.8k
    m_CABACEstimator->cu_residual ( cu, partitioner, cuCtx );
4668
26.8k
    fracBits       += m_CABACEstimator->getEstFracBits();
4669
26.8k
  }
4670
4671
26.8k
  return fracBits;
4672
26.8k
}
4673
4674
double InterSearch::xGetMEDistortionWeight(uint8_t BcwIdx, RefPicList refPicList)
4675
0
{
4676
0
  if( BcwIdx != BCW_DEFAULT )
4677
0
  {
4678
0
    return fabs( (double)getBcwWeight( BcwIdx, refPicList ) / (double)g_BcwWeightBase );
4679
0
  }
4680
0
  else
4681
0
  {
4682
0
    return 0.5;
4683
0
  }
4684
0
}
4685
4686
bool InterSearch::xReadBufferedUniMv( CodingUnit& cu, RefPicList eRefPicList, int32_t iRefIdx, Mv& pcMvPred, Mv& rcMv, uint32_t& ruiBits, Distortion& ruiCost )
4687
0
{
4688
0
  if( m_uniMotions.isReadMode( (uint32_t)eRefPicList, (uint32_t)iRefIdx ) )
4689
0
  {
4690
0
    m_uniMotions.copyTo(rcMv, ruiCost, (uint32_t)eRefPicList, (uint32_t)iRefIdx);
4691
4692
0
    Mv pred = pcMvPred;
4693
0
    pred.changeTransPrecInternal2Amvr( cu.imv );
4694
0
    m_pcRdCost->setPredictor(pred);
4695
0
    m_pcRdCost->setCostScale(0);
4696
4697
0
    Mv mv = rcMv;
4698
0
    mv.changeTransPrecInternal2Amvr( cu.imv );
4699
0
    uint32_t mvBits = m_pcRdCost->getBitsOfVectorWithPredictor( mv.hor, mv.ver, 0 );
4700
4701
0
    ruiBits += mvBits;
4702
0
    ruiCost += m_pcRdCost->getCost(ruiBits);
4703
0
    return true;
4704
0
  }
4705
0
  return false;
4706
0
}
4707
4708
bool InterSearch::xReadBufferedAffineUniMv( CodingUnit& cu, RefPicList eRefPicList, int32_t iRefIdx, Mv acMvPred[3], Mv acMv[3], uint32_t& ruiBits, Distortion& ruiCost, int& mvpIdx, const AffineAMVPInfo& aamvpi )
4709
0
{
4710
0
  if( m_uniMotions.isReadModeAffine( (uint32_t)eRefPicList, (uint32_t)iRefIdx, cu.affineType ) )
4711
0
  {
4712
0
    m_uniMotions.copyAffineMvTo( acMv, ruiCost, (uint32_t)eRefPicList, (uint32_t)iRefIdx, cu.affineType, mvpIdx );
4713
0
    m_pcRdCost->setCostScale(0);
4714
0
    acMvPred[0] = aamvpi.mvCandLT[mvpIdx];
4715
0
    acMvPred[1] = aamvpi.mvCandRT[mvpIdx];
4716
0
    acMvPred[2] = aamvpi.mvCandLB[mvpIdx];
4717
4718
0
    uint32_t mvBits = 0;
4719
0
    for( int verIdx = 0; verIdx < ( cu.affineType ? 3 : 2 ); verIdx++ )
4720
0
    {
4721
0
      Mv pred = verIdx ? acMvPred[verIdx] + acMv[0] - acMvPred[0] : acMvPred[verIdx];
4722
0
      pred.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_QUARTER);
4723
0
      m_pcRdCost->setPredictor(pred);
4724
0
      Mv mv = acMv[verIdx];
4725
0
      mv.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_QUARTER);
4726
0
      mvBits += m_pcRdCost->getBitsOfVectorWithPredictor( mv.hor, mv.ver, 0 );
4727
0
    }
4728
0
    ruiBits += mvBits;
4729
0
    ruiCost += m_pcRdCost->getCost(ruiBits);
4730
0
    return true;
4731
0
  }
4732
0
  return false;
4733
0
}
4734
4735
void InterSearch::xSymMvdCheckBestMvp(
4736
  CodingUnit& cu,
4737
  CPelUnitBuf& origBuf,
4738
  Mv curMv,
4739
  RefPicList curRefList,
4740
  AMVPInfo amvpInfo[2][MAX_REF_PICS],
4741
  int32_t BcwIdx,
4742
  Mv cMvPredSym[2],
4743
  int32_t mvpIdxSym[2],
4744
  Distortion& bestCost,
4745
  bool skip
4746
)
4747
0
{
4748
0
  RefPicList tarRefList = (RefPicList)(1 - curRefList);
4749
0
  int32_t refIdxCur = cu.slice->symRefIdx[curRefList];
4750
0
  int32_t refIdxTar = cu.slice->symRefIdx[tarRefList];
4751
4752
0
  MvField cCurMvField, cTarMvField;
4753
0
  cCurMvField.setMvField(curMv, refIdxCur);
4754
0
  AMVPInfo& amvpCur = amvpInfo[curRefList][refIdxCur];
4755
0
  AMVPInfo& amvpTar = amvpInfo[tarRefList][refIdxTar];
4756
0
  m_pcRdCost->setCostScale(0);
4757
4758
0
  double fWeight = 0.0;
4759
0
  PelUnitBuf bufTmp;
4760
4761
  // get prediction of eCurRefPicList
4762
0
  PelUnitBuf predStorageA = m_tmpPredStorage[curRefList].getCompactBuf( cu );
4763
0
  const Picture* picRefA = cu.slice->getRefPic(curRefList, cCurMvField.refIdx);
4764
0
  Mv mvA = cCurMvField.mv;
4765
0
  xClipMvSearch( mvA, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv, m_ifpLines );
4766
0
  const CPelBuf predBufA = xPredSymLuma( cu, picRefA, mvA, predStorageA );
4767
4768
0
  bufTmp = m_tmpStorageLCU.getCompactBuf( cu );
4769
0
  bufTmp.Y().removeHighFreq( origBuf.Y(), predBufA, m_pcEncCfg->m_bClipForBiPredMeEnabled, cu.slice->clpRngs[ COMP_Y ]/*, getBcwWeight( cu.BcwIdx, tarRefList )*/ );
4770
0
  fWeight = xGetMEDistortionWeight( cu.BcwIdx, tarRefList );
4771
4772
0
  int32_t skipMvpIdx[2];
4773
0
  skipMvpIdx[0] = skip ? mvpIdxSym[0] : -1;
4774
0
  skipMvpIdx[1] = skip ? mvpIdxSym[1] : -1;
4775
4776
0
  for (int i = 0; i < amvpCur.numCand; i++)
4777
0
  {
4778
0
    for (int j = 0; j < amvpTar.numCand; j++)
4779
0
    {
4780
0
      if (skipMvpIdx[curRefList] == i && skipMvpIdx[tarRefList] == j)
4781
0
        continue;
4782
4783
0
      Distortion cost = MAX_DISTORTION;
4784
0
      cTarMvField.setMvField(curMv.getSymmvdMv(amvpCur.mvCand[i], amvpTar.mvCand[j]), refIdxTar);
4785
4786
      // get prediction of eTarRefPicList
4787
0
      PelUnitBuf predStorageB = m_tmpPredStorage[tarRefList].getCompactBuf( cu );
4788
0
      const Picture* picRefB = cu.slice->getRefPic(tarRefList, cTarMvField.refIdx);
4789
0
      Mv mvB = cTarMvField.mv;
4790
0
      xClipMvSearch( mvB, cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv, m_ifpLines );
4791
0
      const CPelBuf predBufB = xPredSymLuma( cu, picRefB, mvB, predStorageB );
4792
4793
      // calc distortion
4794
0
      cost = ( Distortion ) floor( fWeight * ( double ) m_pcRdCost->getDistPart( bufTmp.Y(), predBufB, cu.cs->sps->bitDepths[ CH_L ], COMP_Y, DF_HAD ) );
4795
4796
0
      Mv pred = amvpCur.mvCand[i];
4797
0
      pred.changeTransPrecInternal2Amvr(cu.imv);
4798
0
      m_pcRdCost->setPredictor(pred);
4799
0
      Mv mv = curMv;
4800
0
      mv.changeTransPrecInternal2Amvr(cu.imv);
4801
0
      uint32_t bits = m_pcRdCost->getBitsOfVectorWithPredictor(mv.hor, mv.ver, 0);
4802
0
      bits += m_auiMVPIdxCost[i][AMVP_MAX_NUM_CANDS];
4803
0
      bits += m_auiMVPIdxCost[j][AMVP_MAX_NUM_CANDS];
4804
0
      cost += m_pcRdCost->getCost(bits);
4805
0
      if (cost < bestCost)
4806
0
      {
4807
0
        bestCost = cost;
4808
0
        cMvPredSym[curRefList] = amvpCur.mvCand[i];
4809
0
        cMvPredSym[tarRefList] = amvpTar.mvCand[j];
4810
0
        mvpIdxSym[curRefList] = i;
4811
0
        mvpIdxSym[tarRefList] = j;
4812
0
      }
4813
0
    }
4814
0
  }
4815
0
}
4816
4817
void InterSearch::resetSavedAffineMotion()
4818
156k
{
4819
469k
  for (int i = 0; i < 2; i++)
4820
312k
  {
4821
938k
    for (int j = 0; j < 2; j++)
4822
625k
    {
4823
625k
      m_affineMotion.acMvAffine4Para[i][j] = Mv(0, 0);
4824
625k
      m_affineMotion.acMvAffine6Para[i][j] = Mv(0, 0);
4825
625k
    }
4826
312k
    m_affineMotion.acMvAffine6Para[i][2] = Mv(0, 0);
4827
4828
312k
    m_affineMotion.affine4ParaRefIdx[i] = -1;
4829
312k
    m_affineMotion.affine6ParaRefIdx[i] = -1;
4830
312k
  }
4831
156k
  m_affineMotion.affine4ParaAvail = false;
4832
156k
  m_affineMotion.affine6ParaAvail = false;
4833
156k
}
4834
4835
void InterSearch::storeAffineMotion(Mv acAffineMv[2][3], int16_t affineRefIdx[2], EAffineModel affineType, int BcwIdx)
4836
0
{
4837
0
  if ((BcwIdx == BCW_DEFAULT || !m_affineMotion.affine6ParaAvail) && affineType == AFFINEMODEL_6PARAM)
4838
0
  {
4839
0
    for (int i = 0; i < 2; i++)
4840
0
    {
4841
0
      for (int j = 0; j < 3; j++)
4842
0
      {
4843
0
        m_affineMotion.acMvAffine6Para[i][j] = acAffineMv[i][j];
4844
0
      }
4845
0
      m_affineMotion.affine6ParaRefIdx[i] = affineRefIdx[i];
4846
0
    }
4847
0
    m_affineMotion.affine6ParaAvail = true;
4848
0
  }
4849
4850
0
  if ((BcwIdx == BCW_DEFAULT || !m_affineMotion.affine4ParaAvail) && affineType == AFFINEMODEL_4PARAM)
4851
0
  {
4852
0
    for (int i = 0; i < 2; i++)
4853
0
    {
4854
0
      for (int j = 0; j < 2; j++)
4855
0
      {
4856
0
        m_affineMotion.acMvAffine4Para[i][j] = acAffineMv[i][j];
4857
0
      }
4858
0
      m_affineMotion.affine4ParaRefIdx[i] = affineRefIdx[i];
4859
0
    }
4860
0
    m_affineMotion.affine4ParaAvail = true;
4861
0
  }
4862
0
}
4863
4864
void InterSearch::xPredAffineInterSearch( CodingUnit& cu,
4865
                                          CPelUnitBuf&    origBuf,
4866
                                          int             puIdx,
4867
                                          uint32_t&       lastMode,
4868
                                          Distortion&     affineCost,
4869
                                          Mv              hevcMv[2][MAX_REF_PICS],
4870
                                          Mv              mvAffine4Para[2][MAX_REF_PICS][3],
4871
                                          int             refIdx4Para[2],
4872
                                          uint8_t         BcwIdx,
4873
                                          bool            enforceBcwPred,
4874
                                          uint32_t        BcwIdxBits )
4875
0
{
4876
0
  const Slice &slice = *cu.slice;
4877
4878
0
  affineCost = MAX_DISTORTION;
4879
4880
0
  Mv        cMvZero;
4881
0
  Mv        aacMv[2][3];
4882
0
  Mv        cMvBi[2][3];
4883
0
  AffineMVInfo tmp;
4884
4885
0
  int       iNumPredDir = slice.isInterP() ? 1 : 2;
4886
4887
0
  int mvNum = 2;
4888
0
  mvNum = cu.affineType ? 3 : 2;
4889
4890
  // Mvp
4891
0
  Mv        cMvPred[2][MAX_REF_PICS][3];
4892
0
  Mv        cMvPredBi[2][MAX_REF_PICS][3];
4893
0
  int       aaiMvpIdxBi[2][MAX_REF_PICS];
4894
0
  int       aaiMvpIdx[2][MAX_REF_PICS];
4895
0
  int       aaiMvpNum[2][MAX_REF_PICS];
4896
4897
0
  AffineAMVPInfo aacAffineAMVPInfo[2][MAX_REF_PICS];
4898
0
  AffineAMVPInfo affiAMVPInfoTemp[2];
4899
4900
0
  uint32_t      uiMbBits[3] = { 1, 1, 0 };
4901
0
  int           iRefIdx[2] = { 0,0 }; // If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
4902
0
  int           iRefIdxBi[2];
4903
0
  int           iRefStart, iRefEnd;
4904
0
  int           bestBiPRefIdxL1 = 0;
4905
0
  int           bestBiPMvpL1 = 0;
4906
0
  Distortion    biPDistTemp = MAX_DISTORTION;
4907
4908
0
  Distortion    uiCost[2] = { MAX_DISTORTION, MAX_DISTORTION };
4909
0
  Distortion    uiCostBi = MAX_DISTORTION;
4910
0
  Distortion    uiCostTemp;
4911
4912
0
  uint32_t      uiBits[3] = { 0 };
4913
0
  uint32_t      uiBitsTemp;
4914
0
  Distortion    bestBiPDist = MAX_DISTORTION;
4915
4916
0
  Distortion    uiCostTempL0[MAX_NUM_REF];
4917
0
  for (int iNumRef = 0; iNumRef < MAX_NUM_REF; iNumRef++)
4918
0
  {
4919
0
    uiCostTempL0[iNumRef] = MAX_DISTORTION;
4920
0
  }
4921
0
  uint32_t      uiBitsTempL0[MAX_NUM_REF];
4922
4923
0
  Mv            mvValidList1[4];
4924
0
  int           refIdxValidList1 = 0;
4925
0
  uint32_t      bitsValidList1 = MAX_UINT;
4926
0
  Distortion    costValidList1 = MAX_DISTORTION;
4927
0
  Mv            mvHevc[3];
4928
0
  const bool    affineAmvrEnabled = false;
4929
4930
0
  xGetBlkBits(slice.isInterP(), puIdx, lastMode, uiMbBits);
4931
4932
0
  cu.affine = true;
4933
0
  cu.mergeFlag = false;
4934
0
  if (BcwIdx != BCW_DEFAULT)
4935
0
  {
4936
0
    cu.BcwIdx = BcwIdx;
4937
0
  }
4938
4939
  // Uni-directional prediction
4940
0
  for (int iRefList = 0; iRefList < iNumPredDir; iRefList++)
4941
0
  {
4942
0
    RefPicList  refPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
4943
0
    cu.interDir = (iRefList ? 2 : 1);
4944
0
    for (int iRefIdxTemp = 0; iRefIdxTemp < slice.numRefIdx[refPicList]; iRefIdxTemp++)
4945
0
    {
4946
      // Get RefIdx bits
4947
0
      uiBitsTemp = uiMbBits[iRefList];
4948
0
      if (slice.numRefIdx[refPicList] > 1)
4949
0
      {
4950
0
        uiBitsTemp += iRefIdxTemp + 1;
4951
0
        if (iRefIdxTemp == slice.numRefIdx[refPicList] - 1)
4952
0
        {
4953
0
          uiBitsTemp--;
4954
0
        }
4955
0
      }
4956
4957
      // Do Affine AMVP
4958
0
      bool foundPred = xEstimateAffineAMVP(cu, affiAMVPInfoTemp[refPicList], origBuf, refPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], biPDistTemp);
4959
0
      if( !foundPred )
4960
0
        return;
4961
4962
0
      if (affineAmvrEnabled)
4963
0
      {
4964
0
        biPDistTemp += m_pcRdCost->getCost(xCalcAffineMVBits(cu, cMvPred[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp]));
4965
0
      }
4966
0
      aaiMvpIdx[iRefList][iRefIdxTemp] = cu.mvpIdx[refPicList];
4967
0
      aaiMvpNum[iRefList][iRefIdxTemp] = cu.mvpNum[refPicList];;
4968
0
      if (cu.affineType == AFFINEMODEL_6PARAM && refIdx4Para[iRefList] != iRefIdxTemp)
4969
0
      {
4970
0
        xCopyAffineAMVPInfo(affiAMVPInfoTemp[refPicList], aacAffineAMVPInfo[iRefList][iRefIdxTemp]);
4971
0
        continue;
4972
0
      }
4973
4974
      // set hevc ME result as start search position when it is best than mvp
4975
0
      for (int i = 0; i<3; i++)
4976
0
      {
4977
0
        mvHevc[i] = hevcMv[iRefList][iRefIdxTemp];
4978
0
        mvHevc[i].roundAffinePrecInternal2Amvr(cu.imv);
4979
0
      }
4980
0
      PelUnitBuf predBuf = m_tmpStorageLCU.getCompactBuf(cu);
4981
4982
0
      Distortion uiCandCost = xGetAffineTemplateCost(cu, origBuf, predBuf, mvHevc, aaiMvpIdx[iRefList][iRefIdxTemp],
4983
0
        AMVP_MAX_NUM_CANDS, refPicList, iRefIdxTemp);
4984
4985
0
      if (affineAmvrEnabled)
4986
0
      {
4987
0
        uiCandCost += m_pcRdCost->getCost(xCalcAffineMVBits(cu, mvHevc, cMvPred[iRefList][iRefIdxTemp]));
4988
0
      }
4989
4990
      //check stored affine motion
4991
0
      bool affine4Para = cu.affineType == AFFINEMODEL_4PARAM;
4992
0
      bool savedParaAvail = cu.imv && ((m_affineMotion.affine4ParaRefIdx[iRefList] == iRefIdxTemp && affine4Para && m_affineMotion.affine4ParaAvail) ||
4993
0
        (m_affineMotion.affine6ParaRefIdx[iRefList] == iRefIdxTemp && !affine4Para && m_affineMotion.affine6ParaAvail));
4994
4995
0
      if (savedParaAvail)
4996
0
      {
4997
0
        Mv mvFour[3];
4998
0
        for (int i = 0; i < mvNum; i++)
4999
0
        {
5000
0
          mvFour[i] = affine4Para ? m_affineMotion.acMvAffine4Para[iRefList][i] : m_affineMotion.acMvAffine6Para[iRefList][i];
5001
0
          mvFour[i].roundAffinePrecInternal2Amvr(cu.imv);
5002
0
        }
5003
5004
0
        Distortion candCostInherit = xGetAffineTemplateCost(cu, origBuf, predBuf, mvFour, aaiMvpIdx[iRefList][iRefIdxTemp], AMVP_MAX_NUM_CANDS, refPicList, iRefIdxTemp);
5005
0
        candCostInherit += m_pcRdCost->getCost(xCalcAffineMVBits(cu, mvFour, cMvPred[iRefList][iRefIdxTemp]));
5006
5007
0
        if (candCostInherit < uiCandCost)
5008
0
        {
5009
0
          uiCandCost = candCostInherit;
5010
0
          memcpy(mvHevc, mvFour, 3 * sizeof(Mv));
5011
0
        }
5012
0
      }
5013
5014
0
      if( cu.affineType == AFFINEMODEL_4PARAM && m_AffineProfList->m_affMVListSize && (!cu.cs->sps->BCW || BcwIdx == BCW_DEFAULT ) )
5015
0
      {
5016
0
        int shift = MAX_CU_DEPTH;
5017
0
        for (int i = 0; i < m_AffineProfList->m_affMVListSize; i++)
5018
0
        {
5019
0
          AffineMVInfo *mvInfo = m_AffineProfList->m_affMVList + ((m_AffineProfList->m_affMVListIdx - i - 1 + m_AffineProfList->m_affMVListMaxSize) % (m_AffineProfList->m_affMVListMaxSize));
5020
          //check;
5021
0
          int j = 0;
5022
0
          for (; j < i; j++)
5023
0
          {
5024
0
            AffineMVInfo *prevMvInfo = m_AffineProfList->m_affMVList + ((m_AffineProfList->m_affMVListIdx - j - 1 + m_AffineProfList->m_affMVListMaxSize) % (m_AffineProfList->m_affMVListMaxSize));
5025
0
            if ((mvInfo->affMVs[iRefList][iRefIdxTemp][0] == prevMvInfo->affMVs[iRefList][iRefIdxTemp][0]) &&
5026
0
              (mvInfo->affMVs[iRefList][iRefIdxTemp][1] == prevMvInfo->affMVs[iRefList][iRefIdxTemp][1])
5027
0
              && (mvInfo->x == prevMvInfo->x) && (mvInfo->y == prevMvInfo->y)
5028
0
              && (mvInfo->w == prevMvInfo->w)
5029
0
              )
5030
0
            {
5031
0
              break;
5032
0
            }
5033
0
          }
5034
0
          if (j < i)
5035
0
            continue;
5036
5037
0
          Mv mvTmp[3], *nbMv = mvInfo->affMVs[iRefList][iRefIdxTemp];
5038
0
          int vx, vy;
5039
0
          int dMvHorX, dMvHorY, dMvVerX, dMvVerY;
5040
0
          int mvScaleHor = nbMv[0].hor * (1<< shift);
5041
0
          int mvScaleVer = nbMv[0].ver * (1<< shift);
5042
0
          Mv dMv = nbMv[1] - nbMv[0];
5043
0
          dMvHorX = dMv.hor *(1<<(shift - Log2(mvInfo->w)));
5044
0
          dMvHorY = dMv.ver *(1<< (shift - Log2(mvInfo->w)));
5045
0
          dMvVerX = -dMvHorY;
5046
0
          dMvVerY = dMvHorX;
5047
0
          vx = mvScaleHor + dMvHorX * (cu.Y().x - mvInfo->x) + dMvVerX * (cu.Y().y - mvInfo->y);
5048
0
          vy = mvScaleVer + dMvHorY * (cu.Y().x - mvInfo->x) + dMvVerY * (cu.Y().y - mvInfo->y);
5049
0
          roundAffineMv(vx, vy, shift);
5050
0
          mvTmp[0] = Mv(vx, vy);
5051
0
          mvTmp[0].clipToStorageBitDepth();
5052
0
          clipMv(mvTmp[0], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
5053
0
          mvTmp[0].roundAffinePrecInternal2Amvr(cu.imv);
5054
0
          vx = mvScaleHor + dMvHorX * (cu.Y().x + cu.Y().width - mvInfo->x) + dMvVerX * (cu.Y().y - mvInfo->y);
5055
0
          vy = mvScaleVer + dMvHorY * (cu.Y().x + cu.Y().width - mvInfo->x) + dMvVerY * (cu.Y().y - mvInfo->y);
5056
0
          roundAffineMv(vx, vy, shift);
5057
0
          mvTmp[1] = Mv(vx, vy);
5058
0
          mvTmp[1].clipToStorageBitDepth();
5059
0
          clipMv(mvTmp[1], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
5060
0
          mvTmp[1].roundAffinePrecInternal2Amvr(cu.imv);
5061
0
          Distortion tmpCost = xGetAffineTemplateCost(cu, origBuf, predBuf, mvTmp, aaiMvpIdx[iRefList][iRefIdxTemp], AMVP_MAX_NUM_CANDS, refPicList, iRefIdxTemp);
5062
0
          if (affineAmvrEnabled)
5063
0
          {
5064
0
            tmpCost += m_pcRdCost->getCost(xCalcAffineMVBits(cu, mvTmp, cMvPred[iRefList][iRefIdxTemp]));
5065
0
          }
5066
0
          if (tmpCost < uiCandCost)
5067
0
          {
5068
0
            uiCandCost = tmpCost;
5069
0
            std::memcpy(mvHevc, mvTmp, 3 * sizeof(Mv));
5070
0
          }
5071
0
        }
5072
0
      }
5073
0
      if (cu.affineType == AFFINEMODEL_6PARAM)
5074
0
      {
5075
0
        Mv mvFour[3];
5076
0
        mvFour[0] = mvAffine4Para[iRefList][iRefIdxTemp][0];
5077
0
        mvFour[1] = mvAffine4Para[iRefList][iRefIdxTemp][1];
5078
0
        mvAffine4Para[iRefList][iRefIdxTemp][0].roundAffinePrecInternal2Amvr(cu.imv);
5079
0
        mvAffine4Para[iRefList][iRefIdxTemp][1].roundAffinePrecInternal2Amvr(cu.imv);
5080
5081
0
        int shift = MAX_CU_DEPTH;
5082
0
        int vx2 = (mvFour[0].hor * (1<< shift)) - ((mvFour[1].ver - mvFour[0].ver) * (1<< (shift + Log2(cu.lheight()) - Log2(cu.lwidth()))));
5083
0
        int vy2 = (mvFour[0].ver * (1<< shift)) + ((mvFour[1].hor - mvFour[0].hor) * (1<< (shift + Log2(cu.lheight()) - Log2(cu.lwidth()))));
5084
0
        int offset = (1 << (shift - 1));
5085
0
        vx2 = (vx2 + offset - (vx2 >= 0)) >> shift;
5086
0
        vy2 = (vy2 + offset - (vy2 >= 0)) >> shift;
5087
0
        mvFour[2].hor = vx2;
5088
0
        mvFour[2].ver = vy2;
5089
0
        mvFour[2].clipToStorageBitDepth();
5090
0
        mvFour[0].roundAffinePrecInternal2Amvr(cu.imv);
5091
0
        mvFour[1].roundAffinePrecInternal2Amvr(cu.imv);
5092
0
        mvFour[2].roundAffinePrecInternal2Amvr(cu.imv);
5093
0
        Distortion uiCandCostInherit = xGetAffineTemplateCost(cu, origBuf, predBuf, mvFour, aaiMvpIdx[iRefList][iRefIdxTemp], AMVP_MAX_NUM_CANDS, refPicList, iRefIdxTemp);
5094
0
        if (affineAmvrEnabled)
5095
0
        {
5096
0
          uiCandCostInherit += m_pcRdCost->getCost(xCalcAffineMVBits(cu, mvFour, cMvPred[iRefList][iRefIdxTemp]));
5097
0
        }
5098
0
        if (uiCandCostInherit < uiCandCost)
5099
0
        {
5100
0
          uiCandCost = uiCandCostInherit;
5101
0
          for (int i = 0; i < 3; i++)
5102
0
          {
5103
0
            mvHevc[i] = mvFour[i];
5104
0
          }
5105
0
        }
5106
0
      }
5107
5108
0
      if (uiCandCost < biPDistTemp)
5109
0
      {
5110
0
        ::memcpy(tmp.affMVs[iRefList][iRefIdxTemp], mvHevc, sizeof(Mv) * 3);
5111
0
      }
5112
0
      else
5113
0
      {
5114
0
        ::memcpy(tmp.affMVs[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], sizeof(Mv) * 3);
5115
0
      }
5116
5117
      // GPB list 1, save the best MvpIdx, RefIdx and Cost
5118
0
      if (slice.picHeader->mvdL1Zero && iRefList == 1 && biPDistTemp < bestBiPDist)
5119
0
      {
5120
0
        bestBiPDist = biPDistTemp;
5121
0
        bestBiPMvpL1 = aaiMvpIdx[iRefList][iRefIdxTemp];
5122
0
        bestBiPRefIdxL1 = iRefIdxTemp;
5123
0
      }
5124
5125
      // Update bits
5126
0
      uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
5127
5128
0
      if (m_pcEncCfg->m_bFastMEForGenBLowDelayEnabled && iRefList == 1)   // list 1
5129
0
      {
5130
0
        if (slice.list1IdxToList0Idx[iRefIdxTemp] >= 0 && (cu.affineType != AFFINEMODEL_6PARAM || slice.list1IdxToList0Idx[iRefIdxTemp] == refIdx4Para[0]))
5131
0
        {
5132
0
          int iList1ToList0Idx = slice.list1IdxToList0Idx[iRefIdxTemp];
5133
0
          ::memcpy(tmp.affMVs[1][iRefIdxTemp], tmp.affMVs[0][iList1ToList0Idx], sizeof(Mv) * 3);
5134
0
          uiCostTemp = uiCostTempL0[iList1ToList0Idx];
5135
5136
0
          uiCostTemp -= m_pcRdCost->getCost(uiBitsTempL0[iList1ToList0Idx]);
5137
0
          uiBitsTemp += xCalcAffineMVBits(cu, tmp.affMVs[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp]);
5138
          /*calculate the correct cost*/
5139
0
          uiCostTemp += m_pcRdCost->getCost(uiBitsTemp);
5140
0
          DTRACE(g_trace_ctx, D_COMMON, " (%d) uiCostTemp=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiCostTemp);
5141
0
        }
5142
0
        else
5143
0
        {
5144
0
          xAffineMotionEstimation(cu, origBuf, refPicList, cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, tmp.affMVs[iRefList][iRefIdxTemp], 
5145
0
                                  uiBitsTemp, uiCostTemp, aaiMvpIdx[iRefList][iRefIdxTemp], affiAMVPInfoTemp[refPicList]);
5146
0
        }
5147
0
      }
5148
0
      else
5149
0
      {
5150
0
        xAffineMotionEstimation(cu, origBuf, refPicList, cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, tmp.affMVs[iRefList][iRefIdxTemp], 
5151
0
                                uiBitsTemp, uiCostTemp, aaiMvpIdx[iRefList][iRefIdxTemp], affiAMVPInfoTemp[refPicList]);
5152
0
      }
5153
      
5154
0
      if( slice.sps->BCW && cu.BcwIdx == BCW_DEFAULT && slice.isInterB() )
5155
0
      {
5156
0
        m_uniMotions.setReadModeAffine( true, (uint8_t)iRefList, (uint8_t)iRefIdxTemp, cu.affineType );
5157
0
        m_uniMotions.copyAffineMvFrom( tmp.affMVs[iRefList][iRefIdxTemp], uiCostTemp - m_pcRdCost->getCost(uiBitsTemp), (uint8_t)iRefList, (uint8_t)iRefIdxTemp, cu.affineType,
5158
0
                                       aaiMvpIdx[iRefList][iRefIdxTemp] );
5159
0
      }
5160
5161
      // Set best AMVP Index
5162
0
      xCopyAffineAMVPInfo(affiAMVPInfoTemp[refPicList], aacAffineAMVPInfo[iRefList][iRefIdxTemp]);
5163
0
      if (cu.imv != 2)//|| !m_pcEncCfg->getUseAffineAmvrEncOpt())
5164
0
        xCheckBestAffineMVP(cu, affiAMVPInfoTemp[refPicList], refPicList, tmp.affMVs[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
5165
5166
0
      if (iRefList == 0)
5167
0
      {
5168
0
        uiCostTempL0[iRefIdxTemp] = uiCostTemp;
5169
0
        uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
5170
0
      }
5171
0
      DTRACE(g_trace_ctx, D_COMMON, " (%d) uiCostTemp=%d, uiCost[iRefList]=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiCostTemp, uiCost[iRefList]);
5172
0
      if (uiCostTemp < uiCost[iRefList])
5173
0
      {
5174
0
        uiCost[iRefList] = uiCostTemp;
5175
0
        uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
5176
5177
                                       // set best motion
5178
0
        ::memcpy(aacMv[iRefList], tmp.affMVs[iRefList][iRefIdxTemp], sizeof(Mv) * 3);
5179
0
        iRefIdx[iRefList] = iRefIdxTemp;
5180
0
      }
5181
5182
0
      if (iRefList == 1 && uiCostTemp < costValidList1 && slice.list1IdxToList0Idx[iRefIdxTemp] < 0)
5183
0
      {
5184
0
        costValidList1 = uiCostTemp;
5185
0
        bitsValidList1 = uiBitsTemp;
5186
5187
        // set motion
5188
0
        memcpy(mvValidList1, tmp.affMVs[iRefList][iRefIdxTemp], sizeof(Mv) * 3);
5189
0
        refIdxValidList1 = iRefIdxTemp;
5190
0
      }
5191
0
    } // End refIdx loop
5192
0
  } // end Uni-prediction
5193
5194
0
  if (cu.affineType == AFFINEMODEL_4PARAM)
5195
0
  {
5196
0
    ::memcpy(mvAffine4Para, tmp.affMVs, sizeof(tmp.affMVs));
5197
0
    if (cu.imv == IMV_OFF)
5198
0
    {
5199
0
      m_AffineProfList->insert( tmp, cu.Y());
5200
0
    }
5201
0
  }
5202
5203
  // Bi-directional prediction
5204
0
  if (slice.isInterB() && !CU::isBipredRestriction(cu))
5205
0
  {
5206
0
    cu.interDir = 3;
5207
0
    m_isBi = true;
5208
5209
    // Set as best list0 and list1
5210
0
    iRefIdxBi[0] = iRefIdx[0];
5211
0
    iRefIdxBi[1] = iRefIdx[1];
5212
5213
0
    ::memcpy(cMvBi, aacMv, sizeof(aacMv));
5214
0
    ::memcpy(cMvPredBi, cMvPred, sizeof(cMvPred));
5215
0
    ::memcpy(aaiMvpIdxBi, aaiMvpIdx, sizeof(aaiMvpIdx));
5216
5217
0
    uint32_t uiMotBits[2];
5218
0
    bool doBiPred = true;
5219
5220
0
    if (slice.picHeader->mvdL1Zero) // GPB, list 1 only use Mvp
5221
0
    {
5222
0
      xCopyAffineAMVPInfo(aacAffineAMVPInfo[1][bestBiPRefIdxL1], affiAMVPInfoTemp[REF_PIC_LIST_1]);
5223
0
      cu.mvpIdx[REF_PIC_LIST_1] = bestBiPMvpL1;
5224
0
      aaiMvpIdxBi[1][bestBiPRefIdxL1] = bestBiPMvpL1;
5225
5226
      // Set Mv for list1
5227
0
      Mv pcMvTemp[3] = { affiAMVPInfoTemp[REF_PIC_LIST_1].mvCandLT[bestBiPMvpL1],
5228
0
                         affiAMVPInfoTemp[REF_PIC_LIST_1].mvCandRT[bestBiPMvpL1],
5229
0
                         affiAMVPInfoTemp[REF_PIC_LIST_1].mvCandLB[bestBiPMvpL1] };
5230
0
      ::memcpy(cMvPredBi[1][bestBiPRefIdxL1], pcMvTemp, sizeof(Mv) * 3);
5231
0
      ::memcpy(cMvBi[1], pcMvTemp, sizeof(Mv) * 3);
5232
0
      ::memcpy(tmp.affMVs[1][bestBiPRefIdxL1], pcMvTemp, sizeof(Mv) * 3);
5233
0
      iRefIdxBi[1] = bestBiPRefIdxL1;
5234
5235
0
      if( m_pcEncCfg->m_ifpLines && !xIsAffineMvInRangeFPP( cu, pcMvTemp, m_pcEncCfg->m_ifpLines ) )
5236
0
      {
5237
        // this mvp cannot be used for mv, skip Bi-pred
5238
0
        uiCostBi = MAX_DISTORTION;
5239
0
        doBiPred = false;
5240
0
      }
5241
0
      else
5242
0
      {
5243
5244
        // Get list1 prediction block
5245
0
        CU::setAllAffineMv(cu, cMvBi[1][0], cMvBi[1][1], cMvBi[1][2], REF_PIC_LIST_1);
5246
0
        cu.refIdx[REF_PIC_LIST_1] = iRefIdxBi[1];
5247
5248
0
        PelUnitBuf predBufTmp = m_tmpPredStorage[REF_PIC_LIST_1].getCompactBuf( cu );
5249
0
        xPredOtherListLuma( cu, predBufTmp, REF_PIC_LIST_1 );
5250
5251
        // Update bits
5252
0
        uiMotBits[0] = uiBits[0] - uiMbBits[0];
5253
0
        uiMotBits[1] = uiMbBits[1];
5254
5255
0
        if (slice.numRefIdx[REF_PIC_LIST_1] > 1)
5256
0
        {
5257
0
          uiMotBits[1] += bestBiPRefIdxL1 + 1;
5258
0
          if (bestBiPRefIdxL1 == slice.numRefIdx[REF_PIC_LIST_1] - 1)
5259
0
          {
5260
0
            uiMotBits[1]--;
5261
0
          }
5262
0
        }
5263
0
        uiMotBits[1] += m_auiMVPIdxCost[aaiMvpIdxBi[1][bestBiPRefIdxL1]][AMVP_MAX_NUM_CANDS];
5264
0
        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
5265
0
      }
5266
0
    }
5267
0
    else
5268
0
    {
5269
0
      uiMotBits[0] = uiBits[0] - uiMbBits[0];
5270
0
      uiMotBits[1] = uiBits[1] - uiMbBits[1];
5271
0
      uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
5272
0
    }
5273
5274
0
    if (doBiPred)
5275
0
    {
5276
      // 4-times iteration (default)
5277
0
      int iNumIter = 4;
5278
      // fast encoder setting or GPB: only one iteration
5279
0
      if (m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE3 || m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE2 || slice.picHeader->mvdL1Zero)
5280
0
      {
5281
0
        iNumIter = 1;
5282
0
      }
5283
5284
0
      for (int iIter = 0; iIter < iNumIter; iIter++)
5285
0
      {
5286
        // Set RefList
5287
0
        int iRefList = iIter % 2;
5288
0
        if (m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE3 || m_pcEncCfg->m_fastInterSearchMode == VVENC_FASTINTERSEARCH_MODE2)
5289
0
        {
5290
0
          if (uiCost[0] <= uiCost[1])
5291
0
          {
5292
0
            iRefList = 1;
5293
0
          }
5294
0
          else
5295
0
          {
5296
0
            iRefList = 0;
5297
0
          }
5298
0
        }
5299
0
        else if (iIter == 0)
5300
0
        {
5301
0
          iRefList = 0;
5302
0
        }
5303
5304
        // First iterate, get prediction block of opposite direction
5305
0
        if (iIter == 0 && !slice.picHeader->mvdL1Zero)
5306
0
        {
5307
0
          if( m_pcEncCfg->m_ifpLines && !xIsAffineMvInRangeFPP( cu, aacMv[1 - iRefList], m_pcEncCfg->m_ifpLines ) )
5308
0
          {
5309
0
            continue;
5310
0
          }
5311
5312
0
          CU::setAllAffineMv(cu, aacMv[1 - iRefList][0], aacMv[1 - iRefList][1], aacMv[1 - iRefList][2], RefPicList(1 - iRefList));
5313
0
          cu.refIdx[1 - iRefList] = iRefIdx[1 - iRefList];
5314
5315
0
          PelUnitBuf predBufTmp = m_tmpPredStorage[1 - iRefList].getCompactBuf( cu );
5316
0
          xPredOtherListLuma( cu, predBufTmp, RefPicList(1 - iRefList) );
5317
0
        }
5318
5319
0
        RefPicList refPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
5320
5321
0
        if (slice.picHeader->mvdL1Zero) // GPB, fix List 1, search List 0
5322
0
        {
5323
0
          iRefList = 0;
5324
0
          refPicList = REF_PIC_LIST_0;
5325
0
        }
5326
5327
0
        bool bChanged = false;
5328
5329
0
        iRefStart = 0;
5330
0
        iRefEnd = slice.numRefIdx[refPicList] - 1;
5331
0
        for (int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++)
5332
0
        {
5333
0
          if (cu.affineType == AFFINEMODEL_6PARAM && refIdx4Para[iRefList] != iRefIdxTemp)
5334
0
          {
5335
0
            continue;
5336
0
          }
5337
          // update bits
5338
0
          uiBitsTemp = uiMbBits[2] + uiMotBits[1 - iRefList];
5339
0
          uiBitsTemp += ( (cu.slice->sps->BCW == true) ? BcwIdxBits : 0 );
5340
0
          if (slice.numRefIdx[refPicList] > 1)
5341
0
          {
5342
0
            uiBitsTemp += iRefIdxTemp + 1;
5343
0
            if (iRefIdxTemp == slice.numRefIdx[refPicList] - 1)
5344
0
            {
5345
0
              uiBitsTemp--;
5346
0
            }
5347
0
          }
5348
0
          uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
5349
5350
          // call Affine ME
5351
0
          xAffineMotionEstimation(cu, origBuf, refPicList, cMvPredBi[iRefList][iRefIdxTemp], iRefIdxTemp, tmp.affMVs[iRefList][iRefIdxTemp], 
5352
0
                                  uiBitsTemp, uiCostTemp, aaiMvpIdxBi[iRefList][iRefIdxTemp], aacAffineAMVPInfo[iRefList][iRefIdxTemp], true);
5353
0
          xCopyAffineAMVPInfo(aacAffineAMVPInfo[iRefList][iRefIdxTemp], affiAMVPInfoTemp[refPicList]);
5354
0
          if (cu.imv != 2)
5355
0
          {
5356
0
            xCheckBestAffineMVP(cu, affiAMVPInfoTemp[refPicList], refPicList, tmp.affMVs[iRefList][iRefIdxTemp], cMvPredBi[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
5357
0
          }
5358
5359
0
          if (uiCostTemp < uiCostBi)
5360
0
          {
5361
0
            bChanged = true;
5362
0
            ::memcpy(cMvBi[iRefList], tmp.affMVs[iRefList][iRefIdxTemp], sizeof(Mv) * 3);
5363
0
            iRefIdxBi[iRefList] = iRefIdxTemp;
5364
5365
0
            uiCostBi = uiCostTemp;
5366
0
            uiMotBits[iRefList] = uiBitsTemp - uiMbBits[2] - uiMotBits[1 - iRefList];
5367
0
            uiMotBits[iRefList] -= ( (cu.slice->sps->BCW == true) ? BcwIdxBits : 0 );
5368
0
            uiBits[2] = uiBitsTemp;
5369
5370
0
            if (iNumIter != 1) // MC for next iter
5371
0
            {
5372
              //  Set motion
5373
0
              CU::setAllAffineMv(cu, cMvBi[iRefList][0], cMvBi[iRefList][1], cMvBi[iRefList][2], refPicList);
5374
0
              cu.refIdx[refPicList] = iRefIdxBi[refPicList];
5375
0
              PelUnitBuf predBufTmp = m_tmpPredStorage[iRefList].getCompactBuf( cu );
5376
0
              xPredOtherListLuma( cu, predBufTmp, refPicList );
5377
0
            }
5378
0
          }
5379
0
        } // for loop-iRefIdxTemp
5380
5381
0
        if (!bChanged)
5382
0
        {
5383
0
          if ((uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1]) || enforceBcwPred)
5384
0
          {
5385
0
            xCopyAffineAMVPInfo(aacAffineAMVPInfo[0][iRefIdxBi[0]], affiAMVPInfoTemp[REF_PIC_LIST_0]);
5386
0
            xCheckBestAffineMVP(cu, affiAMVPInfoTemp[REF_PIC_LIST_0], REF_PIC_LIST_0, cMvBi[0], cMvPredBi[0][iRefIdxBi[0]], aaiMvpIdxBi[0][iRefIdxBi[0]], uiBits[2], uiCostBi);
5387
5388
0
            if (!slice.picHeader->mvdL1Zero)
5389
0
            {
5390
0
              xCopyAffineAMVPInfo(aacAffineAMVPInfo[1][iRefIdxBi[1]], affiAMVPInfoTemp[REF_PIC_LIST_1]);
5391
0
              xCheckBestAffineMVP(cu, affiAMVPInfoTemp[REF_PIC_LIST_1], REF_PIC_LIST_1, cMvBi[1], cMvPredBi[1][iRefIdxBi[1]], aaiMvpIdxBi[1][iRefIdxBi[1]], uiBits[2], uiCostBi);
5392
0
            }
5393
0
          }
5394
0
          break;
5395
0
        }
5396
0
      } // for loop-iter
5397
0
    }
5398
0
    m_isBi = false;
5399
0
  } // if (B_SLICE)
5400
5401
0
  cu.mv [REF_PIC_LIST_0][0] = Mv();
5402
0
  cu.mv [REF_PIC_LIST_1][0] = Mv();
5403
0
  cu.mvd[REF_PIC_LIST_0][0] = cMvZero;
5404
0
  cu.mvd[REF_PIC_LIST_1][0] = cMvZero;
5405
0
  cu.refIdx[REF_PIC_LIST_0] = NOT_VALID;
5406
0
  cu.refIdx[REF_PIC_LIST_1] = NOT_VALID;
5407
0
  cu.mvpIdx[REF_PIC_LIST_0] = NOT_VALID;
5408
0
  cu.mvpIdx[REF_PIC_LIST_1] = NOT_VALID;
5409
0
  cu.mvpNum[REF_PIC_LIST_0] = NOT_VALID;
5410
0
  cu.mvpNum[REF_PIC_LIST_1] = NOT_VALID;
5411
5412
0
  for (int verIdx = 0; verIdx < 3; verIdx++)
5413
0
  {
5414
0
    cu.mvd[REF_PIC_LIST_0][verIdx] = cMvZero;
5415
0
    cu.mvd[REF_PIC_LIST_1][verIdx] = cMvZero;
5416
0
  }
5417
5418
  // Set Motion Field
5419
0
  memcpy(aacMv[1], mvValidList1, sizeof(Mv) * 3);
5420
0
  iRefIdx[1] = refIdxValidList1;
5421
0
  uiBits[1] = bitsValidList1;
5422
0
  uiCost[1] = costValidList1;
5423
5424
0
  if (enforceBcwPred)
5425
0
  {
5426
0
    uiCost[0] = uiCost[1] = MAX_UINT;
5427
0
  }
5428
5429
  // Affine ME result set
5430
0
  if (uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1]) // Bi
5431
0
  {
5432
0
    lastMode = 2;
5433
0
    affineCost = uiCostBi;
5434
0
    cu.interDir = 3;
5435
0
    CU::setAllAffineMv(cu, cMvBi[0][0], cMvBi[0][1], cMvBi[0][2], REF_PIC_LIST_0);
5436
0
    CU::setAllAffineMv(cu, cMvBi[1][0], cMvBi[1][1], cMvBi[1][2], REF_PIC_LIST_1);
5437
0
    cu.refIdx[REF_PIC_LIST_0] = iRefIdxBi[0];
5438
0
    cu.refIdx[REF_PIC_LIST_1] = iRefIdxBi[1];
5439
5440
0
    for (int verIdx = 0; verIdx < mvNum; verIdx++)
5441
0
    {
5442
0
      cu.mvd[REF_PIC_LIST_0][verIdx] = cMvBi[0][verIdx] - cMvPredBi[0][iRefIdxBi[0]][verIdx];
5443
0
      cu.mvd[REF_PIC_LIST_1][verIdx] = cMvBi[1][verIdx] - cMvPredBi[1][iRefIdxBi[1]][verIdx];
5444
0
      if (verIdx != 0)
5445
0
      {
5446
0
        cu.mvd[0][verIdx] = cu.mvd[0][verIdx] - cu.mvd[0][0];
5447
0
        cu.mvd[1][verIdx] = cu.mvd[1][verIdx] - cu.mvd[1][0];
5448
0
      }
5449
0
    }
5450
5451
5452
0
    cu.mvpIdx[REF_PIC_LIST_0] = aaiMvpIdxBi[0][iRefIdxBi[0]];
5453
0
    cu.mvpNum[REF_PIC_LIST_0] = aaiMvpNum[0][iRefIdxBi[0]];
5454
0
    cu.mvpIdx[REF_PIC_LIST_1] = aaiMvpIdxBi[1][iRefIdxBi[1]];
5455
0
    cu.mvpNum[REF_PIC_LIST_1] = aaiMvpNum[1][iRefIdxBi[1]];
5456
0
  }
5457
0
  else if (uiCost[0] <= uiCost[1]) // List 0
5458
0
  {
5459
0
    lastMode = 0;
5460
0
    affineCost = uiCost[0];
5461
0
    cu.interDir = 1;
5462
0
    CU::setAllAffineMv(cu, aacMv[0][0], aacMv[0][1], aacMv[0][2], REF_PIC_LIST_0);
5463
0
    cu.refIdx[REF_PIC_LIST_0] = iRefIdx[0];
5464
5465
0
    for (int verIdx = 0; verIdx < mvNum; verIdx++)
5466
0
    {
5467
0
      cu.mvd[REF_PIC_LIST_0][verIdx] = aacMv[0][verIdx] - cMvPred[0][iRefIdx[0]][verIdx];
5468
0
      if (verIdx != 0)
5469
0
      {
5470
0
        cu.mvd[0][verIdx] = cu.mvd[0][verIdx] - cu.mvd[0][0];
5471
0
      }
5472
0
    }
5473
5474
0
    cu.mvpIdx[REF_PIC_LIST_0] = aaiMvpIdx[0][iRefIdx[0]];
5475
0
    cu.mvpNum[REF_PIC_LIST_0] = aaiMvpNum[0][iRefIdx[0]];
5476
0
  }
5477
0
  else
5478
0
  {
5479
0
    lastMode = 1;
5480
0
    affineCost = uiCost[1];
5481
0
    cu.interDir = 2;
5482
0
    CU::setAllAffineMv(cu, aacMv[1][0], aacMv[1][1], aacMv[1][2], REF_PIC_LIST_1);
5483
0
    cu.refIdx[REF_PIC_LIST_1] = iRefIdx[1];
5484
5485
0
    for (int verIdx = 0; verIdx < mvNum; verIdx++)
5486
0
    {
5487
0
      cu.mvd[REF_PIC_LIST_1][verIdx] = aacMv[1][verIdx] - cMvPred[1][iRefIdx[1]][verIdx];
5488
0
      if (verIdx != 0)
5489
0
      {
5490
0
        cu.mvd[1][verIdx] = cu.mvd[1][verIdx] - cu.mvd[1][0];
5491
0
      }
5492
0
    }
5493
5494
0
    cu.mvpIdx[REF_PIC_LIST_1] = aaiMvpIdx[1][iRefIdx[1]];
5495
0
    cu.mvpNum[REF_PIC_LIST_1] = aaiMvpNum[1][iRefIdx[1]];
5496
0
  }
5497
0
  if (BcwIdx != BCW_DEFAULT)
5498
0
  {
5499
0
    cu.BcwIdx = BCW_DEFAULT;
5500
0
  }
5501
0
}
5502
5503
Distortion InterSearch::xGetAffineTemplateCost(CodingUnit& cu, CPelUnitBuf& origBuf, PelUnitBuf& predBuf, Mv acMvCand[3], int iMVPIdx, int iMVPNum, RefPicList refPicList, int iRefIdx)
5504
0
{
5505
0
  Distortion uiCost = MAX_DISTORTION;
5506
5507
0
  const Picture* picRef = cu.slice->getRefPic(refPicList, iRefIdx);
5508
5509
  // prediction pattern
5510
0
  Mv mv[3];
5511
0
  memcpy(mv, acMvCand, sizeof(mv));
5512
5513
0
  if( m_pcEncCfg->m_ifpLines && !xIsAffineMvInRangeFPP( cu, mv, m_pcEncCfg->m_ifpLines ) )
5514
0
  {
5515
0
    return MAX_DISTORTION>>1;  
5516
0
  }
5517
5518
  // What the prediction depends on besides the reference picture and the MVs.
5519
0
  const int predSettings = cu.affineType | int( cu.interDir == 3 ) << 1 | int( m_isBi ) << 2 | int( m_skipPROF ) << 3 | int( m_encOnly ) << 4;
5520
0
  const int mvNum        = cu.affineType == AFFINEMODEL_6PARAM ? 3 : 2;
5521
0
  Distortion dist = 0;
5522
0
  m_affineTemplateDists.startCu( cu.cs->picture, cu.slice->poc, cu.Y() );
5523
0
  if( !m_affineTemplateDists.find( picRef, mv, mvNum, predSettings, dist ) )
5524
0
  {
5525
0
    xPredAffineBlk(COMP_Y, cu, picRef, mv, predBuf, false, cu.slice->clpRngs[COMP_Y], refPicList);
5526
5527
    // calc distortion
5528
0
    dist = m_pcRdCost->getDistPart(origBuf.Y(), predBuf.Y(), cu.cs->sps->bitDepths[CH_L], COMP_Y, DF_HAD );
5529
0
    m_affineTemplateDists.add( picRef, mv, predSettings, dist );
5530
0
  }
5531
0
  uiCost = dist + m_pcRdCost->getCost(m_auiMVPIdxCost[iMVPIdx][iMVPNum]);
5532
5533
0
  DTRACE(g_trace_ctx, D_COMMON, " (%d) affineTemplateCost=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiCost);
5534
0
  return uiCost;
5535
0
}
5536
5537
void solveEqual(double** dEqualCoeff, int iOrder, double* dAffinePara)
5538
0
{
5539
0
  for (int k = 0; k < iOrder; k++)
5540
0
  {
5541
0
    dAffinePara[k] = 0.;
5542
0
  }
5543
5544
  // row echelon
5545
0
  for (int i = 1; i < iOrder; i++)
5546
0
  {
5547
    // find column max
5548
0
    double temp = fabs(dEqualCoeff[i][i - 1]);
5549
0
    int tempIdx = i;
5550
0
    for (int j = i + 1; j < iOrder + 1; j++)
5551
0
    {
5552
0
      if (fabs(dEqualCoeff[j][i - 1]) > temp)
5553
0
      {
5554
0
        temp = fabs(dEqualCoeff[j][i - 1]);
5555
0
        tempIdx = j;
5556
0
      }
5557
0
    }
5558
5559
    // swap line
5560
0
    if (tempIdx != i)
5561
0
    {
5562
0
      for (int j = 0; j < iOrder + 1; j++)
5563
0
      {
5564
0
        dEqualCoeff[0][j] = dEqualCoeff[i][j];
5565
0
        dEqualCoeff[i][j] = dEqualCoeff[tempIdx][j];
5566
0
        dEqualCoeff[tempIdx][j] = dEqualCoeff[0][j];
5567
0
      }
5568
0
    }
5569
5570
    // elimination first column
5571
0
    if (dEqualCoeff[i][i - 1] == 0.)
5572
0
    {
5573
0
      return;
5574
0
    }
5575
0
    for (int j = i + 1; j < iOrder + 1; j++)
5576
0
    {
5577
0
      for (int k = i; k < iOrder + 1; k++)
5578
0
      {
5579
0
        dEqualCoeff[j][k] = dEqualCoeff[j][k] - dEqualCoeff[i][k] * dEqualCoeff[j][i - 1] / dEqualCoeff[i][i - 1];
5580
0
      }
5581
0
    }
5582
0
  }
5583
5584
0
  if (dEqualCoeff[iOrder][iOrder - 1] == 0.)
5585
0
  {
5586
0
    return;
5587
0
  }
5588
0
  dAffinePara[iOrder - 1] = dEqualCoeff[iOrder][iOrder] / dEqualCoeff[iOrder][iOrder - 1];
5589
0
  for (int i = iOrder - 2; i >= 0; i--)
5590
0
  {
5591
0
    if (dEqualCoeff[i + 1][i] == 0.)
5592
0
    {
5593
0
      for (int k = 0; k < iOrder; k++)
5594
0
      {
5595
0
        dAffinePara[k] = 0.;
5596
0
      }
5597
0
      return;
5598
0
    }
5599
0
    double temp = 0;
5600
0
    for (int j = i + 1; j < iOrder; j++)
5601
0
    {
5602
0
      temp += dEqualCoeff[i + 1][j] * dAffinePara[j];
5603
0
    }
5604
0
    dAffinePara[i] = (dEqualCoeff[i + 1][iOrder] - temp) / dEqualCoeff[i + 1][i];
5605
0
  }
5606
0
}
5607
5608
void InterSearch::xCheckBestAffineMVP(CodingUnit& cu, AffineAMVPInfo &affineAMVPInfo, RefPicList refPicList, Mv acMv[3], Mv acMvPred[3], int& riMVPIdx, uint32_t& ruiBits, Distortion& ruiCost)
5609
0
{
5610
0
  if (affineAMVPInfo.numCand < 2)
5611
0
  {
5612
0
    return;
5613
0
  }
5614
5615
0
  int mvNum = cu.affineType ? 3 : 2;
5616
5617
0
  m_pcRdCost->selectMotionLambda();
5618
0
  m_pcRdCost->setCostScale(0);
5619
5620
0
  int iBestMVPIdx = riMVPIdx;
5621
5622
  // Get origin MV bits
5623
0
  Mv tmpPredMv[3];
5624
0
  int iOrgMvBits = xCalcAffineMVBits(cu, acMv, acMvPred);
5625
0
  iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
5626
5627
0
  int iBestMvBits = iOrgMvBits;
5628
0
  for (int iMVPIdx = 0; iMVPIdx < affineAMVPInfo.numCand; iMVPIdx++)
5629
0
  {
5630
0
    if (iMVPIdx == riMVPIdx)
5631
0
    {
5632
0
      continue;
5633
0
    }
5634
0
    tmpPredMv[0] = affineAMVPInfo.mvCandLT[iMVPIdx];
5635
0
    tmpPredMv[1] = affineAMVPInfo.mvCandRT[iMVPIdx];
5636
0
    if (mvNum == 3)
5637
0
    {
5638
0
      tmpPredMv[2] = affineAMVPInfo.mvCandLB[iMVPIdx];
5639
0
    }
5640
0
    int iMvBits = xCalcAffineMVBits(cu, acMv, tmpPredMv);
5641
0
    iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
5642
5643
0
    if (iMvBits < iBestMvBits)
5644
0
    {
5645
0
      iBestMvBits = iMvBits;
5646
0
      iBestMVPIdx = iMVPIdx;
5647
0
    }
5648
0
  }
5649
5650
0
  if (iBestMVPIdx != riMVPIdx)  // if changed
5651
0
  {
5652
0
    acMvPred[0] = affineAMVPInfo.mvCandLT[iBestMVPIdx];
5653
0
    acMvPred[1] = affineAMVPInfo.mvCandRT[iBestMVPIdx];
5654
0
    acMvPred[2] = affineAMVPInfo.mvCandLB[iBestMVPIdx];
5655
0
    riMVPIdx = iBestMVPIdx;
5656
0
    uint32_t uiOrgBits = ruiBits;
5657
0
    ruiBits = uiOrgBits - iOrgMvBits + iBestMvBits;
5658
0
    ruiCost = (ruiCost - m_pcRdCost->getCost(uiOrgBits)) + m_pcRdCost->getCost(ruiBits);
5659
0
  }
5660
0
}
5661
5662
namespace
5663
{
5664
// The control-point MVs one affine motion search has predicted. Its refinement tests many of them again (a neighbour of
5665
// the new centre that was a neighbour of the old one); such a test cannot win, because a set's cost is fixed within the
5666
// search and the best cost only ever decreases, so its prediction and distortion can be skipped.
5667
class AffineCpmvTestedSet
5668
{
5669
public:
5670
  // the most tests of one search: 6-parameter model, 1 start + 4 gradient steps + 5 checkCPMVRdCost tests + 3 rounds x
5671
  // 3 MVs x 8 neighbours (the 4-parameter model needs at most 59)
5672
  static constexpr int MAX_TESTS = 82;
5673
5674
0
  explicit AffineCpmvTestedSet( int numMv ) : m_numMv( numMv ) {}
5675
5676
  // true if these control-point MVs were tested before in this search; otherwise records them and returns false
5677
  bool testedBefore( const Mv mv[3] )
5678
0
  {
5679
0
    for( int i = 0; i < m_numTested; i++ )
5680
0
    {
5681
0
      if( xEqual( m_tested[i], mv ) )
5682
0
      {
5683
0
        return true;
5684
0
      }
5685
0
    }
5686
0
    record( mv );
5687
0
    return false;
5688
0
  }
5689
5690
  // records control-point MVs that were tested (while there is room: when full, a new set is simply tested again)
5691
  void record( const Mv mv[3] )
5692
0
  {
5693
0
    if( m_numTested < MAX_TESTS )
5694
0
    {
5695
0
      for( int k = 0; k < m_numMv; k++ )
5696
0
      {
5697
0
        m_tested[m_numTested][2 * k]     = mv[k].hor;
5698
0
        m_tested[m_numTested][2 * k + 1] = mv[k].ver;
5699
0
      }
5700
0
      m_numTested++;
5701
0
    }
5702
0
  }
5703
5704
private:
5705
  bool xEqual( const int* tested, const Mv mv[3] ) const
5706
0
  {
5707
0
    for( int k = 0; k < m_numMv; k++ )
5708
0
    {
5709
0
      if( tested[2 * k] != mv[k].hor || tested[2 * k + 1] != mv[k].ver )
5710
0
      {
5711
0
        return false;
5712
0
      }
5713
0
    }
5714
0
    return true;
5715
0
  }
5716
5717
  const int m_numMv;            // 3 for the 6-parameter model, 2 for the 4-parameter one (its third MV is unused)
5718
  int       m_numTested = 0;
5719
  int       m_tested[MAX_TESTS][6];   // hor and ver of each MV; left uninitialised, only m_numTested entries are read
5720
};
5721
} // namespace
5722
5723
void InterSearch::xAffineMotionEstimation(CodingUnit& cu,
5724
  CPelUnitBuf&    origBuf,
5725
  RefPicList      refPicList,
5726
  Mv              acMvPred[3],
5727
  int             iRefIdxPred,
5728
  Mv              acMv[3],
5729
  uint32_t&       ruiBits,
5730
  Distortion&     ruiCost,
5731
  int&            mvpIdx,
5732
  const AffineAMVPInfo& aamvpi,
5733
  bool            bBi)
5734
0
{
5735
0
  if( cu.cs->sps->BCW && cu.BcwIdx != BCW_DEFAULT && !bBi && xReadBufferedAffineUniMv( cu, refPicList, iRefIdxPred, acMvPred, acMv, ruiBits, ruiCost, mvpIdx, aamvpi ) )
5736
0
  {
5737
0
    return;
5738
0
  }
5739
5740
0
  int bestMvpIdx = mvpIdx;
5741
0
  const int width = cu.Y().width;
5742
0
  const int height = cu.Y().height;
5743
5744
0
  const Picture* refPic = cu.slice->getRefPic(refPicList, iRefIdxPred);
5745
5746
  // Set Origin YUV: pcYuv
5747
0
  CPelUnitBuf*   pBuf = &origBuf;
5748
0
  double        fWeight = 1.0;
5749
5750
0
  CPelUnitBuf  origBufTmpCnst;
5751
5752
  // if Bi, set to ( 2 * Org - ListX )
5753
0
  if (bBi)
5754
0
  {
5755
0
    PelUnitBuf  origBufTmp = m_tmpStorageLCU.getCompactBuf(cu);
5756
    // NOTE: Other buf contains predicted signal from another direction
5757
0
    PelUnitBuf otherBuf = m_tmpPredStorage[1 - (int)refPicList].getCompactBuf( cu );
5758
0
    origBufTmp.removeHighFreq(origBuf, otherBuf, m_pcEncCfg->m_bClipForBiPredMeEnabled, cu.slice->clpRngs);
5759
5760
0
    origBufTmpCnst = origBufTmp;
5761
0
    pBuf           = &origBufTmpCnst;
5762
0
    fWeight        = xGetMEDistortionWeight(cu.BcwIdx, refPicList);
5763
0
  }
5764
5765
  // pred YUV
5766
0
  PelUnitBuf  predBuf = m_tmpAffiStorage.getCompactBuf(cu);
5767
5768
  // Set start Mv position, use input mv as started search mv
5769
0
  Mv acMvTemp[3];
5770
0
  ::memcpy(acMvTemp, acMv, sizeof(Mv) * 3);
5771
  // Set delta mv
5772
0
  int iParaNum = cu.affineType ? 7 : 5;
5773
0
  int affineParaNum = iParaNum - 1;
5774
0
  int mvNum = cu.affineType ? 3 : 2;
5775
  // solveEqual takes row pointers. The matrix stays on the stack, since the heap takes longer than the small matrix is worth.
5776
0
  double  equalCoeffRows[7][7];
5777
0
  double* pdEqualCoeff[7];
5778
0
  for (int i = 0; i < iParaNum; i++)
5779
0
  {
5780
0
    pdEqualCoeff[i] = equalCoeffRows[i];
5781
0
  }
5782
5783
0
  int64_t  i64EqualCoeff[7][7];
5784
0
  Pel    *piError = m_tmpAffiError;
5785
0
  Pel    *pdDerivate[2];
5786
0
  pdDerivate[0] = m_tmpAffiDeri[0];
5787
0
  pdDerivate[1] = m_tmpAffiDeri[1];
5788
5789
0
  Distortion uiCostBest = MAX_DISTORTION;
5790
0
  uint32_t uiBitsBest = 0;
5791
5792
  // Skip refinement tests of control-point MVs this search already tested. Not with IFP: there, when the start MV is
5793
  // out of range, the gradient below reads the prediction buffer left by the previous search, whose last test a skip
5794
  // would change.
5795
0
  const bool skipRepeatedTests = !m_pcEncCfg->m_ifpLines;
5796
0
  AffineCpmvTestedSet testedMvs( mvNum );
5797
5798
  // Read back what searches of this block found at MVs they tested. Not with IFP: a result read back leaves predBuf
5799
  // unwritten, and with IFP the gradient below can read predBuf left by the previous search (when the start MV is out
5800
  // of range, as above), which would then hold the prediction of other MVs than the ones being looked at. Not at Affine
5801
  // levels above 3 either, which come back to almost no MVs. The prediction is made only when a gradient step needs it:
5802
  // predIsCurrent says predBuf holds the MVs being looked at.
5803
0
  const bool useResults = skipRepeatedTests && m_pcEncCfg->m_Affine <= 3;
5804
0
  if( useResults )
5805
0
  {
5806
    // the prediction settings as in xGetAffineTemplateCost, then the list and whether the target is the bi one
5807
0
    const int settings = cu.affineType | int( cu.interDir == 3 ) << 1 | int( m_isBi ) << 2 | int( m_skipPROF ) << 3 | int( m_encOnly ) << 4
5808
0
                       | int( refPicList ) << 5 | int( bBi ) << 6;
5809
0
    const int otherList = 1 - int( refPicList );
5810
0
    m_affineMeResults.startSearch( cu.cs->picture, cu.slice->poc, refPic, cu.Y(), settings, bBi ? cu.refIdx[otherList] : 0, bBi ? cu.mv[otherList] : nullptr, mvNum );
5811
0
  }
5812
0
  bool predIsCurrent = false;
5813
0
  auto predDist = [&]( const Mv* mv ) -> Distortion
5814
0
  {
5815
0
    Distortion dist = 0;
5816
0
    if( useResults && m_affineMeResults.findDist( mv, dist ) )
5817
0
    {
5818
0
      predIsCurrent = false;
5819
0
      return dist;
5820
0
    }
5821
0
    xPredAffineBlk(COMP_Y, cu, refPic, mv, predBuf, false, cu.slice->clpRngs[COMP_Y], refPicList);
5822
0
    predIsCurrent = true;
5823
0
    dist = m_pcRdCost->getDistPart(predBuf.Y(), pBuf->Y(), cu.cs->sps->bitDepths[CH_L], COMP_Y, DF_HAD);
5824
0
    if( useResults )
5825
0
    {
5826
0
      m_affineMeResults.addDist( mv, dist );
5827
0
    }
5828
0
    return dist;
5829
0
  };
5830
5831
  // do motion compensation with origin mv
5832
5833
0
  clipMv(acMvTemp[0], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
5834
0
  clipMv(acMvTemp[1], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
5835
0
  if (cu.affineType == AFFINEMODEL_6PARAM)
5836
0
  {
5837
0
    clipMv(acMvTemp[2], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
5838
0
  }
5839
5840
0
  acMvTemp[0].roundAffinePrecInternal2Amvr(cu.imv);
5841
0
  acMvTemp[1].roundAffinePrecInternal2Amvr(cu.imv);
5842
0
  if (cu.affineType == AFFINEMODEL_6PARAM)
5843
0
  {
5844
0
    acMvTemp[2].roundAffinePrecInternal2Amvr(cu.imv);
5845
0
  }
5846
0
  if( !m_pcEncCfg->m_ifpLines || xIsAffineMvInRangeFPP( cu, acMvTemp, m_pcEncCfg->m_ifpLines ) )
5847
0
  {
5848
    // get error
5849
0
    uiCostBest = predDist( acMvTemp );
5850
0
    if( skipRepeatedTests )
5851
0
    {
5852
0
      testedMvs.record( acMvTemp );
5853
0
    }
5854
5855
    // get cost with mv
5856
0
    m_pcRdCost->setCostScale(0);
5857
0
    uiBitsBest = ruiBits;
5858
0
    DTRACE(g_trace_ctx, D_COMMON, " (%d) xx uiBitsBest=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiBitsBest);
5859
0
    uiBitsBest += xCalcAffineMVBits(cu, acMvTemp, acMvPred);
5860
0
    DTRACE(g_trace_ctx, D_COMMON, " (%d) yy uiBitsBest=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiBitsBest);
5861
0
    uiCostBest = (Distortion)(floor(fWeight * (double)uiCostBest) + (double)m_pcRdCost->getCost(uiBitsBest));
5862
5863
0
    DTRACE(g_trace_ctx, D_COMMON, " (%d) uiBitsBest=%d, uiCostBest=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiBitsBest, uiCostBest);
5864
5865
0
    ::memcpy(acMv, acMvTemp, sizeof(Mv) * 3);
5866
0
  }
5867
0
  const int predBufStride = predBuf.Y().stride;
5868
0
  Mv prevIterMv[7][3];
5869
0
  int iIterTime;
5870
0
  if (cu.affineType == AFFINEMODEL_6PARAM)
5871
0
  {
5872
0
    iIterTime = bBi ? 3 : 4;
5873
0
  }
5874
0
  else
5875
0
  {
5876
0
    iIterTime = bBi ? 3 : 5;
5877
0
  }
5878
5879
0
  if (!cu.cs->sps->AffineType)// getUseAffineType())
5880
0
  {
5881
0
    iIterTime = bBi ? 5 : 7;
5882
0
  }
5883
5884
0
  for (int iter = 0; iter<iIterTime; iter++)    // iterate loop
5885
0
  {
5886
0
    memcpy(prevIterMv[iter], acMvTemp, sizeof(Mv) * 3);
5887
    /*********************************************************************************
5888
    *                         use gradient to update mv
5889
    *********************************************************************************/
5890
0
    double dAffinePara[6];
5891
0
    if( !useResults || !m_affineMeResults.findStep( acMvTemp, dAffinePara, affineParaNum ) )
5892
0
    {
5893
0
      if( useResults && !predIsCurrent )
5894
0
      {
5895
0
        xPredAffineBlk(COMP_Y, cu, refPic, acMvTemp, predBuf, false, cu.slice->clpRngs[COMP_Y], refPicList);
5896
0
      }
5897
      // get Error Matrix
5898
0
      PelBuf( piError, width, height ).subtract( pBuf->Y(), predBuf.Y() );
5899
5900
      // sobel x direction
5901
      // -1 0 1
5902
      // -2 0 2
5903
      // -1 0 1
5904
0
      Pel* pPred = predBuf.Y().buf;
5905
0
      m_HorizontalSobelFilter(pPred, predBufStride, pdDerivate[0], width, width, height);
5906
5907
      // sobel y direction
5908
      // -1 -2 -1
5909
      //  0  0  0
5910
      //  1  2  1
5911
0
      m_VerticalSobelFilter(pPred, predBufStride, pdDerivate[1], width, width, height);
5912
5913
      // solve delta x and y
5914
0
      for (int row = 0; row < iParaNum; row++)
5915
0
      {
5916
0
        memset(&i64EqualCoeff[row][0], 0, iParaNum * sizeof(int64_t));
5917
0
      }
5918
5919
0
      m_EqualCoeffComputer[cu.affineType]( piError, width, pdDerivate, width, width, height, i64EqualCoeff );
5920
5921
0
      for (int row = 0; row < iParaNum; row++)
5922
0
      {
5923
0
        for (int i = 0; i < iParaNum; i++)
5924
0
        {
5925
0
          pdEqualCoeff[row][i] = (double)i64EqualCoeff[row][i];
5926
0
        }
5927
0
      }
5928
5929
0
      solveEqual(pdEqualCoeff, affineParaNum, dAffinePara);
5930
0
      if( useResults )
5931
0
      {
5932
0
        m_affineMeResults.addStep( acMvTemp, dAffinePara, affineParaNum );
5933
0
      }
5934
0
    }
5935
5936
0
    double dDeltaMv[6];
5937
0
    Mv acDeltaMv[3];
5938
5939
    // convert to delta mv
5940
0
    dDeltaMv[0] = dAffinePara[0];
5941
0
    dDeltaMv[2] = dAffinePara[2];
5942
0
    const bool extParams = cu.affineType == AFFINEMODEL_6PARAM;
5943
0
    if (extParams)
5944
0
    {
5945
0
      dDeltaMv[1] = dAffinePara[1] * width + dAffinePara[0];
5946
0
      dDeltaMv[3] = dAffinePara[3] * width + dAffinePara[2];
5947
0
      dDeltaMv[4] = dAffinePara[4] * height + dAffinePara[0];
5948
0
      dDeltaMv[5] = dAffinePara[5] * height + dAffinePara[2];
5949
0
    }
5950
0
    else
5951
0
    {
5952
0
      dDeltaMv[1] = dAffinePara[1] * width + dAffinePara[0];
5953
0
      dDeltaMv[3] = -dAffinePara[3] * width + dAffinePara[2];
5954
0
    }
5955
5956
0
    const int normShiftTab[3] = { MV_PRECISION_QUARTER - MV_PRECISION_INT, MV_PRECISION_SIXTEENTH - MV_PRECISION_INT, MV_PRECISION_QUARTER - MV_PRECISION_INT };
5957
0
    const int stepShiftTab[3] = { MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER, MV_PRECISION_INTERNAL - MV_PRECISION_SIXTEENTH, MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER };
5958
0
    const int multiShift = 1 << normShiftTab[cu.imv];
5959
0
    const int mvShift = stepShiftTab[cu.imv];
5960
5961
0
    acDeltaMv[0] = Mv((int)(dDeltaMv[0] * multiShift + SIGN(dDeltaMv[0]) * 0.5) * (1<< mvShift), (int)(dDeltaMv[2] * multiShift + SIGN(dDeltaMv[2]) * 0.5) * (1<< mvShift));
5962
0
    acDeltaMv[1] = Mv((int)(dDeltaMv[1] * multiShift + SIGN(dDeltaMv[1]) * 0.5) * (1<< mvShift), (int)(dDeltaMv[3] * multiShift + SIGN(dDeltaMv[3]) * 0.5) * (1<< mvShift));
5963
0
    if (extParams)
5964
0
    {
5965
0
      acDeltaMv[2] = Mv((int)(dDeltaMv[4] * multiShift + SIGN(dDeltaMv[4]) * 0.5) *  (1<< mvShift), (int)(dDeltaMv[5] * multiShift + SIGN(dDeltaMv[5]) * 0.5) *  (1<< mvShift));
5966
0
    }
5967
0
    bool bAllZero = false;
5968
0
    for (int i = 0; i < mvNum; i++)
5969
0
    {
5970
0
      Mv deltaMv = acDeltaMv[i];
5971
0
      if (cu.imv == IMV_4PEL)
5972
0
      {
5973
0
        deltaMv.roundToPrecision(MV_PRECISION_INTERNAL, MV_PRECISION_HALF);
5974
0
      }
5975
0
      if (deltaMv.hor != 0 || deltaMv.ver != 0)
5976
0
      {
5977
0
        bAllZero = false;
5978
0
        break;
5979
0
      }
5980
0
      bAllZero = true;
5981
0
    }
5982
5983
0
    if (bAllZero)
5984
0
      break;
5985
5986
    // do motion compensation with updated mv
5987
0
    for (int i = 0; i < mvNum; i++)
5988
0
    {
5989
0
      acMvTemp[i] += acDeltaMv[i];
5990
0
      acMvTemp[i].hor = Clip3(MV_MIN, MV_MAX, acMvTemp[i].hor);
5991
0
      acMvTemp[i].ver = Clip3(MV_MIN, MV_MAX, acMvTemp[i].ver);
5992
0
      acMvTemp[i].roundAffinePrecInternal2Amvr(cu.imv);
5993
5994
0
      clipMv(acMvTemp[i], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
5995
0
    }
5996
5997
0
    if( skipRepeatedTests )
5998
0
    {
5999
      // Back on MVs this loop already stood on: the step they gave is fixed by them, so from here it only repeats steps, and
6000
      // none of those can beat uiCostBest. The last of them would leave RdCost's MV predictor as xCalcAffineMVBits does here.
6001
0
      int repeatOf = -1;
6002
0
      for( int prevIter = 0; prevIter <= iter && repeatOf < 0; prevIter++ )
6003
0
      {
6004
0
        bool isSame = true;
6005
0
        for( int i = 0; i < mvNum; i++ )
6006
0
        {
6007
0
          isSame = isSame && prevIterMv[prevIter][i] == acMvTemp[i];
6008
0
        }
6009
0
        repeatOf = isSame ? prevIter : -1;
6010
0
      }
6011
0
      if( repeatOf >= 0 )
6012
0
      {
6013
0
        const int lastRepeat = m_pcEncCfg->m_Affine > 1 ? repeatOf : repeatOf + ( iIterTime - 1 - iter ) % ( iter + 1 - repeatOf );
6014
0
        xCalcAffineMVBits( cu, prevIterMv[lastRepeat], acMvPred );
6015
0
        break;
6016
0
      }
6017
0
    }
6018
6019
0
    if( !m_pcEncCfg->m_ifpLines || xIsAffineMvInRangeFPP( cu, acMvTemp, m_pcEncCfg->m_ifpLines ) )
6020
0
    {
6021
      // get error
6022
0
      Distortion uiCostTemp = predDist( acMvTemp );
6023
0
      if( skipRepeatedTests )
6024
0
      {
6025
0
        testedMvs.record( acMvTemp );
6026
0
      }
6027
0
      DTRACE(g_trace_ctx, D_COMMON, " (%d) uiCostTemp=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiCostTemp);
6028
6029
      // get cost with mv
6030
0
      m_pcRdCost->setCostScale(0);
6031
0
      uint32_t uiBitsTemp = ruiBits;
6032
0
      uiBitsTemp += xCalcAffineMVBits(cu, acMvTemp, acMvPred);
6033
0
      uiCostTemp = (Distortion)(floor(fWeight * (double)uiCostTemp) + (double)m_pcRdCost->getCost(uiBitsTemp));
6034
6035
      // store best cost and mv
6036
0
      if (uiCostTemp < uiCostBest)
6037
0
      {
6038
0
        uiCostBest = uiCostTemp;
6039
0
        uiBitsBest = uiBitsTemp;
6040
0
        memcpy(acMv, acMvTemp, sizeof(Mv) * 3);
6041
0
        mvpIdx = bestMvpIdx;
6042
0
      }
6043
0
      else if(m_pcEncCfg->m_Affine > 1)
6044
0
      {
6045
0
        break;
6046
0
      }
6047
0
    }
6048
0
  }
6049
6050
0
  auto checkCPMVRdCost = [&](Mv ctrlPtMv[3])
6051
0
  {
6052
0
    if( !m_pcEncCfg->m_ifpLines || xIsAffineMvInRangeFPP( cu, ctrlPtMv, m_pcEncCfg->m_ifpLines ) )
6053
0
    {
6054
0
      if( skipRepeatedTests && testedMvs.testedBefore( ctrlPtMv ) )
6055
0
      {
6056
        // cannot beat uiCostBest; xCalcAffineMVBits still runs: it leaves RdCost's MV predictor as the test would
6057
0
        xCalcAffineMVBits( cu, ctrlPtMv, acMvPred );
6058
0
        return;
6059
0
      }
6060
      // get error
6061
0
      Distortion costTemp = predDist( ctrlPtMv );
6062
      // get cost with mv
6063
0
      m_pcRdCost->setCostScale(0);
6064
0
      uint32_t bitsTemp = ruiBits;
6065
0
      bitsTemp += xCalcAffineMVBits(cu, ctrlPtMv, acMvPred);
6066
0
      costTemp = (Distortion)(floor(fWeight * (double)costTemp) + (double)m_pcRdCost->getCost(bitsTemp));
6067
      // store best cost and mv
6068
0
      if (costTemp < uiCostBest)
6069
0
      {
6070
0
        uiCostBest = costTemp;
6071
0
        uiBitsBest = bitsTemp;
6072
0
        ::memcpy(acMv, ctrlPtMv, sizeof(Mv) * 3);
6073
0
      }
6074
0
    }
6075
0
  };
6076
6077
0
  const uint32_t mvShiftTable[3] = { MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER, MV_PRECISION_INTERNAL - MV_PRECISION_INTERNAL, MV_PRECISION_INTERNAL - MV_PRECISION_INT };
6078
0
  const uint32_t mvShift = mvShiftTable[cu.imv];
6079
0
  if (uiCostBest <= AFFINE_ME_LIST_MVP_TH*m_hevcCost)
6080
0
  {
6081
0
    Mv mvPredTmp[3] = { acMvPred[0], acMvPred[1], acMvPred[2] };
6082
0
    Mv mvME[3];
6083
0
    ::memcpy(mvME, acMv, sizeof(Mv) * 3);
6084
0
    Mv dMv = mvME[0] - mvPredTmp[0];
6085
6086
0
    for (int j = 0; j < mvNum; j++)
6087
0
    {
6088
0
      if ((!j && mvME[j] != mvPredTmp[j]) || (j && mvME[j] != (mvPredTmp[j] + dMv)))
6089
0
      {
6090
0
        ::memcpy(acMvTemp, mvME, sizeof(Mv) * 3);
6091
0
        acMvTemp[j] = mvPredTmp[j];
6092
6093
0
        if (j)
6094
0
          acMvTemp[j] += dMv;
6095
6096
0
        checkCPMVRdCost(acMvTemp);
6097
0
      }
6098
0
    }
6099
6100
    //keep the rotation/zoom;
6101
0
    if (mvME[0] != mvPredTmp[0])
6102
0
    {
6103
0
      ::memcpy(acMvTemp, mvME, sizeof(Mv) * 3);
6104
0
      for (int i = 1; i < mvNum; i++)
6105
0
      {
6106
0
        acMvTemp[i] -= dMv;
6107
0
      }
6108
0
      acMvTemp[0] = mvPredTmp[0];
6109
6110
0
      checkCPMVRdCost(acMvTemp);
6111
0
    }
6112
6113
    //keep the translation;
6114
0
    if (cu.affineType == AFFINEMODEL_6PARAM && mvME[1] != (mvPredTmp[1] + dMv) && mvME[2] != (mvPredTmp[2] + dMv))
6115
0
    {
6116
0
      ::memcpy(acMvTemp, mvME, sizeof(Mv) * 3);
6117
6118
0
      acMvTemp[1] = mvPredTmp[1] + dMv;
6119
0
      acMvTemp[2] = mvPredTmp[2] + dMv;
6120
6121
0
      checkCPMVRdCost(acMvTemp);
6122
0
    }
6123
6124
    // 8 nearest neighbor search
6125
0
    int testPos[8][2] = { { -1, 0 },{ 0, -1 },{ 0, 1 },{ 1, 0 },{ -1, -1 },{ -1, 1 },{ 1, 1 },{ 1, -1 } };
6126
0
    const int maxSearchRound = 3;
6127
6128
0
    for (int rnd = 0; rnd < maxSearchRound; rnd++)
6129
0
    {
6130
0
      bool modelChange = false;
6131
      //search the model parameters with finear granularity;
6132
0
      for (int j = 0; j < mvNum; j++)
6133
0
      {
6134
0
        bool loopChange = false;
6135
0
        for (int iter = 0; iter < 2; iter++)
6136
0
        {
6137
0
          if (iter == 1 && !loopChange)
6138
0
          {
6139
0
            break;
6140
0
          }
6141
0
          Mv centerMv[3];
6142
0
          memcpy(centerMv, acMv, sizeof(Mv) * 3);
6143
0
          memcpy(acMvTemp, acMv, sizeof(Mv) * 3);
6144
6145
0
          for (int i = ((iter == 0) ? 0 : 4); i < ((iter == 0) ? 4 : 8); i++)
6146
0
          {
6147
0
            acMvTemp[j].set(centerMv[j].hor + (testPos[i][0] * (1 << mvShift)), centerMv[j].ver + (testPos[i][1] * (1 << mvShift)));
6148
0
            clipMv(acMvTemp[j], cu.lumaPos(), cu.lumaSize(), *cu.cs->pcv);
6149
6150
0
            if( !m_pcEncCfg->m_ifpLines || xIsAffineMvInRangeFPP( cu, acMvTemp, m_pcEncCfg->m_ifpLines ) )
6151
0
            {
6152
0
              if( skipRepeatedTests && testedMvs.testedBefore( acMvTemp ) )
6153
0
              {
6154
                // cannot beat uiCostBest; xCalcAffineMVBits still runs: it sets RdCost's MV predictor as the test would
6155
0
                xCalcAffineMVBits( cu, acMvTemp, acMvPred );
6156
0
                continue;
6157
0
              }
6158
0
              Distortion costTemp = predDist( acMvTemp );
6159
0
              uint32_t bitsTemp = ruiBits;
6160
0
              bitsTemp += xCalcAffineMVBits(cu, acMvTemp, acMvPred);
6161
0
              costTemp = (Distortion)(floor(fWeight * (double)costTemp) + (double)m_pcRdCost->getCost(bitsTemp));
6162
6163
0
              if (costTemp < uiCostBest)
6164
0
              {
6165
0
                uiCostBest = costTemp;
6166
0
                uiBitsBest = bitsTemp;
6167
0
                ::memcpy(acMv, acMvTemp, sizeof(Mv) * 3);
6168
0
                modelChange = true;
6169
0
                loopChange = true;
6170
0
              }
6171
0
            }
6172
0
          }
6173
0
        }
6174
0
      }
6175
6176
0
      if (!modelChange)
6177
0
      {
6178
0
        break;
6179
0
      }
6180
0
    }
6181
0
  }
6182
0
  acMvPred[0] = aamvpi.mvCandLT[mvpIdx];
6183
0
  acMvPred[1] = aamvpi.mvCandRT[mvpIdx];
6184
0
  acMvPred[2] = aamvpi.mvCandLB[mvpIdx];
6185
6186
0
  ruiBits = uiBitsBest;
6187
0
  ruiCost = uiCostBest;
6188
0
  DTRACE(g_trace_ctx, D_COMMON, " (%d) uiBitsBest=%d, uiCostBest=%d\n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), uiBitsBest, uiCostBest);
6189
0
}
6190
6191
bool InterSearch::xEstimateAffineAMVP(CodingUnit& cu, AffineAMVPInfo& affineAMVPInfo, CPelUnitBuf& origBuf, RefPicList refPicList, int iRefIdx, Mv acMvPred[3], Distortion& distBiP)
6192
0
{
6193
0
  Mv         bestMvLT, bestMvRT, bestMvLB;
6194
0
  int        iBestIdx = 0;
6195
0
  Distortion uiBestCost = MAX_DISTORTION;
6196
6197
  // Fill the MV Candidates
6198
0
  CU::fillAffineMvpCand(cu, refPicList, iRefIdx, affineAMVPInfo);
6199
0
  CHECK(affineAMVPInfo.numCand == 0, "Assertion failed.");
6200
6201
0
  PelUnitBuf predBuf = m_tmpStorageLCU.getCompactBuf( cu );
6202
6203
0
  bool stop_check = false;
6204
0
  if (affineAMVPInfo.mvCandLT[0] == affineAMVPInfo.mvCandLT[1])
6205
0
  {
6206
0
    if ((affineAMVPInfo.mvCandRT[0] == affineAMVPInfo.mvCandRT[1]) && (affineAMVPInfo.mvCandLB[0] == affineAMVPInfo.mvCandLB[1]))
6207
0
    {
6208
0
      stop_check = true;
6209
0
    }
6210
0
  }
6211
6212
  // initialize Mvp index & Mvp
6213
0
  iBestIdx = -1;
6214
0
  for (int i = 0; i < affineAMVPInfo.numCand; i++)
6215
0
  {
6216
0
    if (i && stop_check)
6217
0
    {
6218
0
      continue;
6219
0
    }
6220
0
    Mv mv[3] = { affineAMVPInfo.mvCandLT[i], affineAMVPInfo.mvCandRT[i], affineAMVPInfo.mvCandLB[i] };
6221
0
    Distortion uiTmpCost = xGetAffineTemplateCost(cu, origBuf, predBuf, mv, i, AMVP_MAX_NUM_CANDS, refPicList, iRefIdx);
6222
6223
0
    if (uiBestCost > uiTmpCost)
6224
0
    {
6225
0
      uiBestCost = uiTmpCost;
6226
0
      bestMvLT = affineAMVPInfo.mvCandLT[i];
6227
0
      bestMvRT = affineAMVPInfo.mvCandRT[i];
6228
0
      bestMvLB = affineAMVPInfo.mvCandLB[i];
6229
0
      iBestIdx = i;
6230
0
      distBiP  = uiTmpCost;
6231
0
    }
6232
0
  }
6233
6234
0
  if( iBestIdx < 0 )
6235
0
    return false;
6236
6237
  // Setting Best MVP
6238
0
  acMvPred[0] = bestMvLT;
6239
0
  acMvPred[1] = bestMvRT;
6240
0
  acMvPred[2] = bestMvLB;
6241
6242
0
  cu.mvpIdx[refPicList] = iBestIdx;
6243
0
  cu.mvpNum[refPicList] = affineAMVPInfo.numCand;
6244
0
  DTRACE(g_trace_ctx, D_COMMON, "#estAffi=%d \n", affineAMVPInfo.numCand);
6245
0
  return true;
6246
0
}
6247
6248
void InterSearch::xCopyAffineAMVPInfo(AffineAMVPInfo& src, AffineAMVPInfo& dst)
6249
0
{
6250
0
  dst.numCand = src.numCand;
6251
0
  DTRACE(g_trace_ctx, D_COMMON, " (%d) #copyAffi=%d \n", DTRACE_GET_COUNTER(g_trace_ctx, D_COMMON), src.numCand);
6252
0
  ::memcpy(dst.mvCandLT, src.mvCandLT, sizeof(Mv)*src.numCand);
6253
0
  ::memcpy(dst.mvCandRT, src.mvCandRT, sizeof(Mv)*src.numCand);
6254
0
  ::memcpy(dst.mvCandLB, src.mvCandLB, sizeof(Mv)*src.numCand);
6255
0
}
6256
6257
uint32_t InterSearch::xCalcAffineMVBits(CodingUnit& cu, Mv acMvTemp[3], Mv acMvPred[3])
6258
0
{
6259
0
  int mvNum = cu.affineType ? 3 : 2;
6260
0
  m_pcRdCost->setCostScale(0);
6261
0
  uint32_t bitsTemp = 0;
6262
6263
0
  for (int verIdx = 0; verIdx < mvNum; verIdx++)
6264
0
  {
6265
0
    Mv pred = verIdx == 0 ? acMvPred[verIdx] : acMvPred[verIdx] + acMvTemp[0] - acMvPred[0];
6266
0
    pred.changeAffinePrecInternal2Amvr(cu.imv);
6267
0
    m_pcRdCost->setPredictor(pred);
6268
0
    Mv mv = acMvTemp[verIdx];
6269
0
    mv.changeAffinePrecInternal2Amvr(cu.imv);
6270
6271
0
    bitsTemp += m_pcRdCost->getBitsOfVectorWithPredictor(mv.hor, mv.ver, 0);
6272
0
  }
6273
6274
0
  return bitsTemp;
6275
0
}
6276
6277
6278
//! set adaptive search range based on poc difference
6279
void InterSearch::setSearchRange( const Slice* slice, const VVEncCfg& encCfg )
6280
1.77k
{
6281
1.77k
  if( !encCfg.m_bUseASR || slice->isIRAP() )
6282
1.77k
  {
6283
1.77k
    return;
6284
1.77k
  }
6285
6286
0
  int iCurrPOC = slice->poc;
6287
0
  int iRefPOC;
6288
0
  int iGOPSize = encCfg.m_GOPSize;
6289
0
  int iOffset = (iGOPSize >> 1);
6290
0
  int iMaxSR = encCfg.m_SearchRange;
6291
0
  int iNumPredDir = slice->isInterP() ? 1 : 2;
6292
6293
0
  for (int iDir = 0; iDir < iNumPredDir; iDir++)
6294
0
  {
6295
0
    RefPicList  e = ( iDir ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
6296
0
    for (int iRefIdx = 0; iRefIdx < slice->numRefIdx[e]; iRefIdx++)
6297
0
    {
6298
0
      iRefPOC = slice->getRefPic(e, iRefIdx)->getPOC();
6299
0
      int newSearchRange = Clip3(encCfg.m_minSearchWindow, iMaxSR, (iMaxSR*ADAPT_SR_SCALE*abs(iCurrPOC - iRefPOC)+iOffset)/iGOPSize);
6300
0
      m_aaiAdaptSR[iDir][iRefIdx] = newSearchRange;
6301
0
    }
6302
0
  }
6303
0
}
6304
6305
void InterSearch::xIBCSearchMVCandUpdate(Distortion  sad, int x, int y, Distortion* sadBestCand, Mv* cMVCand)
6306
1.42M
{
6307
1.42M
  int j = CHROMA_REFINEMENT_CANDIDATES - 1;
6308
6309
1.42M
  if (sad < sadBestCand[CHROMA_REFINEMENT_CANDIDATES - 1])
6310
230k
  {
6311
2.07M
    for (int t = CHROMA_REFINEMENT_CANDIDATES - 1; t >= 0; t--)
6312
1.84M
    {
6313
1.84M
      if (sad < sadBestCand[t])
6314
1.10M
        j = t;
6315
1.84M
    }
6316
6317
1.10M
    for (int k = CHROMA_REFINEMENT_CANDIDATES - 1; k > j; k--)
6318
877k
    {
6319
877k
      sadBestCand[k] = sadBestCand[k - 1];
6320
6321
877k
      cMVCand[k].set(cMVCand[k - 1].hor, cMVCand[k - 1].ver);
6322
877k
    }
6323
230k
    sadBestCand[j] = sad;
6324
230k
    cMVCand[j].set(x, y);
6325
230k
  }
6326
1.42M
}
6327
6328
int InterSearch::xIBCSearchMVChromaRefine(CodingUnit& cu,
6329
  int         roiWidth,
6330
  int         roiHeight,
6331
  int         cuPelX,
6332
  int         cuPelY,
6333
  Distortion* sadBestCand,
6334
  Mv* cMVCand
6335
6336
)
6337
25.3k
{
6338
25.3k
  if ((!isChromaEnabled(cu.chromaFormat)) || (!cu.Cb().valid()))
6339
25.3k
  {
6340
25.3k
    return 0;
6341
25.3k
  }
6342
6343
0
  int bestCandIdx = 0;
6344
0
  Distortion  sadBest = std::numeric_limits<Distortion>::max();
6345
0
  Distortion  tempSad;
6346
6347
0
  Pel* pRef;
6348
0
  Pel* pOrg;
6349
0
  int refStride, orgStride;
6350
0
  int width, height;
6351
6352
0
  int picWidth = cu.cs->slice->pps->picWidthInLumaSamples;
6353
0
  int picHeight = cu.cs->slice->pps->picHeightInLumaSamples;
6354
6355
0
  UnitArea allCompBlocks(cu.chromaFormat, (Area)cu.block(COMP_Y));
6356
0
  for (int cand = 0; cand < CHROMA_REFINEMENT_CANDIDATES; cand++)
6357
0
  {
6358
0
    if (sadBestCand[cand] == std::numeric_limits<Distortion>::max())
6359
0
    {
6360
0
      continue;
6361
0
    }
6362
6363
0
    if ((!cMVCand[cand].hor) && (!cMVCand[cand].ver))
6364
0
      continue;
6365
6366
0
    if (((int)(cuPelY + cMVCand[cand].ver + roiHeight) >= picHeight) || ((cuPelY + cMVCand[cand].ver) < 0))
6367
0
      continue;
6368
6369
0
    if (((int)(cuPelX + cMVCand[cand].hor + roiWidth) >= picWidth) || ((cuPelX + cMVCand[cand].hor) < 0))
6370
0
      continue;
6371
6372
0
    tempSad = sadBestCand[cand];
6373
6374
0
    cu.mv[0][0] = cMVCand[cand];
6375
0
    cu.mv[0][0].changePrecision(MV_PRECISION_INT, MV_PRECISION_INTERNAL);
6376
0
    cu.interDir = 1;
6377
0
    cu.refIdx[0] = cu.cs->slice->numRefIdx[REF_PIC_LIST_0]; // last idx in the list
6378
6379
0
    PelUnitBuf predBufTmp = m_tmpPredStorage[REF_PIC_LIST_0].getCompactBuf(cu);
6380
0
    motionCompensation(cu, predBufTmp, REF_PIC_LIST_0);
6381
6382
0
    for (unsigned int ch = COMP_Cb; ch < getNumberValidComponents(cu.cs->sps->chromaFormatIdc); ch++)
6383
0
    {
6384
0
      width = roiWidth >> getComponentScaleX(ComponentID(ch), cu.chromaFormat);
6385
0
      height = roiHeight >> getComponentScaleY(ComponentID(ch), cu.chromaFormat);
6386
6387
0
      PelUnitBuf origBuf = cu.cs->getOrgBuf(allCompBlocks);
6388
0
      PelUnitBuf* pBuf = &origBuf;
6389
0
      CPelBuf  tmpPattern = pBuf->get(ComponentID(ch));
6390
0
      pOrg = (Pel*)tmpPattern.buf;
6391
6392
0
      Picture* refPic = cu.slice->pic;
6393
0
      const CPelBuf refBuf = refPic->getRecoBuf(allCompBlocks.blocks[ComponentID(ch)]);
6394
0
      pRef = (Pel*)refBuf.buf;
6395
6396
0
      refStride = refBuf.stride;
6397
0
      orgStride = tmpPattern.stride;
6398
6399
      //ComponentID compID = (ComponentID)ch;
6400
0
      PelUnitBuf* pBufRef = &predBufTmp;
6401
0
      CPelBuf  tmpPatternRef = pBufRef->get(ComponentID(ch));
6402
0
      pRef = (Pel*)tmpPatternRef.buf;
6403
0
      refStride = tmpPatternRef.stride;
6404
6405
6406
0
      tempSad += m_bvSearchOps.sumAbsDiffShifted( pOrg, orgStride, pRef, refStride, width, height, cu.cs->sps->bitDepths[CH_C] - 8 );
6407
0
    }
6408
6409
0
    if (tempSad < sadBest)
6410
0
    {
6411
0
      sadBest = tempSad;
6412
0
      bestCandIdx = cand;
6413
0
    }
6414
0
  }
6415
6416
0
  return bestCandIdx;
6417
25.3k
}
6418
// appends the non-zero candidates of src that are not in dst yet, up to dstTotalLength entries in dst
6419
unsigned InterSearch::xMergeCandLists( Mv* dst, unsigned dn, const unsigned dstTotalLength, const Mv* src, const unsigned sn ) const
6420
150k
{
6421
1.14M
  for( unsigned cand = 0; cand < sn && dn < dstTotalLength; cand++ )
6422
994k
  {
6423
994k
    if( src[cand] != Mv() && !m_bvSearchOps.containsMv( dst, dn, src[cand] ) )
6424
786k
    {
6425
786k
      dst[dn++] = src[cand];
6426
786k
    }
6427
994k
  }
6428
6429
150k
  return dn;
6430
150k
}
6431
6432
const unsigned* InterSearch::xGetBvBitsRow( const int x0, const int xStep, const int count, const int y, const bool useIMV )
6433
26.9k
{
6434
26.9k
  if( count <= 0 )
6435
6.14k
  {
6436
6.14k
    return nullptr;
6437
6.14k
  }
6438
20.7k
  m_bvBits.resize( std::max<size_t>( m_bvBits.size(), count ) );
6439
20.7k
  m_pcRdCost->getBvBitsRowIBC( x0, xStep, count, y, useIMV, m_bvBits.data() );
6440
20.7k
  return m_bvBits.data();
6441
26.9k
}
6442
6443
const unsigned* InterSearch::xGetBvBitsColumn( const int x, const int y0, const int yStep, const int count, const bool useIMV )
6444
30.0k
{
6445
30.0k
  if( count <= 0 )
6446
12.1k
  {
6447
12.1k
    return nullptr;
6448
12.1k
  }
6449
17.9k
  m_bvBits.resize( std::max<size_t>( m_bvBits.size(), count ) );
6450
17.9k
  m_pcRdCost->getBvBitsColumnIBC( x, y0, yStep, count, useIMV, m_bvBits.data() );
6451
17.9k
  return m_bvBits.data();
6452
30.0k
}
6453
6454
void InterSearch::xIntraPatternSearchIBC(CodingUnit& cu, TZSearchStruct& cStruct, Mv& rcMv, Distortion& ruiCost, Mv* pcMvSrchRngLT, Mv* pcMvSrchRngRB, Mv* pcMvPred)
6455
30.0k
{
6456
30.0k
  const int   srchRngHorLeft = pcMvSrchRngLT->hor;
6457
30.0k
  const int   srchRngHorRight = pcMvSrchRngRB->hor;
6458
30.0k
  const int   srchRngVerTop = pcMvSrchRngLT->ver;
6459
30.0k
  const int   srchRngVerBottom = pcMvSrchRngRB->ver;
6460
6461
30.0k
  const unsigned int  lcuWidth = cu.cs->slice->sps->CTUSize;
6462
30.0k
  const int   puPelOffsetX = 0;
6463
30.0k
  const int   puPelOffsetY = 0;
6464
30.0k
  const int   cuPelX = cu.Y().x;
6465
30.0k
  const int   cuPelY = cu.Y().y;
6466
6467
30.0k
  int          roiWidth = cu.lwidth();
6468
30.0k
  int          roiHeight = cu.lheight();
6469
6470
30.0k
  Distortion  sad;
6471
30.0k
  Distortion  sadBest = std::numeric_limits<Distortion>::max();
6472
30.0k
  int         bestX = 0;
6473
30.0k
  int         bestY = 0;
6474
6475
30.0k
  const Pel* piRefSrch = cStruct.piRefY; 
6476
6477
30.0k
  int         bestCandIdx = 0;
6478
6479
30.0k
  Distortion  sadBestCand[CHROMA_REFINEMENT_CANDIDATES];
6480
30.0k
  Mv          cMVCand[CHROMA_REFINEMENT_CANDIDATES];
6481
6482
30.0k
  const bool  useAmvr = cu.cs->sps->AMVR;
6483
6484
6485
270k
  for (int cand = 0; cand < CHROMA_REFINEMENT_CANDIDATES; cand++)
6486
240k
  {
6487
240k
    sadBestCand[cand] = std::numeric_limits<Distortion>::max();
6488
240k
    cMVCand[cand].set(0, 0);
6489
240k
  }
6490
6491
30.0k
  m_pcRdCost->setDistParam(m_cDistParam, *cStruct.pcPatternKey, cStruct.piRefY, cStruct.iRefStride, m_lumaClpRng.bd, COMP_Y, cStruct.subShiftMode);
6492
6493
30.0k
  const int picWidth = cu.cs->slice->pps->picWidthInLumaSamples;
6494
30.0k
  const int picHeight = cu.cs->slice->pps->picHeightInLumaSamples;
6495
6496
6497
30.0k
  {
6498
30.0k
    m_cDistParam.subShift = 0;
6499
30.0k
    Distortion tempSadBest = 0;
6500
6501
30.0k
    int srLeft = srchRngHorLeft, srRight = srchRngHorRight, srTop = srchRngVerTop, srBottom = srchRngVerBottom;
6502
30.0k
    m_numBVs = 0;
6503
30.0k
    m_numBVs = xMergeCandLists(m_acBVs, m_numBVs, (2 * IBC_NUM_CANDIDATES), m_defaultCachedBvs->m_bvCands, m_defaultCachedBvs->currCnt);
6504
6505
30.0k
    Mv cMvPredEncOnly[IBC_NUM_CANDIDATES];
6506
30.0k
    int nbPreds = 0;
6507
30.0k
    CU::getIbcMVPsEncOnly(cu, cMvPredEncOnly, nbPreds);
6508
30.0k
    m_numBVs = xMergeCandLists(m_acBVs, m_numBVs, (2 * IBC_NUM_CANDIDATES), cMvPredEncOnly, nbPreds);
6509
6510
281k
    for (unsigned int cand = 0; cand < m_numBVs; cand++)
6511
251k
    {
6512
251k
      int xPred = m_acBVs[cand].hor;
6513
251k
      int yPred = m_acBVs[cand].ver;
6514
6515
251k
      if (!(xPred == 0 && yPred == 0)
6516
251k
        && !((yPred < srTop) || (yPred > srBottom))
6517
225k
        && !((xPred < srLeft) || (xPred > srRight)))
6518
225k
      {
6519
225k
        bool validCand = searchBvIBC(cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, xPred, yPred, lcuWidth);
6520
6521
225k
        if (validCand)
6522
186k
        {
6523
186k
          sad = m_pcRdCost->getBvCostMultiplePredsIBC(xPred, yPred, useAmvr);
6524
186k
          m_cDistParam.cur.buf = piRefSrch + cStruct.iRefStride * yPred + xPred;
6525
186k
          sad += m_cDistParam.distFunc(m_cDistParam);
6526
6527
186k
          xIBCSearchMVCandUpdate(sad, xPred, yPred, sadBestCand, cMVCand);
6528
186k
        }
6529
225k
      }
6530
251k
    }
6531
6532
30.0k
    bestX = cMVCand[0].hor;
6533
30.0k
    bestY = cMVCand[0].ver;
6534
30.0k
    rcMv.set(bestX, bestY);
6535
30.0k
    sadBest = sadBestCand[0];
6536
6537
30.0k
    const int boundY = (0 - roiHeight - puPelOffsetY);
6538
30.0k
    const int aboveStartY = std::max(srchRngVerTop, 0 - cuPelY);
6539
30.0k
    const unsigned* bvBitsAbove = xGetBvBitsColumn( 0, aboveStartY, 1, boundY - aboveStartY + 1, useAmvr );
6540
505k
    for (int y = aboveStartY; y <= boundY; ++y)
6541
478k
    {
6542
478k
      if (!searchBvIBC(cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, 0, y, lcuWidth))
6543
0
      {
6544
0
        continue;
6545
0
      }
6546
6547
478k
      sad = m_pcRdCost->getBvCostIBC( bvBitsAbove[y - aboveStartY] );
6548
478k
      m_cDistParam.cur.buf = piRefSrch + cStruct.iRefStride * y;
6549
478k
      sad += m_cDistParam.distFunc(m_cDistParam);
6550
6551
478k
      xIBCSearchMVCandUpdate(sad, 0, y, sadBestCand, cMVCand);
6552
478k
      tempSadBest = sadBestCand[0];
6553
478k
      if (sadBestCand[0] <= 3)
6554
3.29k
      {
6555
3.29k
        bestX = cMVCand[0].hor;
6556
3.29k
        bestY = cMVCand[0].ver;
6557
3.29k
        sadBest = sadBestCand[0];
6558
3.29k
        rcMv.set(bestX, bestY);
6559
3.29k
        ruiCost = sadBest;
6560
3.29k
        goto end;
6561
3.29k
      }
6562
478k
    }
6563
6564
26.7k
    const int boundX = std::max(srchRngHorLeft, -cuPelX);
6565
26.7k
    const int leftStartX = 0 - roiWidth - puPelOffsetX;
6566
26.7k
    const unsigned* bvBitsLeft = xGetBvBitsRow( leftStartX, -1, leftStartX - boundX + 1, 0, useAmvr );
6567
1.72M
    for (int x = leftStartX; x >= boundX; --x)
6568
1.69M
    {
6569
1.69M
      if (!searchBvIBC(cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, x, 0, lcuWidth))
6570
946k
      {
6571
946k
        continue;
6572
946k
      }
6573
6574
751k
      sad = m_pcRdCost->getBvCostIBC( bvBitsLeft[leftStartX - x] );
6575
751k
      m_cDistParam.cur.buf = piRefSrch + x;
6576
751k
      sad += m_cDistParam.distFunc(m_cDistParam);
6577
6578
6579
751k
      xIBCSearchMVCandUpdate(sad, x, 0, sadBestCand, cMVCand);
6580
751k
      tempSadBest = sadBestCand[0];
6581
751k
      if (sadBestCand[0] <= 3)
6582
1.38k
      {
6583
1.38k
        bestX = cMVCand[0].hor;
6584
1.38k
        bestY = cMVCand[0].ver;
6585
1.38k
        sadBest = sadBestCand[0];
6586
1.38k
        rcMv.set(bestX, bestY);
6587
1.38k
        ruiCost = sadBest;
6588
1.38k
        goto end;
6589
1.38k
      }
6590
751k
    }
6591
6592
25.3k
    bestX = cMVCand[0].hor;
6593
25.3k
    bestY = cMVCand[0].ver;
6594
25.3k
    sadBest = sadBestCand[0];
6595
25.3k
    if ((!bestX && !bestY) || (sadBest - m_pcRdCost->getBvCostMultiplePredsIBC(bestX, bestY, useAmvr) <= 32))
6596
24.2k
    {
6597
      //chroma refine
6598
24.2k
      bestCandIdx = xIBCSearchMVChromaRefine(cu, roiWidth, roiHeight, cuPelX, cuPelY, sadBestCand, cMVCand);
6599
24.2k
      bestX = cMVCand[bestCandIdx].hor;
6600
24.2k
      bestY = cMVCand[bestCandIdx].ver;
6601
24.2k
      sadBest = sadBestCand[bestCandIdx];
6602
24.2k
      rcMv.set(bestX, bestY);
6603
24.2k
      ruiCost = sadBest;
6604
24.2k
      goto end;
6605
24.2k
    }
6606
6607
1.07k
    if (cu.lwidth() < 16 && cu.lheight() < 16)
6608
17
    {
6609
17
      int stepS = 2;
6610
17
      if (m_pcEncCfg->m_IBCFastMethod > 2)
6611
17
      {
6612
17
        if (m_pcEncCfg->m_IBCFastMethod == 5)
6613
0
        {
6614
0
          stepS = 8;
6615
0
        }
6616
17
        else if ((cu.lwidth() > 4) || (cu.lheight() > 4))
6617
17
        {
6618
17
          stepS = 4;
6619
17
        }
6620
17
      }
6621
6622
17
      const int minCuLog2 = m_pcEncCfg->m_log2MinCodingBlockSize;
6623
17
      const int minCuMask = (1 << minCuLog2) - 1;
6624
17
      bool lastDec = false;
6625
6626
17
      for (int searchStep = 0; searchStep < 3; searchStep++)
6627
17
      {
6628
17
        int delaySy = searchStep ? 1 : 0;
6629
17
        int delaySx = searchStep > 1 ? 1 : 0;
6630
17
        int startY = (std::max(srchRngVerTop, -cuPelY) + delaySy);
6631
17
        int startX = (std::max(srchRngHorLeft, -cuPelX) + delaySx);
6632
17
        int endY = srchRngVerBottom;
6633
17
        int endX = srchRngHorRight;
6634
6635
17
        if (m_pcEncCfg->m_IBCFastMethod > 5)
6636
0
        {
6637
0
          startY = bestY - 4;
6638
0
          endY = bestY + 4;
6639
0
          startX = bestX - 4;
6640
0
          endX = bestX + 4;
6641
0
          stepS = 1;
6642
0
          if (searchStep)
6643
0
          {
6644
0
            break;
6645
0
          }
6646
0
        }
6647
6648
432
        for (int y = startY; y <= endY; y += stepS)
6649
415
        {
6650
415
          if ((y == 0) || ((int)(cuPelY + y + roiHeight) >= picHeight))
6651
219
            continue;
6652
196
          bool firstX = true;
6653
196
          int stepSx = searchStep ? stepS : 1;
6654
196
          const unsigned* bvBitsRow = xGetBvBitsRow( startX, stepSx, ( endX - startX ) / stepSx + 1, y, useAmvr );
6655
24.4k
          for (int x = startX, k = 0; x <= endX; firstX = false, x += stepSx, k++)
6656
24.2k
          {
6657
24.2k
            if ((x == 0) || ((int)(cuPelX + x + roiWidth) >= picWidth))
6658
9.52k
              continue;
6659
6660
14.7k
            bool isSameAsLast = !firstX && ((cuPelX + x) & minCuMask) > 1;
6661
14.7k
            if (searchStep || (m_pcEncCfg->m_IBCFastMethod > 5))
6662
0
            {
6663
0
              if (!searchBvIBC(cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, x, y, lcuWidth))
6664
0
              {
6665
0
                continue;
6666
0
              }
6667
0
            }
6668
14.7k
            else if ((isSameAsLast && !lastDec) || (!isSameAsLast && !searchBvIBC(cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, x, y, lcuWidth)))
6669
3.94k
            {
6670
3.94k
              lastDec = false;
6671
3.94k
              continue;
6672
3.94k
            }
6673
10.7k
            lastDec = true;
6674
6675
10.7k
            sad = m_pcRdCost->getBvCostIBC( bvBitsRow[k] );
6676
10.7k
            m_cDistParam.cur.buf = piRefSrch + cStruct.iRefStride * y + x;
6677
10.7k
            sad += m_cDistParam.distFunc(m_cDistParam);
6678
6679
10.7k
            xIBCSearchMVCandUpdate(sad, x, y, sadBestCand, cMVCand);
6680
6681
6682
10.7k
            if (searchStep && sadBestCand[0] <= 5)
6683
0
            {
6684
              //chroma refine & return
6685
0
              bestCandIdx = xIBCSearchMVChromaRefine(cu, roiWidth, roiHeight, cuPelX, cuPelY, sadBestCand, cMVCand);
6686
0
              bestX = cMVCand[bestCandIdx].hor;
6687
0
              bestY = cMVCand[bestCandIdx].ver;
6688
0
              sadBest = sadBestCand[bestCandIdx];
6689
0
              rcMv.set(bestX, bestY);
6690
0
              ruiCost = sadBest;
6691
0
              goto end;
6692
0
            }
6693
10.7k
          }
6694
196
        }
6695
6696
17
        if ((searchStep < 2) && (m_pcEncCfg->m_IBCFastMethod < 6))
6697
17
        {
6698
17
          if ((m_pcEncCfg->m_IBCFastMethod > 2) && (m_pcEncCfg->m_IBCFastMethod < 5))
6699
17
          {
6700
17
            if ((bestX == cMVCand[0].hor) && (bestY == cMVCand[0].ver))
6701
17
            {
6702
17
              sadBest = sadBestCand[bestCandIdx];
6703
17
              rcMv.set(bestX, bestY);
6704
17
              ruiCost = sadBest;
6705
17
              goto end;
6706
17
            }
6707
17
          }
6708
0
          bestX = cMVCand[0].hor;
6709
0
          bestY = cMVCand[0].ver;
6710
0
          sadBest = sadBestCand[0];
6711
6712
0
          int StopSearch = searchStep ? 32 : 16;
6713
0
          if ((searchStep && (sadBest >= tempSadBest)) || (sadBest - m_pcRdCost->getBvCostMultiplePredsIBC(bestX, bestY, useAmvr) <= StopSearch))
6714
0
          {
6715
            //chroma refine
6716
0
            bestCandIdx = xIBCSearchMVChromaRefine(cu, roiWidth, roiHeight, cuPelX, cuPelY, sadBestCand, cMVCand);
6717
6718
0
            bestX = cMVCand[bestCandIdx].hor;
6719
0
            bestY = cMVCand[bestCandIdx].ver;
6720
0
            sadBest = sadBestCand[bestCandIdx];
6721
0
            rcMv.set(bestX, bestY);
6722
0
            ruiCost = sadBest;
6723
0
            goto end;
6724
0
          }
6725
0
        }
6726
17
      }
6727
17
    }
6728
1.07k
  }
6729
6730
1.05k
  bestCandIdx = xIBCSearchMVChromaRefine(cu, roiWidth, roiHeight, cuPelX, cuPelY, sadBestCand, cMVCand);
6731
6732
1.05k
  bestX = cMVCand[bestCandIdx].hor;
6733
1.05k
  bestY = cMVCand[bestCandIdx].ver;
6734
1.05k
  sadBest = sadBestCand[bestCandIdx];
6735
1.05k
  rcMv.set(bestX, bestY);
6736
1.05k
  ruiCost = sadBest;
6737
6738
30.0k
end:
6739
30.0k
  m_numBVs = 0;
6740
30.0k
  m_numBVs = xMergeCandLists(m_acBVs, m_numBVs, (2 * IBC_NUM_CANDIDATES), m_defaultCachedBvs->m_bvCands, m_defaultCachedBvs->currCnt);
6741
6742
30.0k
  m_defaultCachedBvs->currCnt = 0;
6743
30.0k
  m_defaultCachedBvs->currCnt = xMergeCandLists(m_defaultCachedBvs->m_bvCands, m_defaultCachedBvs->currCnt, IBC_NUM_CANDIDATES, cMVCand, CHROMA_REFINEMENT_CANDIDATES);
6744
30.0k
  m_defaultCachedBvs->currCnt = xMergeCandLists(m_defaultCachedBvs->m_bvCands, m_defaultCachedBvs->currCnt, IBC_NUM_CANDIDATES, m_acBVs, m_numBVs);
6745
6746
270k
  for (unsigned int cand = 0; cand < CHROMA_REFINEMENT_CANDIDATES; cand++)
6747
240k
  {
6748
240k
    if (cMVCand[cand].hor == 0 && cMVCand[cand].ver == 0)
6749
79.2k
    {
6750
79.2k
      continue;
6751
79.2k
    }
6752
161k
    m_ctuRecord[cu.lumaPos()][cu.lumaSize()].bvRecord[cMVCand[cand]] = sadBestCand[cand];
6753
161k
  }
6754
6755
30.0k
  return;
6756
1.05k
}
6757
6758
6759
6760
// based on xMotionEstimation
6761
void InterSearch::xIBCEstimation(CodingUnit& cu, PelUnitBuf& origBuf, Mv* pcMvPred, Mv& rcMv, Distortion& ruiCost )
6762
30.0k
{
6763
30.0k
  const int iPicWidth = cu.cs->slice->pps->picWidthInLumaSamples;
6764
30.0k
  const int iPicHeight = cu.cs->slice->pps->picHeightInLumaSamples;
6765
30.0k
  const unsigned int  lcuWidth = cu.cs->slice->sps->CTUSize;
6766
30.0k
  const int           cuPelX = cu.Y().x;
6767
30.0k
  const int           cuPelY = cu.Y().y;
6768
30.0k
  int                 iRoiWidth = cu.lwidth();
6769
30.0k
  int                 iRoiHeight = cu.lheight();
6770
6771
30.0k
  PelUnitBuf* pBuf = &origBuf;
6772
6773
  //  Search key pattern initialization
6774
30.0k
  CPelBuf  tmpPattern = pBuf->Y();
6775
30.0k
  CPelBuf* pcPatternKey = &tmpPattern;
6776
30.0k
  m_lumaClpRng = cu.cs->slice->clpRngs[COMP_Y];
6777
30.0k
  Picture* refPic = cu.slice->pic;
6778
30.0k
  const CPelBuf refBuf = refPic->getRecoBuf(cu.blocks[COMP_Y]);
6779
6780
30.0k
  TZSearchStruct cStruct; 
6781
30.0k
  cStruct.pcPatternKey  = pcPatternKey;
6782
30.0k
  cStruct.iRefStride    = refBuf.stride;
6783
30.0k
  cStruct.piRefY        = refBuf.buf;
6784
30.0k
  CHECK( cu.imv == IMV_HPEL, "IF_IBC" );
6785
30.0k
  cStruct.imvShift      = cu.imv << 1;
6786
30.0k
  cStruct.subShiftMode  = 0;
6787
30.0k
  cStruct.uiBestSad     = MAX_DISTORTION;
6788
6789
30.0k
  m_pcRdCost->getMotionCostIBC(0);
6790
30.0k
  m_pcRdCost->setPredictorsIBC(pcMvPred);
6791
30.0k
  m_pcRdCost->setCostScale(0);
6792
6793
30.0k
  m_pcRdCost->setDistParam(m_cDistParam, *cStruct.pcPatternKey, cStruct.piRefY, cStruct.iRefStride, m_lumaClpRng.bd, COMP_Y, cStruct.subShiftMode);
6794
30.0k
  bool buffered = false;
6795
30.0k
  if (m_pcEncCfg->m_IBCFastMethod)// IBC_FAST_METHOD_BUFFERBV
6796
30.0k
  {
6797
30.0k
    ruiCost = MAX_UINT;
6798
30.0k
    std::unordered_map<Mv, Distortion>& history = m_ctuRecord[cu.lumaPos()][cu.lumaSize()].bvRecord;
6799
30.0k
    for (std::unordered_map<Mv, Distortion>::iterator p = history.begin(); p != history.end(); p++)
6800
18
    {
6801
18
      const Mv& bv = p->first;
6802
6803
18
      int xBv = bv.hor;
6804
18
      int yBv = bv.ver;
6805
18
      if (searchBvIBC(cu, cuPelX, cuPelY, iRoiWidth, iRoiHeight, iPicWidth, iPicHeight, xBv, yBv, lcuWidth))
6806
18
      {
6807
18
        buffered = true;
6808
18
        Distortion sad = m_pcRdCost->getBvCostMultiplePredsIBC(xBv, yBv, cu.cs->sps->AMVR);
6809
18
        m_cDistParam.cur.buf = cStruct.piRefY + cStruct.iRefStride * yBv + xBv;
6810
18
        sad += m_cDistParam.distFunc(m_cDistParam);
6811
18
        if (sad < ruiCost)
6812
18
        {
6813
18
          rcMv = bv;
6814
18
          ruiCost = sad;
6815
18
        }
6816
0
        else if (sad == ruiCost)
6817
0
        {
6818
          // stabilise the search through the unordered list
6819
0
          if (bv.hor < rcMv.hor
6820
0
            || (bv.hor == rcMv.hor && bv.ver < rcMv.ver))
6821
0
          {
6822
            // update the vector.
6823
0
            rcMv = bv;
6824
0
          }
6825
0
        }
6826
18
      }
6827
18
    }
6828
6829
30.0k
    if (buffered)
6830
18
    {
6831
18
      Mv cMvPredEncOnly[IBC_NUM_CANDIDATES];
6832
18
      int nbPreds = 0;
6833
18
      CU::getIbcMVPsEncOnly(cu, cMvPredEncOnly, nbPreds);
6834
6835
18
      for (unsigned int cand = 0; cand < nbPreds; cand++)
6836
0
      {
6837
0
        int xPred = cMvPredEncOnly[cand].hor;
6838
0
        int yPred = cMvPredEncOnly[cand].ver;
6839
6840
0
        if (searchBvIBC(cu, cuPelX, cuPelY, iRoiWidth, iRoiHeight, iPicWidth, iPicHeight, xPred, yPred, lcuWidth))
6841
0
        {
6842
0
          Distortion sad = m_pcRdCost->getBvCostMultiplePredsIBC(xPred, yPred, cu.cs->sps->AMVR);
6843
0
          m_cDistParam.cur.buf = cStruct.piRefY + cStruct.iRefStride * yPred + xPred;
6844
0
          sad += m_cDistParam.distFunc(m_cDistParam);
6845
0
          if (sad < ruiCost)
6846
0
          {
6847
0
            rcMv.set(xPred, yPred);
6848
0
            ruiCost = sad;
6849
0
          }
6850
0
          else if (sad == ruiCost)
6851
0
          {
6852
            // stabilise the search through the unordered list
6853
0
            if (xPred < rcMv.hor
6854
0
              || (xPred == rcMv.hor && yPred < rcMv.ver))
6855
0
            {
6856
              // update the vector.
6857
0
              rcMv.set(xPred, yPred);
6858
0
            }
6859
0
          }
6860
0
          m_ctuRecord[cu.lumaPos()][cu.lumaSize()].bvRecord[Mv(xPred, yPred)] = sad;
6861
0
        }
6862
0
      }
6863
18
    }
6864
30.0k
  }
6865
6866
30.0k
  if (!buffered)
6867
30.0k
  {
6868
30.0k
    Mv        cMvSrchRngLT;
6869
30.0k
    Mv        cMvSrchRngRB;
6870
6871
    // assume that intra BV is integer-pel precision
6872
30.0k
    xSetIntraSearchRangeIBC(cu, cu.lwidth(), cu.lheight(), cMvSrchRngLT, cMvSrchRngRB);
6873
6874
    //  Do integer search
6875
30.0k
    xIntraPatternSearchIBC(cu, cStruct, rcMv, ruiCost, &cMvSrchRngLT, &cMvSrchRngRB, pcMvPred);
6876
30.0k
  }
6877
30.0k
}
6878
// based on xSetSearchRange
6879
void InterSearch::xSetIntraSearchRangeIBC(CodingUnit& cu, int iRoiWidth, int iRoiHeight, Mv& rcMvSrchRngLT, Mv& rcMvSrchRngRB)
6880
30.0k
{
6881
 // const SPS& sps = *cu.cs->sps;
6882
6883
30.0k
  int srLeft, srRight, srTop, srBottom;
6884
6885
30.0k
  const int cuPelX = cu.Y().x;
6886
30.0k
  const int cuPelY = cu.Y().y;
6887
6888
30.0k
  const int lcuWidth = cu.cs->slice->sps->CTUSize;
6889
30.0k
  const int ctuSizeLog2 = floorLog2(lcuWidth);
6890
30.0k
  int numLeftCTUs = (1 << ((7 - ctuSizeLog2) << 1)) - ((ctuSizeLog2 < 7) ? 1 : 0);
6891
6892
30.0k
  srLeft = -(numLeftCTUs * lcuWidth + (cuPelX % lcuWidth));
6893
30.0k
  srTop = -(cuPelY % lcuWidth);
6894
6895
30.0k
  srRight = lcuWidth - (cuPelX % lcuWidth) - iRoiWidth;
6896
30.0k
  srBottom = lcuWidth - (cuPelY % lcuWidth) - iRoiHeight;
6897
6898
30.0k
  rcMvSrchRngLT.hor=srLeft;
6899
30.0k
  rcMvSrchRngLT.ver=srTop;
6900
30.0k
  rcMvSrchRngRB.hor=srRight;
6901
30.0k
  rcMvSrchRngRB.ver=srBottom;
6902
6903
30.0k
  rcMvSrchRngLT <<= 2;
6904
30.0k
  rcMvSrchRngRB <<= 2;
6905
30.0k
  bool temp = m_clipMvInSubPic;
6906
30.0k
  m_clipMvInSubPic = true;
6907
30.0k
  clipMv(rcMvSrchRngLT,cu.lumaPos(),cu.lumaSize(), *cu.cs->pcv, *cu.cs->pps, m_clipMvInSubPic);
6908
30.0k
  clipMv(rcMvSrchRngRB, cu.lumaPos(),cu.lumaSize(), *cu.cs->pcv, * cu.cs->pps, m_clipMvInSubPic);
6909
30.0k
  m_clipMvInSubPic = temp;
6910
30.0k
  rcMvSrchRngLT >>= 2;
6911
30.0k
  rcMvSrchRngRB >>= 2;
6912
30.0k
}
6913
6914
bool InterSearch::predIBCSearch(CodingUnit& cu, Partitioner& partitioner)
6915
30.0k
{
6916
30.0k
  Mv           cMvSrchRngLT;
6917
30.0k
  Mv           cMvSrchRngRB;
6918
30.0k
  cu.imv = IMV_4PEL;
6919
30.0k
  AMVPInfo amvpInfo4Pel;
6920
30.0k
  CU::fillIBCMvpCand(cu, amvpInfo4Pel);
6921
6922
30.0k
  cu.imv = IMV_OFF;// (Int)cu.cs->sps->getUseIMV(); // set as IMV=0 initially
6923
30.0k
  Mv    cMv, cMvPred[2];
6924
30.0k
  AMVPInfo amvpInfo;
6925
30.0k
  CU::fillIBCMvpCand(cu, amvpInfo);
6926
  // store in full pel accuracy, shift before use in search
6927
30.0k
  cMvPred[0] = amvpInfo.mvCand[0];
6928
30.0k
  cMvPred[0].changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_INT);
6929
30.0k
  cMvPred[1] = amvpInfo.mvCand[1];
6930
30.0k
  cMvPred[1].changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_INT);
6931
6932
30.0k
  int iBvpNum = 2;
6933
30.0k
  int bvpIdxBest = 0;
6934
30.0k
  cMv.setZero();
6935
30.0k
  Distortion cost = 0;
6936
30.0k
  if (cu.cs->sps->maxNumIBCMergeCand == 1)
6937
0
  {
6938
0
    iBvpNum = 1;
6939
0
    cMvPred[1] = cMvPred[0];
6940
0
  }
6941
6942
30.0k
  if (cMv.hor == 0 && cMv.ver == 0)
6943
30.0k
  {
6944
    // if hash search does not work or is not enabled
6945
30.0k
    PelUnitBuf origBuf = cu.cs->getOrgBuf(cu);
6946
30.0k
    xIBCEstimation(cu, origBuf, cMvPred, cMv, cost );
6947
30.0k
  }
6948
6949
30.0k
  if (cMv.hor == 0 && cMv.ver == 0)
6950
3.18k
  {
6951
3.18k
    return false;
6952
3.18k
  }
6953
  /// ibc search
6954
  /////////////////////////////////////////////////////////
6955
26.8k
  unsigned int bitsBVPBest, bitsBVPTemp;
6956
26.8k
  bitsBVPBest = MAX_INT;
6957
26.8k
  m_pcRdCost->setCostScale(0);
6958
6959
80.5k
  for (int bvpIdxTemp = 0; bvpIdxTemp < iBvpNum; bvpIdxTemp++)
6960
53.7k
  {
6961
53.7k
    m_pcRdCost->setPredictor(cMvPred[bvpIdxTemp]);
6962
6963
53.7k
    bitsBVPTemp = m_pcRdCost->getBitsOfVectorWithPredictor(cMv.hor, cMv.ver, 0);
6964
6965
53.7k
    if (bitsBVPTemp < bitsBVPBest)
6966
26.8k
    {
6967
26.8k
      bitsBVPBest = bitsBVPTemp;
6968
26.8k
      bvpIdxBest = bvpIdxTemp;
6969
6970
26.8k
      if (cu.cs->sps->AMVR && cMv != cMvPred[bvpIdxTemp])
6971
26.8k
        cu.imv = IMV_FPEL; // set as full-pel
6972
0
      else
6973
0
        cu.imv = IMV_OFF; // set as fractional-pel
6974
6975
26.8k
    }
6976
6977
53.7k
    unsigned int bitsBVPQP = MAX_UINT;
6978
6979
6980
53.7k
    Mv mvPredQuadPel;
6981
53.7k
    if ((cMv.hor % 4 == 0) && (cMv.ver % 4 == 0) && (cu.cs->sps->AMVR))
6982
53.7k
    {
6983
53.7k
      mvPredQuadPel = amvpInfo4Pel.mvCand[bvpIdxTemp];// cMvPred[bvpIdxTemp];
6984
6985
53.7k
      mvPredQuadPel.changePrecision(MV_PRECISION_INTERNAL, MV_PRECISION_4PEL);
6986
6987
53.7k
      m_pcRdCost->setPredictor(mvPredQuadPel);
6988
6989
53.7k
      bitsBVPQP = m_pcRdCost->getBitsOfVectorWithPredictor(cMv.hor >> 2, cMv.ver >> 2, 0);
6990
6991
53.7k
    }
6992
53.7k
    mvPredQuadPel.changePrecision(MV_PRECISION_4PEL, MV_PRECISION_INT);
6993
53.7k
    if (bitsBVPQP < bitsBVPBest && cMv != mvPredQuadPel)
6994
26.8k
    {
6995
26.8k
      bitsBVPBest = bitsBVPQP;
6996
26.8k
      bvpIdxBest = bvpIdxTemp;
6997
6998
26.8k
      if (cu.cs->sps->AMVR)
6999
26.8k
        cu.imv = IMV_4PEL;
7000
26.8k
    }
7001
7002
53.7k
  }
7003
7004
26.8k
  cMv.changePrecision( MV_PRECISION_INT, MV_PRECISION_INTERNAL );
7005
26.8k
  cu.mv[REF_PIC_LIST_0][0] = cMv; // store in fractional pel accuracy
7006
7007
26.8k
  cu.mvpIdx[REF_PIC_LIST_0] = bvpIdxBest;
7008
7009
26.8k
  if (cu.imv == IMV_4PEL && cMv != amvpInfo4Pel.mvCand[bvpIdxBest])
7010
26.8k
    cu.mvd[REF_PIC_LIST_0][0] = cMv - amvpInfo4Pel.mvCand[bvpIdxBest];
7011
18.4E
  else
7012
18.4E
    cu.mvd[REF_PIC_LIST_0][0] = cMv - amvpInfo.mvCand[bvpIdxBest];
7013
7014
26.8k
  if (cu.mvd[REF_PIC_LIST_0][0] == Mv(0, 0))
7015
0
    cu.imv = IMV_OFF;
7016
26.8k
  if (cu.imv == IMV_4PEL)
7017
26.8k
    assert((cMv.hor % 16 == 0) && (cMv.ver % 16 == 0));
7018
26.8k
  if (cu.cs->sps->AMVR)
7019
26.8k
    assert(cu.imv > 0 || cu.mvd[REF_PIC_LIST_0][0] == Mv());
7020
7021
26.8k
  cu.refIdx[REF_PIC_LIST_0] = MAX_NUM_REF;
7022
7023
26.8k
  return true;
7024
26.8k
}
7025
7026
7027
static inline bool isYPartBefore( SplitSeries series, const int ctuSizeLog2, const Position& refPos, const Position& pos )
7028
1.73M
{
7029
1.73M
#ifndef NDEBUG
7030
1.73M
  const int refCtuX = refPos.x >> ctuSizeLog2;
7031
1.73M
  const int refCtuY = refPos.y >> ctuSizeLog2;
7032
1.73M
  const int posCtuX = pos.x >> ctuSizeLog2;
7033
1.73M
  const int posCtuY = pos.y >> ctuSizeLog2;
7034
7035
1.73M
  CHECK( refCtuX != posCtuX || refCtuY != posCtuY, "This method can only be applied for positions within the same CTU" );
7036
7037
1.73M
#endif
7038
1.73M
  const int ctuMask = ( 1 << ctuSizeLog2 ) - 1;
7039
7040
1.73M
  const int refX = refPos.x & ctuMask;
7041
1.73M
  const int refY = refPos.y & ctuMask;
7042
1.73M
  const int posX = pos.x & ctuMask;
7043
1.73M
  const int posY = pos.y & ctuMask;
7044
7045
1.73M
  int x = 0, y = 0, w = 1 << ctuSizeLog2, h = 1 << ctuSizeLog2;
7046
  
7047
2.32M
  while( true )
7048
2.32M
  {
7049
2.32M
    PartSplit split = PartSplit( series & SPLIT_MASK );
7050
7051
2.32M
    switch( split )
7052
2.32M
    {
7053
2.26M
    case CU_QUAD_SPLIT:
7054
2.26M
      w >>= 1;
7055
2.26M
      if( posX >= x + w ) x += w;
7056
2.29M
    case CU_HORZ_SPLIT:
7057
2.29M
      h >>= 1;
7058
2.29M
      if( posY >= y + h ) y += h;
7059
2.29M
      break;
7060
7061
33.6k
    case CU_VERT_SPLIT:
7062
33.6k
      w >>= 1;
7063
33.6k
      if( posX >= x + w ) x += w;
7064
33.6k
      goto checkXonly;
7065
7066
0
    case CU_TRIH_SPLIT:
7067
0
      h >>= 2;
7068
0
      if( posY >= y + h ) { y += h; h <<= 1; }
7069
0
      if( posY >= y + h ) { y += h; h >>= 1; }
7070
0
      break;
7071
7072
0
    case CU_TRIV_SPLIT:
7073
0
      w >>= 2;
7074
0
      if( posX >= x + w ) { x += w; w <<= 1; }
7075
0
      if( posX >= x + w ) { x += w; w >>= 1; }
7076
0
      goto checkXonly;
7077
7078
0
    default:
7079
0
      return false;
7080
2.32M
    }
7081
7082
2.29M
    if( refY >= y + h ) return true;
7083
1.73M
    else if( refY < y ) return false;
7084
7085
1.77M
checkXonly:
7086
1.77M
    if( refX >= x + w ) return true;
7087
870k
    else if( refX < x ) return false;
7088
7089
586k
    series >>= SPLIT_DMULT; continue;
7090
1.77M
  }
7091
7092
77
  return false;
7093
1.73M
}
7094
7095
bool InterSearch::searchBvIBC(const CodingUnit& cu, int xPos, int yPos, int width, int height, int picWidth, int picHeight, int xBv, int yBv, int ctuSize) const
7096
2.59M
{
7097
2.59M
  const int ctuSizeLog2 = Log2(ctuSize);
7098
7099
2.59M
  int refRightX  = xPos + xBv + width  - 1;
7100
2.59M
  int refBottomY = yPos + yBv + height - 1;
7101
7102
2.59M
  int refLeftX = xPos + xBv;
7103
2.59M
  int refTopY  = yPos + yBv;
7104
7105
2.59M
  if ((xPos + xBv) < 0)
7106
14.3k
  {
7107
14.3k
    return false;
7108
14.3k
  }
7109
2.57M
  if (refRightX >= picWidth)
7110
0
  {
7111
0
    return false;
7112
0
  }
7113
7114
2.57M
  if ((yPos + yBv) < 0)
7115
0
  {
7116
0
    return false;
7117
0
  }
7118
2.57M
  if (refBottomY >= picHeight)
7119
0
  {
7120
0
    return false;
7121
0
  }
7122
2.57M
  if ((xBv + width) > 0 && (yBv + height) > 0)
7123
205k
  {
7124
205k
    return false;
7125
205k
  }
7126
7127
  // Don't search the above CTU row
7128
2.37M
  if (refTopY >> ctuSizeLog2 < yPos >> ctuSizeLog2)
7129
0
    return false;
7130
7131
  // Don't search the below CTU row
7132
2.37M
  if (refBottomY >> ctuSizeLog2 > yPos >> ctuSizeLog2)
7133
0
  {
7134
0
    return false;
7135
0
  }
7136
7137
2.37M
  unsigned curTileIdx = cu.cs->pps->getTileIdx(cu.lumaPos());
7138
2.37M
  unsigned refTileIdx = cu.cs->pps->getTileIdx(Position(refLeftX, refTopY));
7139
2.37M
  if (curTileIdx != refTileIdx)
7140
0
  {
7141
0
    return false;
7142
0
  }
7143
2.37M
  refTileIdx = cu.cs->pps->getTileIdx(Position(refLeftX, refBottomY));
7144
2.37M
  if (curTileIdx != refTileIdx)
7145
0
  {
7146
0
    return false;
7147
0
  }
7148
2.37M
  refTileIdx = cu.cs->pps->getTileIdx(Position(refRightX, refTopY));
7149
2.37M
  if (curTileIdx != refTileIdx)
7150
0
  {
7151
0
    return false;
7152
0
  }
7153
2.37M
  refTileIdx = cu.cs->pps->getTileIdx(Position(refRightX, refBottomY));
7154
2.37M
  if (curTileIdx != refTileIdx)
7155
0
  {
7156
0
    return false;
7157
0
  }
7158
7159
2.37M
  const Position cuPos{ xPos, yPos };
7160
7161
  //int numLeftCTUs = (1 << ((7 - ctuSizeLog2) << 1)) - ((ctuSizeLog2 < 7) ? 1 : 0);
7162
2.37M
  static const int numLeftCTUsLUT[3] = { 15, 3, 1 };
7163
7164
  // in the same CTU line
7165
2.37M
  const int numLeftCTUs = numLeftCTUsLUT[ctuSizeLog2 - 5];
7166
7167
2.37M
  if( ( refRightX >> ctuSizeLog2 <= xPos >> ctuSizeLog2 ) && ( refLeftX >> ctuSizeLog2 >= ( xPos >> ctuSizeLog2 ) - numLeftCTUs ) )
7168
2.37M
  {
7169
    // in the same CTU, or left CTU
7170
    // if part of ref block is in the left CTU, some area can be referred from the not-yet updated local CTU buffer
7171
2.37M
    if( ( ctuSizeLog2 == 7 ) && ( ( refLeftX >> ctuSizeLog2 ) == ( ( xPos >> ctuSizeLog2 ) - 1 ) ) )
7172
1.23M
    {
7173
      // ref block's collocated block in current CTU
7174
1.23M
      const Position refPosCol64x64{ ( refLeftX + ctuSize ) & ~63, refTopY & ~63 };
7175
1.23M
      if( refPosCol64x64 == Position{ xPos & ~63, yPos & ~63 } )
7176
668k
        return false;
7177
7178
      //CodingUnit* curef = cu.cs->getCU(refPosCol64x64, CH_L, cu.treeType);
7179
      //bool isDecomp = curef && ((cu.cs != curef->cs) || cu.idx < curef->idx);
7180
563k
      bool isDecomp = isYPartBefore( cu.splitSeries, ctuSizeLog2, cuPos, refPosCol64x64 );
7181
563k
      if( isDecomp )
7182
279k
      {
7183
279k
        return false;
7184
279k
      }
7185
563k
    }
7186
2.37M
  }
7187
18.4E
  else
7188
18.4E
    return false;
7189
7190
  // in the same CTU, or valid area from left CTU. Check if the reference block is already coded
7191
1.42M
  const Position refPosBR{ refRightX, refBottomY };
7192
  //CodingUnit* curef = cu.cs->getCU(refPosBR, CH_L, cu.treeType);
7193
  //bool isDecomp = curef && ((cu.cs != curef->cs) || cu.idx < curef->idx);
7194
1.42M
  bool isDecomp = ( ( refPosBR.x >> ctuSizeLog2 ) < ( cuPos.x >> ctuSizeLog2 ) ) || ( refRightX < xPos && refBottomY < yPos ) || isYPartBefore( cu.splitSeries, ctuSizeLog2, cuPos, refPosBR );
7195
7196
1.42M
  return isDecomp;
7197
2.37M
}
7198
7199
} // namespace vvenc
7200
7201
//! \}
7202