Coverage Report

Created: 2026-08-31 06:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/x265/source/common/quant.cpp
Line
Count
Source
1
/*****************************************************************************
2
 * Copyright (C) 2013-2020 MulticoreWare, Inc
3
 *
4
 * Authors: Steve Borho <steve@borho.org>
5
 *          Min Chen <chenm003@163.com>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
20
 *
21
 * This program is also available under a commercial proprietary license.
22
 * For more information, contact us at license @ x265.com.
23
 *****************************************************************************/
24
25
#include "common.h"
26
#include "primitives.h"
27
#include "quant.h"
28
#include "framedata.h"
29
#include "entropy.h"
30
#include "yuv.h"
31
#include "cudata.h"
32
#include "contexts.h"
33
34
using namespace X265_NS;
35
36
112k
#define SIGN(x,y) ((x^(y >> 31))-(y >> 31))
37
38
namespace {
39
40
struct coeffGroupRDStats
41
{
42
    int     nnzBeforePos0;     /* indicates coeff other than pos 0 are coded */
43
    int64_t codedLevelAndDist; /* distortion and level cost of coded coefficients */
44
    int64_t uncodedDist;       /* uncoded distortion cost of coded coefficients */
45
    int64_t sigCost;           /* cost of signaling significant coeff bitmap */
46
    int64_t sigCost0;          /* cost of signaling sig coeff bit of coeff 0 */
47
};
48
49
inline int fastMin(int x, int y)
50
1.10M
{
51
1.10M
    return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // min(x, y)
52
1.10M
}
53
54
inline int getICRate(uint32_t absLevel, int32_t diffLevel, const int* greaterOneBits, const int* levelAbsBits, const uint32_t absGoRice, const uint32_t maxVlc, const uint32_t c1c2Rate)
55
154k
{
56
154k
    X265_CHECK(absGoRice <= 4, "absGoRice check failure\n");
57
154k
    if (!absLevel)
58
1.97k
    {
59
1.97k
        X265_CHECK(diffLevel < 0, "diffLevel check failure\n");
60
1.97k
        return 0;
61
1.97k
    }
62
152k
    int rate = 0;
63
64
152k
    if (diffLevel < 0)
65
13.0k
    {
66
13.0k
        X265_CHECK(absLevel <= 2, "absLevel check failure\n");
67
13.0k
        rate += greaterOneBits[(absLevel == 2)];
68
69
13.0k
        if (absLevel == 2)
70
4.59k
            rate += levelAbsBits[0];
71
13.0k
    }
72
139k
    else
73
139k
    {
74
139k
        uint32_t symbol = diffLevel;
75
139k
        bool expGolomb = (symbol > maxVlc);
76
77
139k
        if (expGolomb)
78
119k
        {
79
119k
            absLevel = symbol - maxVlc;
80
81
            // NOTE: mapping to x86 hardware instruction BSR
82
119k
            unsigned long size;
83
119k
            BSR(size, absLevel);
84
119k
            int egs = size * 2 + 1;
85
86
119k
            rate += egs << 15;
87
88
            // NOTE: in here, expGolomb=true means (symbol >= maxVlc + 1)
89
119k
            X265_CHECK(fastMin(symbol, (maxVlc + 1)) == (int)maxVlc + 1, "min check failure\n");
90
119k
            symbol = maxVlc + 1;
91
119k
        }
92
93
139k
        uint32_t prefLen = (symbol >> absGoRice) + 1;
94
139k
        uint32_t numBins = fastMin(prefLen + absGoRice, 8 /* g_goRicePrefixLen[absGoRice] + absGoRice */);
95
96
139k
        rate += numBins << 15;
97
139k
        rate += c1c2Rate;
98
139k
    }
99
152k
    return rate;
100
154k
}
101
102
#if CHECKED_BUILD || _DEBUG
103
inline int getICRateNegDiff(uint32_t absLevel, const int* greaterOneBits, const int* levelAbsBits)
104
{
105
    X265_CHECK(absLevel <= 2, "absLevel check failure\n");
106
107
    int rate;
108
    if (absLevel == 0)
109
        rate = 0;
110
    else if (absLevel == 2)
111
        rate = greaterOneBits[1] + levelAbsBits[0];
112
    else
113
        rate = greaterOneBits[0];
114
    return rate;
115
}
116
#endif
117
118
inline int getICRateLessVlc(uint32_t absLevel, int32_t diffLevel, const uint32_t absGoRice)
119
102k
{
120
102k
    X265_CHECK(absGoRice <= 4, "absGoRice check failure\n");
121
102k
    if (!absLevel)
122
0
    {
123
0
        X265_CHECK(diffLevel < 0, "diffLevel check failure\n");
124
0
        return 0;
125
0
    }
126
102k
    int rate;
127
128
102k
    uint32_t symbol = diffLevel;
129
102k
    uint32_t prefLen = (symbol >> absGoRice) + 1;
130
102k
    uint32_t numBins = fastMin(prefLen + absGoRice, 8 /* g_goRicePrefixLen[absGoRice] + absGoRice */);
131
132
102k
    rate = numBins << 15;
133
134
102k
    return rate;
135
102k
}
136
137
/* Calculates the cost for specific absolute transform level */
138
inline uint32_t getICRateCost(uint32_t absLevel, int32_t diffLevel, const int* greaterOneBits, const int* levelAbsBits, uint32_t absGoRice, const uint32_t c1c2Rate)
139
169k
{
140
169k
    X265_CHECK(absLevel, "absLevel should not be zero\n");
141
142
169k
    if (diffLevel < 0)
143
12.7k
    {
144
12.7k
        X265_CHECK((absLevel == 1) || (absLevel == 2), "absLevel range check failure\n");
145
146
12.7k
        uint32_t rate = greaterOneBits[(absLevel == 2)];
147
12.7k
        if (absLevel == 2)
148
5.59k
            rate += levelAbsBits[0];
149
12.7k
        return rate;
150
12.7k
    }
151
156k
    else
152
156k
    {
153
156k
        uint32_t rate;
154
156k
        uint32_t symbol = diffLevel;
155
156k
        if ((symbol >> absGoRice) < COEF_REMAIN_BIN_REDUCTION)
156
52.5k
        {
157
52.5k
            uint32_t length = symbol >> absGoRice;
158
52.5k
            rate = (length + 1 + absGoRice) << 15;
159
52.5k
        }
160
104k
        else
161
104k
        {
162
104k
            uint32_t length = 0;
163
104k
            symbol = (symbol >> absGoRice) - COEF_REMAIN_BIN_REDUCTION;
164
104k
            if (symbol)
165
95.6k
            {
166
95.6k
                unsigned long idx;
167
95.6k
                BSR(idx, symbol + 1);
168
95.6k
                length = idx;
169
95.6k
            }
170
171
104k
            rate = (COEF_REMAIN_BIN_REDUCTION + length + absGoRice + 1 + length) << 15;
172
104k
        }
173
156k
        rate += c1c2Rate;
174
156k
        return rate;
175
156k
    }
176
169k
}
177
178
}
179
180
Quant::rdoQuant_t Quant::rdoQuant_func[NUM_CU_DEPTH] = {&Quant::rdoQuant<2>, &Quant::rdoQuant<3>, &Quant::rdoQuant<4>, &Quant::rdoQuant<5>};
181
182
Quant::Quant()
183
20.5k
{
184
20.5k
    m_resiDctCoeff = NULL;
185
20.5k
    m_fencDctCoeff = NULL;
186
20.5k
    m_fencShortBuf = NULL;
187
20.5k
    m_frameNr      = NULL;
188
20.5k
    m_nr           = NULL;
189
20.5k
}
190
191
bool Quant::init(double psyScale, const ScalingList& scalingList, Entropy& entropy)
192
20.5k
{
193
20.5k
    m_entropyCoder = &entropy;
194
20.5k
    m_psyRdoqScale = (int32_t)(psyScale * 256.0);
195
20.5k
    X265_CHECK((psyScale * 256.0) < (double)MAX_INT, "psyScale value too large\n");
196
20.5k
    m_scalingList  = &scalingList;
197
20.5k
    m_resiDctCoeff = X265_MALLOC(int16_t, MAX_TR_SIZE * MAX_TR_SIZE * 2);
198
20.5k
    m_fencDctCoeff = m_resiDctCoeff + (MAX_TR_SIZE * MAX_TR_SIZE);
199
20.5k
    m_fencShortBuf = X265_MALLOC(int16_t, MAX_TR_SIZE * MAX_TR_SIZE);
200
201
20.5k
    return m_resiDctCoeff && m_fencShortBuf;
202
20.5k
}
203
204
bool Quant::allocNoiseReduction(const x265_param& param)
205
0
{
206
0
    m_frameNr = X265_MALLOC(NoiseReduction, param.frameNumThreads);
207
0
    if (m_frameNr)
208
0
        memset(m_frameNr, 0, sizeof(NoiseReduction) * param.frameNumThreads);
209
0
    else
210
0
        return false;
211
0
    return true;
212
0
}
213
214
Quant::~Quant()
215
20.5k
{
216
20.5k
    X265_FREE(m_frameNr);
217
20.5k
    X265_FREE(m_resiDctCoeff);
218
20.5k
    X265_FREE(m_fencShortBuf);
219
20.5k
}
220
221
void Quant::setQPforQuant(const CUData& ctu, int qp)
222
27.3k
{
223
27.3k
    m_nr = m_frameNr ? &m_frameNr[ctu.m_encData->m_frameEncoderID] : NULL;
224
27.3k
    m_qpParam[TEXT_LUMA].setQpParam(qp + QP_BD_OFFSET);
225
27.3k
    m_rdoqLevel = ctu.m_encData->m_param->rdoqLevel;
226
27.3k
    if (ctu.m_chromaFormat != X265_CSP_I400)
227
27.3k
    {
228
27.3k
        setChromaQP(qp + ctu.m_slice->m_pps->chromaQpOffset[0] + ctu.m_slice->m_chromaQpOffset[0], TEXT_CHROMA_U, ctu.m_chromaFormat);
229
27.3k
        setChromaQP(qp + ctu.m_slice->m_pps->chromaQpOffset[1] + ctu.m_slice->m_chromaQpOffset[1], TEXT_CHROMA_V, ctu.m_chromaFormat);
230
27.3k
    }
231
27.3k
}
232
233
void Quant::setChromaQP(int qpin, TextType ttype, int chFmt)
234
54.6k
{
235
54.6k
    int qp = x265_clip3(-QP_BD_OFFSET, 57, qpin);
236
54.6k
    if (qp >= 30)
237
10.8k
    {
238
10.8k
        if (chFmt == X265_CSP_I420)
239
10.8k
            qp = g_chromaScale[qp];
240
0
        else
241
0
            qp = X265_MIN(qp, QP_MAX_SPEC);
242
10.8k
    }
243
54.6k
    m_qpParam[ttype].setQpParam(qp + QP_BD_OFFSET);
244
54.6k
}
245
246
/* To minimize the distortion only. No rate is considered */
247
uint32_t Quant::signBitHidingHDQ(int16_t* coeff, int32_t* deltaU, uint32_t numSig, const TUEntropyCodingParameters &codeParams, uint32_t log2TrSize)
248
0
{
249
0
    uint32_t trSize = 1 << log2TrSize;
250
0
    const uint16_t* scan = codeParams.scan;
251
252
0
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
253
0
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
254
0
    uint16_t coeffFlag[MLS_GRP_NUM];    // bit mask map for non-zero coeff
255
256
#if CHECKED_BUILD || _DEBUG
257
    // clean output buffer, the asm version of scanPosLast Never output anything after latest non-zero coeff group
258
    memset(coeffNum, 0, sizeof(coeffNum) * sizeof(uint8_t));
259
    memset(coeffSign, 0, sizeof(coeffNum) * sizeof(uint16_t));
260
    memset(coeffFlag, 0, sizeof(coeffNum) * sizeof(uint16_t));
261
#endif
262
0
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, coeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
263
0
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
264
0
    unsigned long tmp;
265
266
    // first CG need specially processing
267
0
    const uint32_t correctOffset = 0x0F & (lastScanPos ^ 0xF);
268
0
    coeffFlag[cgLastScanPos] <<= correctOffset;
269
270
0
    for (int cg = cgLastScanPos; cg >= 0; cg--)
271
0
    {
272
0
        int cgStartPos = cg << LOG2_SCAN_SET_SIZE;
273
0
        int n;
274
275
#if CHECKED_BUILD || _DEBUG
276
        for (n = SCAN_SET_SIZE - 1; n >= 0; --n)
277
            if (coeff[scan[n + cgStartPos]])
278
                break;
279
        int lastNZPosInCG0 = n;
280
#endif
281
282
0
        if (coeffNum[cg] == 0)
283
0
        {
284
0
            X265_CHECK(lastNZPosInCG0 < 0, "all zero block check failure\n");
285
0
            continue;
286
0
        }
287
288
#if CHECKED_BUILD || _DEBUG
289
        for (n = 0;; n++)
290
            if (coeff[scan[n + cgStartPos]])
291
                break;
292
293
        int firstNZPosInCG0 = n;
294
#endif
295
296
0
        BSR(tmp, coeffFlag[cg]);
297
0
        const int firstNZPosInCG = (15 ^ tmp);
298
299
0
        BSF(tmp, coeffFlag[cg]);
300
0
        const int lastNZPosInCG = (15 ^ tmp);
301
302
0
        X265_CHECK(firstNZPosInCG0 == firstNZPosInCG, "firstNZPosInCG0 check failure\n");
303
0
        X265_CHECK(lastNZPosInCG0 == lastNZPosInCG, "lastNZPosInCG0 check failure\n");
304
305
0
        if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
306
0
        {
307
0
            uint32_t signbit = coeff[scan[cgStartPos + firstNZPosInCG]] > 0 ? 0 : 1;
308
0
            uint32_t absSum = 0;
309
310
0
            for (n = firstNZPosInCG; n <= lastNZPosInCG; n++)
311
0
                absSum += coeff[scan[n + cgStartPos]];
312
313
0
            if (signbit != (absSum & 0x1)) // compare signbit with sum_parity
314
0
            {
315
0
                int minCostInc = MAX_INT,  minPos = -1, curCost = MAX_INT;
316
0
                int32_t finalChange = 0, curChange = 0;
317
0
                uint32_t cgFlags = coeffFlag[cg];
318
0
                if (cg == cgLastScanPos)
319
0
                    cgFlags >>= correctOffset;
320
321
0
                for (n = (cg == cgLastScanPos ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
322
0
                {
323
0
                    uint32_t blkPos = scan[n + cgStartPos];
324
0
                    X265_CHECK(!!coeff[blkPos] == !!(cgFlags & 1), "non zero coeff check failure\n");
325
326
0
                    if (cgFlags & 1)
327
0
                    {
328
0
                        if (deltaU[blkPos] > 0)
329
0
                        {
330
0
                            curCost = -deltaU[blkPos];
331
0
                            curChange = 1;
332
0
                        }
333
0
                        else
334
0
                        {
335
0
                            if ((cgFlags == 1) && (abs(coeff[blkPos]) == 1))
336
0
                            {
337
0
                                X265_CHECK(n == firstNZPosInCG, "firstNZPosInCG position check failure\n");
338
0
                                curCost = MAX_INT;
339
0
                            }
340
0
                            else
341
0
                            {
342
0
                                curCost = deltaU[blkPos];
343
0
                                curChange = -1;
344
0
                            }
345
0
                        }
346
0
                    }
347
0
                    else
348
0
                    {
349
0
                        if (cgFlags == 0)
350
0
                        {
351
0
                            X265_CHECK(n < firstNZPosInCG, "firstNZPosInCG position check failure\n");
352
0
                            uint32_t thisSignBit = m_resiDctCoeff[blkPos] >= 0 ? 0 : 1;
353
0
                            if (thisSignBit != signbit)
354
0
                                curCost = MAX_INT;
355
0
                            else
356
0
                            {
357
0
                                curCost = -deltaU[blkPos];
358
0
                                curChange = 1;
359
0
                            }
360
0
                        }
361
0
                        else
362
0
                        {
363
0
                            curCost = -deltaU[blkPos];
364
0
                            curChange = 1;
365
0
                        }
366
0
                    }
367
368
0
                    if (curCost < minCostInc)
369
0
                    {
370
0
                        minCostInc = curCost;
371
0
                        finalChange = curChange;
372
0
                        minPos = blkPos;
373
0
                    }
374
0
                    cgFlags>>=1;
375
0
                }
376
377
                /* do not allow change to violate coeff clamp */
378
0
                if (coeff[minPos] == 32767 || coeff[minPos] == -32768)
379
0
                    finalChange = -1;
380
381
0
                if (!coeff[minPos])
382
0
                    numSig++;
383
0
                else if (finalChange == -1 && abs(coeff[minPos]) == 1)
384
0
                    numSig--;
385
386
0
                {
387
0
                    const int16_t sigMask = ((int16_t)m_resiDctCoeff[minPos]) >> 15;
388
0
                    coeff[minPos] += ((int16_t)finalChange ^ sigMask) - sigMask;
389
0
                }
390
0
            }
391
0
        }
392
0
    }
393
394
0
    return numSig;
395
0
}
396
397
uint32_t Quant::transformNxN(const CUData& cu, const pixel* fenc, uint32_t fencStride, const int16_t* residual, uint32_t resiStride,
398
                             coeff_t* coeff, uint32_t log2TrSize, TextType ttype, uint32_t absPartIdx, bool useTransformSkip)
399
11.2M
{
400
11.2M
    const uint32_t sizeIdx = log2TrSize - 2;
401
402
11.2M
    if (cu.m_tqBypass[0])
403
2.52M
    {
404
2.52M
        X265_CHECK(log2TrSize >= 2 && log2TrSize <= 5, "Block size mistake!\n");
405
2.52M
        return primitives.cu[sizeIdx].copy_cnt(coeff, residual, resiStride);
406
2.52M
    }
407
408
8.70M
    bool isLuma  = ttype == TEXT_LUMA;
409
8.70M
    bool usePsy  = m_psyRdoqScale && isLuma && !useTransformSkip;
410
8.70M
    int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; // Represents scaling through forward transform
411
412
8.70M
    X265_CHECK((cu.m_slice->m_sps->quadtreeTULog2MaxSize >= log2TrSize), "transform size too large\n");
413
8.70M
    if (useTransformSkip)
414
0
    {
415
0
#if X265_DEPTH <= 10
416
0
        X265_CHECK(transformShift >= 0, "invalid transformShift\n");
417
0
        primitives.cu[sizeIdx].cpy2Dto1D_shl(m_resiDctCoeff, residual, resiStride, transformShift);
418
#else
419
        if (transformShift >= 0)
420
            primitives.cu[sizeIdx].cpy2Dto1D_shl(m_resiDctCoeff, residual, resiStride, transformShift);
421
        else
422
            primitives.cu[sizeIdx].cpy2Dto1D_shr(m_resiDctCoeff, residual, resiStride, -transformShift);
423
#endif
424
0
    }
425
8.70M
    else
426
8.70M
    {
427
8.70M
        bool isIntra = cu.isIntra(absPartIdx);
428
429
8.70M
        if (!sizeIdx && isLuma && isIntra)
430
2.71M
            primitives.dst4x4(residual, m_resiDctCoeff, resiStride);
431
5.99M
        else
432
5.99M
            primitives.cu[sizeIdx].dct(residual, m_resiDctCoeff, resiStride);
433
434
        /* NOTE: if RDOQ is disabled globally, psy-rdoq is also disabled, so
435
         * there is no risk of performing this DCT unnecessarily */
436
8.70M
        if (usePsy)
437
3.56M
        {
438
3.56M
            int trSize = 1 << log2TrSize;
439
            /* perform DCT on source pixels for psy-rdoq */
440
3.56M
            primitives.cu[sizeIdx].copy_ps(m_fencShortBuf, trSize, fenc, fencStride);
441
3.56M
            primitives.cu[sizeIdx].dct(m_fencShortBuf, m_fencDctCoeff, trSize);
442
3.56M
        }
443
444
8.70M
        if (m_nr && m_nr->offset)
445
0
        {
446
            /* denoise is not applied to intra residual, so DST can be ignored */
447
0
            int cat = sizeIdx + 4 * !isLuma + 8 * !isIntra;
448
0
            int numCoeff = 1 << (log2TrSize * 2);
449
0
            primitives.denoiseDct(m_resiDctCoeff, m_nr->residualSum[cat], m_nr->offset[cat], numCoeff);
450
0
            m_nr->count[cat]++;
451
0
        }
452
8.70M
    }
453
454
8.70M
    if (m_rdoqLevel)
455
8.70M
        return (this->*rdoQuant_func[log2TrSize - 2])(cu, coeff, ttype, absPartIdx, usePsy);
456
18.4E
    else
457
18.4E
    {
458
18.4E
        int deltaU[32 * 32];
459
460
18.4E
        int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
461
18.4E
        int rem = m_qpParam[ttype].rem;
462
18.4E
        int per = m_qpParam[ttype].per;
463
18.4E
        const int32_t* quantCoeff = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
464
465
18.4E
        int qbits = QUANT_SHIFT + per + transformShift;
466
18.4E
        int add = (cu.m_slice->m_sliceType == I_SLICE ? 171 : 85) << (qbits - 9);
467
18.4E
        int numCoeff = 1 << (log2TrSize * 2);
468
469
18.4E
        uint32_t numSig = primitives.quant(m_resiDctCoeff, quantCoeff, deltaU, coeff, qbits, add, numCoeff);
470
471
18.4E
        if (numSig >= 2 && cu.m_slice->m_pps->bSignHideEnabled)
472
0
        {
473
0
            TUEntropyCodingParameters codeParams;
474
0
            cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, isLuma);
475
0
            return signBitHidingHDQ(coeff, deltaU, numSig, codeParams, log2TrSize);
476
0
        }
477
18.4E
        else
478
18.4E
            return numSig;
479
18.4E
    }
480
8.70M
}
481
482
uint64_t Quant::ssimDistortion(const CUData& cu, const pixel* fenc, uint32_t fStride, const pixel* recon, intptr_t rstride, uint32_t log2TrSize, TextType ttype, uint32_t absPartIdx)
483
0
{
484
0
    static const int ssim_c1 = (int)(.01 * .01 * PIXEL_MAX * PIXEL_MAX * 64 + .5); // 416
485
0
    static const int ssim_c2 = (int)(.03 * .03 * PIXEL_MAX * PIXEL_MAX * 64 * 63 + .5); // 235963
486
0
    int shift = (X265_DEPTH - 8);
487
488
0
    int trSize = 1 << log2TrSize;
489
0
    uint64_t ssDc = 0, ssBlock = 0, ssAc = 0;
490
491
    // Calculation of (X(0) - Y(0)) * (X(0) - Y(0)), DC
492
0
    ssDc = 0;
493
0
    for (int y = 0; y < trSize; y += 4)
494
0
    {
495
0
        for (int x = 0; x < trSize; x += 4)
496
0
        {
497
0
            int temp = fenc[y * fStride + x] - recon[y * rstride + x]; // copy of residual coeff
498
0
            ssDc += temp * temp;
499
0
        }
500
0
    }
501
502
    // Calculation of (X(k) - Y(k)) * (X(k) - Y(k)), AC
503
0
    ssBlock = 0;
504
0
    uint64_t ac_k = 0;
505
0
    primitives.cu[log2TrSize - 2].ssimDist(fenc, fStride, recon, rstride, &ssBlock, shift, &ac_k);
506
0
    ssAc = ssBlock - ssDc;
507
508
    // 1. Calculation of fdc'
509
    // Calculate numerator of dc normalization factor
510
0
    uint64_t fDc_num = 0;
511
512
    // 2. Calculate dc component
513
0
    uint64_t dc_k = 0;
514
0
    for (int block_yy = 0; block_yy < trSize; block_yy += 4)
515
0
    {
516
0
        for (int block_xx = 0; block_xx < trSize; block_xx += 4)
517
0
        {
518
0
            uint32_t temp = fenc[block_yy * fStride + block_xx] >> shift;
519
0
            dc_k += temp * temp;
520
0
        }
521
0
    }
522
523
0
    fDc_num = (2 * dc_k)  + (trSize * trSize * ssim_c1); // 16 pixels -> for each 4x4 block
524
0
    fDc_num /= ((trSize >> 2) * (trSize >> 2));
525
526
    // 1. Calculation of fac'
527
    // Calculate numerator of ac normalization factor
528
0
    uint64_t fAc_num = 0;
529
530
    // 2. Calculate ac component
531
0
    ac_k -= dc_k;
532
533
0
    double s = 1 + 0.005 * cu.m_qp[absPartIdx];
534
535
0
    fAc_num = ac_k + uint64_t(s * ac_k) + ssim_c2;
536
0
    fAc_num /= ((trSize >> 2) * (trSize >> 2));
537
538
    // Calculate dc and ac normalization factor
539
0
    uint64_t ssim_distortion = ((ssDc * cu.m_fDc_den[ttype]) / fDc_num) + ((ssAc * cu.m_fAc_den[ttype]) / fAc_num);
540
0
    return ssim_distortion;
541
0
}
542
543
void Quant::invtransformNxN(const CUData& cu, int16_t* residual, uint32_t resiStride, const coeff_t* coeff,
544
                            uint32_t log2TrSize, TextType ttype, bool bIntra, bool useTransformSkip, uint32_t numSig)
545
48.2k
{
546
48.2k
    const uint32_t sizeIdx = log2TrSize - 2;
547
48.2k
    if (cu.m_tqBypass[0])
548
9.41k
    {
549
9.41k
        primitives.cu[sizeIdx].cpy1Dto2D_shl[resiStride % 64 == 0](residual, coeff, resiStride, 0);
550
9.41k
        return;
551
9.41k
    }
552
    // Values need to pass as input parameter in dequant
553
38.7k
    int rem = m_qpParam[ttype].rem;
554
38.7k
    int per = m_qpParam[ttype].per;
555
38.7k
    int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize;
556
38.7k
    int shift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift;
557
38.7k
    int numCoeff = 1 << (log2TrSize * 2);
558
559
38.7k
    if (m_scalingList->m_bEnabled)
560
0
    {
561
0
        int scalingListType = (bIntra ? 0 : 3) + ttype;
562
0
        const int32_t* dequantCoef = m_scalingList->m_dequantCoef[sizeIdx][scalingListType][rem];
563
0
        primitives.dequant_scaling(coeff, dequantCoef, m_resiDctCoeff, numCoeff, per, shift);
564
0
    }
565
38.7k
    else
566
38.7k
    {
567
38.7k
        int scale = m_scalingList->s_invQuantScales[rem] << per;
568
38.7k
        primitives.dequant_normal(coeff, m_resiDctCoeff, numCoeff, scale, shift);
569
38.7k
    }
570
571
38.7k
    if (useTransformSkip)
572
0
    {
573
0
#if X265_DEPTH <= 10
574
0
        X265_CHECK(transformShift > 0, "invalid transformShift\n");
575
0
        primitives.cu[sizeIdx].cpy1Dto2D_shr(residual, m_resiDctCoeff, resiStride, transformShift);
576
#else
577
        if (transformShift > 0)
578
            primitives.cu[sizeIdx].cpy1Dto2D_shr(residual, m_resiDctCoeff, resiStride, transformShift);
579
        else
580
            primitives.cu[sizeIdx].cpy1Dto2D_shl[resiStride % 64 == 0](residual, m_resiDctCoeff, resiStride, -transformShift);
581
#endif
582
0
    }
583
38.7k
    else
584
38.7k
    {
585
38.7k
        int useDST = !sizeIdx && ttype == TEXT_LUMA && bIntra;
586
38.7k
        X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(coeff), "numSig differ\n");
587
        // DC only
588
38.7k
        if (numSig == 1 && coeff[0] != 0 && !useDST)
589
32.8k
        {
590
32.8k
            const int shift_1st = 7 - 6;
591
32.8k
            const int add_1st = 1 << (shift_1st - 1);
592
32.8k
            const int shift_2nd = 12 - (X265_DEPTH - 8) - 3;
593
32.8k
            const int add_2nd = 1 << (shift_2nd - 1);
594
595
32.8k
            int dc_val = (((m_resiDctCoeff[0] * (64 >> 6) + add_1st) >> shift_1st) * (64 >> 3) + add_2nd) >> shift_2nd;
596
32.8k
            primitives.cu[sizeIdx].blockfill_s[resiStride % 64 == 0](residual, resiStride, (int16_t)dc_val);
597
32.8k
            return;
598
32.8k
        }
599
600
5.98k
        if (useDST)
601
5.98k
            primitives.idst4x4(m_resiDctCoeff, residual, resiStride);
602
0
        else
603
0
            primitives.cu[sizeIdx].idct(m_resiDctCoeff, residual, resiStride);
604
5.98k
    }
605
38.7k
}
606
607
/* Rate distortion optimized quantization for entropy coding engines using
608
 * probability models like CABAC */
