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/EncCu.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     EncCu.cpp
45
    \brief    Coding Unit (CU) encoder class
46
*/
47
48
#include "EncCu.h"
49
#include "EncLib.h"
50
#include "Analyze.h"
51
#include "EncPicture.h"
52
#include "EncModeCtrl.h"
53
#include "BitAllocation.h"
54
#include "EncStage.h"
55
56
#include "CommonLib/dtrace_codingstruct.h"
57
#include "CommonLib/Picture.h"
58
#include "CommonLib/UnitTools.h"
59
#include "CommonLib/dtrace_buffer.h"
60
#include "CommonLib/TimeProfiler.h"
61
#include "CommonLib/SearchSpaceCounter.h"
62
63
#include <mutex>
64
#include <cmath>
65
#include <algorithm>
66
#include <limits>
67
68
//! \ingroup EncoderLib
69
//! \{
70
71
namespace vvenc {
72
73
const MergeIdxPair EncCu::m_GeoModeTest[GEO_MAX_NUM_CANDS] = { MergeIdxPair{0, 1}, MergeIdxPair{1, 0}, MergeIdxPair{0, 2}, MergeIdxPair{1, 2}, MergeIdxPair{2, 0},
74
                                                               MergeIdxPair{2, 1}, MergeIdxPair{0, 3}, MergeIdxPair{1, 3}, MergeIdxPair{2, 3}, MergeIdxPair{3, 0},
75
                                                               MergeIdxPair{3, 1}, MergeIdxPair{3, 2}, MergeIdxPair{0, 4}, MergeIdxPair{1, 4}, MergeIdxPair{2, 4},
76
                                                               MergeIdxPair{3, 4}, MergeIdxPair{4, 0}, MergeIdxPair{4, 1}, MergeIdxPair{4, 2}, MergeIdxPair{4, 3},
77
                                                               MergeIdxPair{0, 5}, MergeIdxPair{1, 5}, MergeIdxPair{2, 5}, MergeIdxPair{3, 5}, MergeIdxPair{4, 5},
78
                                                               MergeIdxPair{5, 0}, MergeIdxPair{5, 1}, MergeIdxPair{5, 2}, MergeIdxPair{5, 3}, MergeIdxPair{5, 4} };
79
80
81
// Shape coefSquareCUsFasterFastMedium (2 x 5 x 2 x 2 x 2): preset (faster and fast + medium) x cusize x nspred x sptype x numcoef
82
83
const double EncCu::coefSquareCUsFasterFastMedium[2][5][2][2][2] = {
84
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  },
85
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  },
86
{{{-1.00000000, -1.00000000, }, {0.07848505, 0.00225808, }, },  {{-1.00000000, -1.00000000, }, {0.07509575, 0.00204789, }, },  },
87
{{{-1.00000000, -1.00000000, }, {0.10833051, 0.00053144, }, },  {{-1.00000000, -1.00000000, }, {0.08304352, 0.00142876, }, },  },
88
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  },
89
},
90
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  },
91
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  },
92
{{{0.06852235, 0.00388054, }, {0.09236045, 0.00084528, }, },  {{0.06955832, 0.00289679, }, {0.09598522, 0.00096187, }, },  },
93
{{{0.07268085, 0.00302796, }, {0.09323753, 0.00050996, }, },  {{0.06123618, 0.00471601, }, {0.09253389, 0.00046826, }, },  },
94
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, },  },
95
},
96
};
97
98
// Shape coefSquareCUsSlowSlower (2 x 5 x 2 x 5 x 2 x 2 x 2): preset (Slow + Slower) x cusize x nspred x qtdepth x mtdepth x sptype x numcoef
99
100
const double EncCu::coefSquareCUsSlowSlower[2][5][2][5][2][2][2] = {
101
{{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
102
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
103
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
104
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
105
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
106
},
107
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
108
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
109
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
110
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
111
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
112
},
113
},
114
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
115
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
116
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
117
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
118
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
119
},
120
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
121
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
122
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
123
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
124
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
125
},
126
},
127
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
128
{{{0.06057349, 0.00447803, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
129
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.06948736, 0.00327774, }, {0.06396861, 0.00789923, }, }, },
130
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
131
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
132
},
133
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
134
{{{0.05526461, 0.00436703, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
135
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.05661641, 0.00546358, }, {0.06680048, 0.00670604, }, }, },
136
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
137
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
138
},
139
},
140
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
141
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.06556926, 0.00455697, }, {0.06803347, 0.00365396, }, }, },
142
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
143
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
144
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
145
},
146
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
147
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.06394328, 0.00403533, }, {0.06688063, 0.00272684, }, }, },
148
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
149
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
150
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
151
},
152
},
153
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.05533525, 0.00235007, }, {0.07184475, 0.00086154, }, }, },
154
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
155
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
156
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
157
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
158
},
159
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
160
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
161
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
162
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
163
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
164
},
165
},
166
},
167
{{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
168
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
169
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
170
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
171
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
172
},
173
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
174
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
175
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
176
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
177
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
178
},
179
},
180
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
181
{{{0.04770815, 0.00774597, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
182
{{{0.05509813, 0.00812349, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
183
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.04719064, 0.01023887, }, {0.04641434, 0.01279769, }, }, },
184
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
185
},
186
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
187
{{{0.02777251, 0.00811989, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
188
{{{0.04848973, 0.00628111, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
189
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.04924294, 0.00769725, }, {0.04491680, 0.01120645, }, }, },
190
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
191
},
192
},
193
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
194
{{{0.06856533, 0.00418949, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
195
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.07059085, 0.00348835, }, {0.06051544, 0.00821365, }, }, },
196
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
197
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
198
},
199
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
200
{{{0.07461087, 0.00229937, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
201
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.05893714, 0.00513168, }, {0.05809189, 0.00772994, }, }, },
202
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
203
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
204
},
205
},
206
{{{{{0.06922080, 0.00274816, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
207
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.06176300, 0.00374356, }, {0.06085891, 0.00361274, }, }, },
208
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
209
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
210
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
211
},
212
{{{{0.06611224, 0.00256748, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
213
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.06364765, 0.00282819, }, {0.05888407, 0.00320947, }, }, },
214
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
215
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
216
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
217
},
218
},
219
{{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{0.05637817, 0.00184637, }, {0.06937475, 0.00091860, }, }, },
220
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
221
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
222
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
223
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
224
},
225
{{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
226
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
227
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
228
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
229
{{{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, {{-1.00000000, -1.00000000, }, {-1.00000000, -1.00000000, }, }, },
230
},
231
},
232
},
233
};
234
235
// ====================================================================================================================
236
EncCu::EncCu()
237
5.72k
  : m_startCtxPending   ( false )
238
5.72k
  , m_CtxCache          ( nullptr )
239
5.72k
  , m_globalCtuQpVector ( nullptr )
240
5.72k
  , m_wppMutex          ( nullptr )
241
5.72k
  , m_CABACEstimator    ( nullptr )
242
5.72k
  , m_syncPicCtx        ( nullptr )
243
5.72k
  , m_boundPicId        ( 0 )
244
5.72k
{
245
5.72k
}
246
247
void EncCu::bindToPicture( const PicEncState& picState )
248
4.65k
{
249
4.65k
  if( m_boundPicId == picState.id )
250
2.87k
  {
251
2.87k
    return;
252
2.87k
  }
253
254
  // The picture lambda sets the chroma distortion weights and the unadjusted lambda. initSlice then
255
  // sets the RD and quantizer lambdas from the slice lambdas, which the slice encoder derived from
256
  // the same picture lambda when it started the picture.
257
1.77k
  m_boundPicId = picState.id;
258
1.77k
  m_syncPicCtx = picState.syncPicCtx;
259
1.77k
  Slice& slice = *picState.pic->cs->slice;
260
1.77k
  setUpLambda( slice, picState.lambda, picState.qp, false, true );
261
1.77k
  initPic    ( picState.pic );
262
1.77k
  initSlice  ( &slice );
263
1.77k
}
264
265
void EncCu::deriveComponentLambdas( const VVEncCfg& encCfg, const Slice& slice, const double lambda, const int qp,
266
                                    double lambdas[MAX_NUM_COMP], double weights[MAX_NUM_COMP] )
267
12.0k
{
268
12.0k
  lambdas[COMP_Y] = lambda;
269
12.0k
  weights[COMP_Y] = 1.0;
270
36.0k
  for( uint32_t compIdx = 1; compIdx < MAX_NUM_COMP; compIdx++ )
271
24.0k
  {
272
24.0k
    const ComponentID compID = ComponentID( compIdx );
273
24.0k
    int chromaQPOffset       = slice.pps->chromaQpOffset[compID] + slice.sliceChromaQpDelta[ compID ];
274
24.0k
    int qpc = slice.sps->chromaQpMappingTable.getMappedChromaQpValue(compID, qp) + chromaQPOffset;
275
24.0k
    double tmpWeight         = pow( 2.0, ( qp - qpc ) / 3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
276
24.0k
    if( encCfg.m_DepQuantEnabled/* && !( m_pcEncCfg->getLFNST() ) */)
277
24.0k
    {
278
24.0k
      tmpWeight *= ( encCfg.m_GOPSize >= 8 ? pow( 2.0, 0.1/3.0 ) : pow( 2.0, 0.2/3.0 ) );  // increase chroma weight for dependent quantization (in order to reduce bit rate shift from chroma to luma)
279
24.0k
    }
280
24.0k
    weights[compIdx] = tmpWeight;
281
24.0k
    lambdas[compIdx] = lambda / tmpWeight;
282
24.0k
  }
283
12.0k
}
284
285
void EncCu::initPic( Picture* pic )
286
1.77k
{
287
1.77k
  m_cInterSearch.setSearchRange( pic->cs->slice, *m_pcEncCfg );
288
289
1.77k
  m_wppMutex = (m_pcEncCfg->m_numThreads > 0 ) ? &pic->wppMutex : nullptr;
290
1.77k
}
291
292
void EncCu::initSlice( const Slice* slice )
293
1.77k
{
294
1.77k
  m_cTrQuant.setLambdas( slice->getLambdas() );
295
1.77k
  m_cRdCost.setLambda( slice->getLambdas()[0], slice->sps->bitDepths );
296
1.77k
}
297
298
void EncCu::setCtuEncRsrc( CABACWriter* cabacEstimator, CtxCache* ctxCache, ReuseUniMv* pReuseUniMv, BlkUniMvInfoBuffer* pBlkUniMvInfoBuffer, AffineProfList* pAffineProfList, IbcBvCand* pCachedBvs )
299
4.65k
{
300
4.65k
  m_CABACEstimator = cabacEstimator;
301
4.65k
  m_CtxCache       = ctxCache;
302
4.65k
  m_cIntraSearch.setCtuEncRsrc( cabacEstimator, ctxCache );
303
4.65k
  m_cInterSearch.setCtuEncRsrc( cabacEstimator, ctxCache, pReuseUniMv, pBlkUniMvInfoBuffer, pAffineProfList, pCachedBvs );
304
4.65k
}
305
306
void EncCu::setUpLambda (Slice& slice, const double dLambda, const int iQP, const bool setSliceLambda, const bool saveUnadjusted)
307
6.43k
{
308
  // store lambda
309
6.43k
  m_cRdCost.setLambda( dLambda, slice.sps->bitDepths );
310
311
  // for RDO
312
  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
313
6.43k
  double dLambdas[MAX_NUM_COMP];
314
6.43k
  double weights [MAX_NUM_COMP];
315
6.43k
  deriveComponentLambdas( *m_pcEncCfg, slice, dLambda, iQP, dLambdas, weights );
316
19.2k
  for( uint32_t compIdx = 1; compIdx < MAX_NUM_COMP; compIdx++ )
317
12.8k
  {
318
12.8k
    m_cRdCost.setDistortionWeight( ComponentID( compIdx ), weights[compIdx] );
319
12.8k
  }
320
321
  // for RDOQ
322
6.43k
  m_cTrQuant.setLambdas( dLambdas );
323
324
  // for SAO, ALF
325
6.43k
  if (setSliceLambda)
326
0
  {
327
0
    slice.setLambdas( dLambdas );
328
0
  }
329
6.43k
  if( saveUnadjusted )
330
6.43k
  {
331
6.43k
    m_cRdCost.saveUnadjustedLambda();
332
6.43k
  }
333
6.43k
}
334
335
void EncCu::updateLambda(const Slice& slice, const double ctuLambda, const int ctuQP, const int newQP, const bool saveUnadjusted)
336
4.16k
{
337
4.16k
  const double  corrFactor = pow (2.0, double (newQP - ctuQP) / 3.0);
338
4.16k
  const double  newLambda  = ctuLambda * corrFactor;
339
  
340
4.16k
  double newLambdas[MAX_NUM_COMP];
341
4.16k
  double weights   [MAX_NUM_COMP];
342
4.16k
  deriveComponentLambdas( *m_pcEncCfg, slice, newLambda, newQP, newLambdas, weights );
343
12.5k
  for( uint32_t compIdx = 1; compIdx < MAX_NUM_COMP; compIdx++ )
344
8.33k
  {
345
8.33k
    m_cRdCost.setDistortionWeight( ComponentID( compIdx ), weights[compIdx] );
346
8.33k
  }
347
348
4.16k
  m_cTrQuant.setLambdas ( newLambdas);
349
4.16k
  m_cRdCost.setLambda   ( newLambda, slice.sps->bitDepths);
350
351
4.16k
  if (saveUnadjusted)
352
4.16k
  {
353
4.16k
    m_cRdCost.saveUnadjustedLambda(); // TODO hlm: check if this actually improves the overall quality
354
4.16k
  }
355
4.16k
}
356
357
void EncCu::init( const VVEncCfg& encCfg, const SPS& sps, std::vector<int>* const globalCtuQpVector, RateCtrl* pRateCtrl, TrQuant* otherTrQuant )
358
5.72k
{
359
5.72k
  DecCu::init( &m_cTrQuant, &m_cIntraSearch, &m_cInterSearch, encCfg.m_internChromaFormat );
360
5.72k
  m_geoRowPrefix.resize( GEO_PREFIX_LANES * ( GEO_MAX_CU_SIZE + 1 ) * GEO_MAX_CU_SIZE );
361
5.72k
  m_cRdCost.create     ();
362
5.72k
  m_cRdCost.setCostMode( encCfg.m_costMode );
363
5.72k
  if ( encCfg.m_lumaLevelToDeltaQPEnabled == 1 )
364
0
  {
365
0
    m_cRdCost.setChromaFormat( encCfg.m_internChromaFormat );
366
0
    m_cRdCost.initLumaLevelToWeightTable( encCfg.m_internalBitDepth[ CH_L ] );
367
0
    xInitLumaDeltaQpLUT();
368
0
  }
369
370
5.72k
  m_modeCtrl.init     ( encCfg, &m_cRdCost );
371
5.72k
  m_cIntraSearch.init ( encCfg, &m_cTrQuant, &m_cRdCost, &m_SortedPelUnitBufs, m_unitCache );
372
5.72k
  m_cInterSearch.init ( encCfg, &m_cTrQuant, &m_cRdCost, &m_modeCtrl, m_cIntraSearch.getSaveCSBuf() );
373
5.72k
  m_cTrQuant.init     ( otherTrQuant ? otherTrQuant->getQuant() : nullptr, encCfg.m_RDOQ, encCfg.m_useRDOQTS, false, true, encCfg.m_quantThresholdVal, encCfg.m_sbbSkipThrVal );
374
375
5.72k
  m_pcRateCtrl = pRateCtrl;
376
377
  // Initialise scaling lists: The encoder will only use the SPS scaling lists. The PPS will never be marked present.
378
5.72k
  const int maxLog2TrDynamicRange[ MAX_NUM_CH ] = { sps.getMaxLog2TrDynamicRange(), sps.getMaxLog2TrDynamicRange() };
379
5.72k
  m_cTrQuant.getQuant()->setFlatScalingList( maxLog2TrDynamicRange, sps.bitDepths );
380
381
5.72k
  m_pcEncCfg       = &encCfg;
382
383
5.72k
  m_GeoCostList.init( encCfg.m_maxNumGeoCand );
384
385
5.72k
  unsigned      uiMaxSize    = encCfg.m_CTUSize;
386
5.72k
  ChromaFormat  chromaFormat = encCfg.m_internChromaFormat;
387
388
5.72k
  Area ctuArea = Area( 0, 0, uiMaxSize, uiMaxSize );
389
390
5.72k
  m_mergeItemList.init( encCfg.m_maxMergeRdCandNumTotal, m_pcEncCfg->m_Geo > 1 ? 3 : 1, chromaFormat, uiMaxSize, uiMaxSize );
391
392
74.4k
  for( int i = 0; i < maxCuDepth; i++ )
393
68.7k
  {
394
68.7k
    Area area = Area( 0, 0, uiMaxSize >> ( i >> 1 ), uiMaxSize >> ( ( i + 1 ) >> 1 ) );
395
396
68.7k
    if( area.width < (1 << MIN_CU_LOG2) || area.height < (1 << MIN_CU_LOG2) )
397
5.72k
    {
398
5.72k
      m_pTempCS[i] = m_pBestCS[i] = nullptr;
399
5.72k
      continue;
400
5.72k
    }
401
402
63.0k
    m_pTempCS[i] = new CodingStructure( m_unitCache, nullptr );
403
63.0k
    m_pBestCS[i] = new CodingStructure( m_unitCache, nullptr );
404
405
63.0k
    m_pTempCS[i]->createForSearch( chromaFormat, area );
406
63.0k
    m_pBestCS[i]->createForSearch( chromaFormat, area );
407
408
63.0k
    m_pOrgBuffer[i].create( chromaFormat, area );
409
63.0k
  }
410
411
5.72k
  m_pTempCS2 = new CodingStructure( m_unitCache, nullptr );
412
5.72k
  m_pBestCS2 = new CodingStructure( m_unitCache, nullptr );
413
414
5.72k
  m_pTempCS2->createForSearch( chromaFormat, ctuArea );
415
5.72k
  m_pBestCS2->createForSearch( chromaFormat, ctuArea );
416
417
5.72k
  m_cuChromaQpOffsetIdxPlus1 = 0;
418
5.72k
  m_tempQpDiff = 0;
419
5.72k
  m_globalCtuQpVector = globalCtuQpVector;
420
421
5.72k
  m_SortedPelUnitBufs.create( chromaFormat, uiMaxSize, uiMaxSize );
422
423
85.9k
  for( uint8_t i = 0; i < MAX_TMP_BUFS; i++)
424
80.1k
  {
425
80.1k
    m_aTmpStorageLCU[i].create(chromaFormat, Area(0, 0, uiMaxSize, uiMaxSize));
426
80.1k
  }
427
40.0k
  for (unsigned ui = 0; ui < MRG_MAX_NUM_CANDS; ui++)
428
34.3k
  {
429
34.3k
    m_acMergeTmpBuffer[ui].create(chromaFormat, Area(0, 0, uiMaxSize, uiMaxSize));
430
34.3k
  }
431
432
5.72k
  const unsigned maxDepth = 2 * MAX_CU_SIZE_IDX;
433
5.72k
  m_CtxBuffer.resize( maxDepth );
434
5.72k
  m_CurrCtx = 0;
435
5.72k
  if( encCfg.m_EDO )
436
5.72k
    m_dbBuffer.create( chromaFormat, Area( 0, 0, uiMaxSize, uiMaxSize ), 0, 8 );
437
438
5.72k
  m_MergeSimpleFlag = 0;
439
5.72k
  m_tileIdx = 0;
440
5.72k
}
441
442
443
void EncCu::destroy()
444
5.72k
{
445
74.4k
  for( int i = 0; i < maxCuDepth; i++ )
446
68.7k
  {
447
68.7k
    if( m_pTempCS[i] )
448
63.0k
    {
449
63.0k
      m_pTempCS[i]->destroy();
450
63.0k
      delete m_pTempCS[i]; m_pTempCS[i] = nullptr;
451
63.0k
    }
452
453
68.7k
    if( m_pBestCS[i] )
454
63.0k
    {
455
63.0k
      m_pBestCS[i]->destroy();
456
63.0k
      delete m_pBestCS[i]; m_pBestCS[i] = nullptr;
457
63.0k
    }
458
459
68.7k
    m_pOrgBuffer[i].destroy();
460
68.7k
  }
461
462
5.72k
  m_pTempCS2->destroy();
463
5.72k
  m_pBestCS2->destroy();
464
465
5.72k
  delete m_pTempCS2; m_pTempCS2 = nullptr;
466
5.72k
  delete m_pBestCS2; m_pBestCS2 = nullptr;
467
468
5.72k
  m_SortedPelUnitBufs.destroy();
469
470
85.9k
  for( uint8_t i = 0; i < MAX_TMP_BUFS; i++)
471
80.1k
  {
472
80.1k
    m_aTmpStorageLCU[i].destroy();
473
80.1k
  }
474
40.0k
  for (unsigned ui = 0; ui < MRG_MAX_NUM_CANDS; ui++)
475
34.3k
  {
476
34.3k
    m_acMergeTmpBuffer[ui].destroy();
477
34.3k
  }
478
479
480
5.72k
  m_dbBuffer.destroy();
481
5.72k
}
482
483
484
EncCu::~EncCu()
485
5.72k
{
486
5.72k
  destroy();
487
5.72k
}
488
489
// ====================================================================================================================
490
// Public member functions
491
// ====================================================================================================================
492
493
void EncCu::encodeCtu( Picture* pic, int (&prevQP)[MAX_NUM_CH], uint32_t ctuXPosInCtus, uint32_t ctuYPosInCtus )
494
4.65k
{
495
4.65k
  CodingStructure&     cs          = *pic->cs;
496
4.65k
  Slice*               slice       = cs.slice;
497
4.65k
  const PreCalcValues& pcv         = *cs.pcv;
498
499
#if ENABLE_MEASURE_SEARCH_SPACE
500
  if( ctuXPosInCtus == 0 && ctuYPosInCtus == 0 )
501
  {
502
    g_searchSpaceAcc.picW = pic->lwidth();
503
    g_searchSpaceAcc.picH = pic->lheight();
504
    g_searchSpaceAcc.addSlice( slice->isIntra(), slice->depth );
505
  }
506
507
#endif
508
4.65k
  const int ctuRsAddr                 = ctuYPosInCtus * pcv.widthInCtus + ctuXPosInCtus;
509
510
4.65k
  const Position pos (ctuXPosInCtus * pcv.maxCUSize, ctuYPosInCtus * pcv.maxCUSize);
511
4.65k
  const UnitArea ctuArea( cs.area.chromaFormat, Area( pos.x, pos.y, pcv.maxCUSize, pcv.maxCUSize ) );
512
4.65k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "ctu", ctuRsAddr ) );
513
514
4.65k
  const int tileXPosInCtus = cs.pps->tileColBd[cs.pps->ctuToTileCol[ctuXPosInCtus]];
515
4.65k
  const int tileYPosInCtus = cs.pps->tileRowBd[cs.pps->ctuToTileRow[ctuYPosInCtus]];
516
517
4.65k
  if( ( cs.slice->sliceType != VVENC_I_SLICE || cs.sps->IBC ) && ctuXPosInCtus == tileXPosInCtus )
518
2.55k
  {
519
2.55k
    const int tileRowId = cs.pps->getTileLineId( ctuXPosInCtus, ctuYPosInCtus );
520
2.55k
    cs.motionLutBuf[tileRowId].lut.resize( 0 );
521
2.55k
    cs.motionLutBuf[tileRowId].lutIbc.resize( 0 );
522
2.55k
  }
523
524
4.65k
  if( ( m_pcEncCfg->m_ensureWppBitEqual || m_pcEncCfg->m_entropyCodingSyncEnabled ) && ctuXPosInCtus == tileXPosInCtus )
525
2.55k
  {
526
2.55k
    m_CABACEstimator->initCtxModels( *slice );
527
528
2.55k
    if( m_pcEncCfg->m_entropyCodingSyncEnabled && ( ctuYPosInCtus > tileYPosInCtus ) )
529
0
    {
530
0
      m_CABACEstimator->getCtx() = m_syncPicCtx[slice->pps->getTileLineId( ctuXPosInCtus, ctuYPosInCtus - 1 )];
531
0
    }
532
533
2.55k
    prevQP[CH_L] = prevQP[CH_C] = slice->sliceQp; // hlm: call CU::predictQP() here!
534
2.55k
  }
535
2.09k
  else if( ctuXPosInCtus == tileXPosInCtus && ctuYPosInCtus == tileYPosInCtus )
536
0
  {
537
0
    m_CABACEstimator->initCtxModels( *slice );
538
0
    prevQP[CH_L] = prevQP[CH_C] = slice->sliceQp; // hlm: call CU::predictQP() here!
539
0
  }
540
541
4.65k
  xCompressCtu( cs, ctuArea, ctuRsAddr, prevQP );
542
543
4.65k
  m_CABACEstimator->resetBits();
544
4.65k
  m_CABACEstimator->coding_tree_unit( cs, ctuArea, prevQP, ctuRsAddr, true, true );
545
546
  // Store probabilities of second CTU in line into buffer - used only if wavefront-parallel-processing is enabled.
547
4.65k
  if( ctuXPosInCtus == tileXPosInCtus && m_pcEncCfg->m_entropyCodingSyncEnabled )
548
0
  {
549
0
    m_syncPicCtx[slice->pps->getTileLineId( ctuXPosInCtus, ctuYPosInCtus )] = m_CABACEstimator->getCtx();
550
0
  }
551
552
4.65k
  DTRACE_AREA_CRC( g_trace_ctx, D_CRC, cs, ctuArea );
553
4.65k
}
554
555
// ====================================================================================================================
556
// Protected member functions
557
// ====================================================================================================================
558
559
void EncCu::xCompressCtu( CodingStructure& cs, const UnitArea& area, const unsigned ctuRsAddr, const int prevQP[] )
560
4.65k
{
561
4.65k
  m_tileIdx = cs.pps->getTileIdx( area.lumaPos() );
562
563
4.65k
  m_modeCtrl.initCTUEncoding( *cs.slice );
564
565
  // init the partitioning manager
566
4.65k
  Partitioner *partitioner = &m_partitioner;
567
4.65k
  partitioner->initCtu( area, CH_L, *cs.slice );
568
  
569
4.65k
  const Position& lumaPos = area.lumaPos();
570
4.65k
  const bool leftSameTile  = lumaPos.x == 0 || m_tileIdx == cs.pps->getTileIdx( lumaPos.offset(-1, 0) );
571
4.65k
  const bool aboveSameTile = lumaPos.y == 0 || m_tileIdx == cs.pps->getTileIdx( lumaPos.offset( 0,-1) );
572
4.65k
  m_EDO = (!m_pcEncCfg->m_tileParallelCtuEnc || (leftSameTile && aboveSameTile)) ? m_pcEncCfg->m_EDO : 0;
573
  
574
4.65k
  if( m_pcEncCfg->m_IBCMode )
575
4.65k
  {
576
4.65k
    m_cInterSearch.resetCtuRecordIBC();
577
4.65k
  }
578
579
  // init current context pointer
580
4.65k
  m_CurrCtx = m_CtxBuffer.data();
581
582
4.65k
  PelStorage* orgBuffer = &m_pOrgBuffer[0];
583
4.65k
  CodingStructure *tempCS =  m_pTempCS [0];
584
4.65k
  CodingStructure *bestCS =  m_pBestCS [0];
585
4.65k
  cs.initSubStructure( *tempCS, partitioner->chType, partitioner->currArea(), false, orgBuffer );
586
4.65k
  cs.initSubStructure( *bestCS, partitioner->chType, partitioner->currArea(), false, orgBuffer );
587
4.65k
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_COMPRESS_CU, tempCS, CH_L );
588
589
  // copy the relevant area
590
4.65k
  UnitArea clippedArea = clipArea( partitioner->currArea(), cs.area );
591
4.65k
  CPelUnitBuf org = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getFiltOrigBuf( clippedArea ) : cs.picture->getOrigBuf( clippedArea );
592
4.65k
  tempCS->getOrgBuf( clippedArea ).copyFrom( org );
593
4.65k
  tempCS->currQP[CH_L] = bestCS->currQP[CH_L] =
594
4.65k
  tempCS->baseQP       = bestCS->baseQP       = cs.slice->sliceQp;
595
4.65k
  tempCS->prevQP[CH_L] = bestCS->prevQP[CH_L] = prevQP[CH_L];
596
597
4.65k
  xCompressCU( tempCS, bestCS, *partitioner );
598
  // all signals were already copied during compression if the CTU was split - at this point only the structures are copied to the top level CS
599
  
600
  // Ensure that a coding was found
601
  // Selected mode's RD-cost must be not MAX_DOUBLE.
602
4.65k
  CHECK( bestCS->cus.empty()                                   , "No possible encoding found" );
603
4.65k
  CHECK( bestCS->cus[0]->predMode == NUMBER_OF_PREDICTION_MODES, "No possible encoding found" );
604
4.65k
  CHECK( bestCS->cost             == MAX_DOUBLE                , "No possible encoding found" );
605
606
4.65k
  if ( m_wppMutex ) m_wppMutex->lock();
607
608
4.65k
  cs.useSubStructure( *bestCS, partitioner->chType, TREE_D, CS::getArea( *bestCS, area, partitioner->chType, partitioner->treeType ) );
609
610
4.65k
  if ( m_wppMutex ) m_wppMutex->unlock();
611
612
4.65k
  if( CS::isDualITree( cs ) && isChromaEnabled( cs.pcv->chrFormat ) )
613
4.65k
  {
614
4.65k
    m_CABACEstimator->getCtx() = m_CurrCtx->start;
615
616
4.65k
    partitioner->initCtu( area, CH_C, *cs.slice );
617
618
4.65k
    cs.initSubStructure( *tempCS, partitioner->chType, partitioner->currArea(), false, orgBuffer );
619
4.65k
    cs.initSubStructure( *bestCS, partitioner->chType, partitioner->currArea(), false, orgBuffer );
620
4.65k
    tempCS->currQP[CH_C] = bestCS->currQP[CH_C] =
621
4.65k
    tempCS->baseQP       = bestCS->baseQP       = cs.slice->sliceQp;
622
4.65k
    tempCS->prevQP[CH_C] = bestCS->prevQP[CH_C] = prevQP[CH_C];
623
624
4.65k
    xCompressCU( tempCS, bestCS, *partitioner );
625
    
626
    // Ensure that a coding was found
627
    // Selected mode's RD-cost must be not MAX_DOUBLE.
628
4.65k
    CHECK( bestCS->cus.empty()                                   , "No possible encoding found" );
629
4.65k
    CHECK( bestCS->cus[0]->predMode == NUMBER_OF_PREDICTION_MODES, "No possible encoding found" );
630
4.65k
    CHECK( bestCS->cost             == MAX_DOUBLE                , "No possible encoding found" );
631
632
4.65k
    if ( m_wppMutex ) m_wppMutex->lock();
633
634
4.65k
    cs.useSubStructure( *bestCS, partitioner->chType, TREE_D, CS::getArea( *bestCS, area, partitioner->chType, partitioner->treeType ) );
635
636
4.65k
    if ( m_wppMutex ) m_wppMutex->unlock();
637
4.65k
  }
638
639
  // reset context states and uninit context pointer
640
4.65k
  m_CABACEstimator->getCtx() = m_CurrCtx->start;
641
4.65k
  m_CurrCtx                  = 0;
642
4.65k
}
643
644
645
646
bool EncCu::xCheckBestMode( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode, const bool useEDO )
647
338k
{
648
338k
  CHECKD( m_startCtxPending, "a mode was coded without resetting the contexts (no xRestoreStartCtx since the last mode)" );
649
650
338k
  bool bestCSUpdated = false;
651
652
338k
  if( !tempCS->cus.empty() )
653
206k
  {
654
206k
    if( tempCS->cus.size() == 1 )
655
156k
    {
656
156k
      const CodingUnit& cu = *tempCS->cus.front();
657
156k
      CHECK( cu.skip && !cu.mergeFlag, "Skip flag without a merge flag is not allowed!" );
658
156k
    }
659
660
206k
    DTRACE_BEST_MODE( tempCS, bestCS, m_cRdCost.getLambda(true), useEDO );
661
662
206k
    if( m_modeCtrl.useModeResult( encTestMode, tempCS, partitioner, useEDO ) )
663
186k
    {
664
186k
      std::swap( tempCS, bestCS );
665
      // store temp best CI for next CU coding (swapped, not copied: the reset below overwrites the estimator's contexts)
666
186k
      m_CurrCtx->best.swap( m_CABACEstimator->getCtx() );
667
186k
      bestCSUpdated = true;
668
186k
    }
669
206k
  }
670
671
  // The next mode starts from the CU's start contexts again. The reset waits for the next reader (xRestoreStartCtx): when
672
  // this was the CU's last mode before a split or its finish, those overwrite the contexts and the reset is skipped.
673
338k
  m_startCtxPending = true;
674
338k
  return bestCSUpdated;
675
676
338k
}
677
678
// Every reader of the estimator's contexts that can follow an xCheckBestMode of the same CU calls this first: the test
679
// entries (intra, the start of the merge test), each encodeResAndCalcRdInterCU call (inter, IMV, merge and IBC
680
// candidates, SBT passes) and a CU that returns without a result.
681
void EncCu::xRestoreStartCtx()
682
125k
{
683
125k
  if( m_startCtxPending )
684
26.8k
  {
685
26.8k
    m_CABACEstimator->getCtx() = m_CurrCtx->start;
686
26.8k
    m_startCtxPending          = false;
687
26.8k
  }
688
125k
}
689
690
// An unconditional reset to the CU's start contexts, which also makes a pending one void.
691
void EncCu::xSetStartCtx()
692
213k
{
693
213k
  m_CABACEstimator->getCtx() = m_CurrCtx->start;
694
213k
  m_startCtxPending          = false;
695
213k
}
696
697
void xCheckFastCuChromaSplitting( CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner&  partitioner, ComprCUCtx& cuECtx )
698
0
{
699
0
  const uint32_t uiLPelX = tempCS->area.Cb().lumaPos().x;
700
0
  const uint32_t uiTPelY = tempCS->area.Cb().lumaPos().y;
701
702
0
  int lumaw = 0, lumah = 0;
703
0
  bool splitver      = true;
704
0
  bool splithor      = true;
705
0
  bool qtSplitChroma = true;
706
707
0
  if( partitioner.isSepTree( *tempCS ) && isChroma( partitioner.chType ) )
708
0
  {
709
0
    Position lumaRefPos( uiLPelX, uiTPelY );
710
0
    CodingUnit* colLumaCu = bestCS->lumaCS->getCU( lumaRefPos, CH_L, TREE_D );
711
712
0
    if( colLumaCu )
713
0
    {
714
0
      lumah = colLumaCu->Y().height;
715
0
      lumaw = colLumaCu->Y().width;
716
0
    }
717
0
  }
718
0
  else
719
0
  {
720
0
    return;
721
0
  }
722
723
0
  if( partitioner.getImplicitSplit( *tempCS ) != CU_DONT_SPLIT ) return;
724
725
0
  const CPelBuf orgCb = tempCS->getOrgBuf( COMP_Cb );
726
0
  const CPelBuf orgCr = tempCS->getOrgBuf( COMP_Cr );
727
728
0
  int th1 = FCBP_TH1;
729
730
0
  if( ( lumaw >> getChannelTypeScaleX( CH_C, tempCS->area.chromaFormat ) ) == orgCb.width )
731
0
  {
732
0
    if( ( bestCS->cost < ( th1*orgCb.width*orgCb.height ) ) )
733
0
    {
734
0
      splitver      = false;
735
0
      qtSplitChroma = false;
736
0
    }
737
0
  }
738
739
0
  if( ( lumah >> getChannelTypeScaleY( CH_C, tempCS->area.chromaFormat ) ) == orgCb.height )
740
0
  {
741
0
    if( ( bestCS->cost < ( th1*orgCb.width*orgCb.height ) ) )
742
0
    {
743
0
      splithor      = false;
744
0
      qtSplitChroma = false;
745
0
    }
746
0
  }
747
748
0
  cuECtx.doHorChromaSplit = splithor;
749
0
  cuECtx.doVerChromaSplit = splitver;
750
0
  cuECtx.doQtChromaSplit  = qtSplitChroma;
751
752
0
  if( orgCb.width == orgCb.height )
753
0
  {
754
0
    int varh_cb, varv_cb;
755
0
    int varh_cr, varv_cr;
756
757
0
    orgCb.calcVarianceSplit( orgCb, orgCb.width, varh_cb, varv_cb );
758
0
    orgCr.calcVarianceSplit( orgCr, orgCr.width, varh_cr, varv_cr );
759
760
0
    if( ( varh_cr*FCBP_TH2 < varv_cr * 100 ) && ( varh_cb*FCBP_TH2 < varv_cb * 100 ) )
761
0
    {
762
0
      cuECtx.doVerChromaSplit = false;
763
0
    }
764
0
    else if( ( varv_cr*FCBP_TH2 < varh_cr * 100 ) && ( varv_cb*FCBP_TH2 < varh_cb * 100 ) )
765
0
    {
766
0
      cuECtx.doHorChromaSplit = false;
767
0
    }
768
0
  }
769
0
}
770
771
void EncCu::xCompressCU( CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& partitioner )
772
156k
{
773
156k
  const Area& lumaArea = tempCS->area.Y();
774
775
156k
  Slice&   slice      = *tempCS->slice;
776
156k
  const PPS &pps      = *tempCS->pps;
777
156k
  const SPS &sps      = *tempCS->sps;
778
156k
  const uint32_t uiLPelX  = tempCS->area.Y().lumaPos().x;
779
156k
  const uint32_t uiTPelY  = tempCS->area.Y().lumaPos().y;
780
156k
  const bool isBimEnabled = (m_pcEncCfg->hasBlockQpOffsets() && !bestCS->picture->m_picShared->m_ctuBimQpOffset.empty());
781
782
156k
  m_modeCtrl.initBlk( tempCS->area, slice.pic->poc );
783
156k
  m_CABACEstimator->determineNeighborCus( *tempCS, partitioner.currArea(), partitioner.chType, partitioner.treeType );
784
785
156k
  if ((m_pcEncCfg->m_usePerceptQPA || isBimEnabled || m_pcEncCfg->m_lumaLevelToDeltaQPEnabled == 1) && ( pps.useDQP || m_pcEncCfg->m_maxDeltaQP == 0 ) && isLuma (partitioner.chType) && partitioner.currQgEnable())
786
8.82k
  {
787
8.82k
    const PreCalcValues &pcv = *pps.pcv;
788
8.82k
    Picture* const pic = bestCS->picture;
789
8.82k
    const uint32_t ctuRsAddr = getCtuAddr (partitioner.currQgPos, pcv);
790
791
8.82k
    if (partitioner.currSubdiv == 0) // CTU-level QP adaptation
792
4.65k
    {
793
4.65k
      if (m_pcEncCfg->m_usePerceptQPA)
794
4.65k
      {
795
4.65k
        if (m_pcEncCfg->m_internalUsePerceptQPATempFiltISlice == 2)
796
0
        {
797
0
          m_tempQpDiff = pic->ctuAdaptedQP[ctuRsAddr] - BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, lumaArea, m_pcRateCtrl->getMinNoiseLevels());
798
0
        }
799
800
4.65k
        int clippedMaxDQP = 0;
801
802
4.65k
        if ((!slice.isIntra()) && (pcv.maxCUSize > 64) && // sub-CTU QPA behavior - Museum fix
803
0
            (uiLPelX + (pcv.maxCUSize >> 1) < (m_pcEncCfg->m_PadSourceWidth)) &&
804
0
            (uiTPelY + (pcv.maxCUSize >> 1) < (m_pcEncCfg->m_PadSourceHeight)))
805
0
        {
806
0
          const uint32_t h = lumaArea.height >> 1;
807
0
          const uint32_t w = lumaArea.width  >> 1;
808
0
          const int adQPTL = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + 0, uiTPelY + 0, w, h), m_pcRateCtrl->getMinNoiseLevels());
809
0
          const int adQPTR = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + w, uiTPelY + 0, w, h), m_pcRateCtrl->getMinNoiseLevels());
810
0
          const int adQPBL = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + 0, uiTPelY + h, w, h), m_pcRateCtrl->getMinNoiseLevels());
811
0
          const int adQPBR = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + w, uiTPelY + h, w, h), m_pcRateCtrl->getMinNoiseLevels());
812
813
0
          tempCS->currQP[partitioner.chType] = tempCS->baseQP =
814
0
          bestCS->currQP[partitioner.chType] = bestCS->baseQP = std::min (std::min (adQPTL, adQPTR), std::min (adQPBL, adQPBR));
815
816
0
          if (m_pcEncCfg->m_internalUsePerceptQPATempFiltISlice == 2)
817
0
          {
818
0
            if ((m_globalCtuQpVector->size() > ctuRsAddr) && (slice.TLayer == 0) && // last CTU row of non-Intra key-frame
819
0
                (m_pcEncCfg->m_IntraPeriod == 2 * m_pcEncCfg->m_GOPSize) && (ctuRsAddr >= pcv.widthInCtus) && (uiTPelY + pcv.maxCUSize > m_pcEncCfg->m_PadSourceHeight))
820
0
            {
821
0
              m_globalCtuQpVector->at (ctuRsAddr) = m_globalCtuQpVector->at (ctuRsAddr - pcv.widthInCtus); // copy the pumping reducing QP offset from the top CTU neighbor
822
0
              tempCS->currQP[partitioner.chType] = tempCS->baseQP =
823
0
              bestCS->currQP[partitioner.chType] = bestCS->baseQP = tempCS->baseQP - m_globalCtuQpVector->at (ctuRsAddr);
824
0
            }
825
0
            tempCS->currQP[partitioner.chType] = tempCS->baseQP =
826
0
            bestCS->currQP[partitioner.chType] = bestCS->baseQP = Clip3 (0, MAX_QP, tempCS->baseQP + m_tempQpDiff);
827
0
          }
828
0
        }
829
4.65k
        else
830
4.65k
        {
831
4.65k
          tempCS->currQP[partitioner.chType] = tempCS->baseQP =
832
4.65k
          bestCS->currQP[partitioner.chType] = bestCS->baseQP = pic->ctuAdaptedQP[ctuRsAddr];
833
4.65k
        }
834
835
4.65k
        int deltaQP       = slice.sliceQp - tempCS->baseQP;
836
4.65k
        if( abs( deltaQP ) > m_pcEncCfg->m_maxDeltaQP )
837
0
        {
838
0
          clippedMaxDQP = deltaQP > 0 ? slice.sliceQp - m_pcEncCfg->m_maxDeltaQP : slice.sliceQp + m_pcEncCfg->m_maxDeltaQP;
839
0
          tempCS->currQP[partitioner.chType] = tempCS->baseQP =
840
0
          bestCS->currQP[partitioner.chType] = bestCS->baseQP = clippedMaxDQP;
841
0
        }
842
843
        //the ctuAdaptedQP correspones with the ctuQpaLambda
844
4.65k
        setUpLambda (slice, pic->ctuQpaLambda[ctuRsAddr], pic->ctuAdaptedQP[ctuRsAddr], false, true);
845
4.65k
      }
846
0
      else // isBimEnabled without QPA
847
0
      {
848
0
        const int baseQp  = tempCS->baseQP;
849
0
        int adaptedLumaQP = 0;
850
0
        int lumaQPoffset  = 0;
851
        
852
0
        if( m_pcEncCfg->m_lumaLevelToDeltaQPEnabled == 1 )
853
0
        {
854
0
          uint32_t meanLuma = 0;
855
0
          if( ( uiLPelX + lumaArea.width > pps.picWidthInLumaSamples ) || ( uiTPelY + lumaArea.height > pps.picHeightInLumaSamples ) )
856
0
          {
857
0
            int wdth = ( uiLPelX + lumaArea.width > pps.picWidthInLumaSamples )   ? pps.picWidthInLumaSamples - uiLPelX  : lumaArea.width;
858
0
            int hght = ( uiTPelY + lumaArea.height > pps.picHeightInLumaSamples ) ? pps.picHeightInLumaSamples - uiTPelY : lumaArea.height;
859
            
860
0
            int sum = 0;
861
0
            for( int y = 0; y < hght; y++ )
862
0
            {
863
0
              for( int x = 0; x < wdth; x++ )
864
0
              {
865
0
                sum += tempCS->getOrgBuf().Y().at( x, y );
866
0
              }
867
0
            }
868
0
            double avg = (double) sum / ( wdth*hght );
869
0
            meanLuma = (uint32_t)( avg + 0.5 );
870
0
          }
871
0
          else
872
0
          {
873
0
            meanLuma = tempCS->getOrgBuf().Y().getAvg();
874
0
          }
875
876
0
          int lumaBD     = m_pcEncCfg->m_internalBitDepth[ CH_L ];
877
0
          int lumaIdxOrg = Clip3<int>( 0, int( 1 << lumaBD ) - 1, meanLuma );
878
0
          int lumaIdx    = lumaBD < 10 ? lumaIdxOrg << (10 - lumaBD) : lumaBD > 10 ? lumaIdxOrg >> (lumaBD - 10) : lumaIdxOrg;
879
0
          lumaQPoffset   = m_lumaLevelToDeltaQPLUT[lumaIdx];
880
0
          adaptedLumaQP  = Clip3( -sps.qpBDOffset[CH_L], MAX_QP, baseQp - lumaQPoffset );
881
0
        }
882
        
883
0
        if( isBimEnabled )
884
0
        {
885
0
          const unsigned bimQpSize = (unsigned) bestCS->picture->m_picShared->m_ctuBimQpOffset.size();
886
0
          uint32_t ctuAddr         = ctuRsAddr;
887
888
0
          double avgBimOffset = 0.0;
889
890
0
          if (bimQpSize != pcv.sizeInCtus) // re-calculate correct address of BIM CTU QP offset
891
0
          {
892
0
            const unsigned bimCtuSize  = m_pcEncCfg->m_bimCtuSize;
893
0
            const unsigned bimCtuWidth = (pcv.lumaWidth + bimCtuSize - 1) / bimCtuSize;
894
895
0
            ctuAddr = getCtuAddrFromCtuSize (partitioner.currQgPos, Log2 (bimCtuSize), bimCtuWidth);
896
0
            CHECK (ctuAddr >= bimQpSize, "ctuAddr exceeds size of m_ctuBimQpOffset");
897
898
0
            int maxY = m_pcEncCfg->m_CTUSize / bimCtuSize;
899
0
            int maxX = m_pcEncCfg->m_CTUSize / bimCtuSize;
900
0
            if( ( partitioner.currQgPos.y + maxY * bimCtuSize ) > pcv.lumaHeight )
901
0
            {
902
0
              int reduceHeight = ( partitioner.currQgPos.y + ( maxY - 1 ) * bimCtuSize ) - pcv.lumaHeight;
903
0
              int reduceY = ( reduceHeight + bimCtuSize ) / bimCtuSize;
904
0
              maxY = maxY - reduceY;
905
0
            }
906
0
            if( ( partitioner.currQgPos.x + maxX * bimCtuSize ) > pcv.lumaWidth )
907
0
            {
908
0
              int reduceWidth = ( partitioner.currQgPos.x + ( maxX - 1 ) * bimCtuSize ) - pcv.lumaWidth;
909
0
              int reduceX = ( reduceWidth + bimCtuSize ) / bimCtuSize;
910
0
              maxX = maxX - reduceX;
911
0
            }
912
0
            for (int y = 0; y < maxY * bimCtuSize; y = y + bimCtuSize)
913
0
            {
914
0
              for (int x = 0; x < maxX * bimCtuSize; x = x + bimCtuSize)
915
0
              {
916
0
                int theBlockId = ctuAddr + (y / bimCtuSize) * ((pcv.lumaWidth + bimCtuSize - 1) / bimCtuSize) + (x / bimCtuSize);
917
0
                avgBimOffset += pic->m_picShared->m_ctuBimQpOffset[theBlockId];
918
0
              }
919
0
            }
920
0
            if (maxY * maxX > 0)
921
0
            {
922
0
              avgBimOffset = avgBimOffset / (double)(maxY * maxX);
923
0
            }
924
0
            else
925
0
            {
926
0
              avgBimOffset = 0.0;
927
0
            }
928
0
          }
929
0
          else
930
0
          {
931
0
            avgBimOffset = pic->m_picShared->m_ctuBimQpOffset[ctuAddr];
932
0
          }
933
0
          int intAvgBimOffset = avgBimOffset >= 0 ? (int)(0.5 + avgBimOffset) : (int)(-0.5 + avgBimOffset);
934
0
          adaptedLumaQP       = Clip3 (-sps.qpBDOffset[CH_L], MAX_QP, baseQp - lumaQPoffset + intAvgBimOffset );
935
0
        }
936
        
937
0
        tempCS->currQP[partitioner.chType] = tempCS->baseQP =
938
0
        bestCS->currQP[partitioner.chType] = bestCS->baseQP = adaptedLumaQP;
939
        
940
0
        int deltaQP         = slice.sliceQp - adaptedLumaQP;
941
0
        if( abs( deltaQP ) > m_pcEncCfg->m_maxDeltaQP )
942
0
        {
943
0
          int clippedMaxDQP = deltaQP > 0 ? slice.sliceQp - m_pcEncCfg->m_maxDeltaQP : slice.sliceQp + m_pcEncCfg->m_maxDeltaQP;
944
0
          tempCS->currQP[partitioner.chType] = tempCS->baseQP =
945
0
          bestCS->currQP[partitioner.chType] = bestCS->baseQP = clippedMaxDQP;
946
0
        }
947
948
0
        updateLambda (slice, slice.getLambdas()[0], baseQp, adaptedLumaQP, true);
949
0
      }
950
4.65k
    }
951
4.16k
    else if (m_pcEncCfg->m_usePerceptQPA && slice.isIntra()) // currSubdiv 2 - use sub-CTU QPA
952
4.16k
    {
953
4.16k
      CHECK ((partitioner.currArea().lwidth() >= pcv.maxCUSize) || (partitioner.currArea().lheight() >= pcv.maxCUSize), "sub-CTU delta-QP error");
954
4.16k
      tempCS->currQP[partitioner.chType] = tempCS->baseQP = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, lumaArea, m_pcRateCtrl->getMinNoiseLevels());
955
956
4.16k
      if (m_pcEncCfg->m_internalUsePerceptQPATempFiltISlice == 2)
957
0
      {
958
0
        tempCS->currQP[partitioner.chType] = tempCS->baseQP = Clip3 (0, MAX_QP, tempCS->baseQP + m_tempQpDiff);
959
0
      }
960
961
4.16k
      int backupBaseQP  = tempCS->baseQP;
962
4.16k
      int deltaQP       = slice.sliceQp - tempCS->baseQP;
963
4.16k
      int clippedMaxDQP = 0;
964
4.16k
      if( abs( deltaQP ) > m_pcEncCfg->m_maxDeltaQP )
965
0
      {
966
0
        clippedMaxDQP = deltaQP > 0 ? slice.sliceQp - m_pcEncCfg->m_maxDeltaQP : slice.sliceQp + m_pcEncCfg->m_maxDeltaQP;
967
0
        tempCS->currQP[partitioner.chType] = tempCS->baseQP = clippedMaxDQP;
968
0
      }
969
4.16k
      updateLambda( slice, pic->ctuQpaLambda[ctuRsAddr], pic->ctuAdaptedQP[ctuRsAddr], backupBaseQP, true );
970
4.16k
    }
971
8.82k
  }
972
973
156k
  if (partitioner.currQtDepth == 0)
974
9.30k
  {
975
9.30k
    m_MergeSimpleFlag = 0;
976
9.30k
  }
977
  // the neighbours determineNeighborCus looked up at the start of this CU
978
156k
  const DeriveCtx& deriveCtx = m_CABACEstimator->getDeriveCtx();
979
156k
  m_modeCtrl.initCULevel( partitioner, *tempCS, m_MergeSimpleFlag, deriveCtx.cuRestrictedLeft[partitioner.chType], deriveCtx.cuRestrictedAbove[partitioner.chType] );
980
156k
  m_sbtCostSave[0] = m_sbtCostSave[1] = MAX_DOUBLE;
981
982
156k
  CHECKD( m_startCtxPending, "a context reset of the parent CU is still pending" );
983
156k
  m_CurrCtx->start = m_CABACEstimator->getCtx();
984
985
156k
  m_cuChromaQpOffsetIdxPlus1 = 0;
986
987
156k
  if( slice.chromaQpAdjEnabled && partitioner.currQgChromaEnable() )
988
0
  {
989
    // TODO M0133 : double check encoder decisions with respect to chroma QG detection and actual encode
990
0
    int cuChromaQpOffsetSubdiv = slice.isIntra() ? slice.picHeader->cuChromaQpOffsetSubdivIntra : slice.picHeader->cuChromaQpOffsetSubdivInter;
991
0
    int lgMinCuSize = sps.log2MinCodingBlockSize +
992
0
      std::max<int>(0, floorLog2(sps.CTUSize) - sps.log2MinCodingBlockSize - int((cuChromaQpOffsetSubdiv + 1) / 2));
993
0
    m_cuChromaQpOffsetIdxPlus1 = ( ( uiLPelX >> lgMinCuSize ) + ( uiTPelY >> lgMinCuSize ) ) % ( pps.chromaQpOffsetListLen + 1 );
994
0
  }
995
996
156k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cux", uiLPelX ) );
997
156k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cuy", uiTPelY ) );
998
156k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cuw", tempCS->area.lwidth() ) );
999
156k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cuh", tempCS->area.lheight() ) );
1000
156k
  DTRACE( g_trace_ctx, D_COMMON, "@(%4d,%4d) [%2dx%2d]\n", tempCS->area.lx(), tempCS->area.ly(), tempCS->area.lwidth(), tempCS->area.lheight() );
1001
1002
156k
  if( tempCS->slice->checkLDC )
1003
156k
  {
1004
156k
    m_bestBcwCost[0] = m_bestBcwCost[1] = std::numeric_limits<double>::max();
1005
156k
    m_bestBcwIdx[0] = m_bestBcwIdx[1] = -1;
1006
156k
  }
1007
1008
156k
  m_cInterSearch.resetSavedAffineMotion();
1009
156k
  {
1010
156k
    const ComprCUCtx &cuECtx      = *m_modeCtrl.comprCUCtx;
1011
156k
    const CodingStructure& cs     = *tempCS;
1012
156k
    const PartSplit implicitSplit = partitioner.getImplicitSplit( cs );
1013
156k
    const bool isBoundary         = implicitSplit != CU_DONT_SPLIT;
1014
156k
    const bool lossless           = false;
1015
156k
    int qp                        = cs.baseQP;
1016
1017
#if ENABLE_MEASURE_SEARCH_SPACE
1018
    if( !isBoundary )
1019
    {
1020
      g_searchSpaceAcc.addPartition( partitioner.currArea(), partitioner.isSepTree( *tempCS ) ? partitioner.chType : MAX_NUM_CH );
1021
    }
1022
1023
#endif
1024
156k
    if( ! isBoundary )
1025
98.3k
    {
1026
98.3k
      if (pps.useDQP && partitioner.isSepTree (*tempCS) && isChroma (partitioner.chType))
1027
68.2k
      {
1028
68.2k
        const ChromaFormat chromaFm = tempCS->area.chromaFormat;
1029
68.2k
        const Position chromaCentral (tempCS->area.Cb().chromaPos().offset (tempCS->area.Cb().chromaSize().width >> 1, tempCS->area.Cb().chromaSize().height >> 1));
1030
68.2k
        const Position lumaRefPos (chromaCentral.x << getChannelTypeScaleX (CH_C, chromaFm), chromaCentral.y << getChannelTypeScaleY (CH_C, chromaFm));
1031
68.2k
        const CodingUnit* colLumaCu = bestCS->lumaCS->getCU (lumaRefPos, CH_L, TREE_D);
1032
        // update qp
1033
68.2k
        qp = colLumaCu->qp;
1034
68.2k
      }
1035
1036
98.3k
      m_cIntraSearch.reset();
1037
1038
      // initCULevel already checked this at the CU's base QP, and nothing it reads has changed since
1039
98.3k
      bool isReuseCU = qp == cs.baseQP ? cuECtx.isReusingCu : m_modeCtrl.isReusingCuValid( cs, partitioner, qp );
1040
1041
98.3k
      bool checkIbc = m_pcEncCfg->m_IBCMode && bestCS->picture->useIBC && (partitioner.chType == CH_L);
1042
98.3k
      if ((m_pcEncCfg->m_IBCFastMethod>3) && (cs.area.lwidth() * cs.area.lheight()) > (16 * 16))
1043
0
      {
1044
0
        checkIbc = false;
1045
0
      }
1046
98.3k
      if( isReuseCU )
1047
0
      {
1048
0
        xReuseCachedResult( tempCS, bestCS, partitioner );
1049
0
      }
1050
98.3k
      else
1051
98.3k
      {
1052
        // add first pass modes
1053
98.3k
        if ( !slice.isIntra() && !slice.isIRAP() && !( cs.area.lwidth() == 4 && cs.area.lheight() == 4 ) && !partitioner.isConsIntra() )
1054
0
        {
1055
          // add inter modes
1056
0
          EncTestMode encTestModeSkip = { ETM_MERGE_SKIP, ETO_STANDARD, qp, lossless };
1057
0
          if (m_modeCtrl.tryMode(encTestModeSkip, cs, partitioner))
1058
0
          {
1059
0
            xCheckRDCostUnifiedMerge(tempCS, bestCS, partitioner, encTestModeSkip);
1060
1061
0
            CodingUnit* cu = bestCS->getCU(partitioner.chType, partitioner.treeType);
1062
0
            if (cu)
1063
0
              cu->mmvdSkip = cu->skip == false ? false : cu->mmvdSkip;
1064
0
          }
1065
0
          EncTestMode encTestMode = { ETM_INTER_ME, ETO_STANDARD, qp, lossless };
1066
0
          if (m_modeCtrl.tryMode(encTestMode, cs, partitioner))
1067
0
          {
1068
0
            xCheckRDCostInter(tempCS, bestCS, partitioner, encTestMode);
1069
0
          }
1070
1071
0
          if (m_pcEncCfg->m_AMVRspeed && !m_modeCtrl.skipsAmvrSearch( *bestCS ))
1072
0
          {
1073
0
            double bestIntPelCost = MAX_DOUBLE;
1074
1075
0
            EncTestMode encTestMode = {ETM_INTER_IMV, ETO_STANDARD, qp, lossless};
1076
0
            if( m_modeCtrl.tryMode( encTestMode, cs, partitioner ) )
1077
0
            {
1078
0
              const bool skipAltHpelIF = ( int( ( encTestMode.opts & ETO_IMV ) >> ETO_IMV_SHIFT ) == 4 ) && ( bestIntPelCost > 1.25 * bestCS->cost );
1079
0
              if (!skipAltHpelIF)
1080
0
              {
1081
0
                xCheckRDCostInterIMV(tempCS, bestCS, partitioner, encTestMode );
1082
0
              }
1083
0
            }
1084
0
          }
1085
0
        }
1086
1087
98.3k
        if (checkIbc && !partitioner.isConsInter())
1088
30.0k
        {
1089
30.0k
          EncTestMode encTestModeIBCMerge = { ETM_IBC_MERGE, ETO_STANDARD, qp, lossless };
1090
30.0k
          if ((m_pcEncCfg->m_IBCFastMethod < 4) && (partitioner.chType == CH_L) && m_modeCtrl.tryMode(encTestModeIBCMerge, cs, partitioner))
1091
30.0k
          {
1092
30.0k
            xCheckRDCostIBCModeMerge2Nx2N(tempCS, bestCS, partitioner, encTestModeIBCMerge);
1093
30.0k
          }
1094
1095
30.0k
          EncTestMode encTestModeIBC = { ETM_IBC, ETO_STANDARD, qp, lossless };
1096
30.0k
          if (m_modeCtrl.tryMode(encTestModeIBC, cs, partitioner))
1097
30.0k
          {
1098
30.0k
            xCheckRDCostIBCMode(tempCS, bestCS, partitioner, encTestModeIBC);
1099
30.0k
          }
1100
30.0k
        }
1101
98.3k
        if( m_EDO && bestCS->cost != MAX_DOUBLE )
1102
26.8k
        {
1103
26.8k
          xCalDebCost(*bestCS, partitioner);
1104
26.8k
        }
1105
1106
        // add intra modes
1107
98.3k
        EncTestMode encTestMode( {ETM_INTRA, ETO_STANDARD, qp, lossless} );
1108
98.3k
        if( !partitioner.isConsInter() && m_modeCtrl.tryMode( encTestMode, cs, partitioner ) )
1109
98.3k
        {
1110
98.3k
          xCheckRDCostIntra( tempCS, bestCS, partitioner, encTestMode );
1111
98.3k
        }
1112
98.3k
      } // reusing cu
1113
1114
98.3k
      m_modeCtrl.beforeSplit( partitioner );
1115
1116
98.3k
      if (cuECtx.bestCS && ((cuECtx.bestCostNoImv == (MAX_DOUBLE * .5) || cuECtx.isReusingCu) && !slice.isIntra()) )
1117
0
      {
1118
0
        m_cInterSearch.loadGlobalUniMvs( lumaArea, *pps.pcv );
1119
0
      }
1120
1121
98.3k
      if (!cs.slice->isIntra() && (partitioner.chType == CH_L) && ( m_pcEncCfg->m_qtbttSpeedUpMode & 2) && (partitioner.currQtDepth < 3) && bestCS->cus.size())
1122
0
      {
1123
0
        int flagDbefore = (bestCS->cus[0]->mergeFlag && !bestCS->cus[0]->mmvdMergeFlag && !bestCS->cus[0]->ispMode && !bestCS->cus[0]->geo) ? 1 : 0;
1124
0
        if (partitioner.currQtDepth == 0)
1125
0
        {
1126
0
          m_MergeSimpleFlag = flagDbefore;
1127
0
        }
1128
0
        else
1129
0
        {
1130
0
          int markFlag = (partitioner.currQtDepth == 1) ? 1 : 3;
1131
0
          m_MergeSimpleFlag = (flagDbefore << partitioner.currQtDepth) | (m_MergeSimpleFlag & markFlag);
1132
0
        }
1133
0
      }
1134
98.3k
    } //boundary
1135
1136
156k
    if( ( m_pcEncCfg->m_IntraPeriod == 1 ) && ( partitioner.chType == CH_C ) )
1137
0
    {
1138
0
      xCheckFastCuChromaSplitting( tempCS, bestCS, partitioner, *m_modeCtrl.comprCUCtx );
1139
0
    }
1140
    //////////////////////////////////////////////////////////////////////////
1141
    // split modes
1142
156k
    EncTestMode lastTestMode;
1143
1144
156k
    if( cuECtx.qtBeforeBt )
1145
24.9k
    {
1146
24.9k
      EncTestMode encTestMode( { ETM_SPLIT_QT, ETO_STANDARD, qp, false } );
1147
24.9k
      if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
1148
16.2k
      {
1149
16.2k
        lastTestMode = encTestMode;
1150
16.2k
        xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
1151
16.2k
      }
1152
24.9k
    }
1153
1154
156k
    if( partitioner.canSplit( CU_HORZ_SPLIT, cs ) )
1155
82.7k
    {
1156
      // add split modes
1157
82.7k
      EncTestMode encTestMode( { ETM_SPLIT_BT_H, ETO_STANDARD, qp, false } );
1158
82.7k
      if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
1159
82.7k
      {
1160
82.7k
        lastTestMode = encTestMode;
1161
82.7k
        xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
1162
82.7k
      }
1163
82.7k
    }
1164
1165
156k
    if( partitioner.canSplit( CU_VERT_SPLIT, cs ) )
1166
78.4k
    {
1167
      // add split modes
1168
78.4k
      EncTestMode encTestMode( { ETM_SPLIT_BT_V, ETO_STANDARD, qp, false } );
1169
78.4k
      if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
1170
78.4k
      {
1171
78.4k
        lastTestMode = encTestMode;
1172
78.4k
        xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
1173
78.4k
      }
1174
78.4k
    }
1175
1176
156k
    if( partitioner.canSplit( CU_TRIH_SPLIT, cs ) )
1177
34.2k
    {
1178
      // add split modes
1179
34.2k
      EncTestMode encTestMode( { ETM_SPLIT_TT_H, ETO_STANDARD, qp, false } );
1180
34.2k
      if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
1181
1.58k
      {
1182
1.58k
        lastTestMode = encTestMode;
1183
1.58k
        xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
1184
1.58k
      }
1185
34.2k
    }
1186
1187
156k
    if( partitioner.canSplit( CU_TRIV_SPLIT, cs ) )
1188
26.8k
    {
1189
      // add split modes
1190
26.8k
      EncTestMode encTestMode( { ETM_SPLIT_TT_V, ETO_STANDARD, qp, false } );
1191
26.8k
      if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
1192
1.18k
      {
1193
1.18k
        lastTestMode = encTestMode;
1194
1.18k
        xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
1195
1.18k
      }
1196
26.8k
    }
1197
1198
156k
    if( !cuECtx.qtBeforeBt )
1199
131k
    {
1200
131k
      EncTestMode encTestMode( { ETM_SPLIT_QT, ETO_STANDARD, qp, false } );
1201
131k
      if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
1202
33.4k
      {
1203
33.4k
        lastTestMode = encTestMode;
1204
33.4k
        xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
1205
33.4k
      }
1206
131k
    }
1207
156k
  }
1208
1209
156k
  if( bestCS->cus.empty() )
1210
0
  {
1211
0
    xRestoreStartCtx();   // the caller continues on another CU level
1212
0
    m_modeCtrl.finishCULevel( partitioner );
1213
0
    return;
1214
0
  }
1215
1216
  //////////////////////////////////////////////////////////////////////////
1217
  // Finishing CU
1218
  // set context states: the best mode's contexts, which xCheckBestMode saved in this call (bestCS has a CU); swapped, not
1219
  // copied, because m_CurrCtx->best is not read again before the next xCheckBestMode on this level overwrites it