609
template<uint32_t log2TrSize>
610
uint32_t Quant::rdoQuant(const CUData& cu, int16_t* dstCoeff, TextType ttype, uint32_t absPartIdx, bool usePsy)
611
8.71M
{
612
8.71M
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
8.71M
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
8.71M
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
8.71M
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
8.71M
    int rem = m_qpParam[ttype].rem;
619
8.71M
    int per = m_qpParam[ttype].per;
620
8.71M
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
8.71M
    int add = (1 << (qbits - 1));
622
8.71M
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
8.71M
    const int numCoeff = 1 << (log2TrSize * 2);
625
8.71M
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
8.71M
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
8.71M
    if (!numSig)
628
8.60M
        return 0;
629
106k
    const uint32_t trSize = 1 << log2TrSize;
630
106k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
106k
    int64_t psyScale = ((int64_t)m_psyRdoqScale * m_qpParam[ttype].lambda);
632
    /* unquant constants for measuring distortion. Scaling list quant coefficients have a (1 << 4)
633
     * scale applied that must be removed during unquant. Note that in real dequant there is clipping
634
     * at several stages. We skip the clipping for simplicity when measuring RD cost */
635
106k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
106k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
106k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
106k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
106k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
621k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
203k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
413k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
106k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
106k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
106k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
106k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
106k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
106k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
106k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
106k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
106k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
106k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
106k
    int64_t totalUncodedCost = 0;
661
662
    /* Total rate distortion cost of this transform block, counting te distortion of uncoded blocks,
663
     * the distortion and signal cost of coded blocks, and the coding cost of significant
664
     * coefficient and coefficient group bitmaps */
665
106k
    int64_t totalRdCost = 0;
666
667
106k
    TUEntropyCodingParameters codeParams;
668
106k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
106k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
106k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
106k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
106k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
106k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
106k
    uint16_t coeffFlag[MLS_GRP_NUM];    // bit mask map for non-zero coeff
676
677
#if CHECKED_BUILD || _DEBUG
678
    // clean output buffer, the asm version of scanPosLast Never output anything after latest non-zero coeff group
679
    memset(coeffNum, 0, sizeof(coeffNum) * sizeof(uint8_t));
680
    memset(coeffSign, 0, sizeof(coeffNum) * sizeof(uint16_t));
681
    memset(coeffFlag, 0, sizeof(coeffNum) * sizeof(uint16_t));
682
#endif
683
106k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
106k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
106k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
106k
    uint32_t scanPos = 0;
691
106k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
106k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
106k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
106k
    memset(&costSig[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
699
700
    /* sum zero coeff (uncodec) cost */
701
702
    // TODO: does we need these cost?
703
106k
    if (usePsyMask)
704
20.0k
    {
705
289k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
269k
        {
707
269k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
269k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
269k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
269k
#if X265_ARCH_X86
711
269k
            bool enable512 = detect512();
712
269k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
269k
            else
715
269k
            {
716
269k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
269k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
269k
            }
719
#else
720
            primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
721
            primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
722
#endif
723
269k
        }
724
20.0k
    }
725
86.6k
    else
726
86.6k
    {
727
        // non-psy path
728
214k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
128k
        {
730
128k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
128k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
128k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
128k
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
128k
        }
735
86.6k
    }
736
106k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
106k
    {
738
        // patternSigCtx = 0
739
106k
        {
740
106k
            2, 1, 1, 0,
741
106k
            1, 1, 0, 0,
742
106k
            1, 0, 0, 0,
743
106k
            0, 0, 0, 0,
744
106k
        },
745
        // patternSigCtx = 1
746
106k
        {
747
106k
            2, 2, 2, 2,
748
106k
            1, 1, 1, 1,
749
106k
            0, 0, 0, 0,
750
106k
            0, 0, 0, 0,
751
106k
        },
752
        // patternSigCtx = 2
753
106k
        {
754
106k
            2, 1, 0, 0,
755
106k
            2, 1, 0, 0,
756
106k
            2, 1, 0, 0,
757
106k
            2, 1, 0, 0,
758
106k
        },
759
        // patternSigCtx = 3
760
106k
        {
761
106k
            2, 2, 2, 2,
762
106k
            2, 2, 2, 2,
763
106k
            2, 2, 2, 2,
764
106k
            2, 2, 2, 2,
765
106k
        },
766
        // 4x4
767
106k
        {
768
106k
            0, 1, 4, 5,
769
106k
            2, 3, 4, 5,
770
106k
            6, 6, 8, 8,
771
106k
            7, 7, 8, 8
772
106k
        }
773
106k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
163k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
56.7k
    {
778
56.7k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
56.7k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
56.7k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
56.7k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
56.7k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
56.7k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
56.7k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
56.7k
        if (c1 == 0)
787
0
            ctxSet++;
788
56.7k
        c1 = 1;
789
790
56.7k
        if (cgScanPos && (coeffNum[cgScanPos] == 0))
791
0
        {
792
            // TODO: does we need zero-coeff cost?
793
0
            const uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
794
0
            uint32_t blkPos = codeParams.scan[scanPosBase];
795
0
            if (usePsyMask)
796
0
            {
797
0
#if X265_ARCH_X86
798
0
                bool enable512 = detect512();
799
0
                if (enable512)
800
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
801
0
                else
802
0
                {
803
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
804
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
805
0
                }
806
#else
807
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
808
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
809
#endif
810
0
                blkPos = codeParams.scan[scanPosBase];
811
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
812
0
                {
813
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
814
0
                    {
815
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
816
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
817
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
818
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
819
820
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
821
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
822
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
823
0
                    }
824
0
                    blkPos += trSize;
825
0
                }
826
0
            }
827
0
            else
828
0
            {
829
                // non-psy path
830
0
                primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
831
0
                blkPos = codeParams.scan[scanPosBase];
832
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
833
0
                {
834
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
835
0
                    {
836
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
837
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
838
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
839
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
840
841
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
842
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
843
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
844
0
                    }
845
0
                    blkPos += trSize;
846
0
                }
847
0
            }
848
849
            /* there were no coded coefficients in this coefficient group */
850
0
            {
851
0
                uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
852
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
853
0
                totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
854
0
            }
855
0
            continue;
856
0
        }
857
858
56.7k
        coeffGroupRDStats cgRdStats;
859
56.7k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
56.7k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
56.7k
        int    c2            = 0;
863
56.7k
        uint32_t goRiceParam = 0;
864
56.7k
        uint32_t levelThreshold = 3;
865
56.7k
        uint32_t c1Idx       = 0;
866
56.7k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
964k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
907k
        {
870
907k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
907k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
907k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
907k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
907k
            int predictedCoef    = m_fencDctCoeff[blkPos] - signCoef; /* predicted DCT = source DCT - residual DCT*/
875
876
            /* RDOQ measures distortion as the squared difference between the unquantized coded level
877
             * and the original DCT coefficient. The result is shifted scaleBits to account for the
878
             * FIX15 nature of the CABAC cost tables minus the forward transform scale */
879
880
            /* cost of not coding this coefficient (all distortion, no signal bits) */
881
907k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
907k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
907k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
301k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
907k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
907k
            const int* greaterOneBits = estBitsSbac.greaterOneBits[4 * ctxSet + c1];
891
            //const uint32_t ctxSig = (blkPos == 0) ? 0 : table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset;
892
907k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
907k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
907k
            const uint32_t ctxSig = (blkPos == 0) ? 0 : ((ctxCnt >> (4 * g_scan4x4[codeParams.scanType][scanPosinCG])) & 0xF) + ctxSigOffset;
895
            // NOTE: above equal to 'table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset'
896
907k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
907k
            if (scanPos > (uint32_t)lastScanPos)
900
786k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
786k
                costCoeff[scanPos] = 0;
903
786k
                costSig[scanPos] = 0;
904
905
                /* No non-zero coefficient yet found, but this does not mean
906
                 * there is no uncoded-cost for this coefficient. Pre-
907
                 * quantization the coefficient may have been non-zero */
908
786k
                totalRdCost += costUncoded[blkPos];
909
786k
            }
910
120k
            else if (!(subFlagMask & 1))
911
2.23k
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
2.23k
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
2.23k
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
2.23k
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
2.23k
                totalRdCost += costCoeff[scanPos];
918
2.23k
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
2.23k
                subFlagMask >>= 1;
921
2.23k
            }
922
118k
            else
923
118k
            {
924
118k
                subFlagMask >>= 1;
925
926
118k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
118k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
118k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
118k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
118k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
118k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
118k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
118k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
118k
                uint32_t level = 0;
939
118k
                uint32_t sigCoefBits = 0;
940
118k
                costCoeff[scanPos] = MAX_INT64;
941
942
118k
                if ((int)scanPos == lastScanPos)
943
56.7k
                    sigRateDelta[blkPos] = 0;
944
62.0k
                else
945
62.0k
                {
946
62.0k
                    if (maxAbsLevel < 3)
947
15.3k
                    {
948
                        /* set default costs to uncoded costs */
949
15.3k
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
15.3k
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
15.3k
                    }
952
62.0k
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
62.0k
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
62.0k
                }
955
956
118k
                const uint32_t unQuantLevel = (maxAbsLevel * (unquantScale[blkPos] << per) + unquantRound);
957
                // NOTE: X265_MAX(maxAbsLevel - 1, 1) ==> (X>=2 -> X-1), (X<2 -> 1)  | (0 < X < 2 ==> X=1)
958
118k
                if (maxAbsLevel == 1)
959
33.9k
                {
960
33.9k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
33.9k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
33.9k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
33.9k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
33.9k
                    int d = abs(signCoef) - unquantAbsLevel;
966
33.9k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
33.9k
                    if (usePsyMask & scanPos)
970
12.0k
                    {
971
12.0k
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
12.0k
                        curCost -= PSYVALUE(reconCoef);
973
12.0k
                    }
974
975
33.9k
                    if (curCost < costCoeff[scanPos])
976
32.9k
                    {
977
32.9k
                        level = 1;
978
32.9k
                        costCoeff[scanPos] = curCost;
979
32.9k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
32.9k
                    }
981
33.9k
                }
982
84.7k
                else if (maxAbsLevel)
983
84.8k
                {
984
84.8k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
84.8k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
84.8k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
84.8k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
84.8k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
84.8k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
84.8k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
84.8k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
84.8k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
84.8k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
84.8k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
84.8k
                    if (usePsyMask & scanPos)
1001
50.1k
                    {
1002
50.1k
                        int reconCoef;
1003
50.1k
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
50.1k
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
50.1k
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
50.1k
                        curCost1 -= PSYVALUE(reconCoef);
1008
50.1k
                    }
1009
84.8k
                    if (curCost0 < costCoeff[scanPos])
1010
84.8k
                    {
1011
84.8k
                        level = maxAbsLevel;
1012
84.8k
                        costCoeff[scanPos] = curCost0;
1013
84.8k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
84.8k
                    }
1015
84.8k
                    if (curCost1 < costCoeff[scanPos])
1016
1.93k
                    {
1017
1.93k
                        level = maxAbsLevel - 1;
1018
1.93k
                        costCoeff[scanPos] = curCost1;
1019
1.93k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
1.93k
                    }
1021
84.8k
                }
1022
1023
118k
                dstCoeff[blkPos] = (int16_t)level;
1024
118k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
18.4E
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
117k
                {
1029
117k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
117k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
117k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
117k
                    int rate0, rate1, rate2;
1033
1034
117k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
32.1k
                    {
1036
                        // NOTE: Min: L - 1 - {1,2,1,3} < -2 ==> L < {0,1,0,2}
1037
                        //            additional L > 0, so I got (L > 0 && L < 2) ==> L = 1
1038
32.1k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
32.1k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
32.1k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
32.1k
                        rate0 = 0;
1044
32.1k
                        rate2 = rateEqual2;
1045
32.1k
                        rate1 = rateNotEqual2;
1046
1047
32.1k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
32.1k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
32.1k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
32.1k
                    }
1051
85.6k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
34.0k
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
34.0k
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
34.0k
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
34.0k
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
34.0k
                    }
1058
51.6k
                    else
1059
51.6k
                    {
1060
51.6k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
51.6k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
51.6k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
51.6k
                    }
1064
117k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
117k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
117k
                }
1067
943
                else
1068
943
                {
1069
943
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
943
                    rateIncDown[blkPos] = 0;
1071
943
                }
1072
1073
                /* Update CABAC estimation state */
1074
118k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
46.2k
                {
1076
46.2k
                    goRiceParam++;
1077
46.2k
                    levelThreshold <<= 1;
1078
46.2k
                }
1079
1080
118k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
118k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
118k
                if (level > 1)
1085
83.7k
                {
1086
83.7k
                    c1 = 0;
1087
83.7k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
83.7k
                    c2Idx++;
1089
83.7k
                }
1090
35.0k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
28.5k
                    c1++;
1092
1093
118k
                if (dstCoeff[blkPos])
1094
117k
                {
1095
117k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
117k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
117k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
117k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
117k
                }
1100
118k
            }
1101
1102
907k
            cgRdStats.sigCost += costSig[scanPos];
1103
907k
        } /* end for (scanPosinCG) */
1104
1105
56.7k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
56.7k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
56.7k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
56.7k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
56.7k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
56.7k
        {
1115
            /* coeff group 0 is implied to be present, no signal cost */
1116
            /* coeff group with last NZ is implied to be present, handled below */
1117
56.7k
        }
1118
4
        else if (sigCoeffGroupFlag64 & cgBlkPosMask)
1119
0
        {
1120
0
            if (!cgRdStats.nnzBeforePos0)
1121
0
            {
1122
                /* if only coeff 0 in this CG is coded, its significant coeff bit is implied */
1123
0
                totalRdCost -= cgRdStats.sigCost0;
1124
0
                cgRdStats.sigCost -= cgRdStats.sigCost0;
1125
0
            }
1126
1127
            /* there are coded coefficients in this group, but now we include the signaling cost
1128
             * of the significant coefficient group flag and evaluate whether the RD cost of the
1129
             * coded group is more than the RD cost of the uncoded group */
1130
1131
0
            uint32_t sigCtx = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1132
1133
0
            int64_t costZeroCG = totalRdCost + SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1134
0
            costZeroCG += cgRdStats.uncodedDist;       /* add distortion for resetting non-zero levels to zero levels */
1135
0
            costZeroCG -= cgRdStats.codedLevelAndDist; /* remove distortion and level cost of coded coefficients */
1136
0
            costZeroCG -= cgRdStats.sigCost;           /* remove signaling cost of significant coeff bitmap */
1137
1138
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][1]);
1139
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add the cost of 1 bit in significant CG bitmap */
1140
1141
0
            if (costZeroCG < totalRdCost && m_rdoqLevel > 1)
1142
0
            {
1143
0
                sigCoeffGroupFlag64 &= ~cgBlkPosMask;
1144
0
                totalRdCost = costZeroCG;
1145
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1146
1147
                /* reset all coeffs to 0. UNCODE THIS COEFF GROUP! */
1148
0
                const uint32_t blkPos = codeParams.scan[cgScanPos * cgSize];
1149
0
                memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1150
0
                memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1151
0
                memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1152
0
                memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1153
0
            }
1154
0
        }