1220
156k
  m_CABACEstimator->getCtx().swap( m_CurrCtx->best );
1221
156k
  m_startCtxPending = false;
1222
1223
  // QP from last processed CU for further processing
1224
  //copy the qp of the last non-chroma CU
1225
156k
  int numCUInThisNode = (int)bestCS->cus.size();
1226
156k
  if( numCUInThisNode > 1 && bestCS->cus.back()->chType == CH_C && !CS::isDualITree( *bestCS ) )
1227
0
  {
1228
0
    CHECK( bestCS->cus[numCUInThisNode-2]->chType != CH_L, "wrong chType" );
1229
0
    bestCS->prevQP[partitioner.chType] = bestCS->cus[numCUInThisNode-2]->qp;
1230
0
  }
1231
156k
  else
1232
156k
  {
1233
156k
    bestCS->prevQP[partitioner.chType] = bestCS->cus.back()->qp;
1234
156k
  }
1235
156k
  if( ( !slice.isIntra() || slice.sps->IBC )
1236
156k
    && partitioner.chType == CH_L
1237
62.4k
    && bestCS->cus.size() == 1 && ( bestCS->cus.back()->predMode == MODE_INTER || bestCS->cus.back()->predMode == MODE_IBC )
1238
0
    && bestCS->area.Y() == (*bestCS->cus.back()).Y() )
1239
0
  {
1240
0
    const CodingUnit& cu = *bestCS->cus.front();
1241
0
    bool isIbcSmallBlk = CU::isIBC(cu) && (cu.lwidth() * cu.lheight() <= 16);
1242
0
    if (!cu.affine && !cu.geo && !isIbcSmallBlk)
1243
0
    {
1244
0
      const MotionInfo &mi = cu.getMotionInfo();
1245
0
      HPMVInfo hMi( mi, ( mi.interDir() == 3 ) ? cu.BcwIdx : BCW_DEFAULT, cu.imv == IMV_HPEL, CU::isIBC( cu ) );
1246
0
      cu.cs->addMiToLut( CU::isIBC( cu ) ? cu.cs->motionLut.lutIbc : cu.cs->motionLut.lut, hMi );
1247
0
    }
1248
0
  }
1249
1250
156k
  m_modeCtrl.finishCULevel( partitioner );
1251
156k
  if( m_cIntraSearch.getSaveCuCostInSCIPU() && bestCS->cus.size() == 1 )
1252
0
  {
1253
0
    m_cIntraSearch.saveCuAreaCostInSCIPU( Area( partitioner.currArea().lumaPos(), partitioner.currArea().lumaSize() ), bestCS->cost );
1254
0
  }
1255
1256
  // Assert if Best prediction mode is NONE
1257
  // Selected mode's RD-cost must be not MAX_DOUBLE.
1258
156k
  CHECK( bestCS->cus.empty()                                   , "No possible encoding found" );
1259
156k
  CHECK( bestCS->cus[0]->predMode == NUMBER_OF_PREDICTION_MODES, "No possible encoding found" );
1260
156k
  CHECK( bestCS->cost             == MAX_DOUBLE                , "No possible encoding found" );
1261
156k
}
1262
1263
1264
void EncCu::xCheckModeSplit(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode )
1265
213k
{
1266
213k
  const ModeType modeTypeParent  = partitioner.modeType;
1267
213k
  const TreeType treeTypeParent  = partitioner.treeType;
1268
213k
  const ChannelType chTypeParent = partitioner.chType;
1269
1270
213k
  int signalModeConsVal = CS::signalModeCons( *tempCS, partitioner.currArea(), getPartSplit(encTestMode), modeTypeParent);
1271
213k
  int numRoundRdo = signalModeConsVal == LDT_MODE_TYPE_SIGNAL ? 2 : 1;
1272
213k
  bool skipInterPass = false;
1273
427k
  for( int i = 0; i < numRoundRdo; i++ )
1274
213k
  {
1275
    //change cons modes
1276
213k
    if( signalModeConsVal == LDT_MODE_TYPE_SIGNAL )
1277
0
    {
1278
0
      CHECK( numRoundRdo != 2, "numRoundRdo shall be 2 - [LDT_MODE_TYPE_SIGNAL]" );
1279
0
      partitioner.modeType = (i == 0) ? MODE_TYPE_INTER : MODE_TYPE_INTRA;
1280
0
    }
1281
213k
    else if( signalModeConsVal == LDT_MODE_TYPE_INFER )
1282
0
    {
1283
0
      CHECK( numRoundRdo != 1, "numRoundRdo shall be 1 - [LDT_MODE_TYPE_INFER]" );
1284
0
      partitioner.modeType = MODE_TYPE_INTRA;
1285
0
    }
1286
213k
    else if( signalModeConsVal == LDT_MODE_TYPE_INHERIT )
1287
213k
    {
1288
213k
      CHECK( numRoundRdo != 1, "numRoundRdo shall be 1 - [LDT_MODE_TYPE_INHERIT]" );
1289
213k
      partitioner.modeType = modeTypeParent;
1290
213k
    }
1291
1292
    //for lite intra encoding fast algorithm, set the status to save inter coding info
1293
213k
    if( modeTypeParent == MODE_TYPE_ALL && partitioner.modeType == MODE_TYPE_INTER )
1294
0
    {
1295
0
      m_cIntraSearch.setSaveCuCostInSCIPU( true );
1296
0
      m_cIntraSearch.setNumCuInSCIPU( 0 );
1297
0
    }
1298
213k
    else if( modeTypeParent == MODE_TYPE_ALL && partitioner.modeType != MODE_TYPE_INTER )
1299
213k
    {
1300
213k
      m_cIntraSearch.setSaveCuCostInSCIPU( false );
1301
213k
      if( partitioner.modeType == MODE_TYPE_ALL )
1302
213k
      {
1303
213k
        m_cIntraSearch.setNumCuInSCIPU( 0 );
1304
213k
      }
1305
213k
    }
1306
1307
213k
    xCheckModeSplitInternal( tempCS, bestCS, partitioner, encTestMode, modeTypeParent, skipInterPass );
1308
    //recover cons modes
1309
213k
    partitioner.modeType = modeTypeParent;
1310
213k
    partitioner.treeType = treeTypeParent;
1311
213k
    partitioner.chType = chTypeParent;
1312
213k
    if( modeTypeParent == MODE_TYPE_ALL )
1313
213k
    {
1314
213k
      m_cIntraSearch.setSaveCuCostInSCIPU( false );
1315
213k
      if( numRoundRdo == 2 && partitioner.modeType == MODE_TYPE_INTRA )
1316
0
      {
1317
0
        m_cIntraSearch.initCuAreaCostInSCIPU();
1318
0
      }
1319
213k
    }
1320
213k
    if( skipInterPass )
1321
0
    {
1322
0
      break;
1323
0
    }
1324
213k
  }
1325
213k
}
1326
1327
void EncCu::xCheckModeSplitInternal(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode, const ModeType modeTypeParent, bool& skipInterPass )
1328
213k
{
1329
213k
  const int qp                     = encTestMode.qp;
1330
213k
  const int oldPrevQp              = tempCS->prevQP[partitioner.chType];
1331
213k
  const auto oldMotionLut          = tempCS->motionLut;
1332
                                   
1333
213k
  const PartSplit split            = getPartSplit( encTestMode );
1334
213k
  const ModeType  modeTypeChild    = partitioner.modeType;
1335
1336
213k
  CHECK( !( split == CU_QUAD_SPLIT || split == CU_HORZ_SPLIT || split == CU_VERT_SPLIT
1337
213k
         || split == CU_TRIH_SPLIT || split == CU_TRIV_SPLIT ), "invalid split type" );
1338
1339
213k
  tempCS->initStructData( qp );
1340
1341
213k
  xSetStartCtx();
1342
1343
213k
  const uint16_t split_ctx_size    = Ctx::SplitFlag.size() + Ctx::SplitQtFlag.size() + Ctx::SplitHvFlag.size() + Ctx::Split12Flag.size() + Ctx::ModeConsFlag.size();
1344
213k
  const TempCtx  ctxSplitFlags     ( m_CtxCache, SubCtx( CtxSet( Ctx::SplitFlag(), split_ctx_size ), m_CABACEstimator->getCtx() ) );
1345
1346
213k
  m_CABACEstimator->determineNeighborCus( *tempCS, partitioner.currArea(), partitioner.chType, partitioner.treeType );
1347
213k
  m_CABACEstimator->resetBits           ();
1348
213k
  m_CABACEstimator->split_cu_mode       ( split, *tempCS, partitioner );
1349
213k
  partitioner     . modeType            = modeTypeParent;
1350
213k
  m_CABACEstimator->mode_constraint     ( split, *tempCS, partitioner, modeTypeChild );
1351
213k
  partitioner     . modeType            = modeTypeChild;
1352
1353
213k
  const int64_t splitBits   = m_CABACEstimator->getEstFracBits();
1354
1355
213k
  const bool chromaNotSplit = modeTypeParent == MODE_TYPE_ALL && modeTypeChild == MODE_TYPE_INTRA;
1356
213k
  const bool isChromaTooBig = isChromaEnabled( tempCS->pps->pcv->chrFormat ) && tempCS->area.Y().maxDim() > tempCS->sps->getMaxTbSize();
1357
213k
  bool       skipSplitTest  = chromaNotSplit && isChromaTooBig;
1358
1359
213k
  if( !skipSplitTest )
1360
213k
  {
1361
213k
    double         a = -1, b = -1;
1362
213k
    const unsigned w       = partitioner.currArea().lwidth();
1363
213k
    const unsigned h       = partitioner.currArea().lheight();
1364
213k
    const bool contextCond = w == h && tempCS->slice->sliceType == VVENC_B_SLICE && isLuma( partitioner.chType ) && m_pcEncCfg->m_splitCostThrParamId >= 0 && m_pcEncCfg->m_splitCostThrParamId <= 3;
1365
1366
213k
    if( contextCond )
1367
0
    {
1368
0
      uint8_t nsPredInd = m_modeCtrl.comprCUCtx->bestNsPredMode.type == ETM_INTRA;
1369
0
      uint8_t szInd     = getLog2( w ) - 3;
1370
0
      uint8_t splitInd  = split == CU_QUAD_SPLIT ? 1 : 0;
1371
0
      if ( m_pcEncCfg->m_splitCostThrParamId <= 1 )
1372
0
      {
1373
0
        a = coefSquareCUsFasterFastMedium[m_pcEncCfg->m_splitCostThrParamId][szInd][nsPredInd][splitInd][0];
1374
0
        b = coefSquareCUsFasterFastMedium[m_pcEncCfg->m_splitCostThrParamId][szInd][nsPredInd][splitInd][1];
1375
0
      }
1376
0
      else
1377
0
      {
1378
0
        uint8_t mtInd = (partitioner.currMtDepth == 0);
1379
0
        a = coefSquareCUsSlowSlower[m_pcEncCfg->m_splitCostThrParamId - 2][szInd][nsPredInd][partitioner.currQtDepth][mtInd][splitInd][0];
1380
0
        b = coefSquareCUsSlowSlower[m_pcEncCfg->m_splitCostThrParamId - 2][szInd][nsPredInd][partitioner.currQtDepth][mtInd][splitInd][1];
1381
0
      }
1382
0
    }
1383
1384
213k
    if( a > -1 && b > -1 )
1385
0
    {
1386
0
      const double bestNsCost    = m_modeCtrl.comprCUCtx->bestCostBeforeSplit == MAX_DOUBLE ? -1 : m_modeCtrl.comprCUCtx->bestCostBeforeSplit;
1387
0
      const double factor        = 1.0 + b * exp( a * qp );
1388
0
      const double predSplitCost = bestNsCost / factor + splitBits;
1389
0
      skipSplitTest              = bestNsCost >= 0 && predSplitCost >= bestNsCost;
1390
0
    }
1391
213k
    else
1392
213k
    {
1393
213k
      int numChild = 3;
1394
213k
      if( split == CU_VERT_SPLIT || split == CU_HORZ_SPLIT ) numChild--;
1395
52.4k
      else if( split == CU_QUAD_SPLIT ) numChild++;
1396
1397
213k
      int64_t approxBits = m_pcEncCfg->m_qtbttSpeedUp > 0 ? numChild << SCALE_BITS : 0;
1398
1399
213k
      const double factor     = ( tempCS->currQP[partitioner.chType] > 30                              ? 1.1  : 1.075 ) +
1400
213k
                                (   m_pcEncCfg->m_qtbttSpeedUp > 0                                     ? 0.01 : 0.0   ) +
1401
213k
                                ( ( m_pcEncCfg->m_qtbttSpeedUp > 0 && isChroma( partitioner.chType ) ) ? 0.2  : 0.0   );
1402
       
1403
213k
      const double baseCost   = bestCS->cost + bestCS->costDbOffset;
1404
213k
      const double predCost   = baseCost / factor + splitBits + approxBits;
1405
213k
      skipSplitTest           = predCost >= baseCost;
1406
213k
    }
1407
213k
  }
1408
1409
213k
  if( skipSplitTest )
1410
132k
  {
1411
132k
    m_CABACEstimator->getCtx() = SubCtx( CtxSet( Ctx::SplitFlag(), split_ctx_size ), ctxSplitFlags );
1412
132k
    xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
1413
132k
    return;
1414
132k
  }
1415
1416
81.1k
  if( partitioner.treeType == TREE_D )
1417
81.1k
  {
1418
81.1k
    if( chromaNotSplit )
1419
0
    {
1420
0
      CHECK( partitioner.chType != CH_L, "chType must be luma" );
1421
0
      partitioner.treeType = TREE_L;
1422
0
    }
1423
81.1k
    else
1424
81.1k
    {
1425
81.1k
      partitioner.treeType = TREE_D;
1426
81.1k
    }
1427
81.1k
  }
1428
1429
81.1k
  partitioner.splitCurrArea( split, *tempCS );
1430
81.1k
  bool qgEnableChildren = partitioner.currQgEnable(); // QG possible at children level
1431
1432
81.1k
  m_CurrCtx++;
1433
1434
81.1k
  AffineMVInfo tmpMVInfo;
1435
81.1k
  bool isAffMVInfoSaved = m_cInterSearch.m_AffineProfList->savePrevAffMVInfo( 0, tmpMVInfo );
1436
1437
81.1k
  BlkUniMvInfo tmpUniMvInfo;
1438
81.1k
  bool         isUniMvInfoSaved = false;
1439
81.1k
  if( !tempCS->slice->isIntra() )
1440
0
  {
1441
0
    m_cInterSearch.m_BlkUniMvInfoBuffer->savePrevUniMvInfo( tempCS->area.Y(), tmpUniMvInfo, isUniMvInfoSaved );
1442
0
  }
1443
1444
81.1k
  DeriveCtx deriveCtx = m_CABACEstimator->getDeriveCtx();
1445
1446
81.1k
  do
1447
208k
  {
1448
208k
    const auto &subCUArea  = partitioner.currArea();
1449
1450
208k
    if( tempCS->picture->Y().contains( subCUArea.lumaPos() ) )
1451
147k
    {
1452
147k
      PelStorage* orgBuffer =  &m_pOrgBuffer[partitioner.currDepth];
1453
147k
      CodingStructure *tempSubCS = m_pTempCS[partitioner.currDepth];
1454
147k
      CodingStructure *bestSubCS = m_pBestCS[partitioner.currDepth];
1455
1456
147k
      tempCS->initSubStructure( *tempSubCS, partitioner.chType, subCUArea, false, orgBuffer );
1457
147k
      tempCS->initSubStructure( *bestSubCS, partitioner.chType, subCUArea, false, orgBuffer );
1458
1459
      // copy org buffer, need to be done after initSubStructure, which resizes the buffer to the sub-CU
1460
147k
      orgBuffer->copyFrom( tempCS->getOrgBuf( subCUArea ) );
1461
1462
147k
      tempSubCS->bestParent = bestSubCS->bestParent = bestCS;
1463
1464
147k
      xCompressCU(tempSubCS, bestSubCS, partitioner );
1465
1466
147k
      tempSubCS->bestParent = bestSubCS->bestParent = nullptr;
1467
1468
147k
      if( bestSubCS->cost == MAX_DOUBLE )
1469
0
      {
1470
0
        CHECK( split == CU_QUAD_SPLIT, "Split decision reusing cannot skip quad split" );
1471
0
        tempCS->cost = MAX_DOUBLE;
1472
0
        tempCS->costDbOffset = 0;
1473
0
        m_CurrCtx--;
1474
0
        partitioner.exitCurrSplit();
1475
0
        xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
1476
0
        if( partitioner.chType == CH_L )
1477
0
        {
1478
0
          tempCS->motionLut = oldMotionLut;
1479
0
        }
1480
1481
0
        m_CABACEstimator->getDeriveCtx() = deriveCtx;
1482
0
        return;
1483
0
      }
1484
1485
147k
      tempCS->useSubStructure( *bestSubCS, partitioner.chType, TREE_D, CS::getArea( *tempCS, subCUArea, partitioner.chType, partitioner.treeType ), partitioner.hasNextPart() || chromaNotSplit );
1486
1487
147k
      if( partitioner.currQgEnable() )
1488
8.33k
      {
1489
8.33k
        tempCS->prevQP[partitioner.chType] = bestSubCS->prevQP[partitioner.chType];
1490
8.33k
      }
1491
147k
      if( partitioner.isConsInter() )
1492
0
      {
1493
0
        for( int i = 0; i < bestSubCS->cus.size(); i++ )
1494
0
        {
1495
0
          CHECK( bestSubCS->cus[i]->predMode != MODE_INTER, "all CUs must be inter mode in an Inter coding region (SCIPU)" );
1496
0
        }
1497
0
      }
1498
147k
      else if( partitioner.isConsIntra() )
1499
0
      {
1500
0
        for( int i = 0; i < bestSubCS->cus.size(); i++ )
1501
0
        {
1502
0
          CHECK( bestSubCS->cus[i]->predMode == MODE_INTER, "all CUs must not be inter mode in an Intra coding region (SCIPU)" );
1503
0
        }
1504
0
      }
1505
1506
147k
      tempSubCS->releaseIntermediateData();
1507
147k
      bestSubCS->releaseIntermediateData();
1508
147k
      if( !tempCS->slice->isIntra() && partitioner.isConsIntra() )
1509
0
      {
1510
0
        tempCS->cost = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
1511
0
        if( tempCS->cost > bestCS->cost )
1512
0
        {
1513
0
          tempCS->cost = MAX_DOUBLE;
1514
0
          tempCS->costDbOffset = 0;
1515
0
          m_CurrCtx--;
1516
0
          partitioner.exitCurrSplit();
1517
0
          if( partitioner.chType == CH_L )
1518
0
          {
1519
0
            tempCS->motionLut = oldMotionLut;
1520
0
          }
1521
1522
0
          m_CABACEstimator->getDeriveCtx() = deriveCtx;
1523
0
          return;
1524
0
        }
1525
0
      }
1526
147k
    }
1527
208k
  } while( partitioner.nextPart( *tempCS ) );
1528
1529
81.1k
  partitioner.exitCurrSplit();
1530
1531
81.1k
  m_CurrCtx--;
1532
1533
81.1k
  m_CABACEstimator->getDeriveCtx() = deriveCtx;
1534
1535
81.1k
  if( chromaNotSplit )
1536
0
  {
1537
    //Note: In local dual tree region, the chroma CU refers to the central luma CU's QP.
1538
    //If the luma CU QP shall be predQP (no residual in it and before it in the QG), it must be revised to predQP before encoding the chroma CU
1539
    //Otherwise, the chroma CU uses predQP+deltaQP in encoding but is decoded as using predQP, thus causing encoder-decoded mismatch on chroma qp.
1540
0
    if( tempCS->pps->useDQP )
1541
0
    {
1542
      //find parent CS that including all coded CUs in the QG before this node
1543
0
      CodingStructure* qgCS = tempCS;
1544
0
      bool deltaQpCodedBeforeThisNode = false;
1545
0
      if( partitioner.currArea().lumaPos() != partitioner.currQgPos )
1546
0
      {
1547
0
        int numParentNodeToQgCS = 0;
1548
0
        while( qgCS->area.lumaPos() != partitioner.currQgPos )
1549
0
        {
1550
0
          CHECK( qgCS->parent == nullptr, "parent of qgCS shall exsit" );
1551
0
          qgCS = qgCS->parent;
1552
0
          numParentNodeToQgCS++;
1553
0
        }
1554
1555
        //check whether deltaQP has been coded (in luma CU or luma&chroma CU) before this node
1556
0
        CodingStructure* parentCS = tempCS->parent;
1557
0
        for( int i = 0; i < numParentNodeToQgCS; i++ )
1558
0
        {
1559
          //checking each parent
1560
0
          CHECK( parentCS == nullptr, "parentCS shall exsit" );
1561
0
          for( const auto &cu : parentCS->cus )
1562
0
          {
1563
0
            if( cu->rootCbf && !isChroma( cu->chType ) )
1564
0
            {
1565
0
              deltaQpCodedBeforeThisNode = true;
1566
0
              break;
1567
0
            }
1568
0
          }
1569
0
          parentCS = parentCS->parent;
1570
0
        }
1571
0
      }
1572
1573
      //revise luma CU qp before the first luma CU with residual in the SCIPU to predQP
1574
0
      if( !deltaQpCodedBeforeThisNode )
1575
0
      {
1576
        //get pred QP of the QG
1577
0
        const CodingUnit* cuFirst = qgCS->getCU( CH_L, TREE_D );
1578
0
        CHECK( cuFirst->lumaPos() != partitioner.currQgPos, "First cu of the Qg is wrong" );
1579
0
        int predQp = CU::predictQP( *cuFirst, qgCS->prevQP[CH_L] );
1580
1581
        //revise to predQP
1582
0
        int firstCuHasResidual = (int)tempCS->cus.size();
1583
0
        for( int i = 0; i < tempCS->cus.size(); i++ )
1584
0
        {
1585
0
          if( tempCS->cus[i]->rootCbf )
1586
0
          {
1587
0
            firstCuHasResidual = i;
1588
0
            break;
1589
0
          }
1590
0
        }
1591
1592
0
        for( int i = 0; i < firstCuHasResidual; i++ )
1593
0
        {
1594
0
          tempCS->cus[i]->qp = predQp;
1595
0
        }
1596
0
      }
1597
0
    }
1598
0
    partitioner.chType   = CH_C;
1599
0
    partitioner.treeType = TREE_C;
1600
1601
0
    m_CurrCtx++;
1602
1603
0
    CodingStructure *tempCSChroma = m_pTempCS2;
1604
0
    CodingStructure *bestCSChroma = m_pBestCS2;
1605
1606
0
    tempCS->initSubStructure( *tempCSChroma, partitioner.chType, partitioner.currArea(), false );
1607
0
    tempCS->initSubStructure( *bestCSChroma, partitioner.chType, partitioner.currArea(), false );
1608
0
    tempCSChroma->lumaCS = tempCS;
1609
0
    bestCSChroma->lumaCS = tempCS;
1610
0
    xCompressCU( tempCSChroma, bestCSChroma, partitioner );
1611
1612
    //attach chromaCS to luma CS and update cost
1613
0
    tempCS->useSubStructure( *bestCSChroma, partitioner.chType, TREE_D, CS::getArea( *bestCSChroma, partitioner.currArea(), partitioner.chType, partitioner.treeType ), false );
1614
1615
    //release tmp resource
1616
0
    tempCSChroma->releaseIntermediateData();
1617
0
    bestCSChroma->releaseIntermediateData();
1618
1619
0
    m_CurrCtx--;
1620
    //recover luma tree status
1621
0
    partitioner.chType = CH_L;
1622
0
    partitioner.treeType = TREE_D;
1623
0
    partitioner.modeType = MODE_TYPE_ALL;
1624
0
  }
1625
1626
  // Finally, add split-signaling bits for RD-cost check
1627
81.1k
  tempCS->fracBits += splitBits; // split bits
1628
81.1k
  tempCS->cost      = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
1629
81.1k
  partitioner.modeType = modeTypeParent;
1630
1631
  // Check Delta QP bits for splitted structure
1632
81.1k
  if( !qgEnableChildren ) // check at deepest QG level only
1633
78.0k
    xCheckDQP( *tempCS, partitioner, true );
1634
1635
  // If the configuration being tested exceeds the maximum number of bytes for a slice / slice-segment, then
1636
  // a proper RD evaluation cannot be performed. Therefore, termination of the
1637
  // slice/slice-segment must be made prior to this CTU.
1638
  // This can be achieved by forcing the decision to be that of the rpcTempCU.
1639
  // The exception is each slice / slice-segment must have at least one CTU.
1640
81.1k
  if( bestCS->cost == MAX_DOUBLE )
1641
58.0k
  {
1642
58.0k
    bestCS->costDbOffset = 0;
1643
58.0k
  }
1644
1645
81.1k
  if( tempCS->cus.size() > 0 && modeTypeParent == MODE_TYPE_ALL && modeTypeChild == MODE_TYPE_INTER )
1646
0
  {
1647
0
    int areaSizeNoResiCu = 0;
1648
0
    for( int k = 0; k < tempCS->cus.size(); k++ )
1649
0
    {
1650
0
      areaSizeNoResiCu += (tempCS->cus[k]->rootCbf == false) ? tempCS->cus[k]->lumaSize().area() : 0;
1651
0
    }
1652
0
    if( areaSizeNoResiCu >= (tempCS->area.lumaSize().area() >> 1) )
1653
0
    {
1654
0
      skipInterPass = true;
1655
0
    }
1656
0
  }
1657
1658
  // RD check for sub partitioned coding structure.
1659
81.1k
  xCheckBestMode( tempCS, bestCS, partitioner, encTestMode, m_EDO );
1660
1661
81.1k
  if( isAffMVInfoSaved )
1662
0
  {
1663
0
    m_cInterSearch.m_AffineProfList->addAffMVInfo(tmpMVInfo);
1664
0
  }
1665
1666
81.1k
  if( !tempCS->slice->isIntra() && isUniMvInfoSaved )
1667
0
  {
1668
0
    m_cInterSearch.m_BlkUniMvInfoBuffer->addUniMvInfo(tmpUniMvInfo);
1669
0
  }
1670
1671
81.1k
  tempCS->motionLut = oldMotionLut;
1672
81.1k
  tempCS->releaseIntermediateData();
1673
81.1k
  tempCS->prevQP[partitioner.chType] = oldPrevQp;
1674
81.1k
}
1675
1676
1677
void EncCu::xCheckRDCostIntra( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode )
1678
100k
{
1679
100k
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTRA, tempCS, partitioner.chType );
1680
1681
100k
  xRestoreStartCtx();
1682
100k
  tempCS->initStructData( encTestMode.qp, false ); // clear motion buffer
1683
1684
100k
  CodingUnit &cu      = tempCS->addCU( CS::getArea( *tempCS, tempCS->area, partitioner.chType, partitioner.treeType ), partitioner.chType );
1685
1686
100k
  partitioner.setCUData( cu );
1687
100k
  cu.slice            = tempCS->slice;
1688
100k
  cu.tileIdx          = m_tileIdx;
1689
100k
  cu.skip             = false;
1690
100k
  cu.mmvdSkip         = false;
1691
100k
  cu.predMode         = MODE_INTRA;
1692
100k
  cu.chromaQpAdj      = m_cuChromaQpOffsetIdxPlus1;
1693
100k
  cu.qp               = encTestMode.qp;
1694
100k
  cu.ispMode          = NOT_INTRA_SUBPARTITIONS;
1695
100k
  cu.initPuData();
1696
1697
100k
  m_cIntraSearch.m_ispTestedModes[0].init(0, 0, 1);
1698
100k
  if (m_pcEncCfg->m_FastIntraTools)
1699
98.3k
  {
1700
98.3k
    m_modeCtrl.comprCUCtx->intraWasTested = false;
1701
98.3k
    m_cIntraSearch.m_ispTestedModes[0].relatedCuIsValid = m_modeCtrl.comprCUCtx->relatedCuIsValid;
1702
98.3k
    if (!bestCS->cus.empty())
1703
26.8k
    {
1704
26.8k
      if ((bestCS->cus[0]->mergeFlag || bestCS->cus[0]->imv || bestCS->cus[0]->affine) && (!bestCS->cus[0]->ciip))
1705
26.8k
      {
1706
26.8k
        m_cIntraSearch.m_ispTestedModes[0].bestBefore[0] = -1;
1707
26.8k
      }
1708
26.8k
    }
1709
98.3k
    if (!bestCS->slice->isIntra())
1710
0
    {
1711
0
      const Position posBL = cu.Y().bottomLeft();
1712
0
      const Position posTR = cu.Y().topRight();
1713
0
      for (int i = 0; i < 2; i++)
1714
0
      {
1715
0
        const CodingUnit* neigh = i ? cu.cs->getCURestricted(posTR.offset(0, -1), cu, CH_L) :cu.cs->getCURestricted(posBL.offset(-1, 0), cu, CH_L);
1716
0
        m_cIntraSearch.m_ispTestedModes[0].bestBefore[i+1] = -1;
1717
0
        if (neigh != nullptr)
1718
0
        {
1719
0
          int bestMode = neigh->firstTU->mtsIdx[0] ? 4 : 0;
1720
0
          bestMode |= neigh->lfnstIdx ? 2 : 0;
1721
0
          bestMode |= neigh->ispMode ? 1 : 0;
1722
0
          m_cIntraSearch.m_ispTestedModes[0].bestBefore[i+1] = bestMode;
1723
0
        }
1724
0
      }
1725
0
    }
1726
98.3k
  }
1727
1728
100k
  tempCS->interHad    = m_modeCtrl.comprCUCtx->interHad;
1729
100k
  double maxCostAllowedForChroma = MAX_DOUBLE;
1730
100k
  if( isLuma( partitioner.chType ) )
1731
30.0k
  {
1732
30.0k
    if (!tempCS->slice->isIntra() && bestCS)
1733
0
    {
1734
0
      m_cIntraSearch.estIntraPredLumaQT(cu, partitioner, bestCS->cost);
1735
0
    }
1736
30.0k
    else
1737
30.0k
    {
1738
30.0k
      m_cIntraSearch.estIntraPredLumaQT(cu, partitioner);
1739
30.0k
    }
1740
30.0k
    if (m_pcEncCfg->m_FastIntraTools)
1741
30.0k
    {
1742
30.0k
      if (m_cIntraSearch.m_ispTestedModes[0].intraWasTested)
1743
30.0k
      {
1744
30.0k
        m_modeCtrl.comprCUCtx->intraWasTested = m_cIntraSearch.m_ispTestedModes[0].intraWasTested;
1745
30.0k
      }
1746
30.0k
    }
1747
1748
30.0k
    if( !partitioner.isSepTree( *tempCS ) )
1749
0
    {
1750
0
      tempCS->lumaCost = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
1751
      // Without EDO the luma cost is a lower bound of the final cost (chroma and the CU's remaining bits only add to
1752
      // it): a test whose luma cost already reaches the best cost cannot win, so its chroma and tail are skipped.
1753
      // With EDO the winner test adds both CUs' deblocking offsets (EncModeCtrl::useModeResult), which still lets
1754
      // some of these tests win, so the full test stays there.
1755
0
      if( !m_EDO && bestCS && bestCS->cost < MAX_DOUBLE && tempCS->lumaCost >= bestCS->cost )
1756
0
      {
1757
0
        xSetStartCtx();
1758
0
        return;
1759
0
      }
1760
0
    }
1761
30.0k
    if (m_pcEncCfg->m_usePbIntraFast && tempCS->dist == MAX_DISTORTION && tempCS->interHad == 0)
1762
0
    {
1763
      // JEM assumes only perfect reconstructions can from now on beat the inter mode
1764
0
      m_modeCtrl.comprCUCtx->interHad = 0;
1765
0
      return;
1766
0
    }
1767
30.0k
  }
1768
1769
100k
  if( tempCS->area.chromaFormat != CHROMA_400 && ( partitioner.chType == CH_C || !CU::isSepTree(cu) ) )
1770
68.2k
  {
1771
68.2k
    bool useIntraSubPartitions = cu.ispMode != NOT_INTRA_SUBPARTITIONS;
1772
68.2k
    Partitioner subTuPartitioner = partitioner;
1773
68.2k
    if ((m_pcEncCfg->m_ISP >= 3) && (!partitioner.isSepTree(*tempCS) && useIntraSubPartitions))
1774
0
    {
1775
0
      maxCostAllowedForChroma = bestCS->cost < MAX_DOUBLE ? bestCS->cost - tempCS->lumaCost : MAX_DOUBLE;
1776
0
    }
1777
68.2k
    m_cIntraSearch.estIntraPredChromaQT(
1778
68.2k
      cu, (!useIntraSubPartitions || (CU::isSepTree(cu) && !isLuma(CH_C))) ? partitioner : subTuPartitioner,
1779
68.2k
      maxCostAllowedForChroma);
1780
68.2k
    if ((m_pcEncCfg->m_ISP >= 3) && useIntraSubPartitions && !cu.ispMode)
1781
0
    {
1782
0
      return;
1783
0
    }
1784
68.2k
  }
1785
1786
100k
  cu.rootCbf = false;
1787
1788
395k
  for (uint32_t t = 0; t < getNumberValidTBlocks(*cu.cs->pcv); t++)
1789
294k
  {
1790
294k
    cu.rootCbf |= cu.firstTU->cbf[t] != 0;
1791
294k
  }
1792
1793
  // Get total bits for current mode: encode CU
1794
100k
  m_CABACEstimator->resetBits();
1795
1796
100k
  if ((!cu.cs->slice->isIntra() || cu.cs->slice->sps->IBC) && cu.Y().valid())
1797
30.0k
  {
1798
30.0k
    m_CABACEstimator->cu_skip_flag(cu);
1799
30.0k
  }
1800
100k
  m_CABACEstimator->pred_mode(cu);
1801
100k
  m_CABACEstimator->cu_pred_data(cu);
1802
1803
  // Encode Coefficients; luma's residual as the luma search counted it, where it can
1804
100k
  const IntraSearch::LumaResi* lumaResi = isLuma( partitioner.chType ) ? m_cIntraSearch.takeLumaResiOfSearch( cu ) : nullptr;
1805
100k
  const uint64_t resiBits[MAX_NUM_TBLOCKS] = { lumaResi ? lumaResi->bits : CABACWriter::TU_RESI_BITS_UNKNOWN,
1806
100k
                                               CABACWriter::TU_RESI_BITS_UNKNOWN, CABACWriter::TU_RESI_BITS_UNKNOWN };
1807
100k
  m_CABACEstimator->setTuResiBits( lumaResi ? resiBits : nullptr, lumaResi ? &lumaResi->flags : nullptr );
1808
100k
  CUCtx cuCtx;
1809
100k
  cuCtx.isDQPCoded = true;
1810
100k
  cuCtx.isChromaQpAdjCoded = true;
1811
100k
  m_CABACEstimator->cu_residual(cu, partitioner, cuCtx);
1812
100k
  m_CABACEstimator->setTuResiBits( nullptr );
1813
1814
100k
  tempCS->fracBits = m_CABACEstimator->getEstFracBits();
1815
100k
  tempCS->cost = m_cRdCost.calcRdCost(tempCS->fracBits, tempCS->dist);
1816
1817
100k
  xEncodeDontSplit(*tempCS, partitioner);
1818
1819
100k
  xCheckDQP(*tempCS, partitioner);
1820
1821
100k
  if( m_EDO )
1822
98.3k
  {
1823
98.3k
    xCalDebCost(*tempCS, partitioner);
1824
98.3k
  }
1825
1826
100k
  DTRACE_MODE_COST(*tempCS, m_cRdCost.getLambda(true));
1827
100k
  xCheckBestMode(tempCS, bestCS, partitioner, encTestMode, m_EDO);
1828
1829
100k
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
1830
100k
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
1831
100k
}
1832
1833
void EncCu::xCheckDQP( CodingStructure& cs, Partitioner& partitioner, bool bKeepCtx )
1834
203k
{
1835
203k
  if( !cs.pps->useDQP )
1836
0
  {
1837
0
    return;
1838
0
  }
1839
1840
203k
  if (partitioner.isSepTree(cs) && isChroma(partitioner.chType))
1841
114k
  {
1842
114k
    return;
1843
114k
  }
1844
1845
88.3k
  if( !partitioner.currQgEnable() ) // do not consider split or leaf/not leaf QG condition (checked by caller)
1846
79.5k
  {
1847
79.5k
    return;
1848
79.5k
  }
1849
1850
8.81k
  CodingUnit* cuFirst = cs.getCU( partitioner.chType, partitioner.treeType );
1851
1852
8.81k
  CHECK( bKeepCtx && cs.cus.size() <= 1 && partitioner.getImplicitSplit( cs ) == CU_DONT_SPLIT, "bKeepCtx should only be set in split case" );
1853
8.81k
  CHECK( !bKeepCtx && cs.cus.size() > 1, "bKeepCtx should never be set for non-split case" );
1854
8.81k
  CHECK( !cuFirst, "No CU available" );
1855
1856
8.81k
  bool hasResidual = false;
1857
8.81k
  for( const auto &cu : cs.cus )
1858
24.2k
  {
1859
    //not include the chroma CU because chroma CU is decided based on corresponding luma QP and deltaQP is not signaled at chroma CU
1860
24.2k
    if( cu->rootCbf && !isChroma( cu->chType ))
1861
1.43k
    {
1862
1.43k
      hasResidual = true;
1863
1.43k
      break;
1864
1.43k
    }
1865
24.2k
  }
1866
1867
8.81k
  int predQP = CU::predictQP( *cuFirst, cs.prevQP[partitioner.chType] );
1868
1869
8.81k
  if( hasResidual )
1870
1.43k
  {
1871
1.43k
    TempCtx ctxTemp( m_CtxCache );
1872
1.43k
    if( !bKeepCtx ) ctxTemp = SubCtx( Ctx::DeltaQP, m_CABACEstimator->getCtx() );
1873
1874
1.43k
    m_CABACEstimator->resetBits();
1875
1.43k
    m_CABACEstimator->cu_qp_delta( *cuFirst, predQP, cuFirst->qp );
1876
1877
1.43k
    cs.fracBits += m_CABACEstimator->getEstFracBits(); // dQP bits
1878
1.43k
    cs.cost      = m_cRdCost.calcRdCost(cs.fracBits, cs.dist);
1879
1880
1881
1.43k
    if( !bKeepCtx ) m_CABACEstimator->getCtx() = SubCtx( Ctx::DeltaQP, ctxTemp );
1882
1883
    // NOTE: reset QPs for CUs without residuals up to first coded CU
1884
1.43k
    for( const auto &cu : cs.cus )
1885
1.44k
    {
1886
      //not include the chroma CU because chroma CU is decided based on corresponding luma QP and deltaQP is not signaled at chroma CU
1887
1.44k
      if( cu->rootCbf && !isChroma( cu->chType ))
1888
1.43k
      {
1889
1.43k
        break;
1890
1.43k
      }
1891
5
      cu->qp = predQP;
1892
5
    }
1893
1.43k
  }
1894
7.38k
  else
1895
7.38k
  {
1896
    // No residuals: reset CU QP to predicted value
1897
7.38k
    for( const auto &cu : cs.cus )
1898
22.8k
    {
1899
22.8k
      cu->qp = predQP;
1900
22.8k
    }
1901
7.38k
  }
1902
8.81k
}
1903
1904
CodingUnit *EncCu::getCuForInterPrediction( CodingStructure *cs, const EncTestMode& encTestMode )
1905
0
{
1906
0
  CodingUnit *cu = cs->getCU( CH_L, TREE_D );
1907
1908
0
  if( cu == nullptr )
1909
0
  {
1910
0
    CHECK( cs->getCU( CH_L, TREE_D ) != nullptr, "Wrong CU/PU setting in CS" );
1911
0
    cu = &cs->addCU( cs->area, CH_L );
1912
0
  }
1913
1914
0
  cu->slice       = cs->slice;
1915
0
  cu->tileIdx     = m_tileIdx;
1916
0
  cu->skip        = false;
1917
0
  cu->mmvdSkip    = false;
1918
0
  cu->mmvdMergeFlag
1919
0
                  = false;
1920
0
  cu->geo         = false;
1921
0
  cu->predMode    = MODE_INTER;
1922
0
  cu->chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
1923
0
  cu->qp          = encTestMode.qp;
1924
0
  cu->affine      = false;
1925
0
  cu->multiRefIdx = 0;
1926
0
  cu->mipFlag     = false;
1927
0
  cu->ciip        = false;
1928
1929
0
  return cu;
1930
0
}
1931
1932
int getDmvrMvdNum( const CodingUnit &cu )
1933
0
{
1934
0
  const int dx = std::max<int>( cu.lwidth()  >> DMVR_SUBCU_SIZE_LOG2, 1 );
1935
0
  const int dy = std::max<int>( cu.lheight() >> DMVR_SUBCU_SIZE_LOG2, 1 );
1936
0
  return dx * dy;
1937
0
}
1938
1939
void EncCu::xCheckRDCostUnifiedMerge( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, EncTestMode &encTestMode )
1940
0
{
1941
0
  const Slice &slice = *tempCS->slice;
1942
1943
0
  CHECK( slice.sliceType == VVENC_I_SLICE, "Merge modes not available for I-slices" );
1944
1945
0
  tempCS->initStructData( encTestMode.qp );
1946
1947
0
  MergeCtx          mergeCtx, gpmMergeCtx;
1948
0
  AffineMergeCtx    affineMergeCtx;
1949
0
  GeoComboCostList &comboList = m_comboList;
1950
0
  const SPS        &sps       = *tempCS->sps;
1951
1952
0
  if( sps.SbtMvp )
1953
0
  {
1954
0
    const Size bufSize           = g_miScaling.scale( tempCS->area.lumaSize() );
1955
0
    affineMergeCtx.subPuMvpMiBuf = MotionBuf        ( m_subPuMiBuf, bufSize );
1956
0
  }
1957
1958
0
  m_mergeBestSATDCost = MAX_DOUBLE;
1959
1960
0
  CodingUnit *cu = getCuForInterPrediction( tempCS, encTestMode );
1961
0
  partitioner.setCUData            ( *cu );
1962
0
  CU::getInterMergeCandidates      ( *cu, mergeCtx, 0 );
1963
0
  if( sps.MMVD )
1964
0
    CU::getInterMMVDMergeCandidates( *cu, mergeCtx );
1965
1966
0
  bool sameMV[MRG_MAX_NUM_CANDS] = { false, };
1967
0
  if( m_pcEncCfg->m_useFastMrg >= 2 )
1968
0
  {
1969
0
    for( int m = 0; m < mergeCtx.numValidMergeCand - 1; m++ )
1970
0
    {
1971
0
      if( !sameMV[m] )
1972
0
      {
1973
0
        for( int n = m + 1; n < mergeCtx.numValidMergeCand; n++ )
1974
0
        {
1975
0
          sameMV[n] |= mergeCtx.mvFieldNeighbours[m][0] == mergeCtx.mvFieldNeighbours[n][0]
1976
0
                    && mergeCtx.mvFieldNeighbours[m][1] == mergeCtx.mvFieldNeighbours[n][1];
1977
0
        }
1978
0
      }
1979
0
    }
1980
0
  }
1981
1982
0
  MergeBufVector mrgPredBufNoCiip;
1983
0
  MergeBufVector geoBuffer;
1984
0
  const double  sqrtLambdaForFirstPass = m_cRdCost.getMotionLambda() * FRAC_BITS_SCALE;
1985
1986
0
  const UnitArea localUnitArea( cu->chromaFormat, Area( 0, 0, cu->Y().width, cu->Y().height ) );
1987
0
  for( int i = 0; i < mergeCtx.numValidMergeCand; i++ )
1988
0
  {
1989
0
    mrgPredBufNoCiip.push_back( m_acMergeTmpBuffer[i].getCompactBuf( localUnitArea ) );
1990
0
  }
1991
1992
0
  int numMergeSatdCand = std::min( bestCS->area.lumaSize().area() >= 64 ? m_pcEncCfg->m_mergeRdCandQuotaRegular : m_pcEncCfg->m_mergeRdCandQuotaRegularSmallBlk, mergeCtx.numValidMergeCand );
1993
1994
0
  bool isCiipEnabled  = sps.CIIP && bestCS->area.lumaSize().area() >= 64 && bestCS->area.lumaSize().maxDim() < MAX_CU_SIZE;
1995
0
       isCiipEnabled &= m_pcEncCfg->m_CIIP <= 1 || !m_modeCtrl.getBlkInfo( tempCS->area ).isSkip; //5
1996
1997
0
  if( isCiipEnabled )
1998
0
  {
1999
0
    numMergeSatdCand += std::min( m_pcEncCfg->m_mergeRdCandQuotaCiip, mergeCtx.numValidMergeCand );
2000
0
  }
2001
2002
0
  const bool affineMrgAvail = ( m_pcEncCfg->m_Affine <= 2 || slice.TLayer <= 3 || m_pcEncCfg->m_SbTMVP )
2003
0
                           && ( m_pcEncCfg->m_Affine || sps.SbtMvp ) && m_pcEncCfg->m_maxNumAffineMergeCand && bestCS->area.Y().minDim() >= 8;
2004
2005
0
  if( affineMrgAvail )
2006
0
  {
2007
0
    CU::getAffineMergeCand( *cu, affineMergeCtx );
2008
0
    numMergeSatdCand += std::min( m_pcEncCfg->m_mergeRdCandQuotaSubBlk, affineMergeCtx.numValidMergeCand );
2009
0
  }
2010
2011
0
  int numSatdCandPreGeo = std::min( numMergeSatdCand, m_pcEncCfg->m_maxMergeRdCandNumTotal );
2012
0
  bool toAddGpmCand     = false;
2013
0
  if( sps.GEO && slice.isInterB() // base checks
2014
0
      && cu->lumaSize().minDim() >= GEO_MIN_CU_SIZE  && cu->lumaSize().maxDim() <= GEO_MAX_CU_SIZE && cu->lumaSize().maxDim() < 8 * cu->lumaSize().minDim() // size checks
2015
0
      && !( m_pcEncCfg->m_Geo > 2 && slice.TLayer <= 1 ) ) // speedups
2016
0
  {
2017
0
    cu->mergeFlag            = true;
2018
0
    cu->geo                  = true;
2019
0
    CU::getGeoMergeCandidates( *cu, gpmMergeCtx );
2020
0
    toAddGpmCand             = prepareGpmComboList( gpmMergeCtx, localUnitArea, sqrtLambdaForFirstPass, comboList, geoBuffer, *cu );
2021
0
    numMergeSatdCand        += toAddGpmCand ? std::min( m_pcEncCfg->m_mergeRdCandQuotaGpm, ( int ) comboList.list.size() ) : 0;
2022
0
  }
2023
2024
0
  numMergeSatdCand  = std::min( numMergeSatdCand, m_pcEncCfg->m_maxMergeRdCandNumTotal );
2025
2026
  // 1. Pass: get SATD-cost for selected candidates and reduce their count
2027
0
  m_mergeItemList.resetList( numMergeSatdCand );
2028
  // until the RD pass below, only xCalcPuMeBits codes, and only merge contexts: save and restore those, not the store
2029
0
  xRestoreStartCtx();
2030
0
  const TempCtx ctxStart   ( m_CtxCache, SubCtx( Ctx::MergeData, m_CABACEstimator->getCtx() ) );
2031
0
  const DFunc   dfunc      = encTestMode.lossless ? DF_SAD : ( m_pcEncCfg->m_fastHad ? DF_HAD_fast : DF_HAD );
2032
0
  DistParam     distParam  = m_cRdCost.setDistParam( tempCS->getOrgBuf().Y(), tempCS->getOrgBuf().Y(), sps.bitDepths[CH_L], dfunc );
2033
0
  m_uiSadBestForQPA        = MAX_DISTORTION;
2034
2035
0
  addRegularCandsToPruningList( mergeCtx, localUnitArea, sqrtLambdaForFirstPass, ctxStart, distParam, *cu, sameMV, mrgPredBufNoCiip );
2036
2037
  // add CIIP candidates directly after adding regular cands
2038
0
  if( isCiipEnabled )
2039
0
  {
2040
0
    addCiipCandsToPruningList( mergeCtx, localUnitArea, sqrtLambdaForFirstPass, ctxStart, distParam, *cu, sameMV );
2041
0
  }
2042
2043
0
  if( sps.MMVD && !!m_mergeItemList.size() && !( m_pcEncCfg->m_useFastMrg >= 2 && m_mergeItemList.size() <= 1 ) )
2044
0
  {
2045
    // With MMVD 1 most MMVD candidates are dropped: their SATD may stop once the cost reaches the drop threshold. Not with
2046
    // fast MMVD (MMVD > 1), which costs mostly the candidates near the best offset's cost, so almost none could stop; not the
2047
    // lossless SAD; not below 512 samples, where the HAD has too few rows of tiles to pay for the check.
2048
0
    const bool useStop = m_pcEncCfg->m_MMVD == 1 && !encTestMode.lossless && cu->lwidth() * cu->lheight() >= 512;
2049
0
    DistParam  stopDistParam;
2050
0
    if( useStop )
2051
0
    {
2052
0
      stopDistParam = m_cRdCost.setDistParam( tempCS->getOrgBuf().Y(), tempCS->getOrgBuf().Y(), sps.bitDepths[CH_L],
2053
0
                                              m_pcEncCfg->m_fastHad ? DF_HAD_STOP_fast : DF_HAD_STOP );
2054
0
    }
2055
0
    addMmvdCandsToPruningList( mergeCtx, localUnitArea, sqrtLambdaForFirstPass, ctxStart, distParam, useStop ? &stopDistParam : nullptr, *cu );
2056
0
  }
2057
2058
0
  if( affineMergeCtx.numValidMergeCand > 0 )
2059
0
  {
2060
0
    addAffineCandsToPruningList( affineMergeCtx, localUnitArea, sqrtLambdaForFirstPass, ctxStart, distParam, *cu );
2061
0
  }
2062
2063
0
  if( m_pcEncCfg->m_useFastMrg > 0 && m_mergeItemList.size() > 0 )
2064
0
  {
2065
0
    m_mergeBestSATDCost    = m_mergeItemList.getMergeItemInList( 0 )->cost;
2066
0
    const double threshold = m_mergeBestSATDCost * MRG_FAST_RATIO[tempCS->picture->useFastMrg];
2067
0
    const   int shrinkSize = std::min( numSatdCandPreGeo, ( int ) updateRdCheckingNum( m_mergeItemList, threshold, numMergeSatdCand ) );
2068
0
    m_mergeItemList        . shrinkList( shrinkSize );
2069
0
  }
2070
0
  else
2071
0
  {
2072
0
    m_mergeItemList        . shrinkList( numSatdCandPreGeo );
2073
0
  }
2074
2075
0
  if( toAddGpmCand )
2076
0
  {
2077
0
    addGpmCandsToPruningList( gpmMergeCtx, localUnitArea, sqrtLambdaForFirstPass, ctxStart, comboList, geoBuffer, distParam, *cu );
2078
0
  }
2079
2080
0
  if(    m_pcEncCfg->m_internalUsePerceptQPATempFiltISlice == 2 && m_uiSadBestForQPA < MAX_DISTORTION && slice.TLayer == 0 // non-Intra key-frame
2081
0
      && m_pcEncCfg->m_salienceBasedOpt
2082
0
      && m_pcEncCfg->m_usePerceptQPA && partitioner.currQgEnable() && partitioner.currSubdiv == 0 ) // CTU-level luma quantization group
2083
0
  {
2084
0
    CHECK( bestCS->cost < MAX_DOUBLE, "This has to be the first test performed!" );
2085
2086
0
    const Picture *pic         = slice.pic;
2087
0
    const bool     isBIM       = m_pcEncCfg->m_RCNumPasses != 2 && m_pcEncCfg->hasBlockQpOffsets() && !pic->m_picShared->m_ctuBimQpOffset.empty();
2088
0
    const uint32_t rsAddr      = getCtuAddr( partitioner.currQgPos, *pic->cs->pcv );
2089
0
    const int      pumpReducQP = BitAllocation::getCtuPumpingReducingQP( &slice, tempCS->getOrgBuf( COMP_Y ), m_uiSadBestForQPA, *m_globalCtuQpVector, rsAddr,
2090
0
                                                                         m_pcEncCfg->m_QP, isBIM );
2091
2092
0
    if( pumpReducQP != 0 ) // subtract QP offset, reduces Intra-period pumping or overcoding
2093
0
    {
2094
0
      const int minQP = BitAllocation::getMinAdaptedQP( &slice, m_pcEncCfg );
2095
0
      encTestMode.qp = Clip3( minQP, MAX_QP, encTestMode.qp - pumpReducQP );
2096
0
      tempCS->currQP[partitioner.chType] = tempCS->baseQP =
2097
0
      bestCS->currQP[partitioner.chType] = bestCS->baseQP = Clip3( minQP, MAX_QP, tempCS->baseQP - pumpReducQP );
2098
2099
0
      updateLambda( slice, pic->ctuQpaLambda[rsAddr], pic->ctuAdaptedQP[rsAddr], tempCS->baseQP, true );
2100
0
    }
2101
0
  }
2102
2103
  // Try to limit number of candidates using SATD-costs
2104
0
  if( m_pcEncCfg->m_useFastMrg > 0 && m_mergeItemList.size() > 0 )
2105
0
  {
2106
    // shrink GEO list as well
2107
0
    const double threshold = m_mergeItemList.getMergeItemInList( 0 )->cost * MRG_FAST_RATIO[0];
2108
0
    numMergeSatdCand       = updateRdCheckingNum( m_mergeItemList, threshold, numMergeSatdCand );
2109
0
    m_mergeBestSATDCost    = m_mergeItemList.size() != 0 ? m_mergeItemList.getMergeItemInList( 0 )->cost : MAX_DOUBLE;
2110
0
  }
2111
0
  else
2112
0
  {
2113
0
    numMergeSatdCand       = std::min<int>( numMergeSatdCand, ( int ) m_mergeItemList.size() );
2114
0
  }
2115
2116
  // 2. Pass: RD checking 
2117
0
  tempCS->initStructData( encTestMode.qp );
2118
0
  m_CABACEstimator->getCtx() = SubCtx( Ctx::MergeData, ctxStart );
2119
2120
0
  double bestEndCost                            =   MAX_DOUBLE;
2121
0
  bool bestIsSkip                               =   false;
2122
0
  PelUnitBuf ciipBuf                            =   m_aTmpStorageLCU[1].getCompactBuf( *cu );
2123
0
  bool ciipChromaDone                           =   false;
2124
0
  bool isRegularTestedAsSkip[MRG_MAX_NUM_CANDS] = { false, };
2125
0
  bool geoWasTested                             =   false;
2126
0
  bool geoChromaReady[GEO_MAX_NUM_UNI_CANDS]    = { false, };
2127
0
  int  stopCand                                 =   numMergeSatdCand;
2128
2129
0
  CHECK( numMergeSatdCand > 0 && m_mergeItemList.size() == 0, "Empty merge item list is not expected" );
2130
2131
0
  for( uint32_t noResidualPass = 0; noResidualPass < 2; noResidualPass++ )
2132
0
  {
2133
0
    const bool forceNoResidual = noResidualPass == 1;
2134
0
    for( uint32_t mrgHadIdx = 0; mrgHadIdx < stopCand; mrgHadIdx++ )
2135
0
    {
2136
0
      auto mergeItem = m_mergeItemList.getMergeItemInList( mrgHadIdx );
2137
0
      CHECK( mergeItem == nullptr, "Wrong merge item" );
2138
2139
0
      const bool isCiip = mergeItem->mergeItemType == MergeItem::MergeItemType::CIIP;
2140
0
      const bool isGeo  = mergeItem->mergeItemType == MergeItem::MergeItemType::GPM;
2141
0
      const bool isRglr = mergeItem->mergeItemType == MergeItem::MergeItemType::REGULAR;
2142
0
      const bool isMmvd = mergeItem->mergeItemType == MergeItem::MergeItemType::MMVD;
2143
2144
0
      if( noResidualPass != 0 && isCiip && isRegularTestedAsSkip[mergeItem->mergeIdx] )
2145
0
      {
2146
0
        continue;
2147
0
      }
2148
2149
0
      if( noResidualPass ? mergeItem->noResidual : bestIsSkip )
2150
0
      {
2151
0
        continue;
2152
0
      }
2153
2154
0
      if( isGeo )
2155
0
      {
2156
0
        if( m_pcEncCfg->m_Geo > 2 && geoWasTested && !bestCS->cus.empty() && !bestCS->getCU( partitioner.chType, partitioner.treeType )->geo )
2157
0
        {
2158
0
          continue;
2159
0
        }
2160
2161
0
        geoWasTested = true;
2162
2163
        // The first pass compared only luma, and few candidates get this far.
2164
0
        uint8_t      splitDir;
2165
0
        MergeIdxPair geoMergeIdx;
2166
0
        MergeItem::updateGpmIdx( mergeItem->mergeIdx, splitDir, geoMergeIdx );
2167
0
        for( const int mergeCand : geoMergeIdx )
2168
0
        {
2169
0
          if( !geoChromaReady[mergeCand] )
2170
0
          {
2171
0
            generateGeoCandChroma( tempCS, partitioner, encTestMode, gpmMergeCtx, mergeCand, geoBuffer[mergeCand] );
2172
0
            geoChromaReady[mergeCand] = true;
2173
0
          }
2174
0
        }
2175
0
      }
2176
2177
0
      cu = getCuForInterPrediction( tempCS, encTestMode );
2178
0
      partitioner.setCUData( *cu );
2179
0
      const bool resetCiip2Regular = mergeItem->exportMergeInfo( *cu, forceNoResidual, gpmMergeCtx );
2180
2181
0
      if( isRglr || resetCiip2Regular )
2182
0
      {
2183
0
        if( CU::checkDMVRCondition( *cu ) ) std::copy_n( m_subPuMvOffset[mergeItem->mergeIdx].data(), getDmvrMvdNum( *cu ), cu->mvdL0SubPu );
2184
0
      }
2185
2186
0
      if( isMmvd && mergeItem->noBdofRefine )
2187
0
      {
2188
        // no BDOF refinement was made for the luma prediction, need to have luma prediction again
2189
0
        mergeItem->lumaPredReady = false;
2190
0
      }
2191
2192
0
      PelUnitBuf *predBuf1   = nullptr, *predBuf2 = isCiip ? &ciipBuf : nullptr;
2193
0
      PelUnitBuf  dstPredBuf = tempCS->getPredBuf();
2194
2195
0
      if( isGeo )
2196
0
      {
2197
0
        predBuf1 = &geoBuffer[cu->geoMergeIdx[0]];
2198
0
        predBuf2 = &geoBuffer[cu->geoMergeIdx[1]];
2199
0
      }
2200
2201
0
      if( resetCiip2Regular )
2202
0
      {
2203
        // the pruning pass predicted only the luma of the regular candidate
2204
0
        dstPredBuf.copyFrom( mrgPredBufNoCiip[mergeItem->mergeIdx], true, false );
2205
0
        const uint8_t mcControl = cu->mcControl;
2206
0
        cu->mcControl = 4;
2207
0
        cu->mvRefine  = true;
2208
0
        m_cInterSearch.motionCompensation( *cu, dstPredBuf, REF_PIC_LIST_X );
2209
0
        cu->mvRefine  = false;
2210
0
        cu->mcControl = mcControl;
2211
0
      }
2212
0
      else
2213
0
      {
2214
0
        if( isCiip && !resetCiip2Regular && isChromaEnabled( cu->chromaFormat ) && cu->chromaSize().width > 2 )
2215
0
        {
2216
0
          if( !ciipChromaDone )
2217
0
          {
2218
0
            cu->intraDir[0] = PLANAR_IDX;
2219
0
            cu->intraDir[1] = DM_CHROMA_IDX;
2220
2221
0
            m_cIntraSearch  . initIntraPatternChType( *cu, cu->Cb() );
2222
0
            m_cIntraSearch  . predIntraAng          ( COMP_Cb, ciipBuf.Cb(), *cu );
2223
0
            m_cIntraSearch  . initIntraPatternChType( *cu, cu->Cr() );
2224
0
            m_cIntraSearch  . predIntraAng          ( COMP_Cr, ciipBuf.Cr(), *cu );
2225
2226
0
            ciipChromaDone  = true;
2227
0
          }
2228
0
        }
2229
2230
0
        if(  mergeItem->lumaPredReady ||  mergeItem->chromaPredReady )
2231
0
          dstPredBuf.copyFrom( mergeItem->getPredBuf( localUnitArea ), mergeItem->lumaPredReady, mergeItem->chromaPredReady );
2232
0
        if( !mergeItem->lumaPredReady || !mergeItem->chromaPredReady )
2233
0
          generateMergePrediction( localUnitArea, mergeItem, *cu, !mergeItem->lumaPredReady, !mergeItem->chromaPredReady, dstPredBuf, true, forceNoResidual, predBuf1, predBuf2 );
2234
0
      }
2235
2236
0
      if( !cu->mmvdSkip && !cu->ciip && !cu->affine && !cu->geo && noResidualPass != 0 )
2237
0
      {
2238
0
        CHECK( mergeItem->mergeIdx >= mergeCtx.numValidMergeCand, "out of normal merge" );
2239
0
        isRegularTestedAsSkip[mergeItem->mergeIdx] = true;
2240
0
      }
2241
2242
0
      xEncodeInterResidual( tempCS, bestCS, partitioner, encTestMode, noResidualPass, noResidualPass == 0 ? &mergeItem->noResidual : nullptr );
2243
2244
0
      if( m_pcEncCfg->m_useFastMrg >= 2 )
2245
0
      {
2246
0
        if( cu->ciip && bestCS->cost == MAX_DOUBLE && mrgHadIdx + 1 == numMergeSatdCand )
2247
0
        {
2248
0
          numMergeSatdCand = ( unsigned ) m_mergeItemList.size();
2249
0
        }
2250
      
2251
0
        if( mrgHadIdx > 0 && tempCS->cost >= bestEndCost && !cu->ciip && !isGeo )
2252
0
        {
2253
0
          stopCand = mrgHadIdx + 1;
2254
0
        }
2255
      
2256
0
        if( noResidualPass == 0 )
2257
0
        {
2258
0
          bestEndCost = std::min( bestEndCost, tempCS->cost );
2259
0
        }
2260
0
      }
2261
2262
0
      if( m_pcEncCfg->m_useFastDecisionForMerge && !bestIsSkip && !cu->ciip )
2263
0
      {
2264
0
        bestIsSkip = !bestCS->cus.empty() && bestCS->getCU( partitioner.chType, partitioner.treeType )->rootCbf == 0;
2265
0
      }
2266
2267
0
      tempCS->initStructData( encTestMode.qp );
2268
0
    }   // end loop mrgHadIdx
2269
0
  }
2270
0
}
2271
2272
unsigned int EncCu::updateRdCheckingNum( MergeItemList &mergeItemList, double threshold, unsigned int numMergeSatdCand )
2273
0
{
2274
0
  for( uint32_t i = 0; i < mergeItemList.size(); i++ )
2275
0
  {
2276
0
    const auto mergeItem = mergeItemList.getMergeItemInList( i );
2277
0
    if( mergeItem == nullptr || mergeItem->cost > threshold )
2278
0
    {
2279
0
      numMergeSatdCand = i;
2280
0
      break;
2281
0
    }
2282
0
  }
2283
0
  return std::min( numMergeSatdCand, ( unsigned ) mergeItemList.size() );
2284
0
}
2285
2286
// The CU used here has the state the RD loop's own CU starts from, which clearing the structure brings back.
2287
void EncCu::generateGeoCandChroma( CodingStructure* tempCS, Partitioner& partitioner, const EncTestMode& encTestMode, const MergeCtx& gpmMergeCtx, int mergeCand, PelUnitBuf& geoBuffer )
2288
0
{
2289
0
  CodingUnit* cu = getCuForInterPrediction( tempCS, encTestMode );
2290
0
  partitioner.setCUData( *cu );
2291
0
  cu->geo = true;
2292
0
  gpmMergeCtx.setMergeInfo( *cu, mergeCand );
2293
0
  cu->mcControl = 4;
2294
0
  m_cInterSearch.motionCompensation( *cu, geoBuffer, REF_PIC_LIST_X );
2295
0
  tempCS->initStructData( encTestMode.qp );
2296
0
}
2297
2298
void EncCu::generateMergePrediction( const UnitArea &unitArea, MergeItem *mergeItem, CodingUnit &pu, bool luma, bool chroma,
2299
                                     PelUnitBuf &dstBuf, bool finalRd, bool forceNoResidual, PelUnitBuf *predBuf1, PelUnitBuf *predBuf2 )