1155
4
        else
1156
4
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
4
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
4
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
4
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
4
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
4
        }
1163
56.7k
    } /* end for (cgScanPos) */
1164
1165
106k
    X265_CHECK(lastScanPos >= 0, "numSig non zero, but no coded CG\n");
1166
1167
    /* calculate RD cost of uncoded block CBF=0, and add cost of CBF=1 to total */
1168
106k
    int64_t bestCost;
1169
106k
    if (!cu.isIntra(absPartIdx) && bIsLuma && !cu.m_tuDepth[absPartIdx])
1170
0
    {
1171
0
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockRootCbpBits[0]);
1172
0
        totalRdCost += SIGCOST(estBitsSbac.blockRootCbpBits[1]);
1173
0
    }
1174
106k
    else
1175
106k
    {
1176
106k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
106k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
106k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
106k
    }
1180
1181
    /* This loop starts with the last non-zero found in the first loop and then refines this last
1182
     * non-zero by measuring the true RD cost of the last NZ at this position, and then the RD costs
1183
     * at all previous coefficients until a coefficient greater than 1 is encountered or we run out
1184
     * of coefficients to evaluate.  This will factor in the cost of coding empty groups and empty
1185
     * coeff prior to the last NZ. The base best cost is the RD cost of CBF=0 */
1186
106k
    int  bestLastIdx = 0;
1187
106k
    bool foundLast = false;
1188
163k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
56.7k
    {
1190
56.7k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
56.7k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
56.7k
        }
1195
1
        else if (sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[cgScanPos]))
1196
0
        {
1197
            /* remove cost of significant coeff group flag, the group's presence would be inferred
1198
             * from lastNZ if it were present in this group */
1199
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1200
0
        }
1201
1
        else
1202
1
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
1
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
1
            continue;
1206
1
        }
1207
1208
877k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
855k
        {
1210
855k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
855k
            if ((int)scanPos > lastScanPos)
1212
786k
                continue;
1213
1214
            /* if the coefficient was coded, measure the RD cost of it as the last non-zero and then
1215
             * continue as if it were uncoded. If the coefficient was already uncoded, remove the
1216
             * cost of signaling it as not-significant */
1217
68.9k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
68.9k
            if (dstCoeff[blkPos])
1219
66.6k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
66.6k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
66.6k
                if (codeParams.scanType == SCAN_VER)
1223
4.22k
                    std::swap(pos[0], pos[1]);
1224
66.6k
                uint32_t bitsLastNZ = 0;
1225
1226
200k
                for (int i = 0; i < 2; i++)
1227
133k
                {
1228
133k
                    int temp = g_lastCoeffTable[pos[i]];
1229
133k
                    int prefixOnes = temp & 15;
1230
133k
                    int suffixLen = temp >> 4;
1231
1232
133k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
133k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
133k
                }
1235
1236
66.6k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
66.6k
                if (costAsLast < bestCost)
1239
40.4k
                {
1240
40.4k
                    bestLastIdx = scanPos + 1;
1241
40.4k
                    bestCost = costAsLast;
1242
40.4k
                }
1243
66.6k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
34.5k
                {
1245
34.5k
                    foundLast = true;
1246
34.5k
                    break;
1247
34.5k
                }
1248
1249
32.1k
                totalRdCost -= costCoeff[scanPos];
1250
32.1k
                totalRdCost += costUncoded[blkPos];
1251
32.1k
            }
1252
2.23k
            else
1253
2.23k
                totalRdCost -= costSig[scanPos];
1254
68.9k
        }
1255
56.7k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
106k
    numSig = 0;
1259
206k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
99.9k
    {
1261
99.9k
        int blkPos = codeParams.scan[pos];
1262
99.9k
        int level  = dstCoeff[blkPos];
1263
99.9k
        numSig += (level != 0);
1264
1265
99.9k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
99.9k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
99.9k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
106k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
914k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
807k
    {
1274
807k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
807k
    }
1276
106k
    for (int pos = (bestLastIdx & ~(SCAN_SET_SIZE - 1)) + SCAN_SET_SIZE; pos <= lastScanPos; pos += SCAN_SET_SIZE)
1277
0
    {
1278
0
        const uint32_t blkPos = codeParams.scan[pos];
1279
0
        memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1280
0
        memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1281
0
        memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1282
0
        memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1283
0
    }
1284
1285
    /* rate-distortion based sign-hiding */
1286
106k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
4.97k
    {
1288
4.97k
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
4.97k
        int lastCG = 1;
1290
1291
9.95k
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
4.97k
        {
1293
4.97k
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
4.97k
            int n;
1295
1296
4.97k
            if (!(sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[subSet])))
1297
0
                continue;
1298
1299
            /* measure distance between first and last non-zero coef in this
1300
             * coding group */
1301
4.97k
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
4.97k
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
4.97k
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
4.97k
            const uint32_t absSumSign = posFirstLast;
1305
1306
4.97k
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
4.83k
            {
1308
4.83k
                const int32_t signbit = ((int32_t)dstCoeff[codeParams.scan[subPos + firstNZPosInCG]]);
1309
1310
#if CHECKED_BUILD || _DEBUG
1311
                int32_t absSum_dummy = 0;
1312
                for (n = firstNZPosInCG; n <= lastNZPosInCG; n++)
1313
                    absSum_dummy += dstCoeff[codeParams.scan[n + subPos]];
1314
                X265_CHECK(((uint32_t)absSum_dummy & 1) == (absSumSign >> 31), "absSumSign check failure\n");
1315
#endif
1316
1317
                //if (signbit != absSumSign)
1318
4.83k
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
2.14k
                {
1320
                    /* We must find a coeff to toggle up or down so the sign bit of the first non-zero coeff
1321
                     * is properly implied. Note dstCoeff[] are signed by this point but curChange and
1322
                     * finalChange imply absolute levels (+1 is away from zero, -1 is towards zero) */
1323
1324
2.14k
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
2.14k
                    uint32_t minPos = 0;
1326
2.14k
                    int8_t finalChange = 0;
1327
2.14k
                    int curChange = 0;
1328
2.14k
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
30.1k
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
27.9k
                    {
1332
27.9k
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
27.9k
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
27.9k
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
27.9k
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
27.9k
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
27.9k
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
27.9k
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
27.9k
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
54.9k
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
27.9k
                        const uint32_t isOne = (absLevel == 1);
1347
27.9k
                        if (dstCoeff[blkPos])
1348
26.9k
                        {
1349
26.9k
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
26.9k
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
26.9k
                            int64_t costUp = DELTARDCOST(origDist, d, rateIncUp[blkPos]);
1352
1353
                            /* if decrementing would make the coeff 0, we can include the
1354
                             * significant coeff flag cost savings */
1355
26.9k
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
26.9k
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
26.9k
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
26.9k
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
26.9k
                            costDown -= lastCoeffAdjust;
1361
26.9k
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
26.9k
                            curChange = 2 * (costUp < costDown) - 1;
1364
26.9k
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
26.9k
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
1.01k
                        else if ((n < firstNZPosInCG) & ((signbit ^ signCoef) < 0))
1368
0
                        {
1369
                            /* don't try to make a new coded coeff before the first coeff if its
1370
                             * sign would be different than the first coeff, the inferred sign would
1371
                             * still be wrong and we'd have to do this again. */
1372
0
                            curCost = MAX_INT64;
1373
0
                        }
1374
1.01k
                        else
1375
1.01k
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
1.01k
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
1.01k
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
1.01k
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
1.01k
                            curChange = 1;
1381
1.01k
                        }
1382
1383
27.9k
                        if (curCost < minCostInc)
1384
7.37k
                        {
1385
7.37k
                            minCostInc = curCost;
1386
7.37k
                            finalChange = (int8_t)curChange;
1387
7.37k
                            minPos = blkPos + (absLevel << 16);
1388
7.37k
                        }
1389
27.9k
                        lastCoeffAdjust = 0;
1390
27.9k
                    }
1391
1392
2.14k
                    const int absInMinPos = (minPos >> 16);
1393
2.14k
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
2.14k
                    if (absInMinPos >= 32767)
1397
                        /* don't allow sign hiding to violate the SPEC range */
1398
0
                        finalChange = -1;
1399
1400
                    // NOTE: Reference code
1401
                    //if (dstCoeff[minPos] == 0)
1402
                    //    numSig++;
1403
                    //else if (finalChange == -1 && abs(dstCoeff[minPos]) == 1)
1404
                    //    numSig--;
1405
2.14k
                    numSig += (absInMinPos == 0) - ((finalChange == -1) & (absInMinPos == 1));
1406
1407
1408
                    // NOTE: Reference code
1409
                    //if (m_resiDctCoeff[minPos] >= 0)
1410
                    //    dstCoeff[minPos] += finalChange;
1411
                    //else
1412
                    //    dstCoeff[minPos] -= finalChange;
1413
2.14k
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
2.14k
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
2.14k
                }
1416
4.83k
            }
1417
1418
4.97k
            lastCG = 0;
1419
4.97k
        }
1420
4.97k
    }
1421
1422
106k
    return numSig;