2300
0
{
2301
0
  CHECK( ( luma && mergeItem->lumaPredReady ) || ( chroma && mergeItem->chromaPredReady ), "Prediction has been avaiable" );
2302
2303
0
  pu.mcControl = ( !luma ? 4 : 0 ) | ( !chroma ? 2 : 0 );
2304
2305
0
  switch( mergeItem->mergeItemType )
2306
0
  {
2307
0
  case MergeItem::MergeItemType::REGULAR:
2308
    // here predBuf1 is predBufNoCiip
2309
0
    pu.mvRefine = true;
2310
0
    m_cInterSearch.motionCompensation( pu, dstBuf, REF_PIC_LIST_X );
2311
0
    pu.mvRefine = false;
2312
0
    if( predBuf1 != nullptr )
2313
0
    {
2314
0
      predBuf1->copyFrom( dstBuf, luma, chroma );
2315
0
    }
2316
0
    break;
2317
2318
0
  case MergeItem::MergeItemType::CIIP:
2319
0
    m_cInterSearch.motionCompensation( pu, dstBuf, REF_PIC_LIST_X );
2320
2321
0
    if( luma )
2322
0
    {
2323
      // generate intrainter Y prediction
2324
0
      dstBuf.Y().weightCiip( predBuf2->Y(), mergeItem->numCiipIntra );
2325
0
    }
2326
2327
0
    if( chroma )
2328
0
    {
2329
0
      if( pu.chromaSize().width > 2 )
2330
0
      {
2331
0
        dstBuf.Cb().weightCiip( predBuf2->Cb(), mergeItem->numCiipIntra );
2332
0
        dstBuf.Cr().weightCiip( predBuf2->Cr(), mergeItem->numCiipIntra );
2333
0
      }
2334
0
    }
2335
2336
0
    break;
2337
2338
0
  case MergeItem::MergeItemType::MMVD:
2339
0
    pu.mcControl           |= finalRd ? 0 : ( pu.mmvdMergeIdx.pos.step > 2 || m_pcEncCfg->m_MMVD > 1 ) ? 1 : 0;
2340
0
    mergeItem->noBdofRefine = pu.mccNoBdof() && pu.cs->sps->BDOF && !pu.cs->picHeader->disBdofFlag;
2341
0
    m_cInterSearch.motionCompensation( pu, dstBuf, REF_PIC_LIST_X );
2342
0
    break;
2343
2344
0
  case MergeItem::MergeItemType::SBTMVP:
2345
0
    m_cInterSearch.motionCompensation( pu, dstBuf, REF_PIC_LIST_X );
2346
0
    break;
2347
2348
0
  case MergeItem::MergeItemType::AFFINE:
2349
0
    m_cInterSearch.motionCompensation( pu, dstBuf, REF_PIC_LIST_X );
2350
0
    break;
2351
2352
0
  case MergeItem::MergeItemType::GPM:
2353
    // here predBuf1 and predBuf2 point to geoBuffer[mergeCand0] and geoBuffer[mergeCand1], respectively
2354
0
    CHECK( predBuf1 == nullptr || predBuf2 == nullptr, "Invalid input buffer to GPM" );
2355
0
    m_cInterSearch.weightedGeoBlk( pu.slice->clpRngs, pu, pu.geoSplitDir, luma && chroma ? MAX_NUM_CH : luma ? CH_L : CH_C, dstBuf, *predBuf1, *predBuf2 );
2356
0
    break;
2357
2358
0
  default:
2359
0
    THROW("Wrong merge item type");
2360
0
  }
2361
2362
0
  auto mergeItemPredBuf = mergeItem->getPredBuf( unitArea );
2363
2364
0
  if( dstBuf.Y().buf == mergeItemPredBuf.Y().buf )
2365
0
  {
2366
    // dst is the internal buffer
2367
0
    mergeItem->lumaPredReady   |= luma;
2368
0
    mergeItem->chromaPredReady |= chroma;
2369
0
  }
2370
0
  else if( finalRd && !forceNoResidual )
2371
0
  {
2372
    // at final RD stage, with and without residuals are both checked
2373
    // it makes sense to buffer the prediction
2374
0
    mergeItemPredBuf.copyFrom( dstBuf, luma, chroma );
2375
0
    mergeItem->lumaPredReady   |= luma;
2376
0
    mergeItem->chromaPredReady |= chroma;
2377
0
  }
2378
0
}
2379
2380
void EncCu::addRegularCandsToPruningList( const MergeCtx &mergeCtx, const UnitArea &localUnitArea, double sqrtLambdaForFirstPassIntra, const TempCtx &ctxStart,
2381
                                          DistParam& distParam, CodingUnit& pu, bool* sameMv, MergeBufVector& regularPred )
2382
0
{
2383
0
  pu.geo = pu.affine
2384
0
         = pu.mmvdMergeFlag = pu.mmvdSkip
2385
0
         = pu.ciip
2386
0
         = false;
2387
2388
0
  for( uint32_t uiMergeCand = 0; uiMergeCand < mergeCtx.numValidMergeCand; uiMergeCand++ )
2389
0
  {
2390
0
    if( sameMv[uiMergeCand] ) continue;
2391
2392
0
    mergeCtx.setMergeInfo   ( pu, uiMergeCand );
2393
2394
0
    if( m_pcEncCfg->m_ifpLines && // what about DMVR?
2395
0
        ( ( pu.refIdx[L0] >= 0 && !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), pu.mv[L0][0].ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv ) ) ||
2396
0
          ( pu.refIdx[L1] >= 0 && !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), pu.mv[L1][0].ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv ) ) ) )
2397
0
    {
2398
0
      continue;
2399
0
    }
2400
2401
0
    pu.interDir             = mergeCtx.interDirNeighbours[uiMergeCand];
2402
0
    pu.BcwIdx               = pu.interDir == 3 ? mergeCtx.BcwIdx[uiMergeCand] : BCW_DEFAULT;
2403
0
    pu.imv                  = mergeCtx.useAltHpelIf[uiMergeCand] ? IMV_HPEL : IMV_OFF;
2404
2405
0
    MergeItem *regularMerge = m_mergeItemList.allocateNewMergeItem();
2406
0
    regularMerge->importMergeInfo( mergeCtx, uiMergeCand, MergeItem::MergeItemType::REGULAR, pu );
2407
0
    auto dstBuf             = regularMerge->getPredBuf( localUnitArea );
2408
    // The SATD of this pass reads luma only, and most candidates end here. Chroma waits for the RD pass, as with the other merge types.
2409
0
    generateMergePrediction ( localUnitArea, regularMerge, pu, true, false, dstBuf, false, false, &regularPred[uiMergeCand], nullptr );
2410
0
    regularMerge->cost      = calcLumaCost4MergePrediction( ctxStart, dstBuf, sqrtLambdaForFirstPassIntra, pu, distParam );
2411
0
    if( CU::checkDMVRCondition( pu ) ) std::copy_n( pu.mvdL0SubPu, getDmvrMvdNum( pu ), m_subPuMvOffset[uiMergeCand].data() );
2412
0
    m_mergeItemList         . insertMergeItemToList( regularMerge );
2413
0
  }
2414
0
}
2415
2416
void EncCu::addCiipCandsToPruningList( const MergeCtx &mergeCtx, const UnitArea &localUnitArea, double sqrtLambdaForFirstPassIntra, const TempCtx &ctxStart, DistParam &distParam, CodingUnit &pu, bool* sameMv )
2417
0
{
2418
0
  int                numCiipIntra = -1;
2419
0
  PelUnitBuf         ciipBuf      = m_aTmpStorageLCU[1].getCompactBuf( pu );
2420
2421
0
  pu.ciip        = true;
2422
0
  pu.intraDir[0] = PLANAR_IDX;
2423
0
  pu.geo         = pu.affine
2424
0
                 = pu.mmvdMergeFlag = pu.mmvdSkip
2425
0
                 = false;
2426
0
  m_cIntraSearch . initIntraPatternChType        ( pu, pu.Y() );
2427
0
  m_cIntraSearch . predIntraAng                  ( COMP_Y, ciipBuf.Y(), pu );
2428
0
  numCiipIntra   = m_cIntraSearch.getNumIntraCiip( pu );
2429
2430
0
  int nonCiipMrgCnds[MRG_MAX_NUM_CANDS] = { 0, };
2431
0
  int numNonCiipCnds                    =   0;
2432
0
  for( ; numNonCiipCnds < m_mergeItemList.size(); numNonCiipCnds++ ) nonCiipMrgCnds[numNonCiipCnds] = m_mergeItemList.getMergeItemInList( numNonCiipCnds )->mergeIdx;
2433
2434
0
  for( int i = 0; i < numNonCiipCnds; i++ )
2435
0
  {
2436
0
    const unsigned int uiMergeCand = nonCiipMrgCnds[i];
2437
2438
0
    if( sameMv[uiMergeCand] ) continue;
2439
2440
0
    mergeCtx.setMergeInfo     ( pu, uiMergeCand );
2441
2442
0
    if( m_pcEncCfg->m_ifpLines && 
2443
0
        ( ( pu.refIdx[L0] >= 0 && !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), pu.mv[L0][0].ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv ) ) ||
2444
0
          ( pu.refIdx[L1] >= 0 && !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), pu.mv[L1][0].ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv ) ) ) )
2445
0
    {
2446
0
      continue;
2447
0
    }
2448
2449
0
    pu.interDir               = mergeCtx.interDirNeighbours[uiMergeCand];
2450
0
    pu.BcwIdx                 = pu.interDir == 3 ? mergeCtx.BcwIdx[uiMergeCand] : BCW_DEFAULT;
2451
0
    pu.imv                    = mergeCtx.useAltHpelIf[uiMergeCand] ? IMV_HPEL : IMV_OFF;
2452
2453
0
    MergeItem* ciipMerge      = m_mergeItemList.allocateNewMergeItem();
2454
0
    ciipMerge->importMergeInfo( mergeCtx, uiMergeCand, MergeItem::MergeItemType::CIIP, pu );
2455
0
    ciipMerge->numCiipIntra   = numCiipIntra;
2456
0
    auto dstBuf               = ciipMerge->getPredBuf( localUnitArea );
2457
0
    generateMergePrediction   ( localUnitArea, ciipMerge, pu, true, false, dstBuf, false, false, nullptr, &ciipBuf );
2458
0
      ciipMerge->cost         = calcLumaCost4MergePrediction( ctxStart, dstBuf, sqrtLambdaForFirstPassIntra, pu, distParam );
2459
0
    if( !m_mergeItemList      . insertMergeItemToList( ciipMerge ) && m_pcEncCfg->m_CIIP > 1 )
2460
0
    {
2461
0
      break;
2462
0
    }
2463
0
  }
2464
0
}
2465
2466
void EncCu::addMmvdCandsToPruningList( const MergeCtx &mergeCtx, const UnitArea &localUnitArea, double sqrtLambdaForFirstPassIntra, const TempCtx& ctxStart,
2467
                                       DistParam& distParam, DistParam* stopDistParam, CodingUnit& pu )
2468
0
{
2469
0
  pu.mmvdSkip              = true;
2470
0
  pu.affine                = pu.geo
2471
0
                           = pu.ciip
2472
0
                           = false;
2473
2474
0
  int       mmvdTestNum    = mergeCtx.numValidMergeCand > 1 ? MmvdIdx::ADD_NUM : MmvdIdx::ADD_NUM >> 1;
2475
0
  int       bestDir        = 0;
2476
0
  size_t    curListSize    = m_mergeItemList.size();
2477
0
  double    bestCostMerge  = m_mergeItemList.getMergeItemInList( curListSize - 1 )->cost;
2478
0
  double    bestCostOffset = MAX_DOUBLE;
2479
0
  int       shiftCandStart = 0;
2480
2481
0
  if( m_pcEncCfg->m_MMVD == 4 )
2482
0
  {
2483
0
    const int cnd1idx = m_mergeItemList.size() == 1 ? 0 : 1;
2484
0
    const int mrgCnd0 = m_mergeItemList.getMergeItemInList(       0 )->mergeIdx;
2485
0
    const int mrgCnd1 = m_mergeItemList.getMergeItemInList( cnd1idx )->mergeIdx;
2486
2487
0
    if( mrgCnd0 > 1 && mrgCnd1 > 1 )
2488
0
    {
2489
0
      mmvdTestNum = 0;
2490
0
    }
2491
0
    else if( mrgCnd0 > 1 || mrgCnd1 > 1 )
2492
0
    {
2493
0
      int shiftCand = mrgCnd0 < 2 ? mrgCnd0 : mrgCnd1;
2494
2495
0
      if( shiftCand )
2496
0
      {
2497
0
        shiftCandStart = MMVD_MAX_REFINE_NUM;
2498
0
      }
2499
0
      else
2500
0
      {
2501
0
        mmvdTestNum    = MMVD_MAX_REFINE_NUM;
2502
0
      }
2503
0
    }
2504
0
  }
2505
2506
  // A candidate's bits depend on its base and step only: the position costs two bins at equal probability, whichever it is.
2507
0
  uint64_t  fracBitsOfStep[MMVD_BASE_MV_NUM][MMVD_REFINE_STEP];
2508
0
  std::fill_n( &fracBitsOfStep[0][0], MMVD_BASE_MV_NUM * MMVD_REFINE_STEP, std::numeric_limits<uint64_t>::max() );
2509
2510
0
  for( int mmvdMergeCand = shiftCandStart; mmvdMergeCand < mmvdTestNum; mmvdMergeCand++ )
2511
0
  {
2512
0
    MmvdIdx mmvdIdx;
2513
0
    mmvdIdx.val = mmvdMergeCand;
2514
2515
0
    if( mmvdIdx.pos.step >= m_pcEncCfg->m_MmvdDisNum )
2516
0
    {
2517
0
      continue;
2518
0
    }
2519
2520
0
    if( m_pcEncCfg->m_MMVD > 1 )
2521
0
    {
2522
0
      int checkMMVD = xCheckMMVDCand( mmvdIdx, bestDir, mmvdTestNum, bestCostOffset, bestCostMerge, m_mergeItemList.getMergeItemInList( curListSize - 1 )->cost );
2523
0
      mmvdMergeCand = mmvdIdx.val;
2524
2525
0
      if( checkMMVD )
2526
0
      {
2527
0
        if( checkMMVD == 2 )
2528
0
        {
2529
0
          break;
2530
0
        }
2531
0
        continue;
2532
0
      }
2533
0
    }
2534
2535
0
    mergeCtx.setMmvdMergeCandiInfo( pu, mmvdIdx );
2536
2537
0
    if( m_pcEncCfg->m_ifpLines &&
2538
0
        ( ( pu.refIdx[L0] >= 0 && !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), pu.mv[L0][0].ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv ) ) ||
2539
0
          ( pu.refIdx[L1] >= 0 && !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), pu.mv[L1][0].ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv ) ) ) )
2540
0
    {
2541
      // skip candidate
2542
0
      continue;
2543
0
    }
2544
2545
0
    pu.interDir               = mergeCtx.interDirNeighbours[mmvdIdx.pos.baseIdx];
2546
0
    pu.BcwIdx                 = pu.interDir == 3 ? mergeCtx.BcwIdx[mmvdIdx.pos.baseIdx] : BCW_DEFAULT;
2547
0
    pu.imv                    = mergeCtx.useAltHpelIf[mmvdIdx.pos.baseIdx] ? IMV_HPEL : IMV_OFF;
2548
2549
0
    MergeItem *mmvdMerge      = m_mergeItemList.allocateNewMergeItem();
2550
0
    mmvdMerge->importMergeInfo( mergeCtx, mmvdIdx.val, MergeItem::MergeItemType::MMVD, pu );
2551
0
    auto dstBuf               = mmvdMerge->getPredBuf( localUnitArea );
2552
0
    generateMergePrediction   ( localUnitArea, mmvdMerge, pu, true, false, dstBuf, false, false, nullptr, nullptr );
2553
    // a dropped candidate's cost is still compared with the best offset's below
2554
0
    const double dropCost     = m_pcEncCfg->m_MMVD > 1 ? std::max( m_mergeItemList.costToEnter(), bestCostOffset ) : m_mergeItemList.costToEnter();
2555
0
    mmvdMerge->cost           = calcLumaCost4MergePrediction( ctxStart, dstBuf, sqrtLambdaForFirstPassIntra, pu, distParam, &fracBitsOfStep[mmvdIdx.pos.baseIdx][mmvdIdx.pos.step], dropCost, stopDistParam );
2556
0
    m_mergeItemList           . insertMergeItemToList( mmvdMerge );
2557
2558
0
    if( m_pcEncCfg->m_MMVD > 1 && mmvdMerge->cost < bestCostOffset )
2559
0
    {
2560
0
      bestCostOffset          = mmvdMerge->cost;
2561
0
      int CandCur             = mmvdIdx.val - MMVD_MAX_REFINE_NUM * mmvdIdx.pos.baseIdx;
2562
0
      if( CandCur < 4 )
2563
0
        bestDir               = CandCur;
2564
0
    }
2565
0
  }
2566
2567
0
  if( m_pcEncCfg->m_useFastMrg >= 2 )
2568
0
  {
2569
0
    m_mergeItemList           . shrinkList( curListSize );
2570
0
  }
2571
0
}
2572
2573
void EncCu::addAffineCandsToPruningList( AffineMergeCtx &affineMergeCtx, const UnitArea &localUnitArea, double sqrtLambdaForFirstPass,
2574
                                         const TempCtx& ctxStart, DistParam& distParam, CodingUnit& pu)
2575
0
{
2576
0
  bool sameMV[AFFINE_MRG_MAX_NUM_CANDS + 1]
2577
0
                      = { false, };
2578
0
  size_t curListSize  = m_mergeItemList.size();
2579
2580
0
  pu.mergeFlag = true;
2581
0
  pu.affine    = true;
2582
0
  pu.imv       = IMV_OFF;
2583
0
  pu.geo       = pu.mmvdMergeFlag = pu.mmvdSkip
2584
0
               = pu.ciip
2585
0
               = false;
2586
2587
0
  if( m_pcEncCfg->m_Affine > 1 )
2588
0
  {
2589
0
    for( int m = 0; m < affineMergeCtx.numValidMergeCand; m++ )
2590
0
    {
2591
0
      if( pu.cs->slice->TLayer > 3 && affineMergeCtx.mergeType[m] != MRG_TYPE_SUBPU_ATMVP )
2592
0
      {
2593
0
        sameMV[m] = m != 0;
2594
0
      }
2595
0
      else if( !sameMV[m + 1] )
2596
0
      {
2597
0
        for( int n = m + 1; n < affineMergeCtx.numValidMergeCand; n++ )
2598
0
        {
2599
0
          sameMV[n] |= affineMergeCtx.mvFieldNeighbours[m][0][0] == affineMergeCtx.mvFieldNeighbours[n][0][0]
2600
0
                    && affineMergeCtx.mvFieldNeighbours[m][1][0] == affineMergeCtx.mvFieldNeighbours[n][1][0];
2601
0
        }
2602
0
      }
2603
0
    }
2604
0
  }
2605
2606
0
  for( uint32_t mergeIdx = 0; mergeIdx < affineMergeCtx.numValidMergeCand; mergeIdx++ )
2607
0
  {
2608
0
    if( ( affineMergeCtx.mergeType[mergeIdx] != MRG_TYPE_SUBPU_ATMVP && m_pcEncCfg->m_Affine == 0 ) || sameMV[mergeIdx] )
2609
0
    {
2610
0
      continue;
2611
0
    }
2612
2613
0
    pu.mergeType              = affineMergeCtx.mergeType[mergeIdx];
2614
0
    pu.affineType             = affineMergeCtx.affineType[mergeIdx];
2615
0
    pu.interDir               = affineMergeCtx.interDirNeighbours[mergeIdx];
2616
0
    pu.BcwIdx                 = pu.interDir == 3 ? affineMergeCtx.BcwIdx[mergeIdx] : BCW_DEFAULT;
2617
2618
    // generate motion buf for IFP
2619
0
    if( affineMergeCtx.mergeType[mergeIdx] == MRG_TYPE_SUBPU_ATMVP )
2620
0
    {
2621
0
      pu.refIdx[L0]           = affineMergeCtx.mvFieldNeighbours[mergeIdx][L0][0].refIdx;
2622
0
      pu.refIdx[L1]           = affineMergeCtx.mvFieldNeighbours[mergeIdx][L1][0].refIdx;
2623
0
      pu.mv    [L0][0]        = affineMergeCtx.mvFieldNeighbours[mergeIdx][L0][0].mv;
2624
0
      pu.mv    [L1][0]        = affineMergeCtx.mvFieldNeighbours[mergeIdx][L1][0].mv;
2625
0
      CU::spanMotionInfo      ( pu, &affineMergeCtx );
2626
0
    }
2627
0
    else
2628
0
    {
2629
0
      CU::setAllAffineMvField ( pu, affineMergeCtx.mvFieldNeighbours[mergeIdx][L0], L0 );
2630
0
      CU::setAllAffineMvField ( pu, affineMergeCtx.mvFieldNeighbours[mergeIdx][L1], L1 );
2631
0
      CU::spanMotionInfo      ( pu );
2632
0
    }
2633
2634
0
    if( m_pcEncCfg->m_ifpLines && !CU::isMotionBufInRangeFPP( pu, m_pcEncCfg->m_ifpLines ) )
2635
0
    {
2636
0
      continue;
2637
0
    }
2638
2639
0
    MergeItem *mergeItem   = m_mergeItemList.allocateNewMergeItem();
2640
0
    mergeItem->importMergeInfo( affineMergeCtx, mergeIdx, affineMergeCtx.mergeType[mergeIdx] == MRG_TYPE_SUBPU_ATMVP ? MergeItem::MergeItemType::SBTMVP : MergeItem::MergeItemType::AFFINE, pu );
2641
0
    auto dstBuf            = mergeItem->getPredBuf( localUnitArea );
2642
0
    generateMergePrediction( localUnitArea, mergeItem, pu, true, false, dstBuf, false, false, nullptr, nullptr );
2643
0
    mergeItem->cost        = calcLumaCost4MergePrediction( ctxStart, dstBuf, sqrtLambdaForFirstPass, pu, distParam );
2644
0
    m_mergeItemList        . insertMergeItemToList( mergeItem );
2645
0
  }
2646
0
  if( m_pcEncCfg->m_useFastMrg >= 2 )
2647
0
  {
2648
0
    m_mergeItemList        . shrinkList( curListSize );
2649
0
  }
2650
0
}
2651
2652
static int numGpmCombosToTry( const VVEncCfg& encCfg )
2653
0
{
2654
0
  return encCfg.m_Geo > 2 ? 10 : GEO_MAX_TRY_WEIGHTED_SAD;
2655
0
}
2656
2657
void EncCu::addGpmCandsToPruningList( const MergeCtx &mergeCtx, const UnitArea &localUnitArea, double sqrtLambdaForFirstPass,
2658
                                      const TempCtx& ctxStart, const GeoComboCostList& comboList, MergeBufVector& geoBuffer, DistParam& distParam, CodingUnit& pu)
2659
0
{
2660
0
  const int geoNumMrgSadCand = std::min( numGpmCombosToTry( *m_pcEncCfg ), ( int ) comboList.list.size() );
2661
0
  double bestGeoCost      = MAX_DOUBLE / 2.0;
2662
0
  MergeItem* best2geo[2]  = { nullptr, nullptr };
2663
2664
0
  pu.mergeFlag = true;
2665
0
  pu.geo       = true;
2666
0
  pu.mergeType = MRG_TYPE_DEFAULT_N;
2667
0
  pu.BcwIdx    = BCW_DEFAULT;
2668
0
  pu.interDir  = 3;
2669
0
  pu.imv       = IMV_OFF;
2670
0
  pu.affine    = pu.mmvdMergeFlag = pu.mmvdSkip
2671
0
               = pu.ciip
2672
0
               = false;
2673
2674
0
  for( int candidateIdx = 0; candidateIdx < geoNumMrgSadCand; candidateIdx++ )
2675
0
  {
2676
0
    const int          splitDir     = comboList.list[candidateIdx].splitDir;
2677
0
    const MergeIdxPair mergeIdxPair { comboList.list[candidateIdx].mergeIdx0, comboList.list[candidateIdx].mergeIdx1 };
2678
0
    const int          gpmIndex     = MergeItem::getGpmUnfiedIndex( splitDir, mergeIdxPair );
2679
2680
0
    pu.mergeIdx            = gpmIndex;
2681
0
    pu.geoMergeIdx         = mergeIdxPair;
2682
0
    pu.geoSplitDir         = splitDir;
2683
2684
0
    MergeItem *mergeItem   = m_mergeItemList.allocateNewMergeItem();
2685
0
    mergeItem->importMergeInfo( mergeCtx, gpmIndex, MergeItem::MergeItemType::GPM, pu );
2686
0
    auto dstBuf            = mergeItem->getPredBuf( localUnitArea );
2687
0
    generateMergePrediction( localUnitArea, mergeItem, pu, true, false, dstBuf, false, false, &geoBuffer[mergeIdxPair[0]], &geoBuffer[mergeIdxPair[1]] );
2688
0
    mergeItem->cost        = calcLumaCost4MergePrediction( ctxStart, dstBuf, sqrtLambdaForFirstPass, pu, distParam );
2689
0
    bestGeoCost            = std::min( mergeItem->cost, bestGeoCost );
2690
2691
0
    if( mergeItem->cost > MRG_FAST_RATIO[0] * bestGeoCost || mergeItem->cost > m_mergeBestSATDCost )
2692
0
    {
2693
0
      m_mergeItemList      . giveBackMergeItem( mergeItem );
2694
2695
0
      if( m_pcEncCfg->m_Geo > 2 ) break;
2696
0
    }
2697
0
    else if( m_pcEncCfg->m_Geo < 2 )
2698
0
    {
2699
0
      m_mergeItemList      . insertMergeItemToList( mergeItem );
2700
0
    }
2701
0
    else
2702
0
    {
2703
0
      if( ( m_mergeItemList.size() > 0 && m_mergeItemList.getMergeItemInList( m_mergeItemList.size() - 1 )->cost <= mergeItem->cost ) ||
2704
0
        ( best2geo[1] && best2geo[1]->cost <= mergeItem->cost ) )
2705
0
      {
2706
0
        m_mergeItemList    . giveBackMergeItem( mergeItem );
2707
0
      }
2708
0
      else
2709
0
      {
2710
0
        if( !best2geo[0] || mergeItem->cost < best2geo[0]->cost )
2711
0
        {
2712
0
          if( best2geo[1] )
2713
0
            m_mergeItemList. giveBackMergeItem( best2geo[1] );
2714
2715
0
          best2geo[1] = best2geo[0]; best2geo[0] = mergeItem;
2716
0
        }
2717
0
        else
2718
0
        {
2719
0
          if( best2geo[1] ) 
2720
0
            m_mergeItemList. giveBackMergeItem( best2geo[1] );
2721
2722
0
          best2geo[1] = mergeItem;
2723
0
        }
2724
0
      }
2725
0
    }
2726
0
  }
2727
2728
0
  if( best2geo[0] )
2729
0
    m_mergeItemList        . insertMergeItemToList( best2geo[0] );
2730
0
  if( best2geo[1] )
2731
0
    m_mergeItemList        . insertMergeItemToList( best2geo[1] );
2732
0
}
2733
2734
// The GPM SAD mask of a split direction for a block, addressed as xGetSADwMask reads it: sample x of row y is
2735
// mask[y * rowStep + x * stepX]. It is 1 on one side of the split line.
2736
struct GeoSadMaskWindow
2737
{
2738
  const Pel* mask;
2739
  int        stepX;
2740
  int        rowStep;
2741
};
2742
2743
static GeoSadMaskWindow geoSadMaskWindow( const int splitDir, const int hIdx, const int wIdx )
2744
0
{
2745
0
  const int16_t* masks = g_globalGeoEncSADmask[g_angle2mask[g_GeoParams[splitDir][0]]];
2746
0
  const int      offX  = g_weightOffset[hIdx][wIdx][splitDir][0];
2747
0
  const int      offY  = g_weightOffset[hIdx][wIdx][splitDir][1];
2748
0
  switch( g_angle2mirror[g_GeoParams[splitDir][0]] )
2749
0
  {
2750
0
  case 2:  return { masks + ( GEO_WEIGHT_MASK_SIZE - 1 - offY ) * GEO_WEIGHT_MASK_SIZE + offX,  1, -GEO_WEIGHT_MASK_SIZE };
2751
0
  case 1:  return { masks + offY * GEO_WEIGHT_MASK_SIZE + ( GEO_WEIGHT_MASK_SIZE - 1 - offX ), -1,  GEO_WEIGHT_MASK_SIZE };
2752
0
  default: return { masks + offY * GEO_WEIGHT_MASK_SIZE + offX,                                  1,  GEO_WEIGHT_MASK_SIZE };
2753
0
  }
2754
0
}
2755
2756
// The run of mask samples per row: [runStart, runEnd). A straight line splits each row once, so the samples equal to
2757
// the row's first one form a prefix: its end is found by binary search.
2758
static void geoSadMaskRowRuns( const GeoSadMaskWindow& win, const int width, const int height, int* runStart, int* runEnd )
2759
0
{
2760
0
  for( int y = 0; y < height; y++ )
2761
0
  {
2762
0
    const Pel* row   = win.mask + y * win.rowStep;
2763
0
    const Pel  first = row[0];
2764
0
    int lo = 1, hi = width;   // the first x with row[x * stepX] != first, or width
2765
0
    while( lo < hi )
2766
0
    {
2767
0
      const int mid = ( lo + hi ) >> 1;
2768
0
      if( row[mid * win.stepX] == first ) lo = mid + 1;
2769
0
      else                                hi = mid;
2770
0
    }
2771
0
    runStart[y] = first ? 0  : lo;
2772
0
    runEnd  [y] = first ? lo : width;
2773
0
  }
2774
0
}
2775
2776
// The runs of every block size and split direction, found once (the masks are fixed; searching them per CU costs more
2777
// than the masked SADs it replaces). Built on first use, after the masks are initialised.
2778
struct GeoSadMaskRuns
2779
{
2780
  uint8_t start[GEO_NUM_CU_SIZE][GEO_NUM_CU_SIZE][GEO_NUM_PARTITION_MODE][GEO_MAX_CU_SIZE];
2781
  uint8_t end  [GEO_NUM_CU_SIZE][GEO_NUM_CU_SIZE][GEO_NUM_PARTITION_MODE][GEO_MAX_CU_SIZE];
2782
2783
  GeoSadMaskRuns()
2784
0
  {
2785
0
    int runStart[GEO_MAX_CU_SIZE], runEnd[GEO_MAX_CU_SIZE];
2786
0
    for( int hIdx = 0; hIdx < GEO_NUM_CU_SIZE; hIdx++ )
2787
0
    {
2788
0
      for( int wIdx = 0; wIdx < GEO_NUM_CU_SIZE; wIdx++ )
2789
0
      {
2790
0
        const int width = 1 << ( wIdx + GEO_MIN_CU_LOG2 ), height = 1 << ( hIdx + GEO_MIN_CU_LOG2 );
2791
0
        for( int splitDir = 0; splitDir < GEO_NUM_PARTITION_MODE; splitDir++ )
2792
0
        {
2793
0
          geoSadMaskRowRuns( geoSadMaskWindow( splitDir, hIdx, wIdx ), width, height, runStart, runEnd );
2794
0
          std::copy( runStart, runStart + height, start[hIdx][wIdx][splitDir] );
2795
0
          std::copy( runEnd,   runEnd   + height, end  [hIdx][wIdx][splitDir] );
2796
0
        }
2797
0
      }
2798
0
    }
2799
0
  }
2800
};
2801
2802
static const GeoSadMaskRuns& geoSadMaskRuns()
2803
0
{
2804
0
  static const GeoSadMaskRuns runs;   // thread-safe initialisation on first use
2805
0
  return runs;
2806
0
}
2807
2808
bool EncCu::prepareGpmComboList( const MergeCtx &mergeCtx, const UnitArea &localUnitArea, double sqrtLambdaForFirstPass,
2809
                                 GeoComboCostList& comboList, MergeBufVector& geoBuffer, CodingUnit& pu )