1423
8.71M
}
unsigned int x265::Quant::rdoQuant<2u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
7.21M
{
612
7.21M
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
7.21M
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
7.21M
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
7.21M
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
7.21M
    int rem = m_qpParam[ttype].rem;
619
7.21M
    int per = m_qpParam[ttype].per;
620
7.21M
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
7.21M
    int add = (1 << (qbits - 1));
622
7.21M
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
7.21M
    const int numCoeff = 1 << (log2TrSize * 2);
625
7.21M
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
7.21M
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
7.21M
    if (!numSig)
628
7.14M
        return 0;
629
65.5k
    const uint32_t trSize = 1 << log2TrSize;
630
65.5k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
65.5k
    int64_t psyScale = ((int64_t)m_psyRdoqScale * m_qpParam[ttype].lambda);
632
    /* unquant constants for measuring distortion. Scaling list quant coefficients have a (1 << 4)
633
     * scale applied that must be removed during unquant. Note that in real dequant there is clipping
634
     * at several stages. We skip the clipping for simplicity when measuring RD cost */
635
65.5k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
65.5k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
65.5k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
65.5k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
65.5k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
65.5k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
65.5k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
65.5k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
65.5k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
65.5k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
65.5k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
65.5k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
65.5k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
65.5k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
65.5k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
65.5k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
65.5k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
65.5k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
65.5k
    int64_t totalUncodedCost = 0;
661
662
    /* Total rate distortion cost of this transform block, counting te distortion of uncoded blocks,
663
     * the distortion and signal cost of coded blocks, and the coding cost of significant
664
     * coefficient and coefficient group bitmaps */
665
65.5k
    int64_t totalRdCost = 0;
666
667
65.5k
    TUEntropyCodingParameters codeParams;
668
65.5k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
65.5k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
65.5k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
65.5k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
65.5k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
65.5k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
65.5k
    uint16_t coeffFlag[MLS_GRP_NUM];    // bit mask map for non-zero coeff
676
677
#if CHECKED_BUILD || _DEBUG
678
    // clean output buffer, the asm version of scanPosLast Never output anything after latest non-zero coeff group
679
    memset(coeffNum, 0, sizeof(coeffNum) * sizeof(uint8_t));
680
    memset(coeffSign, 0, sizeof(coeffNum) * sizeof(uint16_t));
681
    memset(coeffFlag, 0, sizeof(coeffNum) * sizeof(uint16_t));
682
#endif
683
65.5k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
65.5k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
65.5k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
65.5k
    uint32_t scanPos = 0;
691
65.5k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
65.5k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
65.5k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
65.5k
    memset(&costSig[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
699
700
    /* sum zero coeff (uncodec) cost */
701
702
    // TODO: does we need these cost?
703
65.5k
    if (usePsyMask)
704
6.20k
    {
705
6.20k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
0
        {
707
0
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
0
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
0
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
0
#if X265_ARCH_X86
711
0
            bool enable512 = detect512();
712
0
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
0
            else
715
0
            {
716
0
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
0
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
0
            }
719
#else
720
            primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
721
            primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
722
#endif
723
0
        }
724
6.20k
    }
725
59.3k
    else
726
59.3k
    {
727
        // non-psy path
728
59.3k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
0
        {
730
0
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
0
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
0
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
0
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
0
        }
735
59.3k
    }
736
65.5k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
65.5k
    {
738
        // patternSigCtx = 0
739
65.5k
        {
740
65.5k
            2, 1, 1, 0,
741
65.5k
            1, 1, 0, 0,
742
65.5k
            1, 0, 0, 0,
743
65.5k
            0, 0, 0, 0,
744
65.5k
        },
745
        // patternSigCtx = 1
746
65.5k
        {
747
65.5k
            2, 2, 2, 2,
748
65.5k
            1, 1, 1, 1,
749
65.5k
            0, 0, 0, 0,
750
65.5k
            0, 0, 0, 0,
751
65.5k
        },
752
        // patternSigCtx = 2
753
65.5k
        {
754
65.5k
            2, 1, 0, 0,
755
65.5k
            2, 1, 0, 0,
756
65.5k
            2, 1, 0, 0,
757
65.5k
            2, 1, 0, 0,
758
65.5k
        },
759
        // patternSigCtx = 3
760
65.5k
        {
761
65.5k
            2, 2, 2, 2,
762
65.5k
            2, 2, 2, 2,
763
65.5k
            2, 2, 2, 2,
764
65.5k
            2, 2, 2, 2,
765
65.5k
        },
766
        // 4x4
767
65.5k
        {
768
65.5k
            0, 1, 4, 5,
769
65.5k
            2, 3, 4, 5,
770
65.5k
            6, 6, 8, 8,
771
65.5k
            7, 7, 8, 8
772
65.5k
        }
773
65.5k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
82.2k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
16.7k
    {
778
16.7k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
16.7k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
16.7k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
16.7k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
16.7k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
16.7k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
16.7k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
16.7k
        if (c1 == 0)
787
0
            ctxSet++;
788
16.7k
        c1 = 1;
789
790
16.7k
        if (cgScanPos && (coeffNum[cgScanPos] == 0))
791
0
        {
792
            // TODO: does we need zero-coeff cost?
793
0
            const uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
794
0
            uint32_t blkPos = codeParams.scan[scanPosBase];
795
0
            if (usePsyMask)
796
0
            {
797
0
#if X265_ARCH_X86
798
0
                bool enable512 = detect512();
799
0
                if (enable512)
800
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
801
0
                else
802
0
                {
803
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
804
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
805
0
                }
806
#else
807
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
808
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
809
#endif
810
0
                blkPos = codeParams.scan[scanPosBase];
811
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
812
0
                {
813
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
814
0
                    {
815
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
816
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
817
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
818
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
819
820
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
821
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
822
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
823
0
                    }
824
0
                    blkPos += trSize;
825
0
                }
826
0
            }
827
0
            else
828
0
            {
829
                // non-psy path
830
0
                primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
831
0
                blkPos = codeParams.scan[scanPosBase];
832
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
833
0
                {
834
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
835
0
                    {
836
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
837
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
838
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
839
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
840
841
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
842
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
843
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
844
0
                    }
845
0
                    blkPos += trSize;
846
0
                }
847
0
            }
848
849
            /* there were no coded coefficients in this coefficient group */
850
0
            {
851
0
                uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
852
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
853
0
                totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
854
0
            }
855
0
            continue;
856
0
        }
857
858
16.7k
        coeffGroupRDStats cgRdStats;
859
16.7k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
16.7k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
16.7k
        int    c2            = 0;
863
16.7k
        uint32_t goRiceParam = 0;
864
16.7k
        uint32_t levelThreshold = 3;
865
16.7k
        uint32_t c1Idx       = 0;
866
16.7k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
284k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
267k
        {
870
267k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
267k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
267k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
267k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
267k
            int predictedCoef    = m_fencDctCoeff[blkPos] - signCoef; /* predicted DCT = source DCT - residual DCT*/
875
876
            /* RDOQ measures distortion as the squared difference between the unquantized coded level
877
             * and the original DCT coefficient. The result is shifted scaleBits to account for the
878
             * FIX15 nature of the CABAC cost tables minus the forward transform scale */
879
880
            /* cost of not coding this coefficient (all distortion, no signal bits) */
881
267k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
267k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
267k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
93.0k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
267k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
267k
            const int* greaterOneBits = estBitsSbac.greaterOneBits[4 * ctxSet + c1];
891
            //const uint32_t ctxSig = (blkPos == 0) ? 0 : table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset;
892
267k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
267k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
267k
            const uint32_t ctxSig = (blkPos == 0) ? 0 : ((ctxCnt >> (4 * g_scan4x4[codeParams.scanType][scanPosinCG])) & 0xF) + ctxSigOffset;
895
            // NOTE: above equal to 'table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset'
896
267k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
267k
            if (scanPos > (uint32_t)lastScanPos)
900
186k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
186k
                costCoeff[scanPos] = 0;
903
186k
                costSig[scanPos] = 0;
904
905
                /* No non-zero coefficient yet found, but this does not mean
906
                 * there is no uncoded-cost for this coefficient. Pre-
907
                 * quantization the coefficient may have been non-zero */
908
186k
                totalRdCost += costUncoded[blkPos];
909
186k
            }
910
81.0k
            else if (!(subFlagMask & 1))
911
2.23k
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
2.23k
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
2.23k
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
2.23k
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
2.23k
                totalRdCost += costCoeff[scanPos];
918
2.23k
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
2.23k
                subFlagMask >>= 1;
921
2.23k
            }
922
78.8k
            else
923
78.8k
            {
924
78.8k
                subFlagMask >>= 1;
925
926
78.8k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
78.8k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
78.8k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
78.8k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
78.8k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
78.8k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
78.8k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
78.8k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
78.8k
                uint32_t level = 0;
939
78.8k
                uint32_t sigCoefBits = 0;
940
78.8k
                costCoeff[scanPos] = MAX_INT64;
941
942
78.8k
                if ((int)scanPos == lastScanPos)
943
16.7k
                    sigRateDelta[blkPos] = 0;
944
62.0k
                else
945
62.0k
                {
946
62.0k
                    if (maxAbsLevel < 3)
947
15.3k
                    {
948
                        /* set default costs to uncoded costs */
949
15.3k
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
15.3k
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
15.3k
                    }
952
62.0k
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
62.0k
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
62.0k
                }
955
956
78.8k
                const uint32_t unQuantLevel = (maxAbsLevel * (unquantScale[blkPos] << per) + unquantRound);
957
                // NOTE: X265_MAX(maxAbsLevel - 1, 1) ==> (X>=2 -> X-1), (X<2 -> 1)  | (0 < X < 2 ==> X=1)
958
78.8k
                if (maxAbsLevel == 1)
959
13.7k
                {
960
13.7k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
13.7k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
13.7k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
13.7k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
13.7k
                    int d = abs(signCoef) - unquantAbsLevel;
966
13.7k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
13.7k
                    if (usePsyMask & scanPos)
970
12.0k
                    {
971
12.0k
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
12.0k
                        curCost -= PSYVALUE(reconCoef);
973
12.0k
                    }
974
975
13.7k
                    if (curCost < costCoeff[scanPos])
976
12.7k
                    {
977
12.7k
                        level = 1;
978
12.7k
                        costCoeff[scanPos] = curCost;
979
12.7k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
12.7k
                    }
981
13.7k
                }
982
65.0k
                else if (maxAbsLevel)
983
65.0k
                {
984
65.0k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
65.0k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
65.0k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
65.0k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
65.0k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
65.0k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
65.0k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
65.0k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
65.0k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
65.0k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
65.0k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
65.0k
                    if (usePsyMask & scanPos)
1001
50.1k
                    {
1002
50.1k
                        int reconCoef;
1003
50.1k
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
50.1k
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
50.1k
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
50.1k
                        curCost1 -= PSYVALUE(reconCoef);
1008
50.1k
                    }
1009
65.0k
                    if (curCost0 < costCoeff[scanPos])
1010
65.0k
                    {
1011
65.0k
                        level = maxAbsLevel;
1012
65.0k
                        costCoeff[scanPos] = curCost0;
1013
65.0k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
65.0k
                    }
1015
65.0k
                    if (curCost1 < costCoeff[scanPos])
1016
1.73k
                    {
1017
1.73k
                        level = maxAbsLevel - 1;
1018
1.73k
                        costCoeff[scanPos] = curCost1;
1019
1.73k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
1.73k
                    }
1021
65.0k
                }
1022
1023
78.8k
                dstCoeff[blkPos] = (int16_t)level;
1024
78.8k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
78.8k
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
77.7k
                {
1029
77.7k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
77.7k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
77.7k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
77.7k
                    int rate0, rate1, rate2;
1033
1034
77.7k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
11.8k
                    {
1036
                        // NOTE: Min: L - 1 - {1,2,1,3} < -2 ==> L < {0,1,0,2}
1037
                        //            additional L > 0, so I got (L > 0 && L < 2) ==> L = 1
1038
11.8k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
11.8k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
11.8k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
11.8k
                        rate0 = 0;
1044
11.8k
                        rate2 = rateEqual2;
1045
11.8k
                        rate1 = rateNotEqual2;
1046
1047
11.8k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
11.8k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
11.8k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
11.8k
                    }
1051
65.9k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
34.0k
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
34.0k
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
34.0k
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
34.0k
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
34.0k
                    }
1058
31.8k
                    else
1059
31.8k
                    {
1060
31.8k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
31.8k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
31.8k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
31.8k
                    }
1064
77.7k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
77.7k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
77.7k
                }
1067
1.01k
                else
1068
1.01k
                {
1069
1.01k
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
1.01k
                    rateIncDown[blkPos] = 0;
1071
1.01k
                }
1072
1073
                /* Update CABAC estimation state */
1074
78.8k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
26.4k
                {
1076
26.4k
                    goRiceParam++;
1077
26.4k
                    levelThreshold <<= 1;
1078
26.4k
                }
1079
1080
78.8k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
78.8k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
78.8k
                if (level > 1)
1085
63.9k
                {
1086
63.9k
                    c1 = 0;
1087
63.9k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
63.9k
                    c2Idx++;
1089
63.9k
                }
1090
14.8k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
8.31k
                    c1++;
1092
1093
78.8k
                if (dstCoeff[blkPos])
1094
77.7k
                {
1095
77.7k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
77.7k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
77.7k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
77.7k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
77.7k
                }
1100
78.8k
            }
1101
1102
267k
            cgRdStats.sigCost += costSig[scanPos];
1103
267k
        } /* end for (scanPosinCG) */
1104
1105
16.7k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
16.7k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
16.7k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
16.7k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
16.7k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
16.7k
        {
1115
            /* coeff group 0 is implied to be present, no signal cost */
1116
            /* coeff group with last NZ is implied to be present, handled below */
1117
16.7k
        }
1118
0
        else if (sigCoeffGroupFlag64 & cgBlkPosMask)
1119
0
        {
1120
0
            if (!cgRdStats.nnzBeforePos0)
1121
0
            {
1122
                /* if only coeff 0 in this CG is coded, its significant coeff bit is implied */
1123
0
                totalRdCost -= cgRdStats.sigCost0;
1124
0
                cgRdStats.sigCost -= cgRdStats.sigCost0;
1125
0
            }
1126
1127
            /* there are coded coefficients in this group, but now we include the signaling cost
1128
             * of the significant coefficient group flag and evaluate whether the RD cost of the
1129
             * coded group is more than the RD cost of the uncoded group */
1130
1131
0
            uint32_t sigCtx = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1132
1133
0
            int64_t costZeroCG = totalRdCost + SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1134
0
            costZeroCG += cgRdStats.uncodedDist;       /* add distortion for resetting non-zero levels to zero levels */
1135
0
            costZeroCG -= cgRdStats.codedLevelAndDist; /* remove distortion and level cost of coded coefficients */
1136
0
            costZeroCG -= cgRdStats.sigCost;           /* remove signaling cost of significant coeff bitmap */
1137
1138
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][1]);
1139
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add the cost of 1 bit in significant CG bitmap */
1140
1141
0
            if (costZeroCG < totalRdCost && m_rdoqLevel > 1)
1142
0
            {
1143
0
                sigCoeffGroupFlag64 &= ~cgBlkPosMask;
1144
0
                totalRdCost = costZeroCG;
1145
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1146
1147
                /* reset all coeffs to 0. UNCODE THIS COEFF GROUP! */
1148
0
                const uint32_t blkPos = codeParams.scan[cgScanPos * cgSize];
1149
0
                memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1150
0
                memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1151
0
                memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1152
0
                memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1153
0
            }
1154
0
        }
1155
0
        else
1156
0
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
0
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
0
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
0
        }
1163
16.7k
    } /* end for (cgScanPos) */
1164
1165
65.5k
    X265_CHECK(lastScanPos >= 0, "numSig non zero, but no coded CG\n");
1166
1167
    /* calculate RD cost of uncoded block CBF=0, and add cost of CBF=1 to total */
1168
65.5k
    int64_t bestCost;
1169
65.5k
    if (!cu.isIntra(absPartIdx) && bIsLuma && !cu.m_tuDepth[absPartIdx])
1170
0
    {
1171
0
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockRootCbpBits[0]);
1172
0
        totalRdCost += SIGCOST(estBitsSbac.blockRootCbpBits[1]);
1173
0
    }
1174
65.5k
    else
1175
65.5k
    {
1176
65.5k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
65.5k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
65.5k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
65.5k
    }
1180
1181
    /* This loop starts with the last non-zero found in the first loop and then refines this last
1182
     * non-zero by measuring the true RD cost of the last NZ at this position, and then the RD costs
1183
     * at all previous coefficients until a coefficient greater than 1 is encountered or we run out
1184
     * of coefficients to evaluate.  This will factor in the cost of coding empty groups and empty
1185
     * coeff prior to the last NZ. The base best cost is the RD cost of CBF=0 */
1186
65.5k
    int  bestLastIdx = 0;
1187
65.5k
    bool foundLast = false;
1188
82.2k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
16.7k
    {
1190
16.7k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
16.7k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
16.7k
        }
1195
0
        else if (sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[cgScanPos]))
1196
0
        {
1197
            /* remove cost of significant coeff group flag, the group's presence would be inferred
1198
             * from lastNZ if it were present in this group */
1199
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1200
0
        }
1201
0
        else
1202
0
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
0
            continue;
1206
0
        }
1207
1208
217k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
215k
        {
1210
215k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
215k
            if ((int)scanPos > lastScanPos)
1212
186k
                continue;
1213
1214
            /* if the coefficient was coded, measure the RD cost of it as the last non-zero and then
1215
             * continue as if it were uncoded. If the coefficient was already uncoded, remove the
1216
             * cost of signaling it as not-significant */
1217
28.9k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
28.9k
            if (dstCoeff[blkPos])
1219
26.6k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
26.6k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
26.6k
                if (codeParams.scanType == SCAN_VER)
1223
3.85k
                    std::swap(pos[0], pos[1]);
1224
26.6k
                uint32_t bitsLastNZ = 0;
1225
1226
80.0k
                for (int i = 0; i < 2; i++)
1227
53.3k
                {
1228
53.3k
                    int temp = g_lastCoeffTable[pos[i]];
1229
53.3k
                    int prefixOnes = temp & 15;
1230
53.3k
                    int suffixLen = temp >> 4;
1231
1232
53.3k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
53.3k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
53.3k
                }
1235
1236
26.6k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
26.6k
                if (costAsLast < bestCost)
1239
17.8k
                {
1240
17.8k
                    bestLastIdx = scanPos + 1;
1241
17.8k
                    bestCost = costAsLast;
1242
17.8k
                }
1243
26.6k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
14.7k
                {
1245
14.7k
                    foundLast = true;
1246
14.7k
                    break;
1247
14.7k
                }
1248
1249
11.8k
                totalRdCost -= costCoeff[scanPos];
1250
11.8k
                totalRdCost += costUncoded[blkPos];
1251
11.8k
            }
1252
2.23k
            else
1253
2.23k
                totalRdCost -= costSig[scanPos];
1254
28.9k
        }
1255
16.7k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
65.5k
    numSig = 0;
1259
142k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
77.2k
    {
1261
77.2k
        int blkPos = codeParams.scan[pos];
1262
77.2k
        int level  = dstCoeff[blkPos];
1263
77.2k
        numSig += (level != 0);
1264
1265
77.2k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
77.2k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
77.2k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
65.5k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
255k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
190k
    {
1274
190k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
190k
    }
1276
65.5k
    for (int pos = (bestLastIdx & ~(SCAN_SET_SIZE - 1)) + SCAN_SET_SIZE; pos <= lastScanPos; pos += SCAN_SET_SIZE)
1277
0
    {
1278
0
        const uint32_t blkPos = codeParams.scan[pos];
1279
0
        memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1280
0
        memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1281
0
        memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1282
0
        memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1283
0
    }
1284
1285
    /* rate-distortion based sign-hiding */
1286
65.5k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
4.97k
    {
1288
4.97k
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
4.97k
        int lastCG = 1;
1290
1291
9.95k
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
4.97k
        {
1293
4.97k
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
4.97k
            int n;
1295
1296
4.97k
            if (!(sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[subSet])))
1297
0
                continue;
1298
1299
            /* measure distance between first and last non-zero coef in this
1300
             * coding group */
1301
4.97k
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
4.97k
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
4.97k
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
4.97k
            const uint32_t absSumSign = posFirstLast;
1305
1306
4.97k
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
4.83k
            {
1308
4.83k
                const int32_t signbit = ((int32_t)dstCoeff[codeParams.scan[subPos + firstNZPosInCG]]);
1309
1310
#if CHECKED_BUILD || _DEBUG
1311
                int32_t absSum_dummy = 0;
1312
                for (n = firstNZPosInCG; n <= lastNZPosInCG; n++)
1313
                    absSum_dummy += dstCoeff[codeParams.scan[n + subPos]];
1314
                X265_CHECK(((uint32_t)absSum_dummy & 1) == (absSumSign >> 31), "absSumSign check failure\n");
1315
#endif
1316
1317
                //if (signbit != absSumSign)
1318
4.83k
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
2.14k
                {
1320
                    /* We must find a coeff to toggle up or down so the sign bit of the first non-zero coeff
1321
                     * is properly implied. Note dstCoeff[] are signed by this point but curChange and
1322
                     * finalChange imply absolute levels (+1 is away from zero, -1 is towards zero) */
1323
1324
2.14k
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
2.14k
                    uint32_t minPos = 0;
1326
2.14k
                    int8_t finalChange = 0;
1327
2.14k
                    int curChange = 0;
1328
2.14k
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
30.1k
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
27.9k
                    {
1332
27.9k
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
27.9k
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
27.9k
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
27.9k
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
27.9k
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
27.9k
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
27.9k
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
27.9k
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
27.9k
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
27.9k
                        const uint32_t isOne = (absLevel == 1);
1347
27.9k
                        if (dstCoeff[blkPos])
1348
26.9k
                        {
1349
26.9k
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
26.9k
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
26.9k
                            int64_t costUp = DELTARDCOST(origDist, d, rateIncUp[blkPos]);
1352
1353
                            /* if decrementing would make the coeff 0, we can include the
1354
                             * significant coeff flag cost savings */
1355
26.9k
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
26.9k
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
26.9k
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
26.9k
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
26.9k
                            costDown -= lastCoeffAdjust;
1361
26.9k
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
26.9k
                            curChange = 2 * (costUp < costDown) - 1;
1364
26.9k
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
26.9k
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
1.01k
                        else if ((n < firstNZPosInCG) & ((signbit ^ signCoef) < 0))
1368
0
                        {
1369
                            /* don't try to make a new coded coeff before the first coeff if its
1370
                             * sign would be different than the first coeff, the inferred sign would
1371
                             * still be wrong and we'd have to do this again. */
1372
0
                            curCost = MAX_INT64;
1373
0
                        }
1374
1.01k
                        else
1375
1.01k
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
1.01k
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
1.01k
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
1.01k
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
1.01k
                            curChange = 1;
1381
1.01k
                        }
1382
1383
27.9k
                        if (curCost < minCostInc)
1384
7.37k
                        {
1385
7.37k
                            minCostInc = curCost;
1386
7.37k
                            finalChange = (int8_t)curChange;
1387
7.37k
                            minPos = blkPos + (absLevel << 16);
1388
7.37k
                        }
1389
27.9k
                        lastCoeffAdjust = 0;
1390
27.9k
                    }
1391
1392
2.14k
                    const int absInMinPos = (minPos >> 16);
1393
2.14k
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
2.14k
                    if (absInMinPos >= 32767)
1397
                        /* don't allow sign hiding to violate the SPEC range */
1398
0
                        finalChange = -1;
1399
1400
                    // NOTE: Reference code
1401
                    //if (dstCoeff[minPos] == 0)
1402
                    //    numSig++;
1403
                    //else if (finalChange == -1 && abs(dstCoeff[minPos]) == 1)
1404
                    //    numSig--;
1405
2.14k
                    numSig += (absInMinPos == 0) - ((finalChange == -1) & (absInMinPos == 1));
1406
1407
1408
                    // NOTE: Reference code
1409
                    //if (m_resiDctCoeff[minPos] >= 0)
1410
                    //    dstCoeff[minPos] += finalChange;
1411
                    //else
1412
                    //    dstCoeff[minPos] -= finalChange;
1413
2.14k
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
2.14k
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
2.14k
                }
1416
4.83k
            }
1417
1418
4.97k
            lastCG = 0;
1419
4.97k
        }
1420
4.97k
    }
1421
1422
65.5k
    return numSig;
1423
7.21M
}
unsigned int x265::Quant::rdoQuant<3u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
1.21M
{
612
1.21M
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
1.21M
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
1.21M
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
1.21M
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
1.21M
    int rem = m_qpParam[ttype].rem;
619
1.21M
    int per = m_qpParam[ttype].per;
620
1.21M
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
1.21M
    int add = (1 << (qbits - 1));
622
1.21M
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
1.21M
    const int numCoeff = 1 << (log2TrSize * 2);
625
1.21M
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
1.21M
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
1.21M
    if (!numSig)
628
1.18M
        return 0;
629
28.2k
    const uint32_t trSize = 1 << log2TrSize;
630
28.2k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
28.2k
    int64_t psyScale = ((int64_t)m_psyRdoqScale * m_qpParam[ttype].lambda);
632
    /* unquant constants for measuring distortion. Scaling list quant coefficients have a (1 << 4)
633
     * scale applied that must be removed during unquant. Note that in real dequant there is clipping
634
     * at several stages. We skip the clipping for simplicity when measuring RD cost */
635
28.2k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
28.2k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
28.2k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
28.2k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
28.2k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
28.2k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
28.2k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
28.2k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
28.2k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
28.2k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
28.2k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
28.2k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
28.2k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
28.2k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
28.2k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
28.2k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
28.2k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
28.2k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
28.2k
    int64_t totalUncodedCost = 0;
661
662
    /* Total rate distortion cost of this transform block, counting te distortion of uncoded blocks,
663
     * the distortion and signal cost of coded blocks, and the coding cost of significant
664
     * coefficient and coefficient group bitmaps */
665
28.2k
    int64_t totalRdCost = 0;
666
667
28.2k
    TUEntropyCodingParameters codeParams;
668
28.2k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
28.2k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
28.2k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
28.2k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
28.2k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
28.2k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
28.2k
    uint16_t coeffFlag[MLS_GRP_NUM];    // bit mask map for non-zero coeff
676
677
#if CHECKED_BUILD || _DEBUG
678
    // clean output buffer, the asm version of scanPosLast Never output anything after latest non-zero coeff group
679
    memset(coeffNum, 0, sizeof(coeffNum) * sizeof(uint8_t));
680
    memset(coeffSign, 0, sizeof(coeffNum) * sizeof(uint16_t));
681
    memset(coeffFlag, 0, sizeof(coeffNum) * sizeof(uint16_t));
682
#endif
683
28.2k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
28.2k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
28.2k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
28.2k
    uint32_t scanPos = 0;
691
28.2k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
28.2k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
28.2k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
28.2k
    memset(&costSig[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
699
700
    /* sum zero coeff (uncodec) cost */
701
702
    // TODO: does we need these cost?
703
28.2k
    if (usePsyMask)
704
5.18k
    {
705
20.7k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
15.5k
        {
707
15.5k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
15.5k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
15.5k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
15.5k
#if X265_ARCH_X86
711
15.5k
            bool enable512 = detect512();
712
15.5k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
15.5k
            else
715
15.5k
            {
716
15.5k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
15.5k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
15.5k
            }
719
#else
720
            primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
721
            primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
722
#endif
723
15.5k
        }
724
5.18k
    }
725
23.0k
    else
726
23.0k
    {
727
        // non-psy path
728
89.0k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
65.9k
        {
730
65.9k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
65.9k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
65.9k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
65.9k
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
65.9k
        }
735
23.0k
    }
736
28.2k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
28.2k
    {
738
        // patternSigCtx = 0
739
28.2k
        {
740
28.2k
            2, 1, 1, 0,
741
28.2k
            1, 1, 0, 0,
742
28.2k
            1, 0, 0, 0,
743
28.2k
            0, 0, 0, 0,
744
28.2k
        },
745
        // patternSigCtx = 1
746
28.2k
        {
747
28.2k
            2, 2, 2, 2,
748
28.2k
            1, 1, 1, 1,
749
28.2k
            0, 0, 0, 0,
750
28.2k
            0, 0, 0, 0,
751
28.2k
        },
752
        // patternSigCtx = 2
753
28.2k
        {
754
28.2k
            2, 1, 0, 0,
755
28.2k
            2, 1, 0, 0,
756
28.2k
            2, 1, 0, 0,
757
28.2k
            2, 1, 0, 0,
758
28.2k
        },
759
        // patternSigCtx = 3
760
28.2k
        {
761
28.2k
            2, 2, 2, 2,
762
28.2k
            2, 2, 2, 2,
763
28.2k
            2, 2, 2, 2,
764
28.2k
            2, 2, 2, 2,
765
28.2k
        },
766
        // 4x4
767
28.2k
        {
768
28.2k
            0, 1, 4, 5,
769
28.2k
            2, 3, 4, 5,
770
28.2k
            6, 6, 8, 8,
771
28.2k
            7, 7, 8, 8
772
28.2k
        }
773
28.2k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
55.4k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
27.1k
    {
778
27.1k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
27.1k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
27.1k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
27.1k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
27.1k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
27.1k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
27.1k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
27.1k
        if (c1 == 0)
787
0
            ctxSet++;
788
27.1k
        c1 = 1;
789
790
27.1k
        if (cgScanPos && (coeffNum[cgScanPos] == 0))
791
0
        {
792
            // TODO: does we need zero-coeff cost?
793
0
            const uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
794
0
            uint32_t blkPos = codeParams.scan[scanPosBase];
795
0
            if (usePsyMask)
796
0
            {
797
0
#if X265_ARCH_X86
798
0
                bool enable512 = detect512();
799
0
                if (enable512)
800
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
801
0
                else
802
0
                {
803
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
804
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
805
0
                }
806
#else
807
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
808
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
809
#endif
810
0
                blkPos = codeParams.scan[scanPosBase];
811
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
812
0
                {
813
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
814
0
                    {
815
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
816
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
817
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
818
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
819
820
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
821
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
822
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
823
0
                    }
824
0
                    blkPos += trSize;
825
0
                }
826
0
            }
827
0
            else
828
0
            {
829
                // non-psy path
830
0
                primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
831
0
                blkPos = codeParams.scan[scanPosBase];
832
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
833
0
                {
834
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
835
0
                    {
836
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
837
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
838
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
839
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
840
841
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
842
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
843
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
844
0
                    }
845
0
                    blkPos += trSize;
846
0
                }
847
0
            }
848
849
            /* there were no coded coefficients in this coefficient group */
850
0
            {
851
0
                uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
852
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
853
0
                totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
854
0
            }
855
0
            continue;
856
0
        }
857
858
27.1k
        coeffGroupRDStats cgRdStats;
859
27.1k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
27.1k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
27.1k
        int    c2            = 0;
863
27.1k
        uint32_t goRiceParam = 0;
864
27.1k
        uint32_t levelThreshold = 3;
865
27.1k
        uint32_t c1Idx       = 0;
866
27.1k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
461k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
434k
        {
870
434k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
434k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
434k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
434k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
434k
            int predictedCoef    = m_fencDctCoeff[blkPos] - signCoef; /* predicted DCT = source DCT - residual DCT*/
875
876
            /* RDOQ measures distortion as the squared difference between the unquantized coded level
877
             * and the original DCT coefficient. The result is shifted scaleBits to account for the
878
             * FIX15 nature of the CABAC cost tables minus the forward transform scale */
879
880
            /* cost of not coding this coefficient (all distortion, no signal bits) */
881
434k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
434k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
434k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
77.8k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
434k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
434k
            const int* greaterOneBits = estBitsSbac.greaterOneBits[4 * ctxSet + c1];
891
            //const uint32_t ctxSig = (blkPos == 0) ? 0 : table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset;
892
434k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
434k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
434k
            const uint32_t ctxSig = (blkPos == 0) ? 0 : ((ctxCnt >> (4 * g_scan4x4[codeParams.scanType][scanPosinCG])) & 0xF) + ctxSigOffset;
895
            // NOTE: above equal to 'table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset'
896
434k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
434k
            if (scanPos > (uint32_t)lastScanPos)
900
407k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
407k
                costCoeff[scanPos] = 0;
903
407k
                costSig[scanPos] = 0;
904
905
                /* No non-zero coefficient yet found, but this does not mean
906
                 * there is no uncoded-cost for this coefficient. Pre-
907
                 * quantization the coefficient may have been non-zero */
908
407k
                totalRdCost += costUncoded[blkPos];
909
407k
            }
910
27.1k
            else if (!(subFlagMask & 1))
911
0
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
0
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
0
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
0
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
0
                totalRdCost += costCoeff[scanPos];
918
0
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
0
                subFlagMask >>= 1;
921
0
            }
922
27.1k
            else
923
27.1k
            {
924
27.1k
                subFlagMask >>= 1;
925
926
27.1k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
27.1k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
27.1k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
27.1k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
27.1k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
27.1k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
27.1k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
18.4E
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
27.1k
                uint32_t level = 0;
939
27.1k
                uint32_t sigCoefBits = 0;
940
27.1k
                costCoeff[scanPos] = MAX_INT64;
941
942
27.1k
                if ((int)scanPos == lastScanPos)
943
27.1k
                    sigRateDelta[blkPos] = 0;
944
18.4E
                else
945
18.4E
                {
946
18.4E
                    if (maxAbsLevel < 3)
947
0
                    {
948
                        /* set default costs to uncoded costs */
949
0
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
0
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
0
                    }
952
18.4E
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
18.4E
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
18.4E
                }
955
956
27.1k
                const uint32_t unQuantLevel = (maxAbsLevel * (unquantScale[blkPos] << per) + unquantRound);
957
                // NOTE: X265_MAX(maxAbsLevel - 1, 1) ==> (X>=2 -> X-1), (X<2 -> 1)  | (0 < X < 2 ==> X=1)
958
27.1k
                if (maxAbsLevel == 1)
959
17.8k
                {
960
17.8k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
17.8k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
17.8k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
17.8k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
17.8k
                    int d = abs(signCoef) - unquantAbsLevel;
966
17.8k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
17.8k
                    if (usePsyMask & scanPos)
970
0
                    {
971
0
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
0
                        curCost -= PSYVALUE(reconCoef);
973
0
                    }
974
975
17.8k
                    if (curCost < costCoeff[scanPos])
976
17.8k
                    {
977
17.8k
                        level = 1;
978
17.8k
                        costCoeff[scanPos] = curCost;
979
17.8k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
17.8k
                    }
981
17.8k
                }
982
9.27k
                else if (maxAbsLevel)
983
9.34k
                {
984
9.34k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
9.34k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
9.34k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
9.34k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
9.34k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
9.34k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
9.34k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
9.34k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
9.34k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
9.34k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
9.34k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
9.34k
                    if (usePsyMask & scanPos)
1001
0
                    {
1002
0
                        int reconCoef;
1003
0
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
0
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
0
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
0
                        curCost1 -= PSYVALUE(reconCoef);
1008
0
                    }
1009
9.34k
                    if (curCost0 < costCoeff[scanPos])
1010
9.34k
                    {
1011
9.34k
                        level = maxAbsLevel;
1012
9.34k
                        costCoeff[scanPos] = curCost0;
1013
9.34k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
9.34k
                    }
1015
9.34k
                    if (curCost1 < costCoeff[scanPos])
1016
0
                    {
1017
0
                        level = maxAbsLevel - 1;
1018
0
                        costCoeff[scanPos] = curCost1;
1019
0
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
0
                    }
1021
9.34k
                }
1022
1023
27.1k
                dstCoeff[blkPos] = (int16_t)level;
1024
27.1k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
18.4E
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
27.1k
                {
1029
27.1k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
27.1k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
27.1k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
27.1k
                    int rate0, rate1, rate2;
1033
1034
27.1k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
17.8k
                    {
1036
                        // NOTE: Min: L - 1 - {1,2,1,3} < -2 ==> L < {0,1,0,2}
1037
                        //            additional L > 0, so I got (L > 0 && L < 2) ==> L = 1
1038
17.8k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
17.8k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
17.8k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
17.8k
                        rate0 = 0;
1044
17.8k
                        rate2 = rateEqual2;
1045
17.8k
                        rate1 = rateNotEqual2;
1046
1047
17.8k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
17.8k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
17.8k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
17.8k
                    }
1051
9.34k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
0
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
0
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
0
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
0
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
0
                    }
1058
9.34k
                    else
1059
9.34k
                    {
1060
9.34k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
9.34k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
9.34k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
9.34k
                    }
1064
27.1k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
27.1k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
27.1k
                }
1067
18.4E
                else
1068
18.4E
                {
1069
18.4E
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
18.4E
                    rateIncDown[blkPos] = 0;
1071
18.4E
                }
1072
1073
                /* Update CABAC estimation state */
1074
27.1k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
9.34k
                {
1076
9.34k
                    goRiceParam++;
1077
9.34k
                    levelThreshold <<= 1;
1078
9.34k
                }
1079
1080
27.1k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
27.1k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
27.1k
                if (level > 1)
1085
9.34k
                {
1086
9.34k
                    c1 = 0;
1087
9.34k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
9.34k
                    c2Idx++;
1089
9.34k
                }
1090
17.7k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
17.8k
                    c1++;
1092
1093
27.1k
                if (dstCoeff[blkPos])
1094
27.1k
                {
1095
27.1k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
27.1k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
27.1k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
27.1k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
27.1k
                }
1100
27.1k
            }
1101
1102
434k
            cgRdStats.sigCost += costSig[scanPos];
1103
434k
        } /* end for (scanPosinCG) */
1104
1105
27.1k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
27.1k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
27.1k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
27.1k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
27.1k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
27.1k
        {
1115
            /* coeff group 0 is implied to be present, no signal cost */
1116
            /* coeff group with last NZ is implied to be present, handled below */
1117
27.1k
        }
1118
4
        else if (sigCoeffGroupFlag64 & cgBlkPosMask)
1119
0
        {
1120
0
            if (!cgRdStats.nnzBeforePos0)
1121
0
            {
1122
                /* if only coeff 0 in this CG is coded, its significant coeff bit is implied */
1123
0
                totalRdCost -= cgRdStats.sigCost0;
1124
0
                cgRdStats.sigCost -= cgRdStats.sigCost0;
1125
0
            }
1126
1127
            /* there are coded coefficients in this group, but now we include the signaling cost
1128
             * of the significant coefficient group flag and evaluate whether the RD cost of the
1129
             * coded group is more than the RD cost of the uncoded group */
1130
1131
0
            uint32_t sigCtx = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1132
1133
0
            int64_t costZeroCG = totalRdCost + SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1134
0
            costZeroCG += cgRdStats.uncodedDist;       /* add distortion for resetting non-zero levels to zero levels */
1135
0
            costZeroCG -= cgRdStats.codedLevelAndDist; /* remove distortion and level cost of coded coefficients */
1136
0
            costZeroCG -= cgRdStats.sigCost;           /* remove signaling cost of significant coeff bitmap */
1137
1138
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][1]);
1139
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add the cost of 1 bit in significant CG bitmap */
1140
1141
0
            if (costZeroCG < totalRdCost && m_rdoqLevel > 1)
1142
0
            {
1143
0
                sigCoeffGroupFlag64 &= ~cgBlkPosMask;
1144
0
                totalRdCost = costZeroCG;
1145
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1146
1147
                /* reset all coeffs to 0. UNCODE THIS COEFF GROUP! */
1148
0
                const uint32_t blkPos = codeParams.scan[cgScanPos * cgSize];
1149
0
                memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1150
0
                memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1151
0
                memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1152
0
                memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1153
0
            }
1154
0
        }
1155
4
        else
1156
4
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
4
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
4
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
4
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
4
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
4
        }
1163
27.1k
    } /* end for (cgScanPos) */
1164
1165
28.2k
    X265_CHECK(lastScanPos >= 0, "numSig non zero, but no coded CG\n");
1166
1167
    /* calculate RD cost of uncoded block CBF=0, and add cost of CBF=1 to total */
1168
28.2k
    int64_t bestCost;
1169
28.2k
    if (!cu.isIntra(absPartIdx) && bIsLuma && !cu.m_tuDepth[absPartIdx])
1170
0
    {
1171
0
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockRootCbpBits[0]);
1172
0
        totalRdCost += SIGCOST(estBitsSbac.blockRootCbpBits[1]);
1173
0
    }
1174
28.2k
    else
1175
28.2k
    {
1176
28.2k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
28.2k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
28.2k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
28.2k
    }
1180
1181
    /* This loop starts with the last non-zero found in the first loop and then refines this last
1182
     * non-zero by measuring the true RD cost of the last NZ at this position, and then the RD costs
1183
     * at all previous coefficients until a coefficient greater than 1 is encountered or we run out
1184
     * of coefficients to evaluate.  This will factor in the cost of coding empty groups and empty
1185
     * coeff prior to the last NZ. The base best cost is the RD cost of CBF=0 */
1186
28.2k
    int  bestLastIdx = 0;
1187
28.2k
    bool foundLast = false;
1188
55.4k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
27.1k
    {
1190
27.1k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
27.1k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
27.1k
        }
1195
1
        else if (sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[cgScanPos]))
1196
0
        {
1197
            /* remove cost of significant coeff group flag, the group's presence would be inferred
1198
             * from lastNZ if it were present in this group */
1199
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1200
0
        }
1201
1
        else
1202
1
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
1
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
1
            continue;
1206
1
        }
1207
1208
452k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
434k
        {
1210
434k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
434k
            if ((int)scanPos > lastScanPos)
1212
407k
                continue;
1213
1214
            /* if the coefficient was coded, measure the RD cost of it as the last non-zero and then
1215
             * continue as if it were uncoded. If the coefficient was already uncoded, remove the
1216
             * cost of signaling it as not-significant */
1217
27.1k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
27.1k
            if (dstCoeff[blkPos])
1219
27.1k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
27.1k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
27.1k
                if (codeParams.scanType == SCAN_VER)
1223
367
                    std::swap(pos[0], pos[1]);
1224
27.1k
                uint32_t bitsLastNZ = 0;
1225
1226
81.5k
                for (int i = 0; i < 2; i++)
1227
54.3k
                {
1228
54.3k
                    int temp = g_lastCoeffTable[pos[i]];
1229
54.3k
                    int prefixOnes = temp & 15;
1230
54.3k
                    int suffixLen = temp >> 4;
1231
1232
54.3k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
54.3k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
54.3k
                }
1235
1236
27.1k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
27.1k
                if (costAsLast < bestCost)
1239
10.5k
                {
1240
10.5k
                    bestLastIdx = scanPos + 1;
1241
10.5k
                    bestCost = costAsLast;
1242
10.5k
                }
1243
27.1k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
9.34k
                {
1245
9.34k
                    foundLast = true;
1246
9.34k
                    break;
1247
9.34k
                }
1248
1249
17.8k
                totalRdCost -= costCoeff[scanPos];
1250
17.8k
                totalRdCost += costUncoded[blkPos];
1251
17.8k
            }