2810
0
{
2811
0
          sqrtLambdaForFirstPass /= FRAC_BITS_SCALE;
2812
0
  const int bitsForPartitionIdx   = floorLog2(GEO_NUM_PARTITION_MODE);
2813
0
  const int maxNumMergeCandidates = std::min( ( int ) pu.cs->sps->maxNumGeoCand, MRG_MAX_NUM_CANDS );
2814
  // the second arguments to setDistParam is dummy and will be updated before being used
2815
0
  DistParam  distParamWholeBlk     = m_cRdCost.setDistParam( pu.cs->getOrgBuf().Y(), pu.cs->getOrgBuf().Y(), pu.cs->sps->bitDepths[ CH_L ], DF_SAD );
2816
0
  Distortion bestWholeBlkSad       = MAX_UINT64;
2817
0
  double     bestWholeBlkCost      = MAX_DOUBLE;
2818
0
  const ClpRng&  lclpRng           = pu.slice->clpRngs[COMP_Y];
2819
0
  const unsigned rshift            = std::max<int>( 2, ( IF_INTERNAL_PREC - lclpRng.bd ) );
2820
0
  const int      offset            = ( 1 << ( rshift - 1 ) ) + IF_INTERNAL_OFFS;
2821
0
  const int      numSamples        = pu.Y().area();
2822
0
  Distortion sadWholeBlk            [GEO_MAX_NUM_UNI_CANDS];
2823
0
  int        pocMrg                 [GEO_MAX_NUM_UNI_CANDS];
2824
0
  Mv         mergeMv                [GEO_MAX_NUM_UNI_CANDS];
2825
0
  bool       isSkipThisCand         [GEO_MAX_NUM_UNI_CANDS]
2826
0
                                   = { false, };
2827
0
  bool       sameMV                 [MRG_MAX_NUM_CANDS]
2828
0
                                   = { false, };
2829
0
  MergeBufVector geoTempBuf;
2830
2831
0
  if( m_pcEncCfg->m_Geo > 2 )
2832
0
  {
2833
0
    for( int m = 0; m < maxNumMergeCandidates; m++ )
2834
0
    {
2835
0
      if( !sameMV[m] )
2836
0
      {
2837
0
        for( int n = m + 1; n < maxNumMergeCandidates; n++ )
2838
0
        {
2839
0
          sameMV[n] |= mergeCtx.mvFieldNeighbours[m][0] == mergeCtx.mvFieldNeighbours[n][0]
2840
0
                    && mergeCtx.mvFieldNeighbours[m][1] == mergeCtx.mvFieldNeighbours[n][1];
2841
0
        }
2842
0
      }
2843
0
    }
2844
0
  }
2845
2846
0
  for( uint8_t mergeCand = 0; mergeCand < maxNumMergeCandidates; mergeCand++ )
2847
0
  {
2848
0
    geoBuffer .push_back ( m_aTmpStorageLCU[2                         + mergeCand].getCompactBuf( localUnitArea ) );
2849
0
    geoTempBuf.push_back ( m_aTmpStorageLCU[2 + GEO_MAX_NUM_UNI_CANDS + mergeCand].getCompactBuf( localUnitArea ) );
2850
2851
0
    const int  listIdx    = mergeCtx.mvFieldNeighbours[mergeCand][0]      .refIdx == -1 ? 1 : 0;
2852
0
    const auto refPicList = RefPicList(listIdx);
2853
0
    const int  refIdx     = mergeCtx.mvFieldNeighbours[mergeCand][listIdx].refIdx;
2854
2855
0
    pocMrg [mergeCand]    = pu.cs->slice->getRefPic( refPicList, refIdx )->poc;
2856
0
    mergeMv[mergeCand]    = mergeCtx.mvFieldNeighbours[mergeCand][listIdx].mv;
2857
2858
0
    for( int i = 0; i < mergeCand; i++ )
2859
0
    {
2860
0
      if( pocMrg[mergeCand] == pocMrg[i] && mergeMv[mergeCand] == mergeMv[i] )
2861
0
      {
2862
0
        isSkipThisCand[mergeCand] = true;
2863
0
        break;
2864
0
      }
2865
0
    }
2866
2867
0
    if( sameMV[mergeCand] )
2868
0
    {
2869
0
      continue;
2870
0
    }
2871
2872
0
    if( m_pcEncCfg->m_ifpLines ) 
2873
0
    {
2874
0
      bool isOutOfRange  = !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), mergeCtx.mvFieldNeighbours[mergeCand][0].mv.ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv );
2875
0
           isOutOfRange |= !CU::isMvInRangeFPP( pu.ly(), pu.lheight(), mergeCtx.mvFieldNeighbours[mergeCand][1].mv.ver, m_pcEncCfg->m_ifpLines, *pu.cs->pcv );
2876
2877
      // use sameMV to surpress processing of this cand later on...
2878
0
      sameMV[mergeCand] |= isOutOfRange;
2879
2880
0
      if( isOutOfRange )
2881
0
        continue;
2882
0
    }
2883
2884
0
    mergeCtx.setMergeInfo            ( pu, mergeCand );
2885
0
    pu.mcControl = 2;   // chroma waits for the RD pass
2886
0
    m_cInterSearch.motionCompensation( pu, geoBuffer[mergeCand], REF_PIC_LIST_X );
2887
2888
0
    g_pelBufOP.roundGeo( geoBuffer[mergeCand].Y().buf, geoTempBuf[mergeCand].Y().buf, numSamples, rshift, offset, lclpRng );
2889
2890
0
    distParamWholeBlk.cur  = geoTempBuf[mergeCand].Y();
2891
0
    sadWholeBlk[mergeCand] = distParamWholeBlk.distFunc( distParamWholeBlk );
2892
2893
0
    if( sadWholeBlk[mergeCand] < bestWholeBlkSad )
2894
0
    {
2895
0
      bestWholeBlkSad  = sadWholeBlk[mergeCand];
2896
0
      int bitsCand     = mergeCand + 1;
2897
0
      bestWholeBlkCost = ( double ) bestWholeBlkSad + ( double ) bitsCand * sqrtLambdaForFirstPass;
2898
0
    }
2899
0
  }
2900
2901
0
  bool allCandsAreSame = true;
2902
0
  for( uint8_t mergeCand = 1; mergeCand < maxNumMergeCandidates; mergeCand++ )
2903
0
  {
2904
0
    allCandsAreSame &= isSkipThisCand[mergeCand];
2905
0
  }
2906
0
  if( allCandsAreSame )
2907
0
  {
2908
0
    return false;
2909
0
  }
2910
2911
0
  const int wIdx = floorLog2( pu.lwidth() )  - GEO_MIN_CU_LOG2;
2912
0
  const int hIdx = floorLog2( pu.lheight() ) - GEO_MIN_CU_LOG2;
2913
2914
0
  const int      width          = pu.lwidth();
2915
0
  const int      height         = pu.lheight();
2916
0
  const uint32_t distShift      = DISTORTION_PRECISION_ADJUSTMENT( pu.cs->sps->bitDepths[CH_L] );
2917
0
  const GeoSadMaskRuns& maskRuns = geoSadMaskRuns();
2918
2919
  // One lane per candidate. Lanes without a prediction use the original: their sums are never used.
2920
0
  static_assert( MRG_MAX_NUM_CANDS <= GEO_PREFIX_LANES, "every merge candidate needs a lane" );
2921
0
  const CPelBuf orgLuma = pu.cs->getOrgBuf().Y();
2922
0
  const Pel* lanePred[GEO_PREFIX_LANES];
2923
0
  bool       laneUsed[GEO_PREFIX_LANES];
2924
0
  for( int lane = 0; lane < GEO_PREFIX_LANES; lane++ )
2925
0
  {
2926
0
    laneUsed[lane] = lane < maxNumMergeCandidates && !sameMV[lane];
2927
0
    lanePred[lane] = laneUsed[lane] ? geoTempBuf[lane].Y().buf : orgLuma.buf;
2928
0
  }
2929
0
  g_pelBufOP.geoPrefixSums( orgLuma.buf, orgLuma.stride, lanePred, width, width, height, laneUsed, m_geoRowPrefix.data() );
2930
2931
0
  for( int splitDir = 0; splitDir < GEO_NUM_PARTITION_MODE; )
2932
0
  {
2933
    // The masked SAD of the larger part (xGetSADwMask's sum with subShift 0): the mask is one side of a straight line,
2934
    // so in every row its samples are one run, and the sum over it is one difference of the row's prefix sums.
2935
0
    const uint8_t* runStart = maskRuns.start[hIdx][wIdx][splitDir];
2936
0
    const uint8_t* runEnd   = maskRuns.end  [hIdx][wIdx][splitDir];
2937
2938
0
    uint32_t sadLargeOfLane[GEO_PREFIX_LANES];
2939
0
    g_pelBufOP.geoRunSads( m_geoRowPrefix.data(), runStart, runEnd, width, height, laneUsed, sadLargeOfLane );
2940
2941
0
    for( uint8_t mergeCand = 0; mergeCand < maxNumMergeCandidates; mergeCand++ )
2942
0
    {
2943
0
      if( sameMV[mergeCand] )
2944
0
      {
2945
0
        continue;
2946
0
      }
2947
2948
0
      const Distortion sadLarge = sadLargeOfLane[mergeCand] >> distShift;
2949
0
      const Distortion sadSmall = sadWholeBlk[mergeCand] - sadLarge;
2950
2951
0
      const int bitsCand        = mergeCand + 1;
2952
2953
0
      const double cost0        = ( double ) sadLarge + ( double ) bitsCand * sqrtLambdaForFirstPass;
2954
0
      const double cost1        = ( double ) sadSmall + ( double ) bitsCand * sqrtLambdaForFirstPass;
2955
2956
0
      m_GeoCostList.insert( splitDir, 0, mergeCand, cost0 );
2957
0
      m_GeoCostList.insert( splitDir, 1, mergeCand, cost1 );
2958
0
    }
2959
2960
0
    if( m_pcEncCfg->m_Geo == 4 )
2961
0
    {
2962
0
      if( splitDir == 1 )
2963
0
      {
2964
0
        splitDir += 7;
2965
0
      }
2966
0
      else if( splitDir == 35 || ( splitDir + 1 ) % 4 != 0 )
2967
0
      {
2968
0
        splitDir++;
2969
0
      }
2970
0
      else
2971
0
      {
2972
0
        splitDir += 5;
2973
0
      }
2974
0
    }
2975
0
    else
2976
0
    {
2977
0
      splitDir++;
2978
0
    }
2979
0
  }
2980
2981
0
  comboList.list.clear();
2982
2983
0
  for( int splitDir = 0; splitDir < GEO_NUM_PARTITION_MODE; )
2984
0
  {
2985
0
    for( int geoMotionIdx = 0; geoMotionIdx < maxNumMergeCandidates * ( maxNumMergeCandidates - 1 ); geoMotionIdx++ )
2986
0
    {
2987
0
      const MergeIdxPair mergeIdxPair = m_GeoModeTest[geoMotionIdx];
2988
2989
0
      if( sameMV[mergeIdxPair[0]] || sameMV[mergeIdxPair[1]] )
2990
0
      {
2991
0
        continue;
2992
0
      }
2993
2994
0
      double tempCost = m_GeoCostList.getCost( splitDir, mergeIdxPair[0], mergeIdxPair[1] );
2995
2996
0
      if( tempCost > bestWholeBlkCost )
2997
0
      {
2998
0
        continue;
2999
0
      }
3000
3001
0
      tempCost = tempCost + ( double ) bitsForPartitionIdx * sqrtLambdaForFirstPass;
3002
0
      comboList.list.push_back( GeoMergeCombo{ splitDir, mergeIdxPair[0], mergeIdxPair[1], ( uint16_t ) comboList.list.size(), tempCost } );
3003
0
    }
3004
3005
0
    if( m_pcEncCfg->m_Geo == 4 )
3006
0
    {
3007
0
      if( splitDir == 1 )
3008
0
      {
3009
0
        splitDir += 7;
3010
0
      }
3011
0
      else if( splitDir == 35 || ( splitDir + 1 ) % 4 != 0 )
3012
0
      {
3013
0
        splitDir++;
3014
0
      }
3015
0
      else
3016
0
      {
3017
0
        splitDir += 5;
3018
0
      }
3019
0
    }
3020
0
    else
3021
0
    {
3022
0
      splitDir++;
3023
0
    }
3024
0
  }
3025
3026
0
  if( comboList.list.empty() )
3027
0
  {
3028
0
    return false;
3029
0
  }
3030
3031
0
  comboList.sortFirstByCost( numGpmCombosToTry( *m_pcEncCfg ) );
3032
0
  return true;
3033
0
}
3034
3035
// A SATD sum at which a stopping HAD must go on: any larger sum gives ( double ) sum + bitsCost >= dropCost (the caller's
3036
// drop test, in its own double arithmetic) and is at least sadBestForQPA (so m_uiSadBestForQPA keeps its value).
3037
// Below 1e15 the roundings of need and of sum + bitsCost are below 0.5, so every sum above ceil( need ) reaches dropCost;
3038
// a few sums that would just reach it go on to the end, which changes nothing.
3039
static Distortion mergeStopDist( double bitsCost, double dropCost, Distortion sadBestForQPA )
3040
0
{
3041
0
  const double need = dropCost - bitsCost;
3042
0
  if( !( need < 1e15 ) )
3043
0
  {
3044
0
    return MAX_DISTORTION;
3045
0
  }
3046
0
  const Distortion costDist = need > 0 ? ( Distortion ) ( int64_t ) std::ceil( need ) : 0;
3047
0
  return std::max( costDist, sadBestForQPA > 0 ? sadBestForQPA - 1 : 0 );
3048
0
}
3049
3050
double EncCu::calcLumaCost4MergePrediction( const TempCtx &ctxStart, const PelUnitBuf &predBuf, double lambda, CodingUnit &cu, DistParam &distParam, uint64_t* knownFracBits,
3051
                                            double dropCost, DistParam* stopDistParam )
3052
0
{
3053
0
  uint64_t fracBits;
3054
0
  if( knownFracBits && *knownFracBits != std::numeric_limits<uint64_t>::max() )
3055
0
  {
3056
0
    fracBits = *knownFracBits;
3057
0
  }
3058
0
  else
3059
0
  {
3060
0
    m_CABACEstimator->getCtx() = SubCtx( Ctx::MergeData, ctxStart );   // ctxStart holds the merge contexts only
3061
0
    fracBits = xCalcPuMeBits( cu );
3062
0
    if( knownFracBits )
3063
0
    {
3064
0
      *knownFracBits = fracBits;
3065
0
    }
3066
0
  }
3067
3068
0
  const double bitsCost = ( double ) fracBits * lambda;
3069
3070
0
  Distortion dist;
3071
0
  if( stopDistParam && dropCost < MAX_DOUBLE )
3072
0
  {
3073
    // The SATD stops once the cost reaches dropCost: the caller drops the candidate at the partial cost as at the full one.
3074
0
    stopDistParam->cur = predBuf.Y();
3075
0
    stopDistParam->maximumDistortionForEarlyExit = mergeStopDist( bitsCost, dropCost, m_uiSadBestForQPA );
3076
0
    dist = stopDistParam->distFunc( *stopDistParam );
3077
0
  }
3078
0
  else
3079
0
  {
3080
0
    distParam.cur = predBuf.Y();
3081
0
    dist = distParam.distFunc( distParam );
3082
0
  }
3083
3084
0
  double cost   = ( double ) dist + bitsCost;
3085
3086
0
  m_uiSadBestForQPA = std::min( dist, m_uiSadBestForQPA );
3087
3088
0
  return cost;
3089
0
}
3090
3091
//////////////////////////////////////////////////////////////////////////////////////////////
3092
// ibc merge/skip mode check
3093
void EncCu::xCheckRDCostIBCModeMerge2Nx2N(CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& partitioner, const EncTestMode& encTestMode)
3094
30.0k
{
3095
30.0k
  assert(partitioner.chType != CH_C); // chroma IBC is derived
3096
30.0k
  if (tempCS->area.lwidth() == 128 || tempCS->area.lheight() == 128) // disable IBC mode larger than 64x64
3097
0
  {
3098
0
    return;
3099
0
  }
3100
3101
30.0k
  if ((m_pcEncCfg->m_IBCFastMethod > 1) && !bestCS->slice->isIntra() && (bestCS->cus.size() != 0))
3102
0
  {
3103
0
    if (bestCS->getCU(partitioner.chType, partitioner.treeType)->skip)
3104
0
    {
3105
0
      return;
3106
0
    }
3107
0
  }
3108
3109
30.0k
  const SPS& sps = *tempCS->sps;
3110
3111
30.0k
  tempCS->initStructData(encTestMode.qp);
3112
30.0k
  MergeCtx mergeCtx;
3113
3114
30.0k
  {
3115
    // first get merge candidates
3116
30.0k
    CodingUnit cu(tempCS->area);
3117
30.0k
    cu.cs = tempCS;
3118
30.0k
    cu.predMode = MODE_IBC;
3119
30.0k
    cu.slice = tempCS->slice;
3120
30.0k
    cu.tileIdx = m_tileIdx;
3121
30.0k
    cu.initPuData();
3122
30.0k
    cu.cs = tempCS;
3123
30.0k
    cu.mmvdSkip = false;
3124
30.0k
    cu.mmvdMergeFlag = false;
3125
30.0k
    cu.geo = false;
3126
30.0k
    CU::getIBCMergeCandidates(cu, mergeCtx);
3127
30.0k
  }
3128
30.0k
  int candHasNoResidual[MRG_MAX_NUM_CANDS];
3129
210k
  for (unsigned int ui = 0; ui < mergeCtx.numValidMergeCand; ui++)
3130
180k
  {
3131
180k
    candHasNoResidual[ui] = 0;
3132
180k
  }
3133
3134
30.0k
  bool                                        bestIsSkip = false;
3135
30.0k
  unsigned                                    numMrgSATDCand = mergeCtx.numValidMergeCand;
3136
30.0k
  static_vector<unsigned, MRG_MAX_NUM_CANDS>  RdModeList(MRG_MAX_NUM_CANDS);
3137
210k
  for (unsigned i = 0; i < MRG_MAX_NUM_CANDS; i++)
3138
180k
  {
3139
180k
    RdModeList[i] = i;
3140
180k
  }
3141
3142
  //{
3143
30.0k
  static_vector<double, MRG_MAX_NUM_CANDS>  candCostList(MRG_MAX_NUM_CANDS, MAX_DOUBLE);
3144
  // 1. Pass: get SATD-cost for selected candidates and reduce their count
3145
30.0k
  {
3146
30.0k
    const double sqrtLambdaForFirstPass = m_cRdCost.getMotionLambda();
3147
3148
30.0k
    CodingUnit& cu = tempCS->addCU(CS::getArea(*tempCS, tempCS->area, partitioner.chType,partitioner.treeType), partitioner.chType);
3149
3150
30.0k
    partitioner.setCUData(cu);
3151
30.0k
    cu.slice = tempCS->slice;
3152
30.0k
    cu.tileIdx = m_tileIdx;
3153
30.0k
    cu.skip = false;
3154
30.0k
    cu.predMode = MODE_IBC;
3155
30.0k
    cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
3156
30.0k
    cu.qp = encTestMode.qp;
3157
30.0k
    cu.mmvdSkip = false;
3158
30.0k
    cu.geo = false;
3159
30.0k
    DistParam distParam;
3160
30.0k
    cu.initPuData();
3161
30.0k
    cu.mmvdMergeFlag = false;
3162
30.0k
    Picture* refPic = cu.slice->pic;
3163
30.0k
    const UnitArea localUnitArea(tempCS->area.chromaFormat, Area(cu.blocks[COMP_Y].x, cu.blocks[COMP_Y].y, tempCS->area.Y().width, tempCS->area.Y().height));
3164
30.0k
    const CompArea& compArea = localUnitArea.block(COMP_Y);
3165
30.0k
    const CPelBuf refBuf = refPic->getRecoBuf(compArea);
3166
30.0k
    const Pel* piRefSrch = refBuf.buf;
3167
3168
30.0k
      distParam = m_cRdCost.setDistParam(tempCS->getOrgBuf(COMP_Y), refBuf, sps.bitDepths[CH_L], DF_HAD);
3169
30.0k
    int refStride = refBuf.stride;
3170
3171
30.0k
    int numValidBv = mergeCtx.numValidMergeCand;
3172
210k
    for (unsigned int mergeCand = 0; mergeCand < mergeCtx.numValidMergeCand; mergeCand++)
3173
180k
    {
3174
180k
      mergeCtx.setMergeInfo(cu, mergeCand); // set bv info in merge mode
3175
180k
      const int cuPelX = cu.Y().x;
3176
180k
      const int cuPelY = cu.Y().y;
3177
180k
      int roiWidth     = cu.lwidth();
3178
180k
      int roiHeight    = cu.lheight();
3179
180k
      const int picWidth  = cu.cs->slice->pps->picWidthInLumaSamples;
3180
180k
      const int picHeight = cu.cs->slice->pps->picHeightInLumaSamples;
3181
180k
      const unsigned int lcuWidth = cu.cs->slice->sps->CTUSize;
3182
3183
180k
      Mv bv = cu.mv[0][0];
3184
180k
      bv.changePrecision( MV_PRECISION_INTERNAL, MV_PRECISION_INT);
3185
180k
      int xPred = bv.hor;
3186
180k
      int yPred = bv.ver;
3187
      
3188
180k
      if( !m_cInterSearch.searchBvIBC( cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, xPred, yPred, lcuWidth ) ) // not valid bv derived
3189
180k
      {
3190
180k
        numValidBv--;
3191
180k
        continue;
3192
180k
      }
3193
0
      CU::spanMotionInfo(cu);
3194
0
      distParam.cur.buf = piRefSrch + refStride * yPred + xPred;
3195
3196
0
      Distortion sad = distParam.distFunc(distParam);
3197
0
      unsigned int bitsCand = mergeCand + 1;
3198
0
      if (mergeCand == tempCS->sps->maxNumIBCMergeCand - 1)
3199
0
      {
3200
0
        bitsCand--;
3201
0
      }
3202
0
      double cost = (double)sad + (double)bitsCand * sqrtLambdaForFirstPass;
3203
3204
0
      updateCandList( mergeCand, cost, RdModeList, candCostList, numMrgSATDCand );
3205
0
    }
3206
3207
    // Try to limit number of candidates using SATD-costs
3208
30.0k
    if (numValidBv)
3209
0
    {
3210
0
      numMrgSATDCand = numValidBv;
3211
0
      for (unsigned int i = 1; i < numValidBv; i++)
3212
0
      {
3213
0
        if (candCostList[i] > MRG_FAST_RATIO[0] * candCostList[0])
3214
0
        {
3215
0
          numMrgSATDCand = i;
3216
0
          break;
3217
0
        }
3218
0
      }
3219
0
    }
3220
30.0k
    else
3221
30.0k
    {
3222
30.0k
      tempCS->dist = 0;
3223
30.0k
      tempCS->fracBits = 0;
3224
30.0k
      tempCS->cost = MAX_DOUBLE;
3225
30.0k
      tempCS->costDbOffset = 0;
3226
30.0k
      tempCS->initStructData(encTestMode.qp);
3227
30.0k
      return;
3228
30.0k
    }
3229
3230
0
    tempCS->initStructData(encTestMode.qp);
3231
0
  }
3232
  //}
3233
3234
3235
0
  const unsigned int iteration = 2;
3236
 // m_bestModeUpdated = tempCS->cost = bestCS->cost = false;
3237
  // 2. Pass: check candidates using full RD test
3238
0
  for (unsigned int numResidualPass = 0; numResidualPass < iteration; numResidualPass++)
3239
0
  {
3240
0
    for (unsigned int mrgHADIdx = 0; mrgHADIdx < numMrgSATDCand; mrgHADIdx++)
3241
0
    {
3242
0
      unsigned int mergeCand = RdModeList[mrgHADIdx];
3243
0
      if (!(numResidualPass == 1 && candHasNoResidual[mergeCand] == 1))
3244
0
      {
3245
0
        if (!(bestIsSkip && (numResidualPass == 0)))
3246
0
        {
3247
0
          {
3248
3249
            // first get merge candidates
3250
0
            CodingUnit& cu = tempCS->addCU(CS::getArea(*tempCS, tempCS->area, (const ChannelType)partitioner.chType,partitioner.treeType), (const ChannelType)partitioner.chType);
3251
3252
0
            partitioner.setCUData(cu);
3253
0
            cu.slice = tempCS->slice;
3254
0
            cu.tileIdx = m_tileIdx;
3255
0
            cu.skip = false;
3256
0
            cu.predMode = MODE_IBC;
3257
0
            cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
3258
0
            cu.qp = encTestMode.qp;
3259
0
            cu.sbtInfo = 0;
3260
0
            cu.initPuData();
3261
0
            cu.intraDir[0] = DC_IDX; // set intra pred for ibc block
3262
0
            cu.intraDir[1] = PLANAR_IDX; // set intra pred for ibc block
3263
0
            cu.mmvdSkip = false;
3264
0
            cu.mmvdMergeFlag = false;
3265
0
            cu.geo = false;
3266
0
            mergeCtx.setMergeInfo(cu, mergeCand);
3267
0
            CU::spanMotionInfo(cu);
3268
3269
0
            assert(mergeCtx.mrgTypeNeighbours[mergeCand] == MRG_TYPE_IBC);
3270
0
            const bool chroma = !CU::isSepTree(cu);
3271
3272
            //  MC
3273
0
            cu.mcControl = chroma ? 0: 2;
3274
0
            m_cInterSearch.motionCompensationIBC(cu, tempCS->getPredBuf());
3275
0
            xSetStartCtx();
3276
3277
0
            m_cInterSearch.encodeResAndCalcRdInterCU(*tempCS, partitioner, (numResidualPass != 0));
3278
0
            cu.mcControl = 0;
3279
0
            xEncodeDontSplit(*tempCS, partitioner);
3280
0
            xCheckDQP(*tempCS, partitioner);
3281
0
            xCheckBestMode(tempCS, bestCS, partitioner, encTestMode);
3282
3283
0
            tempCS->initStructData(encTestMode.qp);
3284
0
          }
3285
3286
0
          if (m_pcEncCfg->m_useFastDecisionForMerge && !bestIsSkip)
3287
0
          {
3288
0
            if (bestCS->getCU(partitioner.chType, partitioner.treeType) == NULL)
3289
0
              bestIsSkip = 0;
3290
0
            else
3291
0
              bestIsSkip = bestCS->getCU(partitioner.chType, partitioner.treeType)->rootCbf == 0;
3292
0
          }
3293
0
        }
3294
0
      }
3295
0
    }
3296
0
  }
3297
0
}
3298
3299
void EncCu::xCheckRDCostIBCMode(CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& partitioner,
3300
  const EncTestMode& encTestMode)
3301
30.0k
{
3302
30.0k
  if (tempCS->area.lwidth() == 128 || tempCS->area.lheight() == 128)   // disable IBC mode larger than 64x64
3303
0
  {
3304
0
    return;
3305
0
  }
3306
30.0k
  if ((m_pcEncCfg->m_IBCFastMethod > 1) && !bestCS->slice->isIntra() && (bestCS->cus.size() != 0))
3307
0
  {
3308
0
    if (bestCS->getCU(partitioner.chType, partitioner.treeType)->skip)
3309
0
    {
3310
0
      return;
3311
0
    }
3312
0
  }
3313
3314
30.0k
  tempCS->initStructData(encTestMode.qp);
3315
3316
30.0k
  CodingUnit& cu = tempCS->addCU(CS::getArea(*tempCS, tempCS->area, partitioner.chType, partitioner.treeType), partitioner.chType);
3317
3318
30.0k
  partitioner.setCUData(cu);
3319
30.0k
  cu.slice = tempCS->slice;
3320
30.0k
  cu.tileIdx = m_tileIdx;
3321
30.0k
  cu.skip = false;
3322
30.0k
  cu.predMode = MODE_IBC;
3323
30.0k
  cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
3324
30.0k
  cu.qp = encTestMode.qp;
3325
30.0k
  cu.initPuData();
3326
30.0k
  cu.imv = IMV_OFF;
3327
30.0k
  cu.sbtInfo = 0;
3328
30.0k
  cu.mmvdSkip = false;
3329
30.0k
  cu.mmvdMergeFlag = false;
3330
3331
30.0k
  cu.intraDir[0] = DC_IDX; // set intra pred for ibc block
3332
30.0k
  cu.intraDir[1] = PLANAR_IDX; // set intra pred for ibc block
3333
3334
30.0k
  cu.interDir = 1; // use list 0 for IBC mode
3335
30.0k
  cu.refIdx[REF_PIC_LIST_0] = MAX_NUM_REF; // last idx in the list
3336
30.0k
  bool bValid = m_cInterSearch.predIBCSearch(cu, partitioner);
3337
3338
30.0k
  if (bValid)
3339
26.8k
  {
3340
26.8k
    CU::spanMotionInfo(cu);
3341
26.8k
    const bool chroma = !CU::isSepTree(cu);
3342
    //  MC
3343
26.8k
    cu.mcControl = chroma ? 0 : 2;
3344
26.8k
    m_cInterSearch.motionCompensationIBC(cu, tempCS->getPredBuf());
3345
3346
26.8k
    xRestoreStartCtx();
3347
26.8k
    m_cInterSearch.encodeResAndCalcRdInterCU(*tempCS, partitioner, false);
3348
26.8k
    cu.mcControl = 0;
3349
3350
26.8k
    xEncodeDontSplit(*tempCS, partitioner);
3351
26.8k
    xCheckDQP(*tempCS, partitioner);
3352
26.8k
    xCheckBestMode(tempCS, bestCS, partitioner, encTestMode);
3353
26.8k
  } // bValid
3354
3.18k
  else
3355
3.18k
  {
3356
3.18k
    tempCS->dist = 0;
3357
3.18k
    tempCS->fracBits = 0;
3358
3.18k
    tempCS->cost = MAX_DOUBLE;
3359
3.18k
    tempCS->costDbOffset = 0;
3360
3.18k
  }
3361
30.0k
}
3362
3363
void EncCu::xCheckRDCostInter( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode )
3364
0
{
3365
0
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTER_MVD, tempCS, partitioner.chType );
3366
0
  tempCS->initStructData( encTestMode.qp );
3367
3368
0
  m_cInterSearch.setAffineModeSelected( false );
3369
3370
0
  m_cInterSearch.resetBufferedUniMotions();
3371
3372
0
  int bcwLoopNum = BCW_NUM;
3373
3374
0
  if( tempCS->area.Y().area() < BCW_SIZE_CONSTRAINT || !tempCS->slice->isInterB() || !tempCS->sps->BCW )
3375
0
  {
3376
0
    bcwLoopNum = 1;
3377
0
  }
3378
  
3379
0
  double curBestCost = bestCS->cost;
3380
0
  double equBcwCost = MAX_DOUBLE;
3381
3382
0
  for( int bcwLoopIdx = 0; bcwLoopIdx < bcwLoopNum; bcwLoopIdx++ )
3383
0
  {
3384
0
    if( m_pcEncCfg->m_BCW == 2 )
3385
0
    {
3386
0
      bool isBestInter   = m_modeCtrl.getBlkInfo( bestCS->area ).isInter;
3387
0
      uint8_t bestBcwIdx = m_modeCtrl.getBlkInfo( bestCS->area).BcwIdx;
3388
3389
0
      if( isBestInter && g_BcwSearchOrder[bcwLoopIdx] != BCW_DEFAULT && g_BcwSearchOrder[bcwLoopIdx] != bestBcwIdx )
3390
0
      {
3391
0
        continue;
3392
0
      }
3393
0
    }
3394
    
3395
0
    if( !tempCS->slice->checkLDC )
3396
0
    {
3397
0
      if( bcwLoopIdx != 0 && bcwLoopIdx != 3 && bcwLoopIdx != 4 )
3398
0
      {
3399
0
        continue;
3400
0
      }
3401
0
    }
3402
  
3403
0
    CodingUnit &cu      = tempCS->addCU( tempCS->area, partitioner.chType );
3404
3405
0
    partitioner.setCUData( cu );
3406
0
    cu.slice            = tempCS->slice;
3407
0
    cu.tileIdx          = m_tileIdx;
3408
0
    cu.skip             = false;
3409
0
    cu.mmvdSkip         = false;
3410
0
    cu.predMode         = MODE_INTER;
3411
0
    cu.chromaQpAdj      = m_cuChromaQpOffsetIdxPlus1;
3412
0
    cu.qp               = encTestMode.qp;
3413
0
    cu.initPuData();
3414
3415
0
    cu.BcwIdx = g_BcwSearchOrder[bcwLoopIdx];
3416
0
    uint8_t bcwIdx = cu.BcwIdx;
3417
0
    bool testBcw = (bcwIdx != BCW_DEFAULT);
3418
3419
0
    bool StopInterRes = (m_pcEncCfg->m_FastInferMerge >> 3) & 1;
3420
0
    StopInterRes &= bestCS->slice->TLayer > (m_pcEncCfg->m_maxTLayer - (m_pcEncCfg->m_FastInferMerge & 7));
3421
0
    double bestCostInter = StopInterRes ? m_mergeBestSATDCost : MAX_DOUBLE;
3422
3423
0
    bool stopTest = m_cInterSearch.predInterSearch(cu, partitioner, bestCostInter);
3424
3425
0
    if (StopInterRes && (bestCostInter != m_mergeBestSATDCost))
3426
0
    {
3427
0
      int L = (cu.slice->TLayer <= 2) ? 0 : (cu.slice->TLayer - 2);
3428
0
      if ((bestCostInter > MRG_FAST_RATIOMYV[L] * m_mergeBestSATDCost))
3429
0
      {
3430
0
        stopTest = true;
3431
0
      }
3432
0
    }
3433
3434
0
    if( !stopTest )
3435
0
    {
3436
0
      bcwIdx   = CU::getValidBcwIdx(cu);
3437
0
      stopTest = testBcw && bcwIdx == BCW_DEFAULT;
3438
0
    }
3439
    
3440
0
    if( stopTest )
3441
0
    {
3442
0
      tempCS->initStructData(encTestMode.qp);
3443
0
      continue;
3444
0
    }
3445
3446
0
    CHECK(!(testBcw || (!testBcw && bcwIdx == BCW_DEFAULT)), " !( bTestBcw || (!bTestBcw && bcwIdx == BCW_DEFAULT ) )");
3447
0
    if( !testBcw )
3448
0
    {
3449
0
      m_modeCtrl.noteMotionSearchMvd( cu );   // FastAMVR: the MVDs found with equal weights
3450
0
    }
3451
        
3452
0
    xEncodeInterResidual(tempCS, bestCS, partitioner, encTestMode, 0, 0, &equBcwCost);
3453
    
3454
0
    if( bcwIdx == BCW_DEFAULT )
3455
0
    {
3456
0
      m_cInterSearch.setAffineModeSelected( bestCS->cus.front()->affine && !bestCS->cus.front()->mergeFlag );
3457
0
    }
3458
3459
0
    tempCS->initStructData(encTestMode.qp);
3460
  
3461
0
    double skipTH = MAX_DOUBLE;
3462
0
    skipTH = (m_pcEncCfg->m_BCW == 2 ? 1.05 : MAX_DOUBLE);
3463
0
    if( equBcwCost > curBestCost * skipTH )
3464
0
    {
3465
0
      break;
3466
0
    }
3467
3468
0
    if( m_pcEncCfg->m_BCW == 2 )
3469
0
    {
3470
0
      if( ( cu.interDir != 3 && testBcw == 0 && ! m_pcEncCfg->m_picReordering )
3471
0
         || ( g_BcwSearchOrder[bcwLoopIdx] == BCW_DEFAULT && xIsBcwSkip( cu ) ) )
3472
0
      {
3473
0
        break;
3474
0
      }
3475
0
    }
3476
0
  }