1252
18.4E
            else
1253
18.4E
                totalRdCost -= costSig[scanPos];
1254
27.1k
        }
1255
27.1k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
28.2k
    numSig = 0;
1259
38.7k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
10.5k
    {
1261
10.5k
        int blkPos = codeParams.scan[pos];
1262
10.5k
        int level  = dstCoeff[blkPos];
1263
10.5k
        numSig += (level != 0);
1264
1265
10.5k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
10.5k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
10.5k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
28.2k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
452k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
424k
    {
1274
424k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
424k
    }
1276
28.2k
    for (int pos = (bestLastIdx & ~(SCAN_SET_SIZE - 1)) + SCAN_SET_SIZE; pos <= lastScanPos; pos += SCAN_SET_SIZE)
1277
0
    {
1278
0
        const uint32_t blkPos = codeParams.scan[pos];
1279
0
        memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1280
0
        memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1281
0
        memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1282
0
        memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1283
0
    }
1284
1285
    /* rate-distortion based sign-hiding */
1286
28.2k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
0
    {
1288
0
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
0
        int lastCG = 1;
1290
1291
0
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
0
        {
1293
0
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
0
            int n;
1295
1296
0
            if (!(sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[subSet])))
1297
0
                continue;
1298
1299
            /* measure distance between first and last non-zero coef in this
1300
             * coding group */
1301
0
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
0
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
0
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
0
            const uint32_t absSumSign = posFirstLast;
1305
1306
0
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
0
            {
1308
0
                const int32_t signbit = ((int32_t)dstCoeff[codeParams.scan[subPos + firstNZPosInCG]]);
1309
1310
#if CHECKED_BUILD || _DEBUG
1311
                int32_t absSum_dummy = 0;
1312
                for (n = firstNZPosInCG; n <= lastNZPosInCG; n++)
1313
                    absSum_dummy += dstCoeff[codeParams.scan[n + subPos]];
1314
                X265_CHECK(((uint32_t)absSum_dummy & 1) == (absSumSign >> 31), "absSumSign check failure\n");
1315
#endif
1316
1317
                //if (signbit != absSumSign)
1318
0
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
0
                {
1320
                    /* We must find a coeff to toggle up or down so the sign bit of the first non-zero coeff
1321
                     * is properly implied. Note dstCoeff[] are signed by this point but curChange and
1322
                     * finalChange imply absolute levels (+1 is away from zero, -1 is towards zero) */
1323
1324
0
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
0
                    uint32_t minPos = 0;
1326
0
                    int8_t finalChange = 0;
1327
0
                    int curChange = 0;
1328
0
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
0
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
0
                    {
1332
0
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
0
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
0
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
0
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
0
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
0
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
0
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
0
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
0
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
0
                        const uint32_t isOne = (absLevel == 1);
1347
0
                        if (dstCoeff[blkPos])
1348
0
                        {
1349
0
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
0
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
0
                            int64_t costUp = DELTARDCOST(origDist, d, rateIncUp[blkPos]);
1352
1353
                            /* if decrementing would make the coeff 0, we can include the
1354
                             * significant coeff flag cost savings */
1355
0
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
0
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
0
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
0
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
0
                            costDown -= lastCoeffAdjust;
1361
0
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
0
                            curChange = 2 * (costUp < costDown) - 1;
1364
0
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
0
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
0
                        else if ((n < firstNZPosInCG) & ((signbit ^ signCoef) < 0))
1368
0
                        {
1369
                            /* don't try to make a new coded coeff before the first coeff if its
1370
                             * sign would be different than the first coeff, the inferred sign would
1371
                             * still be wrong and we'd have to do this again. */
1372
0
                            curCost = MAX_INT64;
1373
0
                        }
1374
0
                        else
1375
0
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
0
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
0
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
0
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
0
                            curChange = 1;
1381
0
                        }
1382
1383
0
                        if (curCost < minCostInc)
1384
0
                        {
1385
0
                            minCostInc = curCost;
1386
0
                            finalChange = (int8_t)curChange;
1387
0
                            minPos = blkPos + (absLevel << 16);
1388
0
                        }
1389
0
                        lastCoeffAdjust = 0;
1390
0
                    }
1391
1392
0
                    const int absInMinPos = (minPos >> 16);
1393
0
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
0
                    if (absInMinPos >= 32767)
1397
                        /* don't allow sign hiding to violate the SPEC range */
1398
0
                        finalChange = -1;
1399
1400
                    // NOTE: Reference code
1401
                    //if (dstCoeff[minPos] == 0)
1402
                    //    numSig++;
1403
                    //else if (finalChange == -1 && abs(dstCoeff[minPos]) == 1)
1404
                    //    numSig--;
1405
0
                    numSig += (absInMinPos == 0) - ((finalChange == -1) & (absInMinPos == 1));
1406
1407
1408
                    // NOTE: Reference code
1409
                    //if (m_resiDctCoeff[minPos] >= 0)
1410
                    //    dstCoeff[minPos] += finalChange;
1411
                    //else
1412
                    //    dstCoeff[minPos] -= finalChange;
1413
0
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
0
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
0
                }
1416
0
            }
1417
1418
0
            lastCG = 0;
1419
0
        }
1420
0
    }
1421
1422
28.2k
    return numSig;
1423
1.21M
}
unsigned int x265::Quant::rdoQuant<4u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
266k
{
612
266k
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
266k
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
266k
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
266k
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
266k
    int rem = m_qpParam[ttype].rem;
619
266k
    int per = m_qpParam[ttype].per;
620
266k
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
266k
    int add = (1 << (qbits - 1));
622
266k
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
266k
    const int numCoeff = 1 << (log2TrSize * 2);
625
266k
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
266k
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
266k
    if (!numSig)
628
256k
        return 0;
629
10.3k
    const uint32_t trSize = 1 << log2TrSize;
630
10.3k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
10.3k
    int64_t psyScale = ((int64_t)m_psyRdoqScale * m_qpParam[ttype].lambda);
632
    /* unquant constants for measuring distortion. Scaling list quant coefficients have a (1 << 4)
633
     * scale applied that must be removed during unquant. Note that in real dequant there is clipping
634
     * at several stages. We skip the clipping for simplicity when measuring RD cost */
635
10.3k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
10.3k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
10.3k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
10.3k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
10.3k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
10.3k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
10.3k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
10.3k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
10.3k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
10.3k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
10.3k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
10.3k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
10.3k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
10.3k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
10.3k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
10.3k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
10.3k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
10.3k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
10.3k
    int64_t totalUncodedCost = 0;
661
662
    /* Total rate distortion cost of this transform block, counting te distortion of uncoded blocks,
663
     * the distortion and signal cost of coded blocks, and the coding cost of significant
664
     * coefficient and coefficient group bitmaps */
665
10.3k
    int64_t totalRdCost = 0;
666
667
10.3k
    TUEntropyCodingParameters codeParams;
668
10.3k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
10.3k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
10.3k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
10.3k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
10.3k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
10.3k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
10.3k
    uint16_t coeffFlag[MLS_GRP_NUM];    // bit mask map for non-zero coeff
676
677
#if CHECKED_BUILD || _DEBUG
678
    // clean output buffer, the asm version of scanPosLast Never output anything after latest non-zero coeff group
679
    memset(coeffNum, 0, sizeof(coeffNum) * sizeof(uint8_t));
680
    memset(coeffSign, 0, sizeof(coeffNum) * sizeof(uint16_t));
681
    memset(coeffFlag, 0, sizeof(coeffNum) * sizeof(uint16_t));
682
#endif
683
10.3k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
10.3k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
10.3k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
10.3k
    uint32_t scanPos = 0;
691
10.3k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
10.3k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
10.3k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
10.3k
    memset(&costSig[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
699
700
    /* sum zero coeff (uncodec) cost */
701
702
    // TODO: does we need these cost?
703
10.3k
    if (usePsyMask)
704
6.11k
    {
705
97.7k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
91.6k
        {
707
91.6k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
91.6k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
91.6k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
91.6k
#if X265_ARCH_X86
711
91.6k
            bool enable512 = detect512();
712
91.6k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
91.6k
            else
715
91.6k
            {
716
91.6k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
91.6k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
91.6k
            }
719
#else
720
            primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
721
            primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
722
#endif
723
91.6k
        }
724
6.11k
    }
725
4.20k
    else
726
4.20k
    {
727
        // non-psy path
728
66.5k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
62.3k
        {
730
62.3k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
62.3k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
62.3k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
62.3k
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
62.3k
        }
735
4.20k
    }
736
10.3k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
10.3k
    {
738
        // patternSigCtx = 0
739
10.3k
        {
740
10.3k
            2, 1, 1, 0,
741
10.3k
            1, 1, 0, 0,
742
10.3k
            1, 0, 0, 0,
743
10.3k
            0, 0, 0, 0,
744
10.3k
        },
745
        // patternSigCtx = 1
746
10.3k
        {
747
10.3k
            2, 2, 2, 2,
748
10.3k
            1, 1, 1, 1,
749
10.3k
            0, 0, 0, 0,
750
10.3k
            0, 0, 0, 0,
751
10.3k
        },
752
        // patternSigCtx = 2
753
10.3k
        {
754
10.3k
            2, 1, 0, 0,
755
10.3k
            2, 1, 0, 0,
756
10.3k
            2, 1, 0, 0,
757
10.3k
            2, 1, 0, 0,
758
10.3k
        },
759
        // patternSigCtx = 3
760
10.3k
        {
761
10.3k
            2, 2, 2, 2,
762
10.3k
            2, 2, 2, 2,
763
10.3k
            2, 2, 2, 2,
764
10.3k
            2, 2, 2, 2,
765
10.3k
        },
766
        // 4x4
767
10.3k
        {
768
10.3k
            0, 1, 4, 5,
769
10.3k
            2, 3, 4, 5,
770
10.3k
            6, 6, 8, 8,
771
10.3k
            7, 7, 8, 8
772
10.3k
        }
773
10.3k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
20.5k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
10.2k
    {
778
10.2k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
10.2k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
10.2k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
10.2k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
10.2k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
10.2k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
10.2k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
10.2k
        if (c1 == 0)
787
0
            ctxSet++;
788
10.2k
        c1 = 1;
789
790
10.2k
        if (cgScanPos && (coeffNum[cgScanPos] == 0))
791
0
        {
792
            // TODO: does we need zero-coeff cost?
793
0
            const uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
794
0
            uint32_t blkPos = codeParams.scan[scanPosBase];
795
0
            if (usePsyMask)
796
0
            {
797
0
#if X265_ARCH_X86
798
0
                bool enable512 = detect512();
799
0
                if (enable512)
800
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
801
0
                else
802
0
                {
803
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
804
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
805
0
                }
806
#else
807
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
808
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
809
#endif
810
0
                blkPos = codeParams.scan[scanPosBase];
811
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
812
0
                {
813
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
814
0
                    {
815
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
816
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
817
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
818
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
819
820
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
821
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
822
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
823
0
                    }
824
0
                    blkPos += trSize;
825
0
                }
826
0
            }
827
0
            else
828
0
            {
829
                // non-psy path
830
0
                primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
831
0
                blkPos = codeParams.scan[scanPosBase];
832
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
833
0
                {
834
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
835
0
                    {
836
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
837
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
838
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
839
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
840
841
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
842
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
843
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
844
0
                    }
845
0
                    blkPos += trSize;
846
0
                }
847
0
            }
848
849
            /* there were no coded coefficients in this coefficient group */
850
0
            {
851
0
                uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
852
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
853
0
                totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
854
0
            }
855
0
            continue;
856
0
        }
857
858
10.2k
        coeffGroupRDStats cgRdStats;
859
10.2k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
10.2k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
10.2k
        int    c2            = 0;
863
10.2k
        uint32_t goRiceParam = 0;
864
10.2k
        uint32_t levelThreshold = 3;
865
10.2k
        uint32_t c1Idx       = 0;
866
10.2k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
174k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
164k
        {
870
164k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
164k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
164k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
164k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
164k
            int predictedCoef    = m_fencDctCoeff[blkPos] - signCoef; /* predicted DCT = source DCT - residual DCT*/
875
876
            /* RDOQ measures distortion as the squared difference between the unquantized coded level
877
             * and the original DCT coefficient. The result is shifted scaleBits to account for the
878
             * FIX15 nature of the CABAC cost tables minus the forward transform scale */
879
880
            /* cost of not coding this coefficient (all distortion, no signal bits) */
881
164k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
164k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
164k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
91.6k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
164k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
164k
            const int* greaterOneBits = estBitsSbac.greaterOneBits[4 * ctxSet + c1];
891
            //const uint32_t ctxSig = (blkPos == 0) ? 0 : table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset;
892
164k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
164k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
164k
            const uint32_t ctxSig = (blkPos == 0) ? 0 : ((ctxCnt >> (4 * g_scan4x4[codeParams.scanType][scanPosinCG])) & 0xF) + ctxSigOffset;
895
            // NOTE: above equal to 'table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset'
896
164k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
164k
            if (scanPos > (uint32_t)lastScanPos)
900
154k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
154k
                costCoeff[scanPos] = 0;
903
154k
                costSig[scanPos] = 0;
904
905
                /* No non-zero coefficient yet found, but this does not mean
906
                 * there is no uncoded-cost for this coefficient. Pre-
907
                 * quantization the coefficient may have been non-zero */
908
154k
                totalRdCost += costUncoded[blkPos];
909
154k
            }
910
10.2k
            else if (!(subFlagMask & 1))
911
0
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
0
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
0
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
0
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
0
                totalRdCost += costCoeff[scanPos];
918
0
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
0
                subFlagMask >>= 1;
921
0
            }
922
10.2k
            else
923
10.2k
            {
924
10.2k
                subFlagMask >>= 1;
925
926
10.2k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
10.2k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
10.2k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
10.2k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
10.2k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
10.2k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
10.2k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
10.2k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
10.2k
                uint32_t level = 0;
939
10.2k
                uint32_t sigCoefBits = 0;
940
10.2k
                costCoeff[scanPos] = MAX_INT64;
941
942
10.2k
                if ((int)scanPos == lastScanPos)
943
10.2k
                    sigRateDelta[blkPos] = 0;
944
0
                else
945
0
                {
946
0
                    if (maxAbsLevel < 3)
947
0
                    {
948
                        /* set default costs to uncoded costs */
949
0
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
0
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
0
                    }
952
0
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
0
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
0
                }
955
956
10.2k
                const uint32_t unQuantLevel = (maxAbsLevel * (unquantScale[blkPos] << per) + unquantRound);
957
                // NOTE: X265_MAX(maxAbsLevel - 1, 1) ==> (X>=2 -> X-1), (X<2 -> 1)  | (0 < X < 2 ==> X=1)
958
10.2k
                if (maxAbsLevel == 1)
959
2.41k
                {
960
2.41k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
2.41k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
2.41k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
2.41k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
2.41k
                    int d = abs(signCoef) - unquantAbsLevel;
966
2.41k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
2.41k
                    if (usePsyMask & scanPos)
970
0
                    {
971
0
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
0
                        curCost -= PSYVALUE(reconCoef);
973
0
                    }
974
975
2.41k
                    if (curCost < costCoeff[scanPos])
976
2.41k
                    {
977
2.41k
                        level = 1;
978
2.41k
                        costCoeff[scanPos] = curCost;
979
2.41k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
2.41k
                    }
981
2.41k
                }
982
7.85k
                else if (maxAbsLevel)
983
7.85k
                {
984
7.85k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
7.85k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
7.85k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
7.85k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
7.85k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
7.85k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
7.85k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
7.85k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
7.85k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
7.85k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
7.85k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
7.85k
                    if (usePsyMask & scanPos)
1001
0
                    {
1002
0
                        int reconCoef;
1003
0
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
0
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
0
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
0
                        curCost1 -= PSYVALUE(reconCoef);
1008
0
                    }
1009
7.85k
                    if (curCost0 < costCoeff[scanPos])
1010
7.85k
                    {
1011
7.85k
                        level = maxAbsLevel;
1012
7.85k
                        costCoeff[scanPos] = curCost0;
1013
7.85k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
7.85k
                    }
1015
7.85k
                    if (curCost1 < costCoeff[scanPos])
1016
139
                    {
1017
139
                        level = maxAbsLevel - 1;
1018
139
                        costCoeff[scanPos] = curCost1;
1019
139
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
139
                    }
1021
7.85k
                }
1022
1023
10.2k
                dstCoeff[blkPos] = (int16_t)level;
1024
10.2k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
10.2k
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
10.2k
                {
1029
10.2k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
10.2k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
10.2k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
10.2k
                    int rate0, rate1, rate2;
1033
1034
10.2k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
2.41k
                    {
1036
                        // NOTE: Min: L - 1 - {1,2,1,3} < -2 ==> L < {0,1,0,2}
1037
                        //            additional L > 0, so I got (L > 0 && L < 2) ==> L = 1
1038
2.41k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
2.41k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
2.41k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
2.41k
                        rate0 = 0;
1044
2.41k
                        rate2 = rateEqual2;
1045
2.41k
                        rate1 = rateNotEqual2;
1046
1047
2.41k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
2.41k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
2.41k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
2.41k
                    }
1051
7.85k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
0
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
0
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
0
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
0
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
0
                    }
1058
7.85k
                    else
1059
7.85k
                    {
1060
7.85k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
7.85k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
7.85k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
7.85k
                    }
1064
10.2k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
10.2k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
10.2k
                }
1067
0
                else
1068
0
                {
1069
0
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
0
                    rateIncDown[blkPos] = 0;
1071
0
                }
1072
1073
                /* Update CABAC estimation state */
1074
10.2k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
7.85k
                {
1076
7.85k
                    goRiceParam++;
1077
7.85k
                    levelThreshold <<= 1;
1078
7.85k
                }
1079
1080
10.2k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
10.2k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
10.2k
                if (level > 1)
1085
7.85k
                {
1086
7.85k
                    c1 = 0;
1087
7.85k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
7.85k
                    c2Idx++;
1089
7.85k
                }
1090
2.41k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
2.41k
                    c1++;
1092
1093
10.2k
                if (dstCoeff[blkPos])
1094
10.2k
                {
1095
10.2k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
10.2k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
10.2k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
10.2k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
10.2k
                }
1100
10.2k
            }
1101
1102
164k
            cgRdStats.sigCost += costSig[scanPos];
1103
164k
        } /* end for (scanPosinCG) */
1104
1105
10.2k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
10.2k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
10.2k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
10.2k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
10.2k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
10.2k
        {
1115
            /* coeff group 0 is implied to be present, no signal cost */
1116
            /* coeff group with last NZ is implied to be present, handled below */
1117
10.2k
        }
1118
0
        else if (sigCoeffGroupFlag64 & cgBlkPosMask)
1119
0
        {
1120
0
            if (!cgRdStats.nnzBeforePos0)
1121
0
            {
1122
                /* if only coeff 0 in this CG is coded, its significant coeff bit is implied */
1123
0
                totalRdCost -= cgRdStats.sigCost0;
1124
0
                cgRdStats.sigCost -= cgRdStats.sigCost0;
1125
0
            }
1126
1127
            /* there are coded coefficients in this group, but now we include the signaling cost
1128
             * of the significant coefficient group flag and evaluate whether the RD cost of the
1129
             * coded group is more than the RD cost of the uncoded group */
1130
1131
0
            uint32_t sigCtx = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1132
1133
0
            int64_t costZeroCG = totalRdCost + SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1134
0
            costZeroCG += cgRdStats.uncodedDist;       /* add distortion for resetting non-zero levels to zero levels */
1135
0
            costZeroCG -= cgRdStats.codedLevelAndDist; /* remove distortion and level cost of coded coefficients */
1136
0
            costZeroCG -= cgRdStats.sigCost;           /* remove signaling cost of significant coeff bitmap */
1137
1138
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][1]);
1139
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add the cost of 1 bit in significant CG bitmap */
1140
1141
0
            if (costZeroCG < totalRdCost && m_rdoqLevel > 1)
1142
0
            {
1143
0
                sigCoeffGroupFlag64 &= ~cgBlkPosMask;
1144
0
                totalRdCost = costZeroCG;
1145
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1146
1147
                /* reset all coeffs to 0. UNCODE THIS COEFF GROUP! */
1148
0
                const uint32_t blkPos = codeParams.scan[cgScanPos * cgSize];
1149
0
                memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1150
0
                memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1151
0
                memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1152
0
                memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1153
0
            }
1154
0
        }
1155
0
        else
1156
0
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
0
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
0
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
0
        }
1163
10.2k
    } /* end for (cgScanPos) */
1164
1165
10.3k
    X265_CHECK(lastScanPos >= 0, "numSig non zero, but no coded CG\n");
1166
1167
    /* calculate RD cost of uncoded block CBF=0, and add cost of CBF=1 to total */
1168
10.3k
    int64_t bestCost;
1169
10.3k
    if (!cu.isIntra(absPartIdx) && bIsLuma && !cu.m_tuDepth[absPartIdx])
1170
0
    {
1171
0
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockRootCbpBits[0]);
1172
0
        totalRdCost += SIGCOST(estBitsSbac.blockRootCbpBits[1]);
1173
0
    }
1174
10.3k
    else
1175
10.3k
    {
1176
10.3k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
10.3k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
10.3k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
10.3k
    }
1180
1181
    /* This loop starts with the last non-zero found in the first loop and then refines this last
1182
     * non-zero by measuring the true RD cost of the last NZ at this position, and then the RD costs
1183
     * at all previous coefficients until a coefficient greater than 1 is encountered or we run out
1184
     * of coefficients to evaluate.  This will factor in the cost of coding empty groups and empty
1185
     * coeff prior to the last NZ. The base best cost is the RD cost of CBF=0 */
1186
10.3k
    int  bestLastIdx = 0;
1187
10.3k
    bool foundLast = false;
1188
20.5k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
10.2k
    {
1190
10.2k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
10.2k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
10.2k
        }
1195
0
        else if (sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[cgScanPos]))
1196
0
        {
1197
            /* remove cost of significant coeff group flag, the group's presence would be inferred
1198
             * from lastNZ if it were present in this group */
1199
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1200
0
        }
1201
0
        else
1202
0
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
0
            continue;
1206
0
        }
1207
1208
166k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
164k
        {
1210
164k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
164k
            if ((int)scanPos > lastScanPos)
1212
154k
                continue;
1213
1214
            /* if the coefficient was coded, measure the RD cost of it as the last non-zero and then
1215
             * continue as if it were uncoded. If the coefficient was already uncoded, remove the
1216
             * cost of signaling it as not-significant */
1217
10.2k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
10.2k
            if (dstCoeff[blkPos])
1219
10.2k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
10.2k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
10.2k
                if (codeParams.scanType == SCAN_VER)
1223
0
                    std::swap(pos[0], pos[1]);
1224
10.2k
                uint32_t bitsLastNZ = 0;
1225
1226
30.8k
                for (int i = 0; i < 2; i++)
1227
20.5k
                {
1228
20.5k
                    int temp = g_lastCoeffTable[pos[i]];
1229
20.5k
                    int prefixOnes = temp & 15;
1230
20.5k
                    int suffixLen = temp >> 4;
1231
1232
20.5k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
20.5k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
20.5k
                }
1235
1236
10.2k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
10.2k
                if (costAsLast < bestCost)
1239
9.55k
                {
1240
9.55k
                    bestLastIdx = scanPos + 1;
1241
9.55k
                    bestCost = costAsLast;
1242
9.55k
                }
1243
10.2k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
7.85k
                {
1245
7.85k
                    foundLast = true;
1246
7.85k
                    break;
1247
7.85k
                }
1248
1249
2.41k
                totalRdCost -= costCoeff[scanPos];
1250
2.41k
                totalRdCost += costUncoded[blkPos];
1251
2.41k
            }
1252
0
            else
1253
0
                totalRdCost -= costSig[scanPos];
1254
10.2k
        }
1255
10.2k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
10.3k
    numSig = 0;
1259
19.8k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
9.55k
    {
1261
9.55k
        int blkPos = codeParams.scan[pos];
1262
9.55k
        int level  = dstCoeff[blkPos];
1263
9.55k
        numSig += (level != 0);
1264
1265
9.55k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
9.55k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
9.55k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
10.3k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
165k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
154k
    {
1274
154k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
154k
    }
1276
10.3k
    for (int pos = (bestLastIdx & ~(SCAN_SET_SIZE - 1)) + SCAN_SET_SIZE; pos <= lastScanPos; pos += SCAN_SET_SIZE)
1277
0
    {
1278
0
        const uint32_t blkPos = codeParams.scan[pos];
1279
0
        memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1280
0
        memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1281
0
        memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1282
0
        memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1283
0
    }
1284
1285
    /* rate-distortion based sign-hiding */
1286
10.3k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
0
    {
1288
0
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
0
        int lastCG = 1;
1290
1291
0
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
0
        {
1293
0
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
0
            int n;
1295
1296
0
            if (!(sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[subSet])))
1297
0
                continue;
1298
1299
            /* measure distance between first and last non-zero coef in this
1300
             * coding group */
1301
0
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
0
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
0
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
0
            const uint32_t absSumSign = posFirstLast;
1305
1306
0
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
0
            {
1308
0
                const int32_t signbit = ((int32_t)dstCoeff[codeParams.scan[subPos + firstNZPosInCG]]);
1309
1310
#if CHECKED_BUILD || _DEBUG
1311
                int32_t absSum_dummy = 0;
1312
                for (n = firstNZPosInCG; n <= lastNZPosInCG; n++)
1313
                    absSum_dummy += dstCoeff[codeParams.scan[n + subPos]];
1314
                X265_CHECK(((uint32_t)absSum_dummy & 1) == (absSumSign >> 31), "absSumSign check failure\n");
1315
#endif
1316
1317
                //if (signbit != absSumSign)
1318
0
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
0
                {
1320
                    /* We must find a coeff to toggle up or down so the sign bit of the first non-zero coeff
1321
                     * is properly implied. Note dstCoeff[] are signed by this point but curChange and
1322
                     * finalChange imply absolute levels (+1 is away from zero, -1 is towards zero) */
1323
1324
0
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
0
                    uint32_t minPos = 0;
1326
0
                    int8_t finalChange = 0;
1327
0
                    int curChange = 0;
1328
0
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
0
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
0
                    {
1332
0
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
0
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
0
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
0
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
0
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
0
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
0
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
0
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
0
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
0
                        const uint32_t isOne = (absLevel == 1);
1347
0
                        if (dstCoeff[blkPos])
1348
0
                        {
1349
0
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
0
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
0
                            int64_t costUp = DELTARDCOST(origDist, d, rateIncUp[blkPos]);
1352
1353
                            /* if decrementing would make the coeff 0, we can include the
1354
                             * significant coeff flag cost savings */
1355
0
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
0
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
0
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
0
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
0
                            costDown -= lastCoeffAdjust;
1361
0
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
0
                            curChange = 2 * (costUp < costDown) - 1;
1364
0
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
0
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
0
                        else if ((n < firstNZPosInCG) & ((signbit ^ signCoef) < 0))
1368
0
                        {
1369
                            /* don't try to make a new coded coeff before the first coeff if its
1370
                             * sign would be different than the first coeff, the inferred sign would
1371
                             * still be wrong and we'd have to do this again. */
1372
0
                            curCost = MAX_INT64;
1373
0
                        }
1374
0
                        else
1375
0
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
0
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
0
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
0
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
0
                            curChange = 1;
1381
0
                        }
1382
1383
0
                        if (curCost < minCostInc)
1384
0
                        {
1385
0
                            minCostInc = curCost;
1386
0
                            finalChange = (int8_t)curChange;
1387
0
                            minPos = blkPos + (absLevel << 16);
1388
0
                        }
1389
0
                        lastCoeffAdjust = 0;
1390
0
                    }
1391
1392
0
                    const int absInMinPos = (minPos >> 16);
1393
0
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
0
                    if (absInMinPos >= 32767)
1397
                        /* don't allow sign hiding to violate the SPEC range */
1398
0
                        finalChange = -1;
1399
1400
                    // NOTE: Reference code
1401
                    //if (dstCoeff[minPos] == 0)
1402
                    //    numSig++;
1403
                    //else if (finalChange == -1 && abs(dstCoeff[minPos]) == 1)
1404
                    //    numSig--;
1405
0
                    numSig += (absInMinPos == 0) - ((finalChange == -1) & (absInMinPos == 1));
1406
1407
1408
                    // NOTE: Reference code
1409
                    //if (m_resiDctCoeff[minPos] >= 0)
1410
                    //    dstCoeff[minPos] += finalChange;
1411
                    //else
1412
                    //    dstCoeff[minPos] -= finalChange;
1413
0
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
0
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
0
                }
1416
0
            }
1417
1418
0
            lastCG = 0;
1419
0
        }
1420
0
    }
1421
1422
10.3k
    return numSig;
1423
266k
}
unsigned int x265::Quant::rdoQuant<5u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
23.8k
{
612
23.8k
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
23.8k
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
23.8k
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
23.8k
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
23.8k
    int rem = m_qpParam[ttype].rem;
619
23.8k
    int per = m_qpParam[ttype].per;
620
23.8k
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
23.8k
    int add = (1 << (qbits - 1));
622
23.8k
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
23.8k
    const int numCoeff = 1 << (log2TrSize * 2);
625
23.8k
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
23.8k
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
23.8k
    if (!numSig)
628
21.2k
        return 0;
629
2.57k
    const uint32_t trSize = 1 << log2TrSize;
630
2.57k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
2.57k
    int64_t psyScale = ((int64_t)m_psyRdoqScale * m_qpParam[ttype].lambda);
632
    /* unquant constants for measuring distortion. Scaling list quant coefficients have a (1 << 4)
633
     * scale applied that must be removed during unquant. Note that in real dequant there is clipping
634
     * at several stages. We skip the clipping for simplicity when measuring RD cost */
635
2.57k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
2.57k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
2.57k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
2.57k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
2.57k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
2.57k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
2.57k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
2.57k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
2.57k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
2.57k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
2.57k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
2.57k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
2.57k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
2.57k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
2.57k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
2.57k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
2.57k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
2.57k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
2.57k
    int64_t totalUncodedCost = 0;
661
662
    /* Total rate distortion cost of this transform block, counting te distortion of uncoded blocks,
663
     * the distortion and signal cost of coded blocks, and the coding cost of significant
664
     * coefficient and coefficient group bitmaps */
665
2.57k
    int64_t totalRdCost = 0;
666
667
2.57k
    TUEntropyCodingParameters codeParams;
668
2.57k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
2.57k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
2.57k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
2.57k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
2.57k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
2.57k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
2.57k
    uint16_t coeffFlag[MLS_GRP_NUM];    // bit mask map for non-zero coeff
676
677
#if CHECKED_BUILD || _DEBUG
678
    // clean output buffer, the asm version of scanPosLast Never output anything after latest non-zero coeff group
679
    memset(coeffNum, 0, sizeof(coeffNum) * sizeof(uint8_t));
680
    memset(coeffSign, 0, sizeof(coeffNum) * sizeof(uint16_t));
681
    memset(coeffFlag, 0, sizeof(coeffNum) * sizeof(uint16_t));
682
#endif
683
2.57k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
2.57k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
2.57k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
2.57k
    uint32_t scanPos = 0;
691
2.57k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
2.57k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
2.57k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
2.57k
    memset(&costSig[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
699
700
    /* sum zero coeff (uncodec) cost */
701
702
    // TODO: does we need these cost?
703
2.57k
    if (usePsyMask)
704
2.56k
    {
705
164k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
161k
        {
707
161k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
161k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
161k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
161k
#if X265_ARCH_X86
711
161k
            bool enable512 = detect512();
712
161k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
161k
            else
715
161k
            {
716
161k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
161k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
161k
            }
719
#else
720
            primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
721
            primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
722
#endif
723
161k
        }
724
2.56k
    }
725
3
    else
726
3
    {
727
        // non-psy path
728
3
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
0
        {
730
0
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
0
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
0
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
0
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
0
        }
735
3
    }
736
2.57k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
2.57k
    {
738
        // patternSigCtx = 0
739
2.57k
        {
740
2.57k
            2, 1, 1, 0,
741
2.57k
            1, 1, 0, 0,
742
2.57k
            1, 0, 0, 0,
743
2.57k
            0, 0, 0, 0,
744
2.57k
        },
745
        // patternSigCtx = 1
746
2.57k
        {
747
2.57k
            2, 2, 2, 2,
748
2.57k
            1, 1, 1, 1,
749
2.57k
            0, 0, 0, 0,
750
2.57k
            0, 0, 0, 0,
751
2.57k
        },
752
        // patternSigCtx = 2
753
2.57k
        {
754
2.57k
            2, 1, 0, 0,
755
2.57k
            2, 1, 0, 0,
756
2.57k
            2, 1, 0, 0,
757
2.57k
            2, 1, 0, 0,
758
2.57k
        },
759
        // patternSigCtx = 3
760
2.57k
        {
761
2.57k
            2, 2, 2, 2,
762
2.57k
            2, 2, 2, 2,
763
2.57k
            2, 2, 2, 2,
764
2.57k
            2, 2, 2, 2,
765
2.57k
        },
766
        // 4x4
767
2.57k
        {
768
2.57k
            0, 1, 4, 5,
769
2.57k
            2, 3, 4, 5,
770
2.57k
            6, 6, 8, 8,
771
2.57k
            7, 7, 8, 8
772
2.57k
        }
773
2.57k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
5.14k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
2.56k
    {
778
2.56k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
2.56k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
2.56k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
2.56k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
2.56k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
2.56k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
2.56k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
2.56k
        if (c1 == 0)
787
0
            ctxSet++;
788
2.56k
        c1 = 1;
789
790
2.56k
        if (cgScanPos && (coeffNum[cgScanPos] == 0))
791
0
        {
792
            // TODO: does we need zero-coeff cost?
793
0
            const uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
794
0
            uint32_t blkPos = codeParams.scan[scanPosBase];
795
0
            if (usePsyMask)
796
0
            {
797
0
#if X265_ARCH_X86
798
0
                bool enable512 = detect512();
799
0
                if (enable512)
800
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
801
0
                else
802
0
                {
803
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
804
0
                    primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
805
0
                }
806
#else
807
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
808
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
809
#endif
810
0
                blkPos = codeParams.scan[scanPosBase];
811
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
812
0
                {
813
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
814
0
                    {
815
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
816
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
817
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
818
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
819
820
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
821
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
822
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
823
0
                    }
824
0
                    blkPos += trSize;
825
0
                }
826
0
            }
827
0
            else
828
0
            {
829
                // non-psy path
830
0
                primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
831
0
                blkPos = codeParams.scan[scanPosBase];
832
0
                for (int y = 0; y < MLS_CG_SIZE; y++)
833
0
                {
834
0
                    for (int x = 0; x < MLS_CG_SIZE; x++)
835
0
                    {
836
0
                        const uint32_t scanPosOffset =  y * MLS_CG_SIZE + x;
837
0
                        const uint32_t ctxSig = table_cnt[patternSigCtx][g_scan4x4[codeParams.scanType][scanPosOffset]] + ctxSigOffset;
838
0
                        X265_CHECK(trSize > 4, "trSize check failure\n");
839
0
                        X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, codeParams.scan[scanPosBase + scanPosOffset], bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
840
841
0
                        costSig[scanPosBase + scanPosOffset] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
842
0
                        costCoeff[scanPosBase + scanPosOffset] = costUncoded[blkPos + x];
843
0
                        sigRateDelta[blkPos + x] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
844
0
                    }
845
0
                    blkPos += trSize;
846
0
                }
847
0
            }
848
849
            /* there were no coded coefficients in this coefficient group */
850
0
            {
851
0
                uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
852
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
853
0
                totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
854
0
            }
855
0
            continue;
856
0
        }
857
858
2.56k
        coeffGroupRDStats cgRdStats;
859
2.56k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
2.56k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
2.56k
        int    c2            = 0;
863
2.56k
        uint32_t goRiceParam = 0;
864
2.56k
        uint32_t levelThreshold = 3;
865
2.56k
        uint32_t c1Idx       = 0;
866
2.56k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
43.6k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
41.1k
        {
870
41.1k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
41.1k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
41.1k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
41.1k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
41.1k
            int predictedCoef    = m_fencDctCoeff[blkPos] - signCoef; /* predicted DCT = source DCT - residual DCT*/
875
876
            /* RDOQ measures distortion as the squared difference between the unquantized coded level
877
             * and the original DCT coefficient. The result is shifted scaleBits to account for the
878
             * FIX15 nature of the CABAC cost tables minus the forward transform scale */
879
880
            /* cost of not coding this coefficient (all distortion, no signal bits) */
881
41.1k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
41.1k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
41.1k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
38.5k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
41.1k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
41.1k
            const int* greaterOneBits = estBitsSbac.greaterOneBits[4 * ctxSet + c1];
891
            //const uint32_t ctxSig = (blkPos == 0) ? 0 : table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset;
892
41.1k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
41.1k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
41.1k
            const uint32_t ctxSig = (blkPos == 0) ? 0 : ((ctxCnt >> (4 * g_scan4x4[codeParams.scanType][scanPosinCG])) & 0xF) + ctxSigOffset;
895
            // NOTE: above equal to 'table_cnt[(trSize == 4) ? 4 : patternSigCtx][g_scan4x4[codeParams.scanType][scanPosinCG]] + ctxSigOffset'
896
41.1k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
41.1k
            if (scanPos > (uint32_t)lastScanPos)
900
38.5k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
38.5k
                costCoeff[scanPos] = 0;
903
38.5k
                costSig[scanPos] = 0;
904
905
                /* No non-zero coefficient yet found, but this does not mean
906
                 * there is no uncoded-cost for this coefficient. Pre-
907
                 * quantization the coefficient may have been non-zero */
908
38.5k
                totalRdCost += costUncoded[blkPos];
909
38.5k
            }
910
2.56k
            else if (!(subFlagMask & 1))
911
0
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
0
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
0
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
0
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
0
                totalRdCost += costCoeff[scanPos];
918
0
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
0
                subFlagMask >>= 1;
921
0
            }
922
2.56k
            else
923
2.56k
            {
924
2.56k
                subFlagMask >>= 1;
925
926
2.56k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
2.56k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
2.56k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
2.56k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
2.56k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
2.56k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
2.56k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
2.56k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
2.56k
                uint32_t level = 0;
939
2.56k
                uint32_t sigCoefBits = 0;
940
2.56k
                costCoeff[scanPos] = MAX_INT64;
941
942
2.56k
                if ((int)scanPos == lastScanPos)
943
2.56k
                    sigRateDelta[blkPos] = 0;
944
0
                else
945
0
                {
946
0
                    if (maxAbsLevel < 3)
947
0
                    {
948
                        /* set default costs to uncoded costs */
949
0
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
0
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
0
                    }
952
0
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
0
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
0
                }
955
956
2.56k
                const uint32_t unQuantLevel = (maxAbsLevel * (unquantScale[blkPos] << per) + unquantRound);
957
                // NOTE: X265_MAX(maxAbsLevel - 1, 1) ==> (X>=2 -> X-1), (X<2 -> 1)  | (0 < X < 2 ==> X=1)
958
2.56k
                if (maxAbsLevel == 1)
959
0
                {
960
0
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
0
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
0
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
0
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
0
                    int d = abs(signCoef) - unquantAbsLevel;
966
0
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
0
                    if (usePsyMask & scanPos)
970
0
                    {
971
0
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
0
                        curCost -= PSYVALUE(reconCoef);
973
0
                    }
974
975
0
                    if (curCost < costCoeff[scanPos])
976
0
                    {
977
0
                        level = 1;
978
0
                        costCoeff[scanPos] = curCost;
979
0
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
0
                    }
981
0
                }
982
2.56k
                else if (maxAbsLevel)
983
2.56k
                {
984
2.56k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
2.56k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
2.56k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
2.56k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
2.56k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
2.56k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
2.56k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
2.56k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
2.56k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
2.56k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
2.56k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
2.56k
                    if (usePsyMask & scanPos)
1001
0
                    {
1002
0
                        int reconCoef;
1003
0
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
0
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
0
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
0
                        curCost1 -= PSYVALUE(reconCoef);
1008
0
                    }
1009
2.56k
                    if (curCost0 < costCoeff[scanPos])
1010
2.56k
                    {
1011
2.56k
                        level = maxAbsLevel;
1012
2.56k
                        costCoeff[scanPos] = curCost0;
1013
2.56k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
2.56k
                    }
1015
2.56k
                    if (curCost1 < costCoeff[scanPos])
1016
63
                    {
1017
63
                        level = maxAbsLevel - 1;
1018
63
                        costCoeff[scanPos] = curCost1;
1019
63
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
63
                    }
1021
2.56k
                }
1022
1023
2.56k
                dstCoeff[blkPos] = (int16_t)level;
1024
2.56k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
2.56k
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
2.56k
                {
1029
2.56k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
2.56k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
2.56k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
2.56k
                    int rate0, rate1, rate2;
1033
1034
2.56k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
0
                    {
1036
                        // NOTE: Min: L - 1 - {1,2,1,3} < -2 ==> L < {0,1,0,2}
1037
                        //            additional L > 0, so I got (L > 0 && L < 2) ==> L = 1
1038
0
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
0
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
0
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
0
                        rate0 = 0;
1044
0
                        rate2 = rateEqual2;
1045
0
                        rate1 = rateNotEqual2;
1046
1047
0
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
0
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
0
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
0
                    }
1051
2.56k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
0
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
0
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
0
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
0
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
0
                    }
1058
2.56k
                    else
1059
2.56k
                    {
1060
2.56k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
2.56k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
2.56k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
2.56k
                    }
1064
2.56k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
2.56k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
2.56k
                }
1067
0
                else
1068
0
                {
1069
0
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
0
                    rateIncDown[blkPos] = 0;
1071
0
                }
1072
1073
                /* Update CABAC estimation state */
1074
2.56k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
2.56k
                {
1076
2.56k
                    goRiceParam++;
1077
2.56k
                    levelThreshold <<= 1;
1078
2.56k
                }
1079
1080
2.56k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
2.56k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
2.56k
                if (level > 1)
1085
2.56k
                {
1086
2.56k
                    c1 = 0;
1087
2.56k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
2.56k
                    c2Idx++;
1089
2.56k
                }
1090
0
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
0
                    c1++;
1092
1093
2.56k
                if (dstCoeff[blkPos])
1094
2.56k
                {
1095
2.56k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
2.56k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
2.56k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
2.56k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
2.56k
                }
1100
2.56k
            }
1101
1102
41.1k
            cgRdStats.sigCost += costSig[scanPos];
1103
41.1k
        } /* end for (scanPosinCG) */
1104
1105
2.56k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
2.56k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
2.56k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
2.56k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
2.56k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
2.56k
        {
1115
            /* coeff group 0 is implied to be present, no signal cost */
1116
            /* coeff group with last NZ is implied to be present, handled below */
1117
2.56k
        }
1118
0
        else if (sigCoeffGroupFlag64 & cgBlkPosMask)
1119
0
        {
1120
0
            if (!cgRdStats.nnzBeforePos0)
1121
0
            {
1122
                /* if only coeff 0 in this CG is coded, its significant coeff bit is implied */
1123
0
                totalRdCost -= cgRdStats.sigCost0;
1124
0
                cgRdStats.sigCost -= cgRdStats.sigCost0;
1125
0
            }
1126
1127
            /* there are coded coefficients in this group, but now we include the signaling cost
1128
             * of the significant coefficient group flag and evaluate whether the RD cost of the
1129
             * coded group is more than the RD cost of the uncoded group */
1130
1131
0
            uint32_t sigCtx = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1132
1133
0
            int64_t costZeroCG = totalRdCost + SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1134
0
            costZeroCG += cgRdStats.uncodedDist;       /* add distortion for resetting non-zero levels to zero levels */
1135
0
            costZeroCG -= cgRdStats.codedLevelAndDist; /* remove distortion and level cost of coded coefficients */
1136
0
            costZeroCG -= cgRdStats.sigCost;           /* remove signaling cost of significant coeff bitmap */
1137
1138
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][1]);
1139
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add the cost of 1 bit in significant CG bitmap */
1140
1141
0
            if (costZeroCG < totalRdCost && m_rdoqLevel > 1)
1142
0
            {
1143
0
                sigCoeffGroupFlag64 &= ~cgBlkPosMask;
1144
0
                totalRdCost = costZeroCG;
1145
0
                costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[sigCtx][0]);
1146
1147
                /* reset all coeffs to 0. UNCODE THIS COEFF GROUP! */
1148
0
                const uint32_t blkPos = codeParams.scan[cgScanPos * cgSize];
1149
0
                memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1150
0
                memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1151
0
                memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1152
0
                memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1153
0
            }