3477
0
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
3478
0
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
3479
0
}
3480
3481
void EncCu::xCheckRDCostInterIMV(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode)
3482
0
{
3483
0
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_INTER_MVD_IMV, tempCS, partitioner.chType );
3484
0
  bool Test_AMVR = m_pcEncCfg->m_AMVRspeed ? true: false;
3485
0
  if (m_pcEncCfg->m_AMVRspeed > 2 && m_pcEncCfg->m_AMVRspeed < 5 && !bestCS->cus.empty() && bestCS->getCU(partitioner.chType, partitioner.treeType)->skip)
3486
0
  {
3487
0
    Test_AMVR = false;
3488
0
  }
3489
0
  else if (m_pcEncCfg->m_AMVRspeed > 4 && !bestCS->cus.empty() && bestCS->getCU(partitioner.chType, partitioner.treeType)->mergeFlag && !bestCS->getCU(partitioner.chType, partitioner.treeType)->ciip)
3490
0
  {
3491
0
    Test_AMVR = false;
3492
0
  }
3493
0
  bool Do_Limit = !bestCS->cus.empty() && (m_pcEncCfg->m_AMVRspeed == 4 || m_pcEncCfg->m_AMVRspeed == 6) ? true : false;
3494
0
  bool Do_OnceRes = !bestCS->cus.empty() && (m_pcEncCfg->m_AMVRspeed == 7) ? true : false;
3495
3496
0
  if( Test_AMVR )
3497
0
  {
3498
0
    double Fpel_cost    = m_pcEncCfg->m_AMVRspeed == 1 ? MAX_DOUBLE*0.5 : MAX_DOUBLE;
3499
0
    double costCurStart = m_pcEncCfg->m_AMVRspeed == 1 ? m_modeCtrl.comprCUCtx->bestCostNoImv : bestCS->cost;
3500
0
    double costCur      = MAX_DOUBLE;
3501
0
    double bestCostIMV  = MAX_DOUBLE;
3502
3503
0
    if (Do_OnceRes)
3504
0
    {
3505
0
      costCurStart = xCalcDistortion(bestCS, partitioner.chType, bestCS->sps->bitDepths[CH_L], 0);
3506
0
      Fpel_cost = costCurStart;
3507
0
      tempCS->initSubStructure(*m_pTempCS2, partitioner.chType, partitioner.currArea(), false);
3508
0
    }
3509
3510
0
    CodingStructure *tempCSbest = m_pTempCS2;
3511
3512
0
    m_cInterSearch.setAffineModeSelected( false );
3513
3514
0
    m_cInterSearch.resetBufferedUniMotions();
3515
3516
0
    int bcwLoopNum = (tempCS->slice->isInterB() ? BCW_NUM : 1);
3517
0
    bcwLoopNum = (tempCS->sps->BCW ? bcwLoopNum : 1);
3518
3519
0
    if( tempCS->area.lwidth() * tempCS->area.lheight() < BCW_SIZE_CONSTRAINT )
3520
0
    {
3521
0
      bcwLoopNum = 1;
3522
0
    }
3523
3524
0
    for (int i = 1; i <= IMV_HPEL; i++)
3525
0
    {
3526
0
      double curBestCost = bestCS->cost;
3527
0
      double equBcwCost  = MAX_DOUBLE;
3528
3529
0
      for( int bcwLoopIdx = 0; bcwLoopIdx < bcwLoopNum; bcwLoopIdx++ )
3530
0
      {
3531
0
        if( m_pcEncCfg->m_BCW == 2 )
3532
0
        {
3533
0
          bool isBestInter   = m_modeCtrl.getBlkInfo( bestCS->area ).isInter;
3534
0
          uint8_t bestBcwIdx = m_modeCtrl.getBlkInfo( bestCS->area).BcwIdx;
3535
3536
0
          if( isBestInter && g_BcwSearchOrder[bcwLoopIdx] != BCW_DEFAULT && g_BcwSearchOrder[bcwLoopIdx] != bestBcwIdx )
3537
0
          {
3538
0
            continue;
3539
0
          }
3540
          
3541
0
          if( tempCS->slice->checkLDC && g_BcwSearchOrder[bcwLoopIdx] != BCW_DEFAULT
3542
0
            && (m_bestBcwIdx[0] >= 0 && g_BcwSearchOrder[bcwLoopIdx] != m_bestBcwIdx[0])
3543
0
            && (m_bestBcwIdx[1] >= 0 && g_BcwSearchOrder[bcwLoopIdx] != m_bestBcwIdx[1]))
3544
0
          {
3545
0
            continue;
3546
0
          }
3547
0
        }
3548
3549
0
        if( !tempCS->slice->checkLDC )
3550
0
        {
3551
0
          if( bcwLoopIdx != 0 && bcwLoopIdx != 3 && bcwLoopIdx != 4 )
3552
0
          {
3553
0
            continue;
3554
0
          }
3555
0
        }
3556
3557
0
        bool testBcw;
3558
0
        uint8_t bcwIdx;
3559
0
        bool isEqualUni = false;
3560
3561
0
        if (i > IMV_FPEL)
3562
0
        {
3563
0
          bool nextimv = false;
3564
0
          double stopCost = i == IMV_HPEL ? 1.25 : 1.06;
3565
0
          if (Fpel_cost > stopCost * costCurStart)
3566
0
          {
3567
0
            nextimv = true;
3568
0
          }
3569
0
          if ( m_pcEncCfg->m_AMVRspeed == 1 )
3570
0
          {
3571
0
            costCurStart = bestCS->cost;
3572
0
          }
3573
0
          if (nextimv)
3574
0
          {
3575
0
            continue;
3576
0
          }
3577
0
          if( i == IMV_4PEL && m_modeCtrl.skips4PelAmvr() )   // FastAMVR: MVDs too small for 4-sample precision
3578
0
          {
3579
0
            continue;
3580
0
          }
3581
0
        }
3582
3583
0
        bool Do_Search = Do_OnceRes ? false : true;
3584
3585
0
        if (Do_Limit)
3586
0
        {
3587
0
          Do_Search = i == IMV_FPEL ? true : false;
3588
3589
0
          if (i == IMV_HPEL)
3590
0
          {
3591
0
            if (bestCS->slice->TLayer > 3)
3592
0
            {
3593
0
              continue;
3594
0
            }
3595
0
            if (bestCS->getCU(partitioner.chType, partitioner.treeType)->imv != 0)
3596
0
            {
3597
0
              Do_Search = true; //do_est
3598
0
            }
3599
0
          }
3600
0
          if (bestCS->getCU(partitioner.chType, partitioner.treeType)->mmvdMergeFlag || bestCS->getCU(partitioner.chType, partitioner.treeType)->geo)
3601
0
          {
3602
0
            Do_Search = true;
3603
0
          }
3604
0
        }
3605
0
        tempCS->initStructData(encTestMode.qp);
3606
3607
0
        if (!Do_Search)
3608
0
        {
3609
0
          tempCS->copyStructure(*bestCS, partitioner.chType, TREE_D);
3610
0
        }
3611
0
        tempCS->dist = 0;
3612
0
        tempCS->fracBits = 0;
3613
0
        tempCS->cost = MAX_DOUBLE;
3614
0
        CodingUnit &cu = (Do_Search) ? tempCS->addCU(tempCS->area, partitioner.chType) : *tempCS->getCU(partitioner.chType, partitioner.treeType);
3615
0
        if (Do_Search)
3616
0
        {
3617
0
          partitioner.setCUData(cu);
3618
0
          cu.slice = tempCS->slice;
3619
0
          cu.tileIdx = m_tileIdx;
3620
0
          cu.skip = false;
3621
0
          cu.mmvdSkip = false;
3622
0
          cu.predMode = MODE_INTER;
3623
0
          cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
3624
0
          cu.qp = encTestMode.qp;
3625
3626
0
          cu.initPuData();
3627
3628
0
          cu.imv = i;
3629
3630
0
          cu.BcwIdx = g_BcwSearchOrder[bcwLoopIdx];
3631
0
          bcwIdx    = cu.BcwIdx;
3632
0
          testBcw   = (bcwIdx != BCW_DEFAULT);
3633
3634
0
          cu.interDir = 10;
3635
          
3636
0
          double bestCostInter = MAX_DOUBLE;
3637
0
          m_cInterSearch.predInterSearch(cu, partitioner, bestCostInter);
3638
          
3639
0
          if ( cu.interDir <= 3 )
3640
0
          {
3641
0
            bcwIdx = CU::getValidBcwIdx(cu);
3642
0
          }
3643
0
          else
3644
0
          {
3645
0
            continue;
3646
0
          }
3647
          
3648
0
          if( testBcw && bcwIdx == BCW_DEFAULT ) // Enabled Bcw but the search results is uni.
3649
0
          {
3650
0
            continue;
3651
0
          }
3652
0
          CHECK(!(testBcw || (!testBcw && bcwIdx == BCW_DEFAULT)), " !( bTestBcw || (!bTestBcw && bcwIdx == BCW_DEFAULT ) )");
3653
3654
0
          if( m_pcEncCfg->m_BCW == 2 )
3655
0
          {
3656
0
            if( cu.interDir != 3 && testBcw == 0 )
3657
0
            {
3658
0
              isEqualUni = true;
3659
0
            }
3660
0
          }
3661
3662
0
          if (!CU::hasSubCUNonZeroMVd(cu))
3663
0
          {
3664
0
            continue;
3665
0
          }
3666
0
        }
3667
0
        else
3668
0
        {
3669
0
          cu.smvdMode = 0;
3670
0
          cu.affine = false;
3671
0
          cu.imv = i ;
3672
0
          CU::resetMVDandMV2Int(cu);
3673
0
          if (!CU::hasSubCUNonZeroMVd(cu))
3674
0
          {
3675
0
            continue;
3676
0
          }
3677
3678
0
          cu.BcwIdx = g_BcwSearchOrder[bcwLoopIdx];
3679
3680
0
          cu.mvRefine = true;
3681
0
          m_cInterSearch.motionCompensation(cu, tempCS->getPredBuf() );
3682
0
          cu.mvRefine = false;
3683
0
        }
3684
3685
0
        if( Do_OnceRes )
3686
0
        {
3687
0
          costCur = xCalcDistortion(tempCS, partitioner.chType, tempCS->sps->bitDepths[CH_L], cu.imv );
3688
0
          if (costCur < bestCostIMV)
3689
0
          {
3690
0
            bestCostIMV = costCur;
3691
0
            tempCSbest->getPredBuf().copyFrom(tempCS->getPredBuf());
3692
0
            tempCSbest->clearCUs();
3693
0
            tempCSbest->clearTUs();
3694
0
            tempCSbest->copyStructure(*tempCS, partitioner.chType, TREE_D);
3695
0
          }
3696
0
          if (i > IMV_FPEL)
3697
0
          {
3698
0
            costCurStart = costCurStart > costCur ? costCur : costCurStart;
3699
0
          }
3700
0
        }
3701
0
        else
3702
0
        {
3703
0
          xEncodeInterResidual(tempCS, bestCS, partitioner, encTestMode, 0, 0, &equBcwCost);
3704
0
          costCur = tempCS->cost;
3705
3706
0
          if (i > IMV_FPEL)
3707
0
          {
3708
0
            costCurStart = bestCS->cost;
3709
0
          }
3710
0
        }
3711
3712
0
        if (i == IMV_FPEL)
3713
0
        {
3714
0
           Fpel_cost = costCur;
3715
0
        }
3716
3717
0
        double skipTH = MAX_DOUBLE;
3718
0
        skipTH = (m_pcEncCfg->m_BCW == 2 ? 1.05 : MAX_DOUBLE);
3719
0
        if( equBcwCost > curBestCost * skipTH )
3720
0
        {
3721
0
          break;
3722
0
        }
3723
3724
0
        if( m_pcEncCfg->m_BCW == 2 )
3725
0
        {
3726
0
          if( isEqualUni == true && ! m_pcEncCfg->m_picReordering )
3727
0
          {
3728
0
            break;
3729
0
          }
3730
0
          if( g_BcwSearchOrder[bcwLoopIdx] == BCW_DEFAULT && xIsBcwSkip( cu ) )
3731
0
          {
3732
0
            break;
3733
0
          }
3734
0
        }
3735
0
      }
3736
0
    }
3737
3738
0
    if (Do_OnceRes && (bestCostIMV != MAX_DOUBLE))
3739
0
    {
3740
0
      CodingStructure* CSCandBest = tempCSbest;
3741
0
      tempCS->initStructData(bestCS->currQP[partitioner.chType]);
3742
0
      tempCS->copyStructure(*CSCandBest, partitioner.chType, TREE_D);
3743
0
      tempCS->getPredBuf().copyFrom(tempCSbest->getPredBuf());
3744
0
      tempCS->dist = 0;
3745
0
      tempCS->fracBits = 0;
3746
0
      tempCS->cost = MAX_DOUBLE;
3747
3748
0
      xEncodeInterResidual(tempCS, bestCS, partitioner, encTestMode, 0, 0, NULL);
3749
0
    }
3750
3751
0
    tempCS->initStructData(encTestMode.qp);
3752
0
  }
3753
0
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
3754
0
  STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
3755
0
}
3756
3757
void EncCu::xCalDebCost( CodingStructure &cs, Partitioner &partitioner )
3758
125k
{
3759
125k
  PROFILER_SCOPE_AND_STAGE_EXT( 1, _TPROF, P_DEBLOCK_FILTER, &cs, partitioner.chType );
3760
125k
  if ( cs.slice->deblockingFilterDisable )
3761
0
  {
3762
0
    return;
3763
0
  }
3764
3765
125k
  const ChromaFormat format = cs.area.chromaFormat;
3766
125k
  CodingUnit*            cu = cs.getCU(partitioner.chType, partitioner.treeType);
3767
125k
  const Position    lumaPos = cu->Y().valid() ? cu->Y().pos() : recalcPosition( format, cu->chType, CH_L, cu->blocks[cu->chType].pos() );
3768
125k
  bool    topEdgeAvai = lumaPos.y > 0 && ((lumaPos.y % 4) == 0);
3769
125k
  bool   leftEdgeAvai = lumaPos.x > 0 && ((lumaPos.x % 4) == 0);
3770
3771
125k
  if( ! ( topEdgeAvai || leftEdgeAvai ))
3772
25.9k
  {
3773
25.9k
    return;
3774
25.9k
  }
3775
3776
99.2k
  ComponentID compStr = ( CU::isSepTree(*cu) && !isLuma( partitioner.chType ) ) ? COMP_Cb : COMP_Y;
3777
99.2k
  ComponentID compEnd = (( CU::isSepTree(*cu) && isLuma( partitioner.chType )) || cu->chromaFormat == VVENC_CHROMA_400 ) ? COMP_Y : COMP_Cr;
3778
99.2k
  const UnitArea currCsArea = clipArea( CS::getArea( cs, cs.area, partitioner.chType, partitioner.treeType ), *cs.picture );
3779
3780
99.2k
  PelStorage&  picDbBuf = m_dbBuffer; //th we could reduce the buffer size and do some relocate
3781
3782
  //deblock neighbour pixels
3783
99.2k
  const Size     lumaSize = cu->Y().valid() ? cu->Y().size() : recalcSize( format, cu->chType, CH_L, cu->blocks[cu->chType].size() );
3784
3785
99.2k
  int verOffset = lumaPos.y > 7 ? 8 : 4;
3786
99.2k
  int horOffset = lumaPos.x > 7 ? 8 : 4;
3787
3788
99.2k
  LoopFilter::calcFilterStrengths( *cu, true );
3789
3790
99.2k
  if( m_EDO == 2 && CS::isDualITree( cs ) && isLuma( partitioner.chType ) )
3791
54.8k
  {
3792
54.8k
    m_cLoopFilter.getMaxFilterLength( *cu, verOffset, horOffset );
3793
3794
54.8k
    if( 0== (verOffset + horOffset) )
3795
0
    {
3796
0
      return;
3797
0
    }
3798
3799
54.8k
    topEdgeAvai  &= verOffset != 0;
3800
54.8k
    leftEdgeAvai &= horOffset != 0;
3801
54.8k
  }
3802
3803
99.2k
  const UnitArea  areaTop  = UnitArea( format, Area( lumaPos.x,             lumaPos.y - verOffset, lumaSize.width, verOffset       ) );
3804
99.2k
  const UnitArea  areaLeft = UnitArea( format, Area( lumaPos.x - horOffset, lumaPos.y,             horOffset,      lumaSize.height ) );
3805
  // at a CTU top the area above lies in the CTU line above, which may be deblocked meanwhile: it is read as it was encoded
3806
99.2k
  const Picture& pic            = *cs.picture;
3807
99.2k
  const bool     topInLineAbove = ( lumaPos.y & cs.pcv->maxCUSizeMask ) == 0;
3808
208k
  const auto     recoAbove      = [&]( const CompArea& blk ) -> CPelBuf { return topInLineAbove ? pic.getRecoAboveCtuTop( blk ) : pic.getRecoBuf( blk ); };
3809
3810
242k
  for ( int compIdx = compStr; compIdx <= compEnd; compIdx++ )
3811
143k
  {
3812
143k
    ComponentID compId = (ComponentID)compIdx;
3813
3814
    //Copy current CU's reco to Deblock Pic Buffer
3815
143k
    const CompArea&  compArea = currCsArea.block( compId );
3816
143k
    CompArea         locArea  = compArea;
3817
143k
    locArea.x -= cu->blocks[compIdx].x;
3818
143k
    locArea.y -= cu->blocks[compIdx].y;
3819
143k
    PelBuf dbReco = picDbBuf.getBuf( locArea );
3820
143k
      PelBuf reco = cs.getRecoBuf( compId );
3821
143k
      dbReco.copyFrom( reco );
3822
    //left neighbour
3823
143k
    if ( leftEdgeAvai )
3824
100k
    {
3825
100k
      const CompArea&  compArea = areaLeft.block(compId);
3826
100k
      CompArea         locArea = compArea;
3827
100k
      locArea.x -= cu->blocks[compIdx].x;
3828
100k
      locArea.y -= cu->blocks[compIdx].y;
3829
100k
      PelBuf dbReco = picDbBuf.getBuf( locArea );
3830
100k
        dbReco.copyFrom( cs.picture->getRecoBuf( compArea ) );
3831
100k
      }
3832
    //top neighbour
3833
143k
    if ( topEdgeAvai )
3834
104k
    {
3835
104k
      const CompArea&  compArea = areaTop.block( compId );
3836
104k
      CompArea         locArea = compArea;
3837
104k
      locArea.x -= cu->blocks[compIdx].x;
3838
104k
      locArea.y -= cu->blocks[compIdx].y;
3839
104k
      PelBuf dbReco = picDbBuf.getBuf( locArea );
3840
104k
        dbReco.copyFrom( recoAbove( compArea ) );
3841
104k
      }
3842
143k
    }
3843
3844
18.4E
  ChannelType dbChType = CU::isSepTree(*cu) ? partitioner.chType : MAX_NUM_CH;
3845
3846
99.2k
  CHECK( CU::isSepTree(*cu) && !cu->Y().valid() && partitioner.chType == CH_L, "xxx" );
3847
3848
99.2k
  if( cu->Y() .valid() ) m_cLoopFilter.setOrigin( CH_L, cu->lumaPos() );
3849
99.2k
  if( cu->chromaFormat != VVENC_CHROMA_400 && cu->Cb().valid() ) m_cLoopFilter.setOrigin( CH_C, cu->chromaPos() );
3850
3851
  //deblock
3852
99.2k
  if( leftEdgeAvai )
3853
73.2k
  {
3854
73.2k
    m_cLoopFilter.loopFilterCu( *cu, dbChType, EDGE_VER, m_dbBuffer );
3855
73.2k
  }
3856
3857
99.2k
  if( topEdgeAvai )
3858
75.0k
  {
3859
75.0k
    m_cLoopFilter.loopFilterCu( *cu, dbChType, EDGE_HOR, m_dbBuffer );
3860
75.0k
  }
3861
3862
  //calculate difference between DB_before_SSE and DB_after_SSE for neighbouring CUs
3863
99.2k
  Distortion distBeforeDb = 0, distAfterDb = 0, distCur = 0;
3864
242k
  for (int compIdx = compStr; compIdx <= compEnd; compIdx++)
3865
143k
  {
3866
143k
    ComponentID compId = (ComponentID)compIdx;
3867
143k
    {
3868
143k
      CompArea compArea = currCsArea.block( compId );
3869
143k
      CompArea         locArea  = compArea;
3870
143k
      locArea.x -= cu->blocks[compIdx].x;
3871
143k
      locArea.y -= cu->blocks[compIdx].y;
3872
143k
      CPelBuf reco      = picDbBuf.getBuf( locArea );
3873
143k
      CPelBuf org       = cs.getOrgBuf( compId );
3874
143k
      distCur += xGetDistortionDb( cs, org, reco, compArea, false );
3875
143k
    }
3876
3877
143k
    if ( leftEdgeAvai )
3878
100k
    {
3879
100k
      const CompArea&  compArea = areaLeft.block( compId );
3880
100k
      CompArea         locArea  = compArea;
3881
100k
      locArea.x -= cu->blocks[compIdx].x;
3882
100k
      locArea.y -= cu->blocks[compIdx].y;
3883
100k
      CPelBuf org    = cs.picture->getOrigBuf( compArea );
3884
100k
      if ( cs.picture->getFilteredOrigBuffer().valid() )
3885
0
      {
3886
0
        org = cs.picture->getFiltOrigBuf( compArea );
3887
0
      }
3888
100k
      CPelBuf reco   = cs.picture->getRecoBuf( compArea );
3889
100k
      CPelBuf recoDb = picDbBuf.getBuf( locArea );
3890
100k
      distBeforeDb  += xGetDistortionDb( cs, org, reco,   compArea, true );
3891
100k
      distAfterDb   += xGetDistortionDb( cs, org, recoDb, compArea, false  );
3892
100k
    }
3893
3894
143k
    if ( topEdgeAvai )
3895
104k
    {
3896
104k
      const CompArea&  compArea = areaTop.block( compId );
3897
104k
      CompArea         locArea  = compArea;
3898
104k
      locArea.x -= cu->blocks[compIdx].x;
3899
104k
      locArea.y -= cu->blocks[compIdx].y;
3900
104k
      CPelBuf org    = cs.picture->getOrigBuf( compArea );
3901
104k
      if ( cs.picture->getFilteredOrigBuffer().valid() )
3902
0
      {
3903
0
        org = cs.picture->getFiltOrigBuf( compArea );
3904
0
      }
3905
104k
      CPelBuf reco   = recoAbove( compArea );
3906
104k
      CPelBuf recoDb = picDbBuf.getBuf( locArea );
3907
104k
      distBeforeDb  += xGetDistortionDb( cs, org, reco,   compArea, true );
3908
104k
      distAfterDb   += xGetDistortionDb( cs, org, recoDb, compArea, false  );
3909
104k
    }
3910
143k
  }
3911
3912
  //updated cost
3913
99.2k
  int64_t distTmp = distCur - cs.dist + distAfterDb - distBeforeDb;
3914
99.2k
  cs.costDbOffset = distTmp < 0 ? -m_cRdCost.calcRdCost( 0, -distTmp ) : m_cRdCost.calcRdCost( 0, distTmp );
3915
99.2k
}
3916
3917
Distortion EncCu::xGetDistortionDb(CodingStructure &cs, CPelBuf& org, CPelBuf& reco, const CompArea& compArea, bool beforeDb)
3918
553k
{
3919
553k
  Distortion dist;
3920
553k
  const ComponentID compID = compArea.compID;
3921
3922
553k
  dist = m_cRdCost.getDistPart(org, reco, cs.sps->bitDepths[toChannelType(compID)], compID, DF_SSE);
3923
553k
  return dist;
3924
553k
}
3925
3926
bool checkValidMvs( const CodingUnit& cu)
3927
0
{
3928
  // clang-format off
3929
0
  const int affineShiftTab[3] =
3930
0
  {
3931
0
    MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER,
3932
0
    MV_PRECISION_INTERNAL - MV_PRECISION_SIXTEENTH,
3933
0
    MV_PRECISION_INTERNAL - MV_PRECISION_INT
3934
0
  };
3935
3936
0
  const int normalShiftTab[NUM_IMV_MODES] =
3937
0
  {
3938
0
    MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER,
3939
0
    MV_PRECISION_INTERNAL - MV_PRECISION_INT,
3940
0
    MV_PRECISION_INTERNAL - MV_PRECISION_4PEL,
3941
0
    MV_PRECISION_INTERNAL - MV_PRECISION_HALF,
3942
0
  };
3943
  // clang-format on
3944
3945
0
  int mvShift;
3946
3947
0
  for (int refList = 0; refList < NUM_REF_PIC_LIST_01; refList++)
3948
0
  {
3949
0
    if (cu.refIdx[refList] >= 0)
3950
0
    {
3951
0
      if (!cu.affine)
3952
0
      {
3953
0
        mvShift = normalShiftTab[cu.imv];
3954
0
        Mv signaledmvd(cu.mvd[refList][0].hor >> mvShift, cu.mvd[refList][0].ver >> mvShift);
3955
0
        if (!((signaledmvd.hor >= MVD_MIN) && (signaledmvd.hor <= MVD_MAX)) || !((signaledmvd.ver >= MVD_MIN) && (signaledmvd.ver <= MVD_MAX)))
3956
0
          return false;
3957
0
      }
3958
0
      else
3959
0
      {
3960
0
        for (int ctrlP = 1 + (cu.affineType == AFFINEMODEL_6PARAM); ctrlP >= 0; ctrlP--)
3961
0
        {
3962
0
          mvShift = affineShiftTab[cu.imv];
3963
0
          Mv signaledmvd(cu.mvd[refList][ctrlP].hor >> mvShift, cu.mvd[refList][ctrlP].ver >> mvShift);
3964
0
          if (!((signaledmvd.hor >= MVD_MIN) && (signaledmvd.hor <= MVD_MAX)) || !((signaledmvd.ver >= MVD_MIN) && (signaledmvd.ver <= MVD_MAX)))
3965
0
            return false;;
3966
0
        }
3967
0
      }
3968
0
    }
3969
0
  }
3970
  // avoid MV exceeding 18-bit dynamic range
3971
0
  const int maxMv = 1 << 17;
3972
0
  if (!cu.affine && !cu.mergeFlag)
3973
0
  {
3974
0
    if(    ( cu.refIdx[ 0 ] >= 0 && ( cu.mv[ 0 ][ 0 ].getAbsHor() >= maxMv || cu.mv[ 0 ][ 0 ].getAbsVer() >= maxMv ) )
3975
0
        || ( cu.refIdx[ 1 ] >= 0 && ( cu.mv[ 1 ][ 0 ].getAbsHor() >= maxMv || cu.mv[ 1 ][ 0 ].getAbsVer() >= maxMv ) ) )
3976
0
    {
3977
0
      return false;
3978
0
    }
3979
0
  }
3980
0
  if( cu.affine && !cu.mergeFlag )
3981
0
  {
3982
0
    for( int refList = 0; refList < NUM_REF_PIC_LIST_01; refList++ )
3983
0
    {
3984
0
      if( cu.refIdx[ refList ] >= 0 )
3985
0
      {
3986
0
        for( int ctrlP = 1 + ( cu.affineType == AFFINEMODEL_6PARAM ); ctrlP >= 0; ctrlP-- )
3987
0
        {
3988
0
          if( cu.mv[ refList ][ ctrlP ].getAbsHor() >= maxMv || cu.mv[ refList ][ ctrlP ].getAbsVer() >= maxMv )
3989
0
          {
3990
0
            return false;
3991
0
          }
3992
0
        }
3993
0
      }
3994
0
    }
3995
0
  }
3996
0
  return true;
3997
0
}
3998
3999
4000
void EncCu::xEncodeInterResidual( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode, int residualPass, bool* bestHasNonResi, double* equBcwCost )
4001
0
{
4002
0
  if( residualPass == 1 && encTestMode.lossless )
4003
0
  {
4004
0
    return;
4005
0
  }
4006
4007
0
  CodingUnit*            cu        = tempCS->getCU( partitioner.chType, partitioner.treeType );
4008
0
  double   bestCostInternal        = MAX_DOUBLE;
4009
4010
0
  if( !checkValidMvs( *cu ) )
4011
0
    return;
4012
4013
0
  double  currBestCost = MAX_DOUBLE;
4014
4015
  // For SBT
4016
0
  double     bestCost          = bestCS->cost;
4017
0
  double     bestCostBegin     = bestCS->cost;
4018
0
  const CodingUnit* prevBestCU = bestCS->getCU( partitioner.chType, partitioner.treeType );
4019
0
  uint8_t    prevBestSbt       = ( prevBestCU == nullptr ) ? 0 : prevBestCU->sbtInfo;
4020
0
  Distortion sbtOffDist        = 0;
4021
0
  bool       sbtOffRootCbf     = 0;
4022
0
  double     sbtOffCost        = MAX_DOUBLE;
4023
0
  uint8_t    currBestSbt       = 0;
4024
0
  uint8_t    histBestSbt       = MAX_UCHAR;
4025
0
  Distortion curPuSse          = MAX_DISTORTION;
4026
0
  uint8_t    numRDOTried       = 0;
4027
0
  bool       doPreAnalyzeResi  = false;
4028
0
  const bool mtsAllowed        =   tempCS->sps->MTSInter && cu->Y().maxDim() <= MTS_INTER_MAX_CU_SIZE;
4029
0
  const uint8_t sbtAllowed     = ( tempCS->pps->picWidthInLumaSamples < SBT_FAST64_WIDTH_THRESHOLD || m_pcEncCfg->m_SBT > 1 ) && cu->Y().maxDim() > 32 ? 0 : CU::checkAllowedSbt(*cu);
4030
4031
0
  if( sbtAllowed )
4032
0
  {
4033
    //SBT resolution-dependent fast algorithm: not try size-64 SBT in RDO for low-resolution sequences (now resolution below HD)
4034
0
    doPreAnalyzeResi = ( sbtAllowed || mtsAllowed ) && residualPass == 0;
4035
0
    m_cInterSearch.getBestSbt( tempCS, cu, histBestSbt, curPuSse, sbtAllowed, doPreAnalyzeResi, mtsAllowed );
4036
0
  }
4037
4038
0
  cu->skip    = false;
4039
0
  cu->sbtInfo = 0;
4040
4041
0
  const bool skipResidual = residualPass == 1;
4042
0
  if( skipResidual || histBestSbt == MAX_UCHAR || !CU::isSbtMode( histBestSbt ) )
4043
0
  {
4044
0
    xRestoreStartCtx();
4045
0
    m_cInterSearch.encodeResAndCalcRdInterCU( *tempCS, partitioner, skipResidual, bestCS->cost );
4046
0
    xEncodeDontSplit( *tempCS, partitioner );
4047
0
    xCheckDQP       ( *tempCS, partitioner );
4048
4049
0
    if( NULL != bestHasNonResi && (bestCostInternal > tempCS->cost) )
4050
0
    {
4051
0
      bestCostInternal = tempCS->cost;
4052
0
      if( !cu->ciip )
4053
0
        *bestHasNonResi = !cu->rootCbf;
4054
0
    }
4055
4056
0
    if( cu->rootCbf == false )
4057
0
    {
4058
0
      if( cu->ciip )
4059
0
      {
4060
0
        tempCS->cost = MAX_DOUBLE;
4061
0
        tempCS->costDbOffset = 0;
4062
0
        return;
4063
0
      }
4064
0
    }
4065
0
    currBestCost = tempCS->cost;
4066
0
    if( sbtAllowed )
4067
0
    {
4068
0
      sbtOffCost    = tempCS->cost;
4069
0
      sbtOffDist    = tempCS->dist;
4070
0
      sbtOffRootCbf = cu->rootCbf;
4071
0
      currBestSbt   = cu->firstTU->mtsIdx[COMP_Y] > MTS_SKIP ? SBT_OFF_MTS : SBT_OFF_DCT;
4072
0
      numRDOTried  += mtsAllowed ? 2 : 1;
4073
0
    }
4074
4075
0
    DTRACE_MODE_COST( *tempCS, m_cRdCost.getLambda( true ) );
4076
0
    xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
4077
4078
0
    STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_RD_TESTS][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
4079
0
    STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_RD_TESTS][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
4080
0
  }
4081
4082
0
  if( sbtAllowed && ( m_pcEncCfg->m_SBT == 1 || sbtOffRootCbf ) )
4083
0
  {
4084
0
    bool swapped = false; // avoid unwanted data copy
4085
0
    uint8_t numSbtRdo = CU::numSbtModeRdo( sbtAllowed );
4086
    //early termination if all SBT modes are not allowed
4087
    //normative
4088
0
    if( !sbtAllowed || skipResidual )
4089
0
    {
4090
0
      numSbtRdo = 0;
4091
0
    }
4092
    //fast algorithm
4093
0
    if( ( histBestSbt != MAX_UCHAR && !CU::isSbtMode( histBestSbt ) ) || m_cInterSearch.getSkipSbtAll() )
4094
0
    {
4095
0
      numSbtRdo = 0;
4096
0
    }
4097
0
    if( bestCost != MAX_DOUBLE && sbtOffCost != MAX_DOUBLE )
4098
0
    {
4099
0
      double th = 1.07;
4100
0
      if( !( prevBestSbt == 0 || m_sbtCostSave[0] == MAX_DOUBLE ) )
4101
0
      {
4102
0
        assert( m_sbtCostSave[1] <= m_sbtCostSave[0] );
4103
0
        th *= ( m_sbtCostSave[0] / m_sbtCostSave[1] );
4104
0
      }
4105
0
      if( sbtOffCost > bestCost * th )
4106
0
      {
4107
0
        numSbtRdo = 0;
4108
0
      }
4109
0
    }
4110
0
    if( !sbtOffRootCbf && sbtOffCost != MAX_DOUBLE )
4111
0
    {
4112
0
      double th = Clip3( 0.05, 0.55, ( 27 - cu->qp ) * 0.02 + 0.35 );
4113
0
      if( sbtOffCost < m_cRdCost.calcRdCost( ( cu->lwidth() * cu->lheight() ) << SCALE_BITS, 0 ) * th )
4114
0
      {
4115
0
        numSbtRdo = 0;
4116
0
      }
4117
0
    }
4118
4119
0
    if( histBestSbt != MAX_UCHAR && numSbtRdo != 0 )
4120
0
    {
4121
0
      numSbtRdo = 1;
4122
0
      m_cInterSearch.initSbtRdoOrder( CU::getSbtMode( CU::getSbtIdx( histBestSbt ), CU::getSbtPos( histBestSbt ) ) );
4123
0
    }
4124
4125
0
    for( int sbtModeIdx = 0; sbtModeIdx < numSbtRdo; sbtModeIdx++ )
4126
0
    {
4127
0
      uint8_t sbtMode = m_cInterSearch.getSbtRdoOrder( sbtModeIdx );
4128
0
      uint8_t sbtIdx = CU::getSbtIdxFromSbtMode( sbtMode );
4129
0
      uint8_t sbtPos = CU::getSbtPosFromSbtMode( sbtMode );
4130
4131
      //fast algorithm (early skip, save & load)
4132
0
      if( histBestSbt == MAX_UCHAR )
4133
0
      {
4134
0
        uint8_t skipCode = m_cInterSearch.skipSbtByRDCost( cu->lwidth(), cu->lheight(), cu->mtDepth, sbtIdx, sbtPos, bestCS->cost, sbtOffDist, sbtOffCost, sbtOffRootCbf );
4135
0
        if( skipCode != MAX_UCHAR )
4136
0
        {
4137
0
          continue;
4138
0
        }
4139
4140
0
        if( sbtModeIdx > 0 )
4141
0
        {
4142
0
          uint8_t prevSbtMode = m_cInterSearch.getSbtRdoOrder( sbtModeIdx - 1 );
4143
          //make sure the prevSbtMode is the same size as the current SBT mode (otherwise the estimated dist may not be comparable)
4144
0
          if( CU::isSameSbtSize( prevSbtMode, sbtMode ) )
4145
0
          {
4146
0
            Distortion currEstDist = m_cInterSearch.getEstDistSbt( sbtMode );
4147
0
            Distortion prevEstDist = m_cInterSearch.getEstDistSbt( prevSbtMode );
4148
0
            if( currEstDist > prevEstDist * 1.15 )
4149
0
            {
4150
0
              continue;
4151
0
            }
4152
0
          }
4153
0
        }
4154
0
      }
4155
4156
      //init tempCS and TU
4157
0
      if( bestCost == bestCS->cost ) //The first EMT pass didn't become the bestCS, so we clear the TUs generated
4158
0
      {
4159
0
        tempCS->clearTUs();
4160
0
      }
4161
0
      else if( !swapped )
4162
0
      {
4163
0
        tempCS->initStructData( encTestMode.qp );
4164
0
        tempCS->copyStructure( *bestCS, partitioner.chType, partitioner.treeType );
4165
0
        tempCS->getPredBuf().copyFrom( bestCS->getPredBuf() );
4166
0
        bestCost = bestCS->cost;
4167
0
        cu = tempCS->getCU( partitioner.chType, partitioner.treeType );
4168
0
        swapped = true;
4169
0
      }
4170
0
      else
4171
0
      {
4172
0
        tempCS->clearTUs();
4173
0
        bestCost = bestCS->cost;
4174
0
        cu = tempCS->getCU( partitioner.chType, partitioner.treeType );
4175
0
      }
4176
4177
      //we need to restart the distortion for the new tempCS, the bit count and the cost
4178
0
      tempCS->dist     = 0;
4179
0
      tempCS->fracBits = 0;
4180
0
      tempCS->cost     = MAX_DOUBLE;
4181
0
      cu->skip         = false;
4182
4183
4184
      //set SBT info
4185
0
      cu->sbtInfo = (sbtPos << 4) + sbtIdx;
4186
4187
      //try residual coding
4188
0
      xRestoreStartCtx();
4189
0
      m_cInterSearch.encodeResAndCalcRdInterCU( *tempCS, partitioner, skipResidual, bestCS->cost );
4190
0
      numRDOTried++;
4191
4192
0
      xEncodeDontSplit( *tempCS, partitioner );
4193
0
      xCheckDQP( *tempCS, partitioner );
4194
4195
0
      if( NULL != bestHasNonResi && ( bestCostInternal > tempCS->cost ) )
4196
0
      {
4197
0
        bestCostInternal = tempCS->cost;
4198
0
        if( !( cu->ciip ) )
4199
0
          *bestHasNonResi = !cu->rootCbf;
4200
0
      }
4201
4202
0
      if( tempCS->cost < currBestCost )
4203
0
      {
4204
0
        currBestSbt = cu->sbtInfo;
4205
0
        currBestCost = tempCS->cost;
4206
0
      }
4207
0
      else if( m_pcEncCfg->m_SBT > 2 )
4208
0
      {
4209
0
        sbtModeIdx = numSbtRdo;
4210
0
      }
4211
4212
0
      DTRACE_MODE_COST( *tempCS, m_cRdCost.getLambda( true ) );
4213
0
      xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
4214
0
      STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_RD_TESTS][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
4215
0
      STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_RD_TESTS][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
4216
0
    }
4217
4218
0
    if( bestCostBegin != bestCS->cost )
4219
0
    {
4220
0
      m_sbtCostSave[0] = sbtOffCost;
4221
0
      m_sbtCostSave[1] = currBestCost;
4222
0
    }
4223
4224
0
    if( histBestSbt == MAX_UCHAR && doPreAnalyzeResi && numRDOTried > 1 )
4225
0
    {
4226
0
      auto& slsSbt = static_cast<CacheBlkInfoCtrl&>( m_modeCtrl );
4227
0
      int slShift = 4 + std::min( Log2( cu->lwidth() ) + Log2( cu->lheight() ), 9 );
4228
0
      slsSbt.saveBestSbt( cu->cs->area, (uint32_t)( curPuSse >> slShift ), currBestSbt );
4229
0
    }
4230
    
4231
0
    if( ETM_INTER_ME == encTestMode.type )
4232
0
    {
4233
0
      if( equBcwCost != NULL )
4234
0
      {
4235
0
        if( tempCS->cost < ( *equBcwCost ) && cu->BcwIdx == BCW_DEFAULT )
4236
0
        {
4237
0
          ( *equBcwCost ) = tempCS->cost;
4238
0
        }
4239
0
      }
4240
0
      else
4241
0
      {
4242
0
        CHECK( equBcwCost == NULL, "equBcwCost == NULL" );
4243
0
      }
4244
0
      if( tempCS->slice->checkLDC && !cu->imv && cu->BcwIdx != BCW_DEFAULT && tempCS->cost < m_bestBcwCost[1] )
4245
0
      {
4246
0
        if( tempCS->cost < m_bestBcwCost[0] )
4247
0
        {
4248
0
          m_bestBcwCost[1] = m_bestBcwCost[0];
4249
0
          m_bestBcwCost[0] = tempCS->cost;
4250
0
          m_bestBcwIdx[1] = m_bestBcwIdx[0];
4251
0
          m_bestBcwIdx[0] = cu->BcwIdx;
4252
0
        }
4253
0
        else
4254
0
        {
4255
0
          m_bestBcwCost[1] = tempCS->cost;
4256
0
          m_bestBcwIdx[1] = cu->BcwIdx;
4257
0
        }
4258
0
      }
4259
0
    }
4260
0
  }
4261
4262
0
  tempCS->cost = currBestCost;
4263
0
}
4264
4265
void EncCu::xEncodeDontSplit( CodingStructure &cs, Partitioner &partitioner )
4266
125k
{
4267
125k
  m_CABACEstimator->resetBits();
4268
4269
125k
  m_CABACEstimator->split_cu_mode( CU_DONT_SPLIT, cs, partitioner );
4270
125k
  if( partitioner.treeType == TREE_C )
4271
125k
    CHECK( m_CABACEstimator->getEstFracBits() != 0, "must be 0 bit" );
4272
4273
125k
  cs.fracBits += m_CABACEstimator->getEstFracBits(); // split bits
4274
125k
  cs.cost      = m_cRdCost.calcRdCost( cs.fracBits, cs.dist );
4275
125k
}
4276
4277
void EncCu::xReuseCachedResult( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner )
4278
0
{
4279
0
  EncTestMode cachedMode;
4280
4281
0
  if( ! m_modeCtrl.setCsFrom( *tempCS, cachedMode, partitioner ) )
4282
0
  {
4283
0
    THROW( "Should never happen!" );
4284
0
  }
4285
4286
0
  CodingUnit& cu = *tempCS->cus.front();
4287
0
  partitioner.setCUData( cu );
4288
4289
0
  if( CU::isIntra( cu ) )
4290
0
  {
4291
0
    if( isLuma( cu.chType ) )
4292
0
    {
4293
0
      cu.getMotionBuf().memset( -1 ); // clear motion buf
4294
0
    }
4295
0
    xReconIntraQT( cu );
4296
0
  }
4297
0
  else
4298
0
  {
4299
0
    xDeriveCUMV( cu );
4300
0
    xReconInter( cu );
4301
0
  }
4302
4303
0
  xSetStartCtx();
4304
0
  m_CABACEstimator->resetBits();
4305
4306
0
  CUCtx cuCtx;
4307
0
  cuCtx.isDQPCoded = true;
4308
0
  cuCtx.isChromaQpAdjCoded = true;
4309
0
  m_CABACEstimator->coding_unit( cu, partitioner, cuCtx );
4310
4311
0
  tempCS->fracBits = m_CABACEstimator->getEstFracBits();
4312
0
  tempCS->cost     = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
4313
4314
0
  xEncodeDontSplit( *tempCS,         partitioner );
4315
0
  xCheckDQP       ( *tempCS,         partitioner );
4316
0
  xCheckBestMode  (  tempCS, bestCS, partitioner, cachedMode, m_EDO );
4317
0
}
4318
4319
uint64_t EncCu::xCalcPuMeBits( const CodingUnit &cu )
4320
0
{
4321
0
  CHECK( !cu.mergeFlag, "Should only be used for merge!" );
4322
0
  CHECK( CU::isIBC( cu ), "Should not be used for IBC" );
4323
4324
0
  m_CABACEstimator->resetBits();
4325
0
  m_CABACEstimator->merge_flag(cu);
4326
0
  if( cu.mergeFlag )
4327
0
  {
4328
0
    m_CABACEstimator->merge_data( cu );
4329
0
  }
4330
0
  return m_CABACEstimator->getEstFracBits();
4331
0
}
4332
4333
double EncCu::xCalcDistortion(CodingStructure *&cur_CS, ChannelType chType, int BitDepth, int imv)
4334
0
{
4335
0
  const auto currDist1 = m_cRdCost.getDistPart(cur_CS->getOrgBuf( COMP_Y ), cur_CS->getPredBuf( COMP_Y ), BitDepth, COMP_Y, m_pcEncCfg->m_fastHad ? DF_HAD_fast : DF_HAD );
4336
0
  unsigned int uiMvBits = 0;
4337
0
  unsigned imvShift = imv == IMV_HPEL ? 1 : (imv << 1);
4338
0
  const CodingUnit& cu = *cur_CS->getCU( chType, TREE_D);
4339
0
  if (cu.interDir != 2)
4340
0
  {
4341
0
    uiMvBits += m_cRdCost.getBitsOfVectorWithPredictor(cu.mvd[0][0].hor, cu.mvd[0][0].ver, imvShift + MV_FRACTIONAL_BITS_DIFF);
4342
0
  }
4343
0
  if (cu.interDir != 1)
4344
0
  {
4345
0
    uiMvBits += m_cRdCost.getBitsOfVectorWithPredictor(cu.mvd[1][0].hor, cu.mvd[1][0].ver, imvShift + MV_FRACTIONAL_BITS_DIFF);
4346
0
  }
4347
0
  return (double(currDist1) + (double)m_cRdCost.getCost(uiMvBits));
4348
0
}
4349
4350
int EncCu::xCheckMMVDCand(MmvdIdx& mmvdMergeCand, int& bestDir, int tempNum, double& bestCostOffset, double& bestCostMerge, double bestCostList )
4351
0
{
4352
0
  int baseIdx = mmvdMergeCand.val / MMVD_MAX_REFINE_NUM;
4353
0
  int CandCur = mmvdMergeCand.val - MMVD_MAX_REFINE_NUM * baseIdx;
4354
4355
0
  if( m_pcEncCfg->m_MMVD > 2 )
4356
0
  {
4357
0
    if( CandCur % 4 == 0 )
4358
0
    {
4359
0
      if( ( bestCostOffset >= bestCostMerge ) && ( CandCur >= 4 ) )
4360
0
      {
4361
0
        if( mmvdMergeCand.val > MMVD_MAX_REFINE_NUM )
4362
0
        {
4363
0
          return 2;
4364
0
        }
4365
0
        else
4366
0
        {
4367
0
          mmvdMergeCand.val = MMVD_MAX_REFINE_NUM;
4368
0
          if( tempNum == mmvdMergeCand.val )
4369
0
          {
4370
0
            return 2;
4371
0
          }
4372
0
        }
4373
0
      }
4374
      //reset
4375
0
      bestCostOffset = MAX_DOUBLE;
4376
0
      bestCostMerge  = bestCostList;
4377
0
    }
4378
0
  }
4379
4380
0
  if( mmvdMergeCand.val == MMVD_MAX_REFINE_NUM )
4381
0
  {
4382
0
    bestDir = 0;
4383
0
  }
4384
0
  if( CandCur >= 4 )
4385
0
  {
4386
0
    if( CandCur % 4 != bestDir )
4387
0
    {
4388
0
      return 1;
4389
0
    }
4390
0
  }
4391
0
  return 0;
4392
0
}
4393
4394
void EncCu::xInitLumaDeltaQpLUT()
4395
0
{
4396
  //TODO: to be discussed: add config parameters for these?
4397
0
  std::vector<int> defaultLumaLevelTodQp_QpChangePoints   =  { -3,  -2,  -1,   0,   1,   2,   3,   4,   5,   6 };
4398
0
  std::vector<int> defaultLumaLevelTodQp_LumaChangePoints =  {  0, 301, 367, 434, 501, 567, 634, 701, 767, 834 };
4399
  
4400
0
  int         lastDeltaQPValue = 0;
4401
0
  std::size_t nextSparseIndex = 0;
4402
0
  for( int index = 0; index < LUMA_LEVEL_TO_DQP_LUT_MAXSIZE; index++ )
4403
0
  {
4404
0
    while( nextSparseIndex < defaultLumaLevelTodQp_QpChangePoints.size() && index >= defaultLumaLevelTodQp_LumaChangePoints[nextSparseIndex] )
4405
0
    {
4406
0
      lastDeltaQPValue = defaultLumaLevelTodQp_QpChangePoints[nextSparseIndex];
4407
0
      nextSparseIndex++;
4408
0
    }
4409
0
    m_lumaLevelToDeltaQPLUT[index] = lastDeltaQPValue;
4410
0
  }
4411
0
}
4412
4413
MergeItem::MergeItem()
4414
45.8k
{
4415
4416
45.8k
}
4417
MergeItem::~MergeItem()
4418
45.8k
{
4419
4420
45.8k
}
4421
4422
void MergeItem::create( ChromaFormat chromaFormat, const Area &area )
4423
45.8k
{
4424
45.8k
  if( m_pelStorage.bufs.empty() )
4425
45.8k
  {
4426
45.8k
    m_pelStorage.create( chromaFormat, area );
4427
45.8k
    m_mvStorage .resize( area.area() >> ( MIN_CU_LOG2 << 1 ) );
4428
45.8k
  }
4429
4430
45.8k
  init();
4431
45.8k
}
4432
4433
void MergeItem::init()
4434
45.8k
{
4435
  // reset data
4436
45.8k
  cost        = MAX_DOUBLE;
4437
45.8k
  mergeIdx    = 0;
4438
45.8k
  bcwIdx      = 0;
4439
45.8k
  interDir    = 0;
4440
45.8k
  useAltHpelIf  = false;
4441
45.8k
  affineType    = AFFINEMODEL_4PARAM;
4442
45.8k
  mergeItemType = MergeItemType::NUM;
4443
4444
45.8k
  noBdofRefine  = false;
4445
45.8k
  noResidual    = false;
4446
4447
45.8k
  lumaPredReady   = false;
4448
45.8k
  chromaPredReady = false;
4449
45.8k
}
4450
4451
void MergeItem::importMergeInfo(const MergeCtx& mergeCtx, int _mergeIdx, MergeItemType _mergeItemType, CodingUnit& pu)
4452
0
{
4453
0
  mergeIdx      = _mergeIdx;
4454
0
  mergeItemType = _mergeItemType;
4455
4456
0
  if( mergeItemType != MergeItemType::GPM && mergeItemType != MergeItemType::MMVD )
4457
0
  {
4458
0
    mvField[REF_PIC_LIST_0][0] = mergeCtx.mvFieldNeighbours [mergeIdx][REF_PIC_LIST_0];
4459
0
    mvField[REF_PIC_LIST_1][0] = mergeCtx.mvFieldNeighbours [mergeIdx][REF_PIC_LIST_1];
4460
0
    interDir                   = mergeCtx.interDirNeighbours[mergeIdx];
4461
0
    bcwIdx                     = mergeCtx.BcwIdx            [mergeIdx];
4462
0
    useAltHpelIf               = mergeCtx.useAltHpelIf      [mergeIdx];
4463
0
  }
4464
4465
0
  switch( _mergeItemType )
4466
0
  {
4467
0
  case MergeItemType::REGULAR:
4468
0
  case MergeItemType::CIIP:
4469
0
    break;
4470
4471
0
  case MergeItemType::MMVD:
4472
0
  {
4473
0
    MmvdIdx candIdx;
4474
4475
0
    candIdx.val                = mergeIdx;
4476
0
    mvField[L0][0]             . setMvField( pu.mv[L0][0], pu.refIdx[0] );
4477
0
    mvField[L1][0]             . setMvField( pu.mv[L1][0], pu.refIdx[1] );
4478
0
    interDir                   = pu.interDir;
4479
0
    bcwIdx                     = pu.BcwIdx;
4480
0
    useAltHpelIf               = mergeCtx.useAltHpelIf[candIdx.pos.baseIdx];
4481
4482
0
    break;
4483
0
  }
4484
4485
0
  case MergeItemType::GPM:
4486
0
    mvField[L0][0]             . setMvField( Mv( 0, 0 ), -1 );
4487
0
    mvField[L1][0]             . setMvField( Mv( 0, 0 ), -1 );
4488
0
    bcwIdx                     = BCW_DEFAULT;
4489
0
    useAltHpelIf               = false;
4490
4491
0
    break;
4492
4493
0
  case MergeItemType::IBC:
4494
0
  default:
4495
0
    THROW( "Wrong merge item type" );
4496
0
  }
4497
4498
  // exportMergeInfo regenerates the motion of all these candidates: regular, CIIP and MMVD have one motion
4499
  // for the whole CU, which mvField holds, and GPM's comes from the split and the merge indices it stores
4500
0
}
4501
4502
void MergeItem::importMergeInfo( const AffineMergeCtx &mergeCtx, int _mergeIdx, MergeItemType _mergeItemType, CodingUnit& pu )
4503
0
{
4504
0
  mergeIdx      = _mergeIdx;
4505
0
  mergeItemType = _mergeItemType;
4506
4507
0
  affineType    = mergeCtx.affineType         [mergeIdx];
4508
0
  interDir      = mergeCtx.interDirNeighbours [mergeIdx];
4509
0
  bcwIdx        = mergeCtx.BcwIdx             [mergeIdx];
4510
0
  useAltHpelIf  = false;
4511
4512
0
  switch( _mergeItemType )
4513
0
  {
4514
0
  case MergeItemType::SBTMVP:
4515
    // the pu motion was already generated preparing for IFP check (unconditional)
4516
0
    mvField[L0][0] . setMvField( pu.mv[L0][0], pu.refIdx[L0] );
4517
0
    mvField[L1][0] . setMvField( pu.mv[L1][0], pu.refIdx[L1] );
4518
4519
0
    break;
4520
4521
0
  case MergeItemType::AFFINE:
4522
    // the pu motion was already generated preparing for IFP check (unconditional)
4523
0
    mvField[L0][0] . setMvField( pu.mv[L0][0], pu.refIdx[L0] );
4524
0
    mvField[L0][1] . setMvField( pu.mv[L0][1], pu.refIdx[L0] );
4525
0
    mvField[L0][2] . setMvField( pu.mv[L0][2], pu.refIdx[L0] );
4526
0
    mvField[L1][0] . setMvField( pu.mv[L1][0], pu.refIdx[L1] );
4527
0
    mvField[L1][1] . setMvField( pu.mv[L1][1], pu.refIdx[L1] );
4528
0
    mvField[L1][2] . setMvField( pu.mv[L1][2], pu.refIdx[L1] );
4529
4530
0
    break;
4531
4532
0
  default:
4533
0
    THROW( "Wrong merge item type" );
4534
0
  }
4535
4536
  // the MI buf was already generated preparing for IFP check (unconditional)
4537
0
  getMvBuf( pu ).copyFrom( pu.getMotionBuf() );
4538
0
}
4539
4540
bool MergeItem::exportMergeInfo( CodingUnit &pu, bool forceNoResidual, const MergeCtx& gpmMergeCtx ) const
4541
0
{
4542
0
  pu.mergeFlag        = true;
4543
0
  pu.mmvdMergeFlag    = false;
4544
0
  pu.interDir         = interDir;
4545
0
  pu.mergeIdx         = mergeIdx;
4546
0
  pu.mergeType        = MRG_TYPE_DEFAULT_N;
4547
0
  pu.mv[REF_PIC_LIST_0][0]  = mvField[REF_PIC_LIST_0][0].mv;
4548
0
  pu.mv[REF_PIC_LIST_1][0]  = mvField[REF_PIC_LIST_1][0].mv;
4549
0
  pu.refIdx[REF_PIC_LIST_0] = mvField[REF_PIC_LIST_0][0].refIdx;
4550
0
  pu.refIdx[REF_PIC_LIST_1] = mvField[REF_PIC_LIST_1][0].refIdx;
4551
0
  pu.mvd[REF_PIC_LIST_0][0] = Mv();
4552
0
  pu.mvd[REF_PIC_LIST_1][0] = Mv();
4553
0
  pu.mvpIdx[REF_PIC_LIST_0] = NOT_VALID;
4554
0
  pu.mvpIdx[REF_PIC_LIST_1] = NOT_VALID;
4555
0
  pu.mvpNum[REF_PIC_LIST_0] = NOT_VALID;
4556
0
  pu.mvpNum[REF_PIC_LIST_1] = NOT_VALID;
4557
0
  pu.BcwIdx         = ( interDir == 3 ) ? bcwIdx : BCW_DEFAULT;
4558
0
  pu.mcControl      = 0;
4559
0
  pu.mmvdSkip       = false;
4560
0
  pu.affine         = false;
4561
0
  pu.affineType     = AFFINEMODEL_4PARAM;
4562
0
  pu.geo            = false;
4563
0
  pu.mtsFlag        = false;
4564
0
  pu.ciip           = false;
4565
0
  pu.imv            = ( !pu.geo && useAltHpelIf ) ? IMV_HPEL : IMV_OFF;
4566
0
  pu.mvRefine       = false;
4567
4568
0
  const bool resetCiip2Regular = mergeItemType == MergeItemType::CIIP && forceNoResidual;
4569
0
  MergeItemType updatedType    = resetCiip2Regular ? MergeItemType::REGULAR : mergeItemType;
4570
4571
0
  switch( updatedType )
4572
0
  {
4573
0
  case MergeItemType::REGULAR:
4574
0
    CU::restrictBiPredMergeCandsOne( pu );
4575
0
    break;
4576
4577
0
  case MergeItemType::CIIP:
4578
0
    CHECK( forceNoResidual, "Cannot force no residuals for CIIP" );
4579
0
    pu.ciip           = true;
4580
0
    pu.intraDir[CH_L] = PLANAR_IDX;
4581
0
    pu.intraDir[CH_C] = DM_CHROMA_IDX;
4582
0
    break;
4583
4584
0
  case MergeItemType::MMVD:
4585
0
    pu.mmvdMergeFlag    = true;
4586
0
    pu.mmvdMergeIdx.val = mergeIdx;
4587
0
    if( forceNoResidual )
4588
0
    {
4589
0
      pu.mmvdSkip       = true;
4590
0
    }
4591
0
    CU::restrictBiPredMergeCandsOne( pu );
4592
0
    break;
4593
4594
0
  case MergeItemType::SBTMVP:
4595
0
    pu.affine    = true;
4596
0
    pu.mergeType = MRG_TYPE_SUBPU_ATMVP;
4597
0
    break;
4598
4599
0
  case MergeItemType::AFFINE:
4600
0
    pu.affine     = true;
4601
0
    pu.affineType = affineType;
4602
0
    pu.mv[L0][0]  = mvField[L0][0].mv;
4603
0
    pu.mv[L1][0]  = mvField[L1][0].mv;
4604
0
    pu.mv[L0][1]  = mvField[L0][1].mv;
4605
0
    pu.mv[L1][1]  = mvField[L1][1].mv;
4606
0
    pu.mv[L0][2]  = mvField[L0][2].mv;
4607
0
    pu.mv[L1][2]  = mvField[L1][2].mv;
4608
0
    pu.refIdx[L0] = mvField[L0][0].refIdx;
4609
0
    pu.refIdx[L1] = mvField[L1][0].refIdx;
4610
0
    break;
4611
4612
0
  case MergeItemType::GPM:
4613
0
    pu.mergeIdx = -1;
4614
0
    pu.geo      = true;
4615
0
    pu.BcwIdx   = BCW_DEFAULT;
4616
0
    updateGpmIdx( mergeIdx, pu.geoSplitDir, pu.geoMergeIdx );
4617
0
    pu.imv      = IMV_OFF;
4618
0
    break;
4619
4620
0
  case MergeItemType::IBC:
4621
0
  default:
4622
0
    THROW( "Wrong merge item type" );
4623
0
  }
4624
4625
0
  if( updatedType == MergeItemType::REGULAR || updatedType == MergeItemType::CIIP || updatedType == MergeItemType::MMVD )
4626
0
  {
4627
0
    CU::spanMotionInfo( pu );
4628
0
  }
4629
0
  else if( updatedType == MergeItemType::GPM )
4630
0
  {
4631
0
    CU::spanGeoMotionInfo( pu, gpmMergeCtx, pu.geoSplitDir, pu.geoMergeIdx[0], pu.geoMergeIdx[1] );
4632
0
  }
4633
0
  else
4634
0
  {
4635
0
    pu.getMotionBuf().copyFrom( getMvBuf( pu ) );
4636
0
  }
4637
4638
0
  return resetCiip2Regular;
4639
0
}
4640
4641
MergeItemList::MergeItemList()
4642
5.72k
{
4643
4644
5.72k
}
4645
4646
MergeItemList::~MergeItemList()
4647
5.72k
{
4648
5.72k
  for( MergeItem* p : m_list )
4649
0
  {
4650
0
    delete p;
4651
0
  }
4652
5.72k
  m_list.clear();
4653
4654
5.72k
  for( MergeItem *p : m_mergeItems )
4655
45.8k
  {
4656
45.8k
    delete p;
4657
45.8k
  }
4658
5.72k
  m_mergeItems.clear();
4659
5.72k
}
4660
4661
void MergeItemList::init( size_t maxSize, size_t maxExtSize, ChromaFormat chromaFormat, SizeType ctuWidth, SizeType ctuHeight )
4662
5.72k
{
4663
5.72k
  CHECK( !m_mergeItems.empty() || !m_list.empty(), "MergeItemList already initialized" );
4664
4665
5.72k
  m_list      . reserve( maxSize + 1 ); // to avoid reallocation when inserting a new item
4666
5.72k
  m_mergeItems. reserve( maxSize + 1 );
4667
5.72k
  m_maxSize   = maxSize;
4668
5.72k
  m_maxExtSize= maxExtSize;
4669
5.72k
  m_numExt    = 0;
4670
4671
51.5k
  for( int i = 0; i < maxSize + m_maxExtSize; i++ )
4672
45.8k
  {
4673
45.8k
    MergeItem *p = new MergeItem;
4674
45.8k
    p->create( chromaFormat, Area{ 0, 0, ctuWidth, ctuHeight } );
4675
45.8k
    m_mergeItems.push_back( p );
4676
45.8k
  }
4677
5.72k
}
4678
4679
MergeItem *MergeItemList::allocateNewMergeItem()
4680
0
{
4681
0
  m_numExt++;
4682
0
  CHECK( m_mergeItems.empty(), "Missing merge items!" );
4683
0
  CHECK( m_numExt > m_maxExtSize, "Taking out more external items than specified during list allocation!" );
4684
0
  MergeItem *p = m_mergeItems.back();
4685
0
  m_mergeItems.pop_back();
4686
0
  p->init();
4687
0
  return p;
4688
0
}
4689
4690
bool MergeItemList::insertMergeItemToList( MergeItem *p )
4691
0
{
4692
0
  CHECK( m_list.size() + m_mergeItems.size() + m_numExt != m_maxSize + m_maxExtSize, "Wrong number of items held" );
4693
4694
0
  m_numExt--;
4695
4696
0
  if( m_list.empty() )
4697
0
  {
4698
0
    m_list.push_back( p );
4699
0
  }
4700
0
  else if( m_list.size() == m_maxTrackingNum && p->cost >= m_list.back()->cost )
4701
0
  {
4702
0
    m_mergeItems.push_back( p );
4703
0
    return false;
4704
0
  }
4705
0
  else
4706
0
  {
4707
0
    if( m_list.size() == m_maxTrackingNum )
4708
0
    {
4709
0
      m_mergeItems.push_back( m_list.back() );
4710
0
      m_list      .pop_back();
4711
0
    }
4712
0
    auto it = std::find_if( m_list.begin(), m_list.end(), [&p]( const MergeItem *mi ) { return p->cost < mi->cost; } );
4713
0
    m_list.insert( it, p );
4714
0
  }
4715
4716
0
  return true;
4717
0
}
4718
4719
void MergeItemList::giveBackMergeItem( MergeItem *p )
4720
0
{
4721
0
  CHECK( m_list.size() + m_mergeItems.size() + m_numExt != m_maxSize + m_maxExtSize, "Wrong number of items held" );
4722
4723
0
  m_numExt--;
4724
4725
0
  m_mergeItems.push_back( p );
4726
0
}
4727
4728
MergeItem *MergeItemList::getMergeItemInList( size_t index )
4729
0
{
4730
0
  return index < m_maxTrackingNum ? m_list[index] : nullptr;
4731
0
}
4732
4733
void MergeItemList::resetList( size_t maxTrackingNum )
4734
0
{
4735
0
  CHECK( maxTrackingNum > m_maxSize, "Not enough items allocated to track " << maxTrackingNum << " items" );
4736
4737
0
  for( auto p : m_list )
4738
0
  {
4739
0
    m_mergeItems.push_back( p );
4740
0
  }
4741
0
  m_list.clear  ();
4742
4743
0
  m_maxTrackingNum = maxTrackingNum;
4744
0
}
4745
4746
void MergeItemList::shrinkList( size_t reduceTo )
4747
0
{
4748
0
  CHECK( reduceTo > m_maxSize, "Not enough items allocated to track " << reduceTo << " items" );
4749
4750
0
  while( m_list.size() > reduceTo )
4751
0
  {
4752
0
    m_mergeItems.push_back( m_list.back() );
4753
0
    m_list      .pop_back();
4754
0
  }
4755
0
}
4756
4757
} // namespace vvenc
4758
4759
//! \}