1154
0
        }
1155
0
        else
1156
0
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
0
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
0
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
0
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
0
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
0
        }
1163
2.56k
    } /* end for (cgScanPos) */
1164
1165
2.57k
    X265_CHECK(lastScanPos >= 0, "numSig non zero, but no coded CG\n");
1166
1167
    /* calculate RD cost of uncoded block CBF=0, and add cost of CBF=1 to total */
1168
2.57k
    int64_t bestCost;
1169
2.57k
    if (!cu.isIntra(absPartIdx) && bIsLuma && !cu.m_tuDepth[absPartIdx])
1170
0
    {
1171
0
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockRootCbpBits[0]);
1172
0
        totalRdCost += SIGCOST(estBitsSbac.blockRootCbpBits[1]);
1173
0
    }
1174
2.57k
    else
1175
2.57k
    {
1176
2.57k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
2.57k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
2.57k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
2.57k
    }
1180
1181
    /* This loop starts with the last non-zero found in the first loop and then refines this last
1182
     * non-zero by measuring the true RD cost of the last NZ at this position, and then the RD costs
1183
     * at all previous coefficients until a coefficient greater than 1 is encountered or we run out
1184
     * of coefficients to evaluate.  This will factor in the cost of coding empty groups and empty
1185
     * coeff prior to the last NZ. The base best cost is the RD cost of CBF=0 */
1186
2.57k
    int  bestLastIdx = 0;
1187
2.57k
    bool foundLast = false;
1188
5.14k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
2.56k
    {
1190
2.56k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
2.56k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
2.56k
        }
1195
0
        else if (sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[cgScanPos]))
1196
0
        {
1197
            /* remove cost of significant coeff group flag, the group's presence would be inferred
1198
             * from lastNZ if it were present in this group */
1199
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1200
0
        }
1201
0
        else
1202
0
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
0
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
0
            continue;
1206
0
        }
1207
1208
41.1k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
41.1k
        {
1210
41.1k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
41.1k
            if ((int)scanPos > lastScanPos)
1212
38.5k
                continue;
1213
1214
            /* if the coefficient was coded, measure the RD cost of it as the last non-zero and then
1215
             * continue as if it were uncoded. If the coefficient was already uncoded, remove the
1216
             * cost of signaling it as not-significant */
1217
2.56k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
2.56k
            if (dstCoeff[blkPos])
1219
2.56k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
2.56k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
2.56k
                if (codeParams.scanType == SCAN_VER)
1223
0
                    std::swap(pos[0], pos[1]);
1224
2.56k
                uint32_t bitsLastNZ = 0;
1225
1226
7.70k
                for (int i = 0; i < 2; i++)
1227
5.13k
                {
1228
5.13k
                    int temp = g_lastCoeffTable[pos[i]];
1229
5.13k
                    int prefixOnes = temp & 15;
1230
5.13k
                    int suffixLen = temp >> 4;
1231
1232
5.13k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
5.13k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
5.13k
                }
1235
1236
2.56k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
2.56k
                if (costAsLast < bestCost)
1239
2.56k
                {
1240
2.56k
                    bestLastIdx = scanPos + 1;
1241
2.56k
                    bestCost = costAsLast;
1242
2.56k
                }
1243
2.56k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
2.56k
                {
1245
2.56k
                    foundLast = true;
1246
2.56k
                    break;
1247
2.56k
                }
1248
1249
0
                totalRdCost -= costCoeff[scanPos];
1250
0
                totalRdCost += costUncoded[blkPos];
1251
0
            }
1252
0
            else
1253
0
                totalRdCost -= costSig[scanPos];
1254
2.56k
        }
1255
2.56k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
2.57k
    numSig = 0;
1259
5.14k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
2.56k
    {
1261
2.56k
        int blkPos = codeParams.scan[pos];
1262
2.56k
        int level  = dstCoeff[blkPos];
1263
2.56k
        numSig += (level != 0);
1264
1265
2.56k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
2.56k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
2.56k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
2.57k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
41.1k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
38.5k
    {
1274
38.5k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
38.5k
    }
1276
2.57k
    for (int pos = (bestLastIdx & ~(SCAN_SET_SIZE - 1)) + SCAN_SET_SIZE; pos <= lastScanPos; pos += SCAN_SET_SIZE)
1277
0
    {
1278
0
        const uint32_t blkPos = codeParams.scan[pos];
1279
0
        memset(&dstCoeff[blkPos + 0 * trSize], 0, 4 * sizeof(*dstCoeff));
1280
0
        memset(&dstCoeff[blkPos + 1 * trSize], 0, 4 * sizeof(*dstCoeff));
1281
0
        memset(&dstCoeff[blkPos + 2 * trSize], 0, 4 * sizeof(*dstCoeff));
1282
0
        memset(&dstCoeff[blkPos + 3 * trSize], 0, 4 * sizeof(*dstCoeff));
1283
0
    }
1284
1285
    /* rate-distortion based sign-hiding */
1286
2.57k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
0
    {
1288
0
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
0
        int lastCG = 1;
1290
1291
0
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
0
        {
1293
0
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
0
            int n;
1295
1296
0
            if (!(sigCoeffGroupFlag64 & (1ULL << codeParams.scanCG[subSet])))
1297
0
                continue;
1298
1299
            /* measure distance between first and last non-zero coef in this
1300
             * coding group */
1301
0
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
0
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
0
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
0
            const uint32_t absSumSign = posFirstLast;
1305
1306
0
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
0
            {
1308
0
                const int32_t signbit = ((int32_t)dstCoeff[codeParams.scan[subPos + firstNZPosInCG]]);
1309
1310
#if CHECKED_BUILD || _DEBUG
1311
                int32_t absSum_dummy = 0;
1312
                for (n = firstNZPosInCG; n <= lastNZPosInCG; n++)
1313
                    absSum_dummy += dstCoeff[codeParams.scan[n + subPos]];
1314
                X265_CHECK(((uint32_t)absSum_dummy & 1) == (absSumSign >> 31), "absSumSign check failure\n");
1315
#endif
1316
1317
                //if (signbit != absSumSign)
1318
0
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
0
                {
1320
                    /* We must find a coeff to toggle up or down so the sign bit of the first non-zero coeff
1321
                     * is properly implied. Note dstCoeff[] are signed by this point but curChange and
1322
                     * finalChange imply absolute levels (+1 is away from zero, -1 is towards zero) */
1323
1324
0
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
0
                    uint32_t minPos = 0;
1326
0
                    int8_t finalChange = 0;
1327
0
                    int curChange = 0;
1328
0
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
0
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
0
                    {
1332
0
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
0
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
0
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
0
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
0
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
0
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
0
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
0
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
0
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
0
                        const uint32_t isOne = (absLevel == 1);
1347
0
                        if (dstCoeff[blkPos])
1348
0
                        {
1349
0
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
0
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
0
                            int64_t costUp = DELTARDCOST(origDist, d, rateIncUp[blkPos]);
1352
1353
                            /* if decrementing would make the coeff 0, we can include the
1354
                             * significant coeff flag cost savings */
1355
0
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
0
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
0
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
0
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
0
                            costDown -= lastCoeffAdjust;
1361
0
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
0
                            curChange = 2 * (costUp < costDown) - 1;
1364
0
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
0
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
0
                        else if ((n < firstNZPosInCG) & ((signbit ^ signCoef) < 0))
1368
0
                        {
1369
                            /* don't try to make a new coded coeff before the first coeff if its
1370
                             * sign would be different than the first coeff, the inferred sign would
1371
                             * still be wrong and we'd have to do this again. */
1372
0
                            curCost = MAX_INT64;
1373
0
                        }
1374
0
                        else
1375
0
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
0
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
0
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
0
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
0
                            curChange = 1;
1381
0
                        }
1382
1383
0
                        if (curCost < minCostInc)
1384
0
                        {
1385
0
                            minCostInc = curCost;
1386
0
                            finalChange = (int8_t)curChange;
1387
0
                            minPos = blkPos + (absLevel << 16);
1388
0
                        }
1389
0
                        lastCoeffAdjust = 0;
1390
0
                    }
1391
1392
0
                    const int absInMinPos = (minPos >> 16);
1393
0
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
0
                    if (absInMinPos >= 32767)
1397
                        /* don't allow sign hiding to violate the SPEC range */
1398
0
                        finalChange = -1;
1399
1400
                    // NOTE: Reference code
1401
                    //if (dstCoeff[minPos] == 0)
1402
                    //    numSig++;
1403
                    //else if (finalChange == -1 && abs(dstCoeff[minPos]) == 1)
1404
                    //    numSig--;
1405
0
                    numSig += (absInMinPos == 0) - ((finalChange == -1) & (absInMinPos == 1));
1406
1407
1408
                    // NOTE: Reference code
1409
                    //if (m_resiDctCoeff[minPos] >= 0)
1410
                    //    dstCoeff[minPos] += finalChange;
1411
                    //else
1412
                    //    dstCoeff[minPos] -= finalChange;
1413
0
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
0
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
0
                }
1416
0
            }
1417
1418
0
            lastCG = 0;
1419
0
        }
1420
0
    }
1421
1422
2.57k
    return numSig;
1423
23.8k
}
1424
1425
/* Context derivation process of coeff_abs_significant_flag */
1426
uint32_t Quant::getSigCtxInc(uint32_t patternSigCtx, uint32_t log2TrSize, uint32_t trSize, uint32_t blkPos, bool bIsLuma,
1427
                             uint32_t firstSignificanceMapContext)
1428
0
{
1429
0
    static const uint8_t ctxIndMap[16] =
1430
0
    {
1431
0
        0, 1, 4, 5,
1432
0
        2, 3, 4, 5,
1433
0
        6, 6, 8, 8,
1434
0
        7, 7, 8, 8
1435
0
    };
1436
1437
0
    if (!blkPos) // special case for the DC context variable
1438
0
        return 0;
1439
1440
0
    if (log2TrSize == 2) // 4x4
1441
0
        return ctxIndMap[blkPos];
1442
1443
0
    const uint32_t posY = blkPos >> log2TrSize;
1444
0
    const uint32_t posX = blkPos & (trSize - 1);
1445
0
    X265_CHECK((blkPos - (posY << log2TrSize)) == posX, "block pos check failed\n");
1446
1447
0
    int posXinSubset = blkPos & 3;
1448
0
    X265_CHECK((posX & 3) == (blkPos & 3), "pos alignment fail\n");
1449
0
    int posYinSubset = posY & 3;
1450
1451
    // NOTE: [patternSigCtx][posXinSubset][posYinSubset]
1452
0
    static const uint8_t table_cnt[4][4][4] =
1453
0
    {
1454
        // patternSigCtx = 0
1455
0
        {
1456
0
            { 2, 1, 1, 0 },
1457
0
            { 1, 1, 0, 0 },
1458
0
            { 1, 0, 0, 0 },
1459
0
            { 0, 0, 0, 0 },
1460
0
        },
1461
        // patternSigCtx = 1
1462
0
        {
1463
0
            { 2, 1, 0, 0 },
1464
0
            { 2, 1, 0, 0 },
1465
0
            { 2, 1, 0, 0 },
1466
0
            { 2, 1, 0, 0 },
1467
0
        },
1468
        // patternSigCtx = 2
1469
0
        {
1470
0
            { 2, 2, 2, 2 },
1471
0
            { 1, 1, 1, 1 },
1472
0
            { 0, 0, 0, 0 },
1473
0
            { 0, 0, 0, 0 },
1474
0
        },
1475
        // patternSigCtx = 3
1476
0
        {
1477
0
            { 2, 2, 2, 2 },
1478
0
            { 2, 2, 2, 2 },
1479
0
            { 2, 2, 2, 2 },
1480
0
            { 2, 2, 2, 2 },
1481
0
        }
1482
0
    };
1483
1484
0
    int cnt = table_cnt[patternSigCtx][posXinSubset][posYinSubset];
1485
0
    int offset = firstSignificanceMapContext;
1486
1487
0
    offset += cnt;
1488
1489
0
    return (bIsLuma && (posX | posY) >= 4) ? 3 + offset : offset;
1490
0
}
1491