Coverage Report

Created: 2026-12-01 06:48

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
122k
#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.16M
{
51
1.16M
    return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // min(x, y)
52
1.16M
}
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
173k
{
56
173k
    X265_CHECK(absGoRice <= 4, "absGoRice check failure\n");
57
173k
    if (!absLevel)
58
2.19k
    {
59
2.19k
        X265_CHECK(diffLevel < 0, "diffLevel check failure\n");
60
2.19k
        return 0;
61
2.19k
    }
62
170k
    int rate = 0;
63
64
170k
    if (diffLevel < 0)
65
14.6k
    {
66
14.6k
        X265_CHECK(absLevel <= 2, "absLevel check failure\n");
67
14.6k
        rate += greaterOneBits[(absLevel == 2)];
68
69
14.6k
        if (absLevel == 2)
70
5.13k
            rate += levelAbsBits[0];
71
14.6k
    }
72
156k
    else
73
156k
    {
74
156k
        uint32_t symbol = diffLevel;
75
156k
        bool expGolomb = (symbol > maxVlc);
76
77
156k
        if (expGolomb)
78
132k
        {
79
132k
            absLevel = symbol - maxVlc;
80
81
            // NOTE: mapping to x86 hardware instruction BSR
82
132k
            unsigned long size;
83
132k
            BSR(size, absLevel);
84
132k
            int egs = size * 2 + 1;
85
86
132k
            rate += egs << 15;
87
88
            // NOTE: in here, expGolomb=true means (symbol >= maxVlc + 1)
89
132k
            X265_CHECK(fastMin(symbol, (maxVlc + 1)) == (int)maxVlc + 1, "min check failure\n");
90
132k
            symbol = maxVlc + 1;
91
132k
        }
92
93
156k
        uint32_t prefLen = (symbol >> absGoRice) + 1;
94
156k
        uint32_t numBins = fastMin(prefLen + absGoRice, 8 /* g_goRicePrefixLen[absGoRice] + absGoRice */);
95
96
156k
        rate += numBins << 15;
97
156k
        rate += c1c2Rate;
98
156k
    }
99
170k
    return rate;
100
173k
}
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
110k
{
120
110k
    X265_CHECK(absGoRice <= 4, "absGoRice check failure\n");
121
110k
    if (!absLevel)
122
0
    {
123
0
        X265_CHECK(diffLevel < 0, "diffLevel check failure\n");
124
0
        return 0;
125
0
    }
126
110k
    int rate;
127
128
110k
    uint32_t symbol = diffLevel;
129
110k
    uint32_t prefLen = (symbol >> absGoRice) + 1;
130
110k
    uint32_t numBins = fastMin(prefLen + absGoRice, 8 /* g_goRicePrefixLen[absGoRice] + absGoRice */);
131
132
110k
    rate = numBins << 15;
133
134
110k
    return rate;
135
110k
}
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
186k
{
140
186k
    X265_CHECK(absLevel, "absLevel should not be zero\n");
141
142
186k
    if (diffLevel < 0)
143
14.3k
    {
144
14.3k
        X265_CHECK((absLevel == 1) || (absLevel == 2), "absLevel range check failure\n");
145
146
14.3k
        uint32_t rate = greaterOneBits[(absLevel == 2)];
147
14.3k
        if (absLevel == 2)
148
6.14k
            rate += levelAbsBits[0];
149
14.3k
        return rate;
150
14.3k
    }
151
172k
    else
152
172k
    {
153
172k
        uint32_t rate;
154
172k
        uint32_t symbol = diffLevel;
155
172k
        if ((symbol >> absGoRice) < COEF_REMAIN_BIN_REDUCTION)
156
57.5k
        {
157
57.5k
            uint32_t length = symbol >> absGoRice;
158
57.5k
            rate = (length + 1 + absGoRice) << 15;
159
57.5k
        }
160
114k
        else
161
114k
        {
162
114k
            uint32_t length = 0;
163
114k
            symbol = (symbol >> absGoRice) - COEF_REMAIN_BIN_REDUCTION;
164
114k
            if (symbol)
165
105k
            {
166
105k
                unsigned long idx;
167
105k
                BSR(idx, symbol + 1);
168
105k
                length = idx;
169
105k
            }
170
171
114k
            rate = (COEF_REMAIN_BIN_REDUCTION + length + absGoRice + 1 + length) << 15;
172
114k
        }
173
172k
        rate += c1c2Rate;
174
172k
        return rate;
175
172k
    }
176
186k
}
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
23.6k
{
184
23.6k
    m_resiDctCoeff = NULL;
185
23.6k
    m_fencDctCoeff = NULL;
186
23.6k
    m_fencShortBuf = NULL;
187
23.6k
    m_frameNr      = NULL;
188
23.6k
    m_nr           = NULL;
189
23.6k
}
190
191
bool Quant::init(double psyScale, const ScalingList& scalingList, Entropy& entropy)
192
23.6k
{
193
23.6k
    m_entropyCoder = &entropy;
194
23.6k
    m_psyRdoqScale = (int32_t)(psyScale * 256.0);
195
23.6k
    X265_CHECK((psyScale * 256.0) < (double)MAX_INT, "psyScale value too large\n");
196
23.6k
    m_scalingList  = &scalingList;
197
23.6k
    m_resiDctCoeff = X265_MALLOC(int16_t, MAX_TR_SIZE * MAX_TR_SIZE * 2);
198
23.6k
    m_fencDctCoeff = m_resiDctCoeff + (MAX_TR_SIZE * MAX_TR_SIZE);
199
23.6k
    m_fencShortBuf = X265_MALLOC(int16_t, MAX_TR_SIZE * MAX_TR_SIZE);
200
201
23.6k
    return m_resiDctCoeff && m_fencShortBuf;
202
23.6k
}
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
23.6k
{
216
23.6k
    X265_FREE(m_frameNr);
217
23.6k
    X265_FREE(m_resiDctCoeff);
218
23.6k
    X265_FREE(m_fencShortBuf);
219
23.6k
}
220
221
void Quant::setQPforQuant(const CUData& ctu, int qp)
222
30.7k
{
223
30.7k
    m_nr = m_frameNr ? &m_frameNr[ctu.m_encData->m_frameEncoderID] : NULL;
224
30.7k
    m_qpParam[TEXT_LUMA].setQpParam(qp + QP_BD_OFFSET);
225
30.7k
    m_rdoqLevel = ctu.m_encData->m_param->rdoqLevel;
226
30.7k
    if (ctu.m_chromaFormat != X265_CSP_I400)
227
30.7k
    {
228
30.7k
        setChromaQP(qp + ctu.m_slice->m_pps->chromaQpOffset[0] + ctu.m_slice->m_chromaQpOffset[0], TEXT_CHROMA_U, ctu.m_chromaFormat);
229
30.7k
        setChromaQP(qp + ctu.m_slice->m_pps->chromaQpOffset[1] + ctu.m_slice->m_chromaQpOffset[1], TEXT_CHROMA_V, ctu.m_chromaFormat);
230
30.7k
    }
231
30.7k
}
232
233
void Quant::setChromaQP(int qpin, TextType ttype, int chFmt)
234
61.4k
{
235
61.4k
    int qp = x265_clip3(-QP_BD_OFFSET, 57, qpin);
236
61.4k
    if (qp >= 30)
237
14.7k
    {
238
14.7k
        if (chFmt == X265_CSP_I420)
239
14.7k
            qp = g_chromaScale[qp];
240
0
        else
241
0
            qp = X265_MIN(qp, QP_MAX_SPEC);
242
14.7k
    }
243
61.4k
    m_qpParam[ttype].setQpParam(qp + QP_BD_OFFSET);
244
61.4k
}
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
13.4M
{
400
13.4M
    const uint32_t sizeIdx = log2TrSize - 2;
401
402
13.4M
    if (cu.m_tqBypass[0])
403
3.52M
    {
404
3.52M
        X265_CHECK(log2TrSize >= 2 && log2TrSize <= 5, "Block size mistake!\n");
405
3.52M
        return primitives.cu[sizeIdx].copy_cnt(coeff, residual, resiStride);
406
3.52M
    }
407
408
9.92M
    bool isLuma  = ttype == TEXT_LUMA;
409
9.92M
    bool usePsy  = m_psyRdoqScale && isLuma && !useTransformSkip;
410
9.92M
    int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; // Represents scaling through forward transform
411
412
9.92M
    X265_CHECK((cu.m_slice->m_sps->quadtreeTULog2MaxSize >= log2TrSize), "transform size too large\n");
413
9.92M
    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
9.92M
    else
426
9.92M
    {
427
9.92M
        bool isIntra = cu.isIntra(absPartIdx);
428
429
9.92M
        if (!sizeIdx && isLuma && isIntra)
430
3.08M
            primitives.dst4x4(residual, m_resiDctCoeff, resiStride);
431
6.83M
        else
432
6.83M
            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
9.92M
        if (usePsy)
437
4.05M
        {
438
4.05M
            int trSize = 1 << log2TrSize;
439
            /* perform DCT on source pixels for psy-rdoq */
440
4.05M
            primitives.cu[sizeIdx].copy_ps(m_fencShortBuf, trSize, fenc, fencStride);
441
4.05M
            primitives.cu[sizeIdx].dct(m_fencShortBuf, m_fencDctCoeff, trSize);
442
4.05M
        }
443
444
9.92M
        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
9.92M
    }
453
454
9.92M
    if (m_rdoqLevel)
455
9.92M
        return (this->*rdoQuant_func[log2TrSize - 2])(cu, coeff, ttype, absPartIdx, usePsy);
456
354
    else
457
354
    {
458
354
        int deltaU[32 * 32];
459
460
354
        int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
461
354
        int rem = m_qpParam[ttype].rem;
462
354
        int per = m_qpParam[ttype].per;
463
354
        const int32_t* quantCoeff = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
464
465
354
        int qbits = QUANT_SHIFT + per + transformShift;
466
354
        int add = (cu.m_slice->m_sliceType == I_SLICE ? 171 : 85) << (qbits - 9);
467
354
        int numCoeff = 1 << (log2TrSize * 2);
468
469
354
        uint32_t numSig = primitives.quant(m_resiDctCoeff, quantCoeff, deltaU, coeff, qbits, add, numCoeff);
470
471
354
        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
354
        else
478
354
            return numSig;
479
354
    }
480
9.92M
}
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
55.5k
{
546
55.5k
    const uint32_t sizeIdx = log2TrSize - 2;
547
55.5k
    if (cu.m_tqBypass[0])
548
12.2k
    {
549
12.2k
        primitives.cu[sizeIdx].cpy1Dto2D_shl[resiStride % 64 == 0](residual, coeff, resiStride, 0);
550
12.2k
        return;
551
12.2k
    }
552
    // Values need to pass as input parameter in dequant
553
43.2k
    int rem = m_qpParam[ttype].rem;
554
43.2k
    int per = m_qpParam[ttype].per;
555
43.2k
    int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize;
556
43.2k
    int shift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift;
557
43.2k
    int numCoeff = 1 << (log2TrSize * 2);
558
559
43.2k
    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
43.2k
    else
566
43.2k
    {
567
43.2k
        int scale = m_scalingList->s_invQuantScales[rem] << per;
568
43.2k
        primitives.dequant_normal(coeff, m_resiDctCoeff, numCoeff, scale, shift);
569
43.2k
    }
570
571
43.2k
    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
43.2k
    else
584
43.2k
    {
585
43.2k
        int useDST = !sizeIdx && ttype == TEXT_LUMA && bIntra;
586
43.2k
        X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(coeff), "numSig differ\n");
587
        // DC only
588
43.2k
        if (numSig == 1 && coeff[0] != 0 && !useDST)
589
36.7k
        {
590
36.7k
            const int shift_1st = 7 - 6;
591
36.7k
            const int add_1st = 1 << (shift_1st - 1);
592
36.7k
            const int shift_2nd = 12 - (X265_DEPTH - 8) - 3;
593
36.7k
            const int add_2nd = 1 << (shift_2nd - 1);
594
595
36.7k
            int dc_val = (((m_resiDctCoeff[0] * (64 >> 6) + add_1st) >> shift_1st) * (64 >> 3) + add_2nd) >> shift_2nd;
596
36.7k
            primitives.cu[sizeIdx].blockfill_s[resiStride % 64 == 0](residual, resiStride, (int16_t)dc_val);
597
36.7k
            return;
598
36.7k
        }
599
600
6.55k
        if (useDST)
601
6.55k
            primitives.idst4x4(m_resiDctCoeff, residual, resiStride);
602
0
        else
603
0
            primitives.cu[sizeIdx].idct(m_resiDctCoeff, residual, resiStride);
604
6.55k
    }
605
43.2k
}
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
9.92M
{
612
9.92M
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
9.92M
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
9.92M
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
9.92M
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
9.92M
    int rem = m_qpParam[ttype].rem;
619
9.92M
    int per = m_qpParam[ttype].per;
620
9.92M
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
9.92M
    int add = (1 << (qbits - 1));
622
9.92M
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
9.92M
    const int numCoeff = 1 << (log2TrSize * 2);
625
9.92M
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
9.92M
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
9.92M
    if (!numSig)
628
9.86M
        return 0;
629
59.1k
    const uint32_t trSize = 1 << log2TrSize;
630
59.1k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
59.1k
    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
59.1k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
59.1k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
59.1k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
59.1k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
59.1k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
558k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
220k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
458k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
59.1k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
59.1k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
59.1k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
59.1k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
59.1k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
59.1k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
59.1k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
59.1k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
59.1k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
59.1k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
59.1k
    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
59.1k
    int64_t totalRdCost = 0;
666
667
59.1k
    TUEntropyCodingParameters codeParams;
668
59.1k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
59.1k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
59.1k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
59.1k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
59.1k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
59.1k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
59.1k
    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
59.1k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
59.1k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
59.1k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
59.1k
    uint32_t scanPos = 0;
691
59.1k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
59.1k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
59.1k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
59.1k
    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
59.1k
    if (usePsyMask)
704
22.3k
    {
705
326k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
304k
        {
707
304k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
304k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
304k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
304k
#if X265_ARCH_X86
711
304k
            bool enable512 = detect512();
712
304k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
304k
            else
715
304k
            {
716
304k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
304k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
304k
            }
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
304k
        }
724
22.3k
    }
725
36.8k
    else
726
36.8k
    {
727
        // non-psy path
728
169k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
132k
        {
730
132k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
132k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
132k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
132k
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
132k
        }
735
36.8k
    }
736
59.1k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
59.1k
    {
738
        // patternSigCtx = 0
739
59.1k
        {
740
59.1k
            2, 1, 1, 0,
741
59.1k
            1, 1, 0, 0,
742
59.1k
            1, 0, 0, 0,
743
59.1k
            0, 0, 0, 0,
744
59.1k
        },
745
        // patternSigCtx = 1
746
59.1k
        {
747
59.1k
            2, 2, 2, 2,
748
59.1k
            1, 1, 1, 1,
749
59.1k
            0, 0, 0, 0,
750
59.1k
            0, 0, 0, 0,
751
59.1k
        },
752
        // patternSigCtx = 2
753
59.1k
        {
754
59.1k
            2, 1, 0, 0,
755
59.1k
            2, 1, 0, 0,
756
59.1k
            2, 1, 0, 0,
757
59.1k
            2, 1, 0, 0,
758
59.1k
        },
759
        // patternSigCtx = 3
760
59.1k
        {
761
59.1k
            2, 2, 2, 2,
762
59.1k
            2, 2, 2, 2,
763
59.1k
            2, 2, 2, 2,
764
59.1k
            2, 2, 2, 2,
765
59.1k
        },
766
        // 4x4
767
59.1k
        {
768
59.1k
            0, 1, 4, 5,
769
59.1k
            2, 3, 4, 5,
770
59.1k
            6, 6, 8, 8,
771
59.1k
            7, 7, 8, 8
772
59.1k
        }
773
59.1k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
118k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
59.4k
    {
778
59.4k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
59.4k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
59.4k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
59.4k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
59.4k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
59.4k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
59.4k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
59.4k
        if (c1 == 0)
787
0
            ctxSet++;
788
59.4k
        c1 = 1;
789
790
59.4k
        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
59.4k
        coeffGroupRDStats cgRdStats;
859
59.4k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
59.4k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
59.4k
        int    c2            = 0;
863
59.4k
        uint32_t goRiceParam = 0;
864
59.4k
        uint32_t levelThreshold = 3;
865
59.4k
        uint32_t c1Idx       = 0;
866
59.4k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
1.00M
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
950k
        {
870
950k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
950k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
950k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
950k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
950k
            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
950k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
950k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
950k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
335k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
950k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
950k
            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
950k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
950k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
950k
            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
950k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
950k
            if (scanPos > (uint32_t)lastScanPos)
900
820k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
820k
                costCoeff[scanPos] = 0;
903
820k
                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
820k
                totalRdCost += costUncoded[blkPos];
909
820k
            }
910
129k
            else if (!(subFlagMask & 1))
911
2.11k
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
2.11k
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
2.11k
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
2.11k
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
2.11k
                totalRdCost += costCoeff[scanPos];
918
2.11k
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
2.11k
                subFlagMask >>= 1;
921
2.11k
            }
922
127k
            else
923
127k
            {
924
127k
                subFlagMask >>= 1;
925
926
127k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
127k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
127k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
127k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
127k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
127k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
127k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
127k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
127k
                uint32_t level = 0;
939
127k
                uint32_t sigCoefBits = 0;
940
127k
                costCoeff[scanPos] = MAX_INT64;
941
942
127k
                if ((int)scanPos == lastScanPos)
943
59.3k
                    sigRateDelta[blkPos] = 0;
944
68.1k
                else
945
68.1k
                {
946
68.1k
                    if (maxAbsLevel < 3)
947
17.6k
                    {
948
                        /* set default costs to uncoded costs */
949
17.6k
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
17.6k
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
17.6k
                    }
952
68.1k
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
68.1k
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
68.1k
                }
955
956
127k
                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
127k
                if (maxAbsLevel == 1)
959
34.1k
                {
960
34.1k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
34.1k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
34.1k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
34.1k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
34.1k
                    int d = abs(signCoef) - unquantAbsLevel;
966
34.1k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
34.1k
                    if (usePsyMask & scanPos)
970
13.6k
                    {
971
13.6k
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
13.6k
                        curCost -= PSYVALUE(reconCoef);
973
13.6k
                    }
974
975
34.1k
                    if (curCost < costCoeff[scanPos])
976
33.2k
                    {
977
33.2k
                        level = 1;
978
33.2k
                        costCoeff[scanPos] = curCost;
979
33.2k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
33.2k
                    }
981
34.1k
                }
982
93.3k
                else if (maxAbsLevel)
983
93.3k
                {
984
93.3k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
93.3k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
93.3k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
93.3k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
93.3k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
93.3k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
93.3k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
93.3k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
93.3k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
93.3k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
93.3k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
93.3k
                    if (usePsyMask & scanPos)
1001
54.6k
                    {
1002
54.6k
                        int reconCoef;
1003
54.6k
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
54.6k
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
54.6k
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
54.6k
                        curCost1 -= PSYVALUE(reconCoef);
1008
54.6k
                    }
1009
93.3k
                    if (curCost0 < costCoeff[scanPos])
1010
93.3k
                    {
1011
93.3k
                        level = maxAbsLevel;
1012
93.3k
                        costCoeff[scanPos] = curCost0;
1013
93.3k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
93.3k
                    }
1015
93.3k
                    if (curCost1 < costCoeff[scanPos])
1016
1.97k
                    {
1017
1.97k
                        level = maxAbsLevel - 1;
1018
1.97k
                        costCoeff[scanPos] = curCost1;
1019
1.97k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
1.97k
                    }
1021
93.3k
                }
1022
1023
127k
                dstCoeff[blkPos] = (int16_t)level;
1024
127k
                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
126k
                {
1029
126k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
126k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
126k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
126k
                    int rate0, rate1, rate2;
1033
1034
126k
                    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
94.4k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
36.7k
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
36.7k
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
36.7k
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
36.7k
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
36.7k
                    }
1058
57.6k
                    else
1059
57.6k
                    {
1060
57.6k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
57.6k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
57.6k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
57.6k
                    }
1064
126k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
126k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
126k
                }
1067
957
                else
1068
957
                {
1069
957
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
957
                    rateIncDown[blkPos] = 0;
1071
957
                }
1072
1073
                /* Update CABAC estimation state */
1074
127k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
51.5k
                {
1076
51.5k
                    goRiceParam++;
1077
51.5k
                    levelThreshold <<= 1;
1078
51.5k
                }
1079
1080
127k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
127k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
127k
                if (level > 1)
1085
92.2k
                {
1086
92.2k
                    c1 = 0;
1087
92.2k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
92.2k
                    c2Idx++;
1089
92.2k
                }
1090
35.3k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
28.1k
                    c1++;
1092
1093
127k
                if (dstCoeff[blkPos])
1094
126k
                {
1095
126k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
126k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
126k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
126k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
126k
                }
1100
127k
            }
1101
1102
950k
            cgRdStats.sigCost += costSig[scanPos];
1103
950k
        } /* end for (scanPosinCG) */
1104
1105
59.4k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
59.4k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
59.4k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
59.4k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
59.4k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
59.4k
        {
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
59.4k
        }
1118
2
        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
2
        else
1156
2
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
2
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
2
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
2
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
2
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
2
        }
1163
59.4k
    } /* end for (cgScanPos) */
1164
1165
59.1k
    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
59.1k
    int64_t bestCost;
1169
59.1k
    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
59.1k
    else
1175
59.1k
    {
1176
59.1k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
59.1k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
59.1k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
59.1k
    }
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
59.1k
    int  bestLastIdx = 0;
1187
59.1k
    bool foundLast = false;
1188
118k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
59.3k
    {
1190
59.3k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
59.3k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
59.3k
        }
1195
18.4E
        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
18.4E
        else
1202
18.4E
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
18.4E
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
18.4E
            continue;
1206
18.4E
        }
1207
1208
914k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
893k
        {
1210
893k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
893k
            if ((int)scanPos > lastScanPos)
1212
820k
                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
72.8k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
72.8k
            if (dstCoeff[blkPos])
1219
70.8k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
70.8k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
70.8k
                if (codeParams.scanType == SCAN_VER)
1223
4.80k
                    std::swap(pos[0], pos[1]);
1224
70.8k
                uint32_t bitsLastNZ = 0;
1225
1226
212k
                for (int i = 0; i < 2; i++)
1227
141k
                {
1228
141k
                    int temp = g_lastCoeffTable[pos[i]];
1229
141k
                    int prefixOnes = temp & 15;
1230
141k
                    int suffixLen = temp >> 4;
1231
1232
141k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
141k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
141k
                }
1235
1236
70.8k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
70.8k
                if (costAsLast < bestCost)
1239
44.9k
                {
1240
44.9k
                    bestLastIdx = scanPos + 1;
1241
44.9k
                    bestCost = costAsLast;
1242
44.9k
                }
1243
70.8k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
38.7k
                {
1245
38.7k
                    foundLast = true;
1246
38.7k
                    break;
1247
38.7k
                }
1248
1249
32.1k
                totalRdCost -= costCoeff[scanPos];
1250
32.1k
                totalRdCost += costUncoded[blkPos];
1251
32.1k
            }
1252
1.99k
            else
1253
1.99k
                totalRdCost -= costSig[scanPos];
1254
72.8k
        }
1255
59.3k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
59.1k
    numSig = 0;
1259
169k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
110k
    {
1261
110k
        int blkPos = codeParams.scan[pos];
1262
110k
        int level  = dstCoeff[blkPos];
1263
110k
        numSig += (level != 0);
1264
1265
110k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
110k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
110k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
59.1k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
898k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
839k
    {
1274
839k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
839k
    }
1276
59.1k
    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
59.3k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
5.46k
    {
1288
5.46k
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
5.46k
        int lastCG = 1;
1290
1291
10.9k
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
5.46k
        {
1293
5.46k
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
5.46k
            int n;
1295
1296
5.46k
            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
5.46k
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
5.46k
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
5.46k
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
5.46k
            const uint32_t absSumSign = posFirstLast;
1305
1306
5.46k
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
5.37k
            {
1308
5.37k
                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
5.37k
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
2.61k
                {
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.61k
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
2.61k
                    uint32_t minPos = 0;
1326
2.61k
                    int8_t finalChange = 0;
1327
2.61k
                    int curChange = 0;
1328
2.61k
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
36.4k
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
33.8k
                    {
1332
33.8k
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
33.8k
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
33.8k
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
33.8k
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
33.8k
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
33.8k
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
33.8k
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
33.8k
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
66.4k
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
33.8k
                        const uint32_t isOne = (absLevel == 1);
1347
33.8k
                        if (dstCoeff[blkPos])
1348
32.5k
                        {
1349
32.5k
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
32.5k
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
32.5k
                            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
32.5k
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
32.5k
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
32.5k
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
32.5k
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
32.5k
                            costDown -= lastCoeffAdjust;
1361
32.5k
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
32.5k
                            curChange = 2 * (costUp < costDown) - 1;
1364
32.5k
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
32.5k
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
1.29k
                        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.29k
                        else
1375
1.29k
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
1.29k
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
1.29k
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
1.29k
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
1.29k
                            curChange = 1;
1381
1.29k
                        }
1382
1383
33.8k
                        if (curCost < minCostInc)
1384
9.30k
                        {
1385
9.30k
                            minCostInc = curCost;
1386
9.30k
                            finalChange = (int8_t)curChange;
1387
9.30k
                            minPos = blkPos + (absLevel << 16);
1388
9.30k
                        }
1389
33.8k
                        lastCoeffAdjust = 0;
1390
33.8k
                    }
1391
1392
2.61k
                    const int absInMinPos = (minPos >> 16);
1393
2.61k
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
2.61k
                    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.61k
                    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.61k
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
2.61k
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
2.61k
                }
1416
5.37k
            }
1417
1418
5.46k
            lastCG = 0;
1419
5.46k
        }
1420
5.46k
    }
1421
1422
59.1k
    return numSig;
1423
9.92M
}
unsigned int x265::Quant::rdoQuant<2u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
8.21M
{
612
8.21M
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
8.21M
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
8.21M
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
8.21M
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
8.21M
    int rem = m_qpParam[ttype].rem;
619
8.21M
    int per = m_qpParam[ttype].per;
620
8.21M
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
8.21M
    int add = (1 << (qbits - 1));
622
8.21M
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
8.21M
    const int numCoeff = 1 << (log2TrSize * 2);
625
8.21M
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
8.21M
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
8.21M
    if (!numSig)
628
8.19M
        return 0;
629
18.5k
    const uint32_t trSize = 1 << log2TrSize;
630
18.5k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
18.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
18.5k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
18.5k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
18.5k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
18.5k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
18.5k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
18.5k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
18.5k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
18.5k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
18.5k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
18.5k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
18.5k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
18.5k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
18.5k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
18.5k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
18.5k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
18.5k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
18.5k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
18.5k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
18.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
18.5k
    int64_t totalRdCost = 0;
666
667
18.5k
    TUEntropyCodingParameters codeParams;
668
18.5k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
18.5k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
18.5k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
18.5k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
18.5k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
18.5k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
18.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
18.5k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
18.5k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
18.5k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
18.5k
    uint32_t scanPos = 0;
691
18.5k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
18.5k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
18.5k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
18.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
18.5k
    if (usePsyMask)
704
6.78k
    {
705
6.78k
        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.78k
    }
725
11.7k
    else
726
11.7k
    {
727
        // non-psy path
728
11.7k
        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
11.7k
    }
736
18.5k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
18.5k
    {
738
        // patternSigCtx = 0
739
18.5k
        {
740
18.5k
            2, 1, 1, 0,
741
18.5k
            1, 1, 0, 0,
742
18.5k
            1, 0, 0, 0,
743
18.5k
            0, 0, 0, 0,
744
18.5k
        },
745
        // patternSigCtx = 1
746
18.5k
        {
747
18.5k
            2, 2, 2, 2,
748
18.5k
            1, 1, 1, 1,
749
18.5k
            0, 0, 0, 0,
750
18.5k
            0, 0, 0, 0,
751
18.5k
        },
752
        // patternSigCtx = 2
753
18.5k
        {
754
18.5k
            2, 1, 0, 0,
755
18.5k
            2, 1, 0, 0,
756
18.5k
            2, 1, 0, 0,
757
18.5k
            2, 1, 0, 0,
758
18.5k
        },
759
        // patternSigCtx = 3
760
18.5k
        {
761
18.5k
            2, 2, 2, 2,
762
18.5k
            2, 2, 2, 2,
763
18.5k
            2, 2, 2, 2,
764
18.5k
            2, 2, 2, 2,
765
18.5k
        },
766
        // 4x4
767
18.5k
        {
768
18.5k
            0, 1, 4, 5,
769
18.5k
            2, 3, 4, 5,
770
18.5k
            6, 6, 8, 8,
771
18.5k
            7, 7, 8, 8
772
18.5k
        }
773
18.5k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
37.1k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
18.6k
    {
778
18.6k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
18.6k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
18.6k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
18.6k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
18.6k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
18.6k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
18.6k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
18.6k
        if (c1 == 0)
787
0
            ctxSet++;
788
18.6k
        c1 = 1;
789
790
18.6k
        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
18.6k
        coeffGroupRDStats cgRdStats;
859
18.6k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
18.6k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
18.6k
        int    c2            = 0;
863
18.6k
        uint32_t goRiceParam = 0;
864
18.6k
        uint32_t levelThreshold = 3;
865
18.6k
        uint32_t c1Idx       = 0;
866
18.6k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
316k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
298k
        {
870
298k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
298k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
298k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
298k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
298k
            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
298k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
298k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
298k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
101k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
298k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
298k
            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
298k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
298k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
298k
            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
298k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
298k
            if (scanPos > (uint32_t)lastScanPos)
900
209k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
209k
                costCoeff[scanPos] = 0;
903
209k
                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
209k
                totalRdCost += costUncoded[blkPos];
909
209k
            }
910
88.9k
            else if (!(subFlagMask & 1))
911
2.11k
            {
912
                // fast zero coeff path
913
                /* set default costs to uncoded costs */
914
2.11k
                costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
915
2.11k
                costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
916
2.11k
                sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
917
2.11k
                totalRdCost += costCoeff[scanPos];
918
2.11k
                rateIncUp[blkPos] = greaterOneBits[0];
919
920
2.11k
                subFlagMask >>= 1;
921
2.11k
            }
922
86.8k
            else
923
86.8k
            {
924
86.8k
                subFlagMask >>= 1;
925
926
86.8k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
86.8k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
86.8k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
86.8k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
86.8k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
86.8k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
86.8k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
86.8k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
86.8k
                uint32_t level = 0;
939
86.8k
                uint32_t sigCoefBits = 0;
940
86.8k
                costCoeff[scanPos] = MAX_INT64;
941
942
86.8k
                if ((int)scanPos == lastScanPos)
943
18.6k
                    sigRateDelta[blkPos] = 0;
944
68.1k
                else
945
68.1k
                {
946
68.1k
                    if (maxAbsLevel < 3)
947
17.6k
                    {
948
                        /* set default costs to uncoded costs */
949
17.6k
                        costSig[scanPos] = SIGCOST(estBitsSbac.significantBits[0][ctxSig]);
950
17.6k
                        costCoeff[scanPos] = costUncoded[blkPos] + costSig[scanPos];
951
17.6k
                    }
952
68.1k
                    sigRateDelta[blkPos] = estBitsSbac.significantBits[1][ctxSig] - estBitsSbac.significantBits[0][ctxSig];
953
68.1k
                    sigCoefBits = estBitsSbac.significantBits[1][ctxSig];
954
68.1k
                }
955
956
86.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
86.8k
                if (maxAbsLevel == 1)
959
15.6k
                {
960
15.6k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
15.6k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
15.6k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
15.6k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
15.6k
                    int d = abs(signCoef) - unquantAbsLevel;
966
15.6k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
15.6k
                    if (usePsyMask & scanPos)
970
13.6k
                    {
971
13.6k
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
13.6k
                        curCost -= PSYVALUE(reconCoef);
973
13.6k
                    }
974
975
15.6k
                    if (curCost < costCoeff[scanPos])
976
14.6k
                    {
977
14.6k
                        level = 1;
978
14.6k
                        costCoeff[scanPos] = curCost;
979
14.6k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
14.6k
                    }
981
15.6k
                }
982
71.1k
                else if (maxAbsLevel)
983
71.1k
                {
984
71.1k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
71.1k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
71.1k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
71.1k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
71.1k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
71.1k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
71.1k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
71.1k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
71.1k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
71.1k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
71.1k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
71.1k
                    if (usePsyMask & scanPos)
1001
54.6k
                    {
1002
54.6k
                        int reconCoef;
1003
54.6k
                        reconCoef = abs(unquantAbsLevel0 + SIGN(predictedCoef, signCoef));
1004
54.6k
                        curCost0 -= PSYVALUE(reconCoef);
1005
1006
54.6k
                        reconCoef = abs(unquantAbsLevel1 + SIGN(predictedCoef, signCoef));
1007
54.6k
                        curCost1 -= PSYVALUE(reconCoef);
1008
54.6k
                    }
1009
71.1k
                    if (curCost0 < costCoeff[scanPos])
1010
71.1k
                    {
1011
71.1k
                        level = maxAbsLevel;
1012
71.1k
                        costCoeff[scanPos] = curCost0;
1013
71.1k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
71.1k
                    }
1015
71.1k
                    if (curCost1 < costCoeff[scanPos])
1016
1.89k
                    {
1017
1.89k
                        level = maxAbsLevel - 1;
1018
1.89k
                        costCoeff[scanPos] = curCost1;
1019
1.89k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
1.89k
                    }
1021
71.1k
                }
1022
1023
86.8k
                dstCoeff[blkPos] = (int16_t)level;
1024
86.8k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
86.8k
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
85.8k
                {
1029
85.8k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
85.8k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
85.8k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
85.8k
                    int rate0, rate1, rate2;
1033
1034
85.8k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
13.6k
                    {
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
13.6k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
13.6k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
13.6k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
13.6k
                        rate0 = 0;
1044
13.6k
                        rate2 = rateEqual2;
1045
13.6k
                        rate1 = rateNotEqual2;
1046
1047
13.6k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
13.6k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
13.6k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
13.6k
                    }
1051
72.2k
                    else if (diff0 >= 0 && diff2 <= maxVlc)     // prob except from above path (98.6, 97.9, 96.9)%
1052
36.7k
                    {
1053
                        // NOTE: no c1c2 correct rate since all of rate include this factor
1054
36.7k
                        rate1 = getICRateLessVlc(level + 0, diff0 + 1, goRiceParam);
1055
36.7k
                        rate2 = getICRateLessVlc(level + 1, diff0 + 2, goRiceParam);
1056
36.7k
                        rate0 = getICRateLessVlc(level - 1, diff0 + 0, goRiceParam);
1057
36.7k
                    }
1058
35.4k
                    else
1059
35.4k
                    {
1060
35.4k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
35.4k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
35.4k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
35.4k
                    }
1064
85.8k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
85.8k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
85.8k
                }
1067
985
                else
1068
985
                {
1069
985
                    rateIncUp[blkPos] = greaterOneBits[0];
1070
985
                    rateIncDown[blkPos] = 0;
1071
985
                }
1072
1073
                /* Update CABAC estimation state */
1074
86.8k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
29.2k
                {
1076
29.2k
                    goRiceParam++;
1077
29.2k
                    levelThreshold <<= 1;
1078
29.2k
                }
1079
1080
86.8k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
86.8k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
86.8k
                if (level > 1)
1085
70.0k
                {
1086
70.0k
                    c1 = 0;
1087
70.0k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
70.0k
                    c2Idx++;
1089
70.0k
                }
1090
16.7k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
9.56k
                    c1++;
1092
1093
86.8k
                if (dstCoeff[blkPos])
1094
85.8k
                {
1095
85.8k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
85.8k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
85.8k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
85.8k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
85.8k
                }
1100
86.8k
            }
1101
1102
298k
            cgRdStats.sigCost += costSig[scanPos];
1103
298k
        } /* end for (scanPosinCG) */
1104
1105
18.6k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
18.6k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
18.6k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
18.6k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
18.6k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
18.6k
        {
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
18.6k
        }
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
18.6k
    } /* end for (cgScanPos) */
1164
1165
18.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
18.5k
    int64_t bestCost;
1169
18.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
18.5k
    else
1175
18.5k
    {
1176
18.5k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
18.5k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
18.5k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
18.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
18.5k
    int  bestLastIdx = 0;
1187
18.5k
    bool foundLast = false;
1188
37.1k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
18.6k
    {
1190
18.6k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
18.6k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
18.6k
        }
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
243k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
241k
        {
1210
241k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
241k
            if ((int)scanPos > lastScanPos)
1212
209k
                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
32.1k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
32.1k
            if (dstCoeff[blkPos])
1219
30.1k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
30.1k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
30.1k
                if (codeParams.scanType == SCAN_VER)
1223
4.38k
                    std::swap(pos[0], pos[1]);
1224
30.1k
                uint32_t bitsLastNZ = 0;
1225
1226
90.3k
                for (int i = 0; i < 2; i++)
1227
60.2k
                {
1228
60.2k
                    int temp = g_lastCoeffTable[pos[i]];
1229
60.2k
                    int prefixOnes = temp & 15;
1230
60.2k
                    int suffixLen = temp >> 4;
1231
1232
60.2k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
60.2k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
60.2k
                }
1235
1236
30.1k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
30.1k
                if (costAsLast < bestCost)
1239
19.4k
                {
1240
19.4k
                    bestLastIdx = scanPos + 1;
1241
19.4k
                    bestCost = costAsLast;
1242
19.4k
                }
1243
30.1k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
16.5k
                {
1245
16.5k
                    foundLast = true;
1246
16.5k
                    break;
1247
16.5k
                }
1248
1249
13.6k
                totalRdCost -= costCoeff[scanPos];
1250
13.6k
                totalRdCost += costUncoded[blkPos];
1251
13.6k
            }
1252
1.99k
            else
1253
1.99k
                totalRdCost -= costSig[scanPos];
1254
32.1k
        }
1255
18.6k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
18.5k
    numSig = 0;
1259
103k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
85.2k
    {
1261
85.2k
        int blkPos = codeParams.scan[pos];
1262
85.2k
        int level  = dstCoeff[blkPos];
1263
85.2k
        numSig += (level != 0);
1264
1265
85.2k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
85.2k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
85.2k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
18.5k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
231k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
212k
    {
1274
212k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
212k
    }
1276
18.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
18.6k
    if (cu.m_slice->m_pps->bSignHideEnabled && numSig >= 2)
1287
5.46k
    {
1288
5.46k
        const int realLastScanPos = (bestLastIdx - 1) >> LOG2_SCAN_SET_SIZE;
1289
5.46k
        int lastCG = 1;
1290
1291
10.9k
        for (int subSet = realLastScanPos; subSet >= 0; subSet--)
1292
5.46k
        {
1293
5.46k
            int subPos = subSet << LOG2_SCAN_SET_SIZE;
1294
5.46k
            int n;
1295
1296
5.46k
            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
5.46k
            const uint32_t posFirstLast = primitives.findPosFirstLast(&dstCoeff[codeParams.scan[subPos]], trSize, g_scan4x4[codeParams.scanType]);
1302
5.46k
            const int firstNZPosInCG = (uint8_t)posFirstLast;
1303
5.46k
            const int lastNZPosInCG = (int8_t)(posFirstLast >> 8);
1304
5.46k
            const uint32_t absSumSign = posFirstLast;
1305
1306
5.46k
            if (lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD)
1307
5.37k
            {
1308
5.37k
                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
5.37k
                if (((int32_t)(signbit ^ absSumSign)) < 0)
1319
2.61k
                {
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.61k
                    int64_t minCostInc = MAX_INT64, curCost = MAX_INT64;
1325
2.61k
                    uint32_t minPos = 0;
1326
2.61k
                    int8_t finalChange = 0;
1327
2.61k
                    int curChange = 0;
1328
2.61k
                    uint32_t lastCoeffAdjust = (lastCG & (abs(dstCoeff[codeParams.scan[lastNZPosInCG + subPos]]) == 1)) * 4 * IEP_RATE;
1329
1330
36.4k
                    for (n = (lastCG ? lastNZPosInCG : SCAN_SET_SIZE - 1); n >= 0; --n)
1331
33.8k
                    {
1332
33.8k
                        const uint32_t blkPos = codeParams.scan[n + subPos];
1333
33.8k
                        const int32_t signCoef = m_resiDctCoeff[blkPos]; /* pre-quantization DCT coeff */
1334
33.8k
                        const int absLevel = abs(dstCoeff[blkPos]);
1335
                        // TODO: this is constant in non-scaling mode
1336
33.8k
                        const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
1337
33.8k
                        const uint32_t unQuantLevel = (absLevel * (unquantScale[blkPos] << per) + unquantRound);
1338
1339
33.8k
                        int d = abs(signCoef) - (unQuantLevel >> unquantShift);
1340
33.8k
                        X265_CHECK((uint32_t)UNQUANT(absLevel) == (unQuantLevel >> unquantShift), "dquant check failed\n");
1341
1342
33.8k
                        const int64_t origDist = (((int64_t)d * d));
1343
1344
33.8k
#define DELTARDCOST(d0, d, deltabits) ((((int64_t)d * d - d0) << scaleBits) + ((lambda2 * (int64_t)(deltabits)) >> 8))
1345
1346
33.8k
                        const uint32_t isOne = (absLevel == 1);
1347
33.8k
                        if (dstCoeff[blkPos])
1348
32.5k
                        {
1349
32.5k
                            d = abs(signCoef) - ((unQuantLevel + preDQuantLevelDiff) >> unquantShift);
1350
32.5k
                            X265_CHECK((uint32_t)UNQUANT(absLevel + 1) == ((unQuantLevel + preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1351
32.5k
                            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
32.5k
                            d = abs(signCoef) - ((unQuantLevel - preDQuantLevelDiff) >> unquantShift);
1356
32.5k
                            X265_CHECK((uint32_t)UNQUANT(absLevel - 1) == ((unQuantLevel - preDQuantLevelDiff) >> unquantShift), "dquant check failed\n");
1357
32.5k
                            int downBits = rateIncDown[blkPos] - (isOne ? (IEP_RATE + sigRateDelta[blkPos]) : 0);
1358
32.5k
                            int64_t costDown = DELTARDCOST(origDist, d, downBits);
1359
1360
32.5k
                            costDown -= lastCoeffAdjust;
1361
32.5k
                            curCost = ((n == firstNZPosInCG) & isOne) ? MAX_INT64 : costDown;
1362
1363
32.5k
                            curChange = 2 * (costUp < costDown) - 1;
1364
32.5k
                            curCost = (costUp < costDown) ? costUp : curCost;
1365
32.5k
                        }
1366
                        //else if ((n < firstNZPosInCG) & (signbit != ((uint32_t)signCoef >> 31)))
1367
1.29k
                        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.29k
                        else
1375
1.29k
                        {
1376
                            /* evaluate changing an uncoded coeff 0 to a coded coeff +/-1 */
1377
1.29k
                            d = abs(signCoef) - ((preDQuantLevelDiff + unquantRound) >> unquantShift);
1378
1.29k
                            X265_CHECK((uint32_t)UNQUANT(1) == ((preDQuantLevelDiff + unquantRound) >> unquantShift), "dquant check failed\n");
1379
1.29k
                            curCost = DELTARDCOST(origDist, d, rateIncUp[blkPos] + IEP_RATE + sigRateDelta[blkPos]);
1380
1.29k
                            curChange = 1;
1381
1.29k
                        }
1382
1383
33.8k
                        if (curCost < minCostInc)
1384
9.30k
                        {
1385
9.30k
                            minCostInc = curCost;
1386
9.30k
                            finalChange = (int8_t)curChange;
1387
9.30k
                            minPos = blkPos + (absLevel << 16);
1388
9.30k
                        }
1389
33.8k
                        lastCoeffAdjust = 0;
1390
33.8k
                    }
1391
1392
2.61k
                    const int absInMinPos = (minPos >> 16);
1393
2.61k
                    minPos = (uint16_t)minPos;
1394
1395
                    // if (dstCoeff[minPos] == 32767 || dstCoeff[minPos] == -32768)
1396
2.61k
                    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.61k
                    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.61k
                    const int16_t resiCoeffSign = ((int16_t)m_resiDctCoeff[minPos] >> 16);
1414
2.61k
                    dstCoeff[minPos] += (((int16_t)finalChange ^ resiCoeffSign) - resiCoeffSign);
1415
2.61k
                }
1416
5.37k
            }
1417
1418
5.46k
            lastCG = 0;
1419
5.46k
        }
1420
5.46k
    }
1421
1422
18.5k
    return numSig;
1423
8.21M
}
unsigned int x265::Quant::rdoQuant<3u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
1.37M
{
612
1.37M
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
1.37M
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
1.37M
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
1.37M
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
1.37M
    int rem = m_qpParam[ttype].rem;
619
1.37M
    int per = m_qpParam[ttype].per;
620
1.37M
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
1.37M
    int add = (1 << (qbits - 1));
622
1.37M
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
1.37M
    const int numCoeff = 1 << (log2TrSize * 2);
625
1.37M
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
1.37M
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
1.37M
    if (!numSig)
628
1.35M
        return 0;
629
26.1k
    const uint32_t trSize = 1 << log2TrSize;
630
26.1k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
26.1k
    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
26.1k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
26.1k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
26.1k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
26.1k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
26.1k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
26.1k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
26.1k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
26.1k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
26.1k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
26.1k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
26.1k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
26.1k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
26.1k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
26.1k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
26.1k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
26.1k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
26.1k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
26.1k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
26.1k
    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
26.1k
    int64_t totalRdCost = 0;
666
667
26.1k
    TUEntropyCodingParameters codeParams;
668
26.1k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
26.1k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
26.1k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
26.1k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
26.1k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
26.1k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
26.1k
    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
26.1k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
26.1k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
26.1k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
26.1k
    uint32_t scanPos = 0;
691
26.1k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
26.1k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
26.1k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
26.1k
    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
26.1k
    if (usePsyMask)
704
5.83k
    {
705
23.3k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
17.4k
        {
707
17.4k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
17.4k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
17.4k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
17.4k
#if X265_ARCH_X86
711
17.4k
            bool enable512 = detect512();
712
17.4k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
17.4k
            else
715
17.4k
            {
716
17.4k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
17.4k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
17.4k
            }
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
17.4k
        }
724
5.83k
    }
725
20.3k
    else
726
20.3k
    {
727
        // non-psy path
728
81.6k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
61.3k
        {
730
61.3k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
61.3k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
61.3k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
61.3k
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
61.3k
        }
735
20.3k
    }
736
26.1k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
26.1k
    {
738
        // patternSigCtx = 0
739
26.1k
        {
740
26.1k
            2, 1, 1, 0,
741
26.1k
            1, 1, 0, 0,
742
26.1k
            1, 0, 0, 0,
743
26.1k
            0, 0, 0, 0,
744
26.1k
        },
745
        // patternSigCtx = 1
746
26.1k
        {
747
26.1k
            2, 2, 2, 2,
748
26.1k
            1, 1, 1, 1,
749
26.1k
            0, 0, 0, 0,
750
26.1k
            0, 0, 0, 0,
751
26.1k
        },
752
        // patternSigCtx = 2
753
26.1k
        {
754
26.1k
            2, 1, 0, 0,
755
26.1k
            2, 1, 0, 0,
756
26.1k
            2, 1, 0, 0,
757
26.1k
            2, 1, 0, 0,
758
26.1k
        },
759
        // patternSigCtx = 3
760
26.1k
        {
761
26.1k
            2, 2, 2, 2,
762
26.1k
            2, 2, 2, 2,
763
26.1k
            2, 2, 2, 2,
764
26.1k
            2, 2, 2, 2,
765
26.1k
        },
766
        // 4x4
767
26.1k
        {
768
26.1k
            0, 1, 4, 5,
769
26.1k
            2, 3, 4, 5,
770
26.1k
            6, 6, 8, 8,
771
26.1k
            7, 7, 8, 8
772
26.1k
        }
773
26.1k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
52.4k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
26.2k
    {
778
26.2k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
26.2k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
26.2k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
26.2k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
26.2k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
26.2k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
26.2k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
26.2k
        if (c1 == 0)
787
0
            ctxSet++;
788
26.2k
        c1 = 1;
789
790
26.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
26.2k
        coeffGroupRDStats cgRdStats;
859
26.2k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
26.2k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
26.2k
        int    c2            = 0;
863
26.2k
        uint32_t goRiceParam = 0;
864
26.2k
        uint32_t levelThreshold = 3;
865
26.2k
        uint32_t c1Idx       = 0;
866
26.2k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
446k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
420k
        {
870
420k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
420k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
420k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
420k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
420k
            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
420k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
420k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
420k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
87.4k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
420k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
420k
            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
420k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
420k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
420k
            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
420k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
420k
            if (scanPos > (uint32_t)lastScanPos)
900
393k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
393k
                costCoeff[scanPos] = 0;
903
393k
                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
393k
                totalRdCost += costUncoded[blkPos];
909
393k
            }
910
26.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
26.2k
            else
923
26.2k
            {
924
26.2k
                subFlagMask >>= 1;
925
926
26.2k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
26.2k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
26.2k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
26.2k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
26.2k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
26.2k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
26.2k
                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
26.2k
                uint32_t level = 0;
939
26.2k
                uint32_t sigCoefBits = 0;
940
26.2k
                costCoeff[scanPos] = MAX_INT64;
941
942
26.2k
                if ((int)scanPos == lastScanPos)
943
26.2k
                    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
26.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
26.2k
                if (maxAbsLevel == 1)
959
15.8k
                {
960
15.8k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
15.8k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
15.8k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
15.8k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
15.8k
                    int d = abs(signCoef) - unquantAbsLevel;
966
15.8k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
15.8k
                    if (usePsyMask & scanPos)
970
0
                    {
971
0
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
0
                        curCost -= PSYVALUE(reconCoef);
973
0
                    }
974
975
15.8k
                    if (curCost < costCoeff[scanPos])
976
15.8k
                    {
977
15.8k
                        level = 1;
978
15.8k
                        costCoeff[scanPos] = curCost;
979
15.8k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
15.8k
                    }
981
15.8k
                }
982
10.4k
                else if (maxAbsLevel)
983
10.4k
                {
984
10.4k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
10.4k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
10.4k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
10.4k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
10.4k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
10.4k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
10.4k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
10.4k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
10.4k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
10.4k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
10.4k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
10.4k
                    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
10.4k
                    if (curCost0 < costCoeff[scanPos])
1010
10.4k
                    {
1011
10.4k
                        level = maxAbsLevel;
1012
10.4k
                        costCoeff[scanPos] = curCost0;
1013
10.4k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
10.4k
                    }
1015
10.4k
                    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
10.4k
                }
1022
1023
26.2k
                dstCoeff[blkPos] = (int16_t)level;
1024
26.2k
                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
26.2k
                {
1029
26.2k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
26.2k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
26.2k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
26.2k
                    int rate0, rate1, rate2;
1033
1034
26.2k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
15.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
15.8k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
15.8k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
15.8k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
15.8k
                        rate0 = 0;
1044
15.8k
                        rate2 = rateEqual2;
1045
15.8k
                        rate1 = rateNotEqual2;
1046
1047
15.8k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
15.8k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
15.8k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
15.8k
                    }
1051
10.4k
                    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
10.4k
                    else
1059
10.4k
                    {
1060
10.4k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
10.4k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
10.4k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
10.4k
                    }
1064
26.2k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
26.2k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
26.2k
                }
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
26.2k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
10.4k
                {
1076
10.4k
                    goRiceParam++;
1077
10.4k
                    levelThreshold <<= 1;
1078
10.4k
                }
1079
1080
26.2k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
26.2k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
26.2k
                if (level > 1)
1085
10.4k
                {
1086
10.4k
                    c1 = 0;
1087
10.4k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
10.4k
                    c2Idx++;
1089
10.4k
                }
1090
15.8k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
15.8k
                    c1++;
1092
1093
26.2k
                if (dstCoeff[blkPos])
1094
26.2k
                {
1095
26.2k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
26.2k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
26.2k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
26.2k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
26.2k
                }
1100
26.2k
            }
1101
1102
420k
            cgRdStats.sigCost += costSig[scanPos];
1103
420k
        } /* end for (scanPosinCG) */
1104
1105
26.2k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
26.2k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
26.2k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
26.2k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
26.2k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
26.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
26.2k
        }
1118
2
        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
2
        else
1156
2
        {
1157
            /* there were no coded coefficients in this coefficient group */
1158
2
            uint32_t ctxSig = getSigCoeffGroupCtxInc(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
1159
2
            costCoeffGroupSig[cgScanPos] = SIGCOST(estBitsSbac.significantCoeffGroupBits[ctxSig][0]);
1160
2
            totalRdCost += costCoeffGroupSig[cgScanPos];  /* add cost of 0 bit in significant CG bitmap */
1161
2
            totalRdCost -= cgRdStats.sigCost;             /* remove cost of significant coefficient bitmap */
1162
2
        }
1163
26.2k
    } /* end for (cgScanPos) */
1164
1165
26.1k
    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
26.1k
    int64_t bestCost;
1169
26.1k
    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
26.1k
    else
1175
26.1k
    {
1176
26.1k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
26.1k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
26.1k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
26.1k
    }
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
26.1k
    int  bestLastIdx = 0;
1187
26.1k
    bool foundLast = false;
1188
52.4k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
26.2k
    {
1190
26.2k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
26.2k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
26.2k
        }
1195
18.4E
        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
18.4E
        else
1202
18.4E
        {
1203
            /* remove cost of signaling this empty group as not present */
1204
18.4E
            totalRdCost -= costCoeffGroupSig[cgScanPos];
1205
18.4E
            continue;
1206
18.4E
        }
1207
1208
436k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
420k
        {
1210
420k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
420k
            if ((int)scanPos > lastScanPos)
1212
394k
                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
26.2k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
26.2k
            if (dstCoeff[blkPos])
1219
26.2k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
26.2k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
26.2k
                if (codeParams.scanType == SCAN_VER)
1223
418
                    std::swap(pos[0], pos[1]);
1224
26.2k
                uint32_t bitsLastNZ = 0;
1225
1226
78.8k
                for (int i = 0; i < 2; i++)
1227
52.5k
                {
1228
52.5k
                    int temp = g_lastCoeffTable[pos[i]];
1229
52.5k
                    int prefixOnes = temp & 15;
1230
52.5k
                    int suffixLen = temp >> 4;
1231
1232
52.5k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
52.5k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
52.5k
                }
1235
1236
26.2k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
26.2k
                if (costAsLast < bestCost)
1239
11.8k
                {
1240
11.8k
                    bestLastIdx = scanPos + 1;
1241
11.8k
                    bestCost = costAsLast;
1242
11.8k
                }
1243
26.2k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
10.4k
                {
1245
10.4k
                    foundLast = true;
1246
10.4k
                    break;
1247
10.4k
                }
1248
1249
15.8k
                totalRdCost -= costCoeff[scanPos];
1250
15.8k
                totalRdCost += costUncoded[blkPos];
1251
15.8k
            }
1252
18.4E
            else
1253
18.4E
                totalRdCost -= costSig[scanPos];
1254
26.2k
        }
1255
26.2k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
26.1k
    numSig = 0;
1259
37.9k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
11.8k
    {
1261
11.8k
        int blkPos = codeParams.scan[pos];
1262
11.8k
        int level  = dstCoeff[blkPos];
1263
11.8k
        numSig += (level != 0);
1264
1265
11.8k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
11.8k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
11.8k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
26.1k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
434k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
408k
    {
1274
408k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
408k
    }
1276
26.1k
    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
26.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
26.1k
    return numSig;
1423
1.37M
}
unsigned int x265::Quant::rdoQuant<4u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
307k
{
612
307k
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
307k
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
307k
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
307k
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
307k
    int rem = m_qpParam[ttype].rem;
619
307k
    int per = m_qpParam[ttype].per;
620
307k
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
307k
    int add = (1 << (qbits - 1));
622
307k
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
307k
    const int numCoeff = 1 << (log2TrSize * 2);
625
307k
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
307k
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
307k
    if (!numSig)
628
296k
        return 0;
629
11.5k
    const uint32_t trSize = 1 << log2TrSize;
630
11.5k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
11.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
11.5k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
11.5k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
11.5k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
11.5k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
11.5k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
11.5k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
11.5k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
11.5k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
11.5k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
11.5k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
11.5k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
11.5k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
11.5k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
11.5k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
11.5k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
11.5k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
11.5k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
11.5k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
11.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
11.5k
    int64_t totalRdCost = 0;
666
667
11.5k
    TUEntropyCodingParameters codeParams;
668
11.5k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
11.5k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
11.5k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
11.5k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
11.5k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
11.5k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
11.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
11.5k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
11.5k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
11.5k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
11.5k
    uint32_t scanPos = 0;
691
11.5k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
11.5k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
11.5k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
11.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
11.5k
    if (usePsyMask)
704
6.82k
    {
705
109k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
102k
        {
707
102k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
102k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
102k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
102k
#if X265_ARCH_X86
711
102k
            bool enable512 = detect512();
712
102k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
102k
            else
715
102k
            {
716
102k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
102k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
102k
            }
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
102k
        }
724
6.82k
    }
725
4.71k
    else
726
4.71k
    {
727
        // non-psy path
728
75.8k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
729
71.1k
        {
730
71.1k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
731
71.1k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
732
71.1k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
733
71.1k
            primitives.cu[log2TrSize - 2].nonPsyRdoQuant(m_resiDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, blkPos);
734
71.1k
        }
735
4.71k
    }
736
11.5k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
11.5k
    {
738
        // patternSigCtx = 0
739
11.5k
        {
740
11.5k
            2, 1, 1, 0,
741
11.5k
            1, 1, 0, 0,
742
11.5k
            1, 0, 0, 0,
743
11.5k
            0, 0, 0, 0,
744
11.5k
        },
745
        // patternSigCtx = 1
746
11.5k
        {
747
11.5k
            2, 2, 2, 2,
748
11.5k
            1, 1, 1, 1,
749
11.5k
            0, 0, 0, 0,
750
11.5k
            0, 0, 0, 0,
751
11.5k
        },
752
        // patternSigCtx = 2
753
11.5k
        {
754
11.5k
            2, 1, 0, 0,
755
11.5k
            2, 1, 0, 0,
756
11.5k
            2, 1, 0, 0,
757
11.5k
            2, 1, 0, 0,
758
11.5k
        },
759
        // patternSigCtx = 3
760
11.5k
        {
761
11.5k
            2, 2, 2, 2,
762
11.5k
            2, 2, 2, 2,
763
11.5k
            2, 2, 2, 2,
764
11.5k
            2, 2, 2, 2,
765
11.5k
        },
766
        // 4x4
767
11.5k
        {
768
11.5k
            0, 1, 4, 5,
769
11.5k
            2, 3, 4, 5,
770
11.5k
            6, 6, 8, 8,
771
11.5k
            7, 7, 8, 8
772
11.5k
        }
773
11.5k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
23.1k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
11.5k
    {
778
11.5k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
11.5k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
11.5k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
11.5k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
11.5k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
11.5k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
11.5k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
11.5k
        if (c1 == 0)
787
0
            ctxSet++;
788
11.5k
        c1 = 1;
789
790
11.5k
        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
11.5k
        coeffGroupRDStats cgRdStats;
859
11.5k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
11.5k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
11.5k
        int    c2            = 0;
863
11.5k
        uint32_t goRiceParam = 0;
864
11.5k
        uint32_t levelThreshold = 3;
865
11.5k
        uint32_t c1Idx       = 0;
866
11.5k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
196k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
185k
        {
870
185k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
185k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
185k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
185k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
185k
            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
185k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
185k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
185k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
102k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
185k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
185k
            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
185k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
185k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
185k
            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
185k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
185k
            if (scanPos > (uint32_t)lastScanPos)
900
173k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
173k
                costCoeff[scanPos] = 0;
903
173k
                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
173k
                totalRdCost += costUncoded[blkPos];
909
173k
            }
910
11.5k
            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
11.5k
            else
923
11.5k
            {
924
11.5k
                subFlagMask >>= 1;
925
926
11.5k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
11.5k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
11.5k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
11.5k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
11.5k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
11.5k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
11.5k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
11.5k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
11.5k
                uint32_t level = 0;
939
11.5k
                uint32_t sigCoefBits = 0;
940
11.5k
                costCoeff[scanPos] = MAX_INT64;
941
942
11.5k
                if ((int)scanPos == lastScanPos)
943
11.5k
                    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
11.5k
                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
11.5k
                if (maxAbsLevel == 1)
959
2.71k
                {
960
2.71k
                    uint32_t levelBits = (c1c2idx & 1) ? greaterOneBits[0] + IEP_RATE : ((1 + goRiceParam) << 15) + IEP_RATE;
961
2.71k
                    X265_CHECK(levelBits == getICRateCost(1, 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE, "levelBits mistake\n");
962
963
2.71k
                    int unquantAbsLevel = unQuantLevel >> unquantShift;
964
2.71k
                    X265_CHECK(UNQUANT(1) == unquantAbsLevel, "DQuant check failed\n");
965
2.71k
                    int d = abs(signCoef) - unquantAbsLevel;
966
2.71k
                    int64_t curCost = RDCOST(d, sigCoefBits + levelBits);
967
968
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
969
2.71k
                    if (usePsyMask & scanPos)
970
0
                    {
971
0
                        int reconCoef = abs(unquantAbsLevel + SIGN(predictedCoef, signCoef));
972
0
                        curCost -= PSYVALUE(reconCoef);
973
0
                    }
974
975
2.71k
                    if (curCost < costCoeff[scanPos])
976
2.71k
                    {
977
2.71k
                        level = 1;
978
2.71k
                        costCoeff[scanPos] = curCost;
979
2.71k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
980
2.71k
                    }
981
2.71k
                }
982
8.85k
                else if (maxAbsLevel)
983
8.85k
                {
984
8.85k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
8.85k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
8.85k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
8.85k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
8.85k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
8.85k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
8.85k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
8.85k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
8.85k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
8.85k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
8.85k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
8.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
8.85k
                    if (curCost0 < costCoeff[scanPos])
1010
8.85k
                    {
1011
8.85k
                        level = maxAbsLevel;
1012
8.85k
                        costCoeff[scanPos] = curCost0;
1013
8.85k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
8.85k
                    }
1015
8.85k
                    if (curCost1 < costCoeff[scanPos])
1016
51
                    {
1017
51
                        level = maxAbsLevel - 1;
1018
51
                        costCoeff[scanPos] = curCost1;
1019
51
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
51
                    }
1021
8.85k
                }
1022
1023
11.5k
                dstCoeff[blkPos] = (int16_t)level;
1024
11.5k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
11.5k
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
11.5k
                {
1029
11.5k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
11.5k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
11.5k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
11.5k
                    int rate0, rate1, rate2;
1033
1034
11.5k
                    if (diff0 < -2)  // prob (92.9, 86.5, 74.5)%
1035
2.71k
                    {
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.71k
                        X265_CHECK(level == 1, "absLevel check failure\n");
1039
1040
2.71k
                        const int rateEqual2 = greaterOneBits[1] + levelAbsBits[0];;
1041
2.71k
                        const int rateNotEqual2 = greaterOneBits[0];
1042
1043
2.71k
                        rate0 = 0;
1044
2.71k
                        rate2 = rateEqual2;
1045
2.71k
                        rate1 = rateNotEqual2;
1046
1047
2.71k
                        X265_CHECK(rate1 == getICRateNegDiff(level + 0, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1048
2.71k
                        X265_CHECK(rate2 == getICRateNegDiff(level + 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1049
2.71k
                        X265_CHECK(rate0 == getICRateNegDiff(level - 1, greaterOneBits, levelAbsBits), "rate1 check failure!\n");
1050
2.71k
                    }
1051
8.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
8.85k
                    else
1059
8.85k
                    {
1060
8.85k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
8.85k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
8.85k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
8.85k
                    }
1064
11.5k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
11.5k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
11.5k
                }
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
11.5k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
8.85k
                {
1076
8.85k
                    goRiceParam++;
1077
8.85k
                    levelThreshold <<= 1;
1078
8.85k
                }
1079
1080
11.5k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
11.5k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
11.5k
                if (level > 1)
1085
8.85k
                {
1086
8.85k
                    c1 = 0;
1087
8.85k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
8.85k
                    c2Idx++;
1089
8.85k
                }
1090
2.71k
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
2.71k
                    c1++;
1092
1093
11.5k
                if (dstCoeff[blkPos])
1094
11.5k
                {
1095
11.5k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
11.5k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
11.5k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
11.5k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
11.5k
                }
1100
11.5k
            }
1101
1102
185k
            cgRdStats.sigCost += costSig[scanPos];
1103
185k
        } /* end for (scanPosinCG) */
1104
1105
11.5k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
11.5k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
11.5k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
11.5k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
11.5k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
11.5k
        {
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
11.5k
        }
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
11.5k
    } /* end for (cgScanPos) */
1164
1165
11.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
11.5k
    int64_t bestCost;
1169
11.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
11.5k
    else
1175
11.5k
    {
1176
11.5k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
11.5k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
11.5k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
11.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
11.5k
    int  bestLastIdx = 0;
1187
11.5k
    bool foundLast = false;
1188
23.1k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
11.5k
    {
1190
11.5k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
11.5k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
11.5k
        }
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
187k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
185k
        {
1210
185k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
185k
            if ((int)scanPos > lastScanPos)
1212
173k
                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
11.5k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
11.5k
            if (dstCoeff[blkPos])
1219
11.5k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
11.5k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
11.5k
                if (codeParams.scanType == SCAN_VER)
1223
0
                    std::swap(pos[0], pos[1]);
1224
11.5k
                uint32_t bitsLastNZ = 0;
1225
1226
34.6k
                for (int i = 0; i < 2; i++)
1227
23.1k
                {
1228
23.1k
                    int temp = g_lastCoeffTable[pos[i]];
1229
23.1k
                    int prefixOnes = temp & 15;
1230
23.1k
                    int suffixLen = temp >> 4;
1231
1232
23.1k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
23.1k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
23.1k
                }
1235
1236
11.5k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
11.5k
                if (costAsLast < bestCost)
1239
10.7k
                {
1240
10.7k
                    bestLastIdx = scanPos + 1;
1241
10.7k
                    bestCost = costAsLast;
1242
10.7k
                }
1243
11.5k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
8.85k
                {
1245
8.85k
                    foundLast = true;
1246
8.85k
                    break;
1247
8.85k
                }
1248
1249
2.71k
                totalRdCost -= costCoeff[scanPos];
1250
2.71k
                totalRdCost += costUncoded[blkPos];
1251
2.71k
            }
1252
0
            else
1253
0
                totalRdCost -= costSig[scanPos];
1254
11.5k
        }
1255
11.5k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
11.5k
    numSig = 0;
1259
22.3k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
10.7k
    {
1261
10.7k
        int blkPos = codeParams.scan[pos];
1262
10.7k
        int level  = dstCoeff[blkPos];
1263
10.7k
        numSig += (level != 0);
1264
1265
10.7k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
10.7k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
10.7k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
11.5k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
185k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
174k
    {
1274
174k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
174k
    }
1276
11.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
11.5k
    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
11.5k
    return numSig;
1423
307k
}
unsigned int x265::Quant::rdoQuant<5u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)
Line
Count
Source
611
27.8k
{
612
27.8k
    const int transformShift = MAX_TR_DYNAMIC_RANGE - X265_DEPTH - log2TrSize; /* Represents scaling through forward transform */
613
27.8k
    int scalingListType = (cu.isIntra(absPartIdx) ? 0 : 3) + ttype;
614
27.8k
    const uint32_t usePsyMask = usePsy ? -1 : 0;
615
616
27.8k
    X265_CHECK(scalingListType < 6, "scaling list type out of range\n");
617
618
27.8k
    int rem = m_qpParam[ttype].rem;
619
27.8k
    int per = m_qpParam[ttype].per;
620
27.8k
    int qbits = QUANT_SHIFT + per + transformShift; /* Right shift of non-RDOQ quantizer level = (coeff*Q + offset)>>q_bits */
621
27.8k
    int add = (1 << (qbits - 1));
622
27.8k
    const int32_t* qCoef = m_scalingList->m_quantCoef[log2TrSize - 2][scalingListType][rem];
623
624
27.8k
    const int numCoeff = 1 << (log2TrSize * 2);
625
27.8k
    uint32_t numSig = primitives.nquant(m_resiDctCoeff, qCoef, dstCoeff, qbits, add, numCoeff);
626
27.8k
    X265_CHECK((int)numSig == primitives.cu[log2TrSize - 2].count_nonzero(dstCoeff), "numSig differ\n");
627
27.8k
    if (!numSig)
628
24.9k
        return 0;
629
2.92k
    const uint32_t trSize = 1 << log2TrSize;
630
2.92k
    int64_t lambda2 = m_qpParam[ttype].lambda2;
631
2.92k
    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.92k
    const int32_t* unquantScale = m_scalingList->m_dequantCoef[log2TrSize - 2][scalingListType][rem];
636
2.92k
    int unquantShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - transformShift + (m_scalingList->m_bEnabled ? 4 : 0);
637
2.92k
    int unquantRound = (unquantShift > per) ? 1 << (unquantShift - per - 1) : 0;
638
2.92k
    const int scaleBits = SCALE_BITS - 2 * transformShift;
639
640
2.92k
#define UNQUANT(lvl)    (((lvl) * (unquantScale[blkPos] << per) + unquantRound) >> unquantShift)
641
2.92k
#define SIGCOST(bits)   ((lambda2 * (bits)) >> 8)
642
2.92k
#define RDCOST(d, bits) ((((int64_t)d * d) << scaleBits) + SIGCOST(bits))
643
2.92k
#define PSYVALUE(rec)   ((psyScale * (rec)) >> X265_MAX(0, (2 * transformShift + 1)))
644
645
2.92k
    int64_t costCoeff[trSize * trSize];   /* d*d + lambda * bits */
646
2.92k
    int64_t costUncoded[trSize * trSize]; /* d*d + lambda * 0    */
647
2.92k
    int64_t costSig[trSize * trSize];     /* lambda * bits       */
648
649
2.92k
    int rateIncUp[trSize * trSize];      /* signal overhead of increasing level */
650
2.92k
    int rateIncDown[trSize * trSize];    /* signal overhead of decreasing level */
651
2.92k
    int sigRateDelta[trSize * trSize];   /* signal difference between zero and non-zero */
652
653
2.92k
    int64_t costCoeffGroupSig[MLS_GRP_NUM]; /* lambda * bits of group coding cost */
654
2.92k
    uint64_t sigCoeffGroupFlag64 = 0;
655
656
2.92k
    const uint32_t cgSize = (1 << MLS_CG_SIZE); /* 4x4 num coef = 16 */
657
2.92k
    bool bIsLuma = ttype == TEXT_LUMA;
658
659
    /* total rate distortion cost of transform block, as CBF=0 */
660
2.92k
    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.92k
    int64_t totalRdCost = 0;
666
667
2.92k
    TUEntropyCodingParameters codeParams;
668
2.92k
    cu.getTUEntropyCodingParameters(codeParams, absPartIdx, log2TrSize, bIsLuma);
669
2.92k
    const uint32_t log2TrSizeCG = log2TrSize - 2;
670
2.92k
    const uint32_t cgNum = 1 << (log2TrSizeCG * 2);
671
2.92k
    const uint32_t cgStride = (trSize >> MLS_CG_LOG2_SIZE);
672
673
2.92k
    uint8_t coeffNum[MLS_GRP_NUM];      // value range[0, 16]
674
2.92k
    uint16_t coeffSign[MLS_GRP_NUM];    // bit mask map for non-zero coeff sign
675
2.92k
    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.92k
    const int lastScanPos = primitives.scanPosLast(codeParams.scan, dstCoeff, coeffSign, coeffFlag, coeffNum, numSig, g_scan4x4[codeParams.scanType], trSize);
684
2.92k
    const int cgLastScanPos = (lastScanPos >> LOG2_SCAN_SET_SIZE);
685
686
687
    /* TODO: update bit estimates if dirty */
688
2.92k
    EstBitsSbac& estBitsSbac = m_entropyCoder->m_estBitsSbac;
689
690
2.92k
    uint32_t scanPos = 0;
691
2.92k
    uint32_t c1 = 1;
692
693
    // process trail all zero Coeff Group
694
695
    /* coefficients after lastNZ have no distortion signal cost */
696
2.92k
    const int zeroCG = cgNum - 1 - cgLastScanPos;
697
2.92k
    memset(&costCoeff[(cgLastScanPos + 1) << MLS_CG_SIZE], 0, zeroCG * MLS_CG_BLK_SIZE * sizeof(int64_t));
698
2.92k
    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.92k
    if (usePsyMask)
704
2.92k
    {
705
187k
        for (int cgScanPos = cgLastScanPos + 1; cgScanPos < (int)cgNum ; cgScanPos++)
706
184k
        {
707
184k
            X265_CHECK(coeffNum[cgScanPos] == 0, "count of coeff failure\n");
708
184k
            uint32_t scanPosBase = (cgScanPos << MLS_CG_SIZE);
709
184k
            uint32_t blkPos      = codeParams.scan[scanPosBase];
710
184k
#if X265_ARCH_X86
711
184k
            bool enable512 = detect512();
712
184k
            if (enable512)
713
0
                primitives.cu[log2TrSize - 2].psyRdoQuant(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
714
184k
            else
715
184k
            {
716
184k
                primitives.cu[log2TrSize - 2].psyRdoQuant_1p(m_resiDctCoeff,  costUncoded, &totalUncodedCost, &totalRdCost,blkPos);
717
184k
                primitives.cu[log2TrSize - 2].psyRdoQuant_2p(m_resiDctCoeff, m_fencDctCoeff, costUncoded, &totalUncodedCost, &totalRdCost, &psyScale, blkPos);
718
184k
            }
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
184k
        }
724
2.92k
    }
725
0
    else
726
0
    {
727
        // non-psy path
728
0
        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
0
    }
736
2.92k
    static const uint8_t table_cnt[5][SCAN_SET_SIZE] =
737
2.92k
    {
738
        // patternSigCtx = 0
739
2.92k
        {
740
2.92k
            2, 1, 1, 0,
741
2.92k
            1, 1, 0, 0,
742
2.92k
            1, 0, 0, 0,
743
2.92k
            0, 0, 0, 0,
744
2.92k
        },
745
        // patternSigCtx = 1
746
2.92k
        {
747
2.92k
            2, 2, 2, 2,
748
2.92k
            1, 1, 1, 1,
749
2.92k
            0, 0, 0, 0,
750
2.92k
            0, 0, 0, 0,
751
2.92k
        },
752
        // patternSigCtx = 2
753
2.92k
        {
754
2.92k
            2, 1, 0, 0,
755
2.92k
            2, 1, 0, 0,
756
2.92k
            2, 1, 0, 0,
757
2.92k
            2, 1, 0, 0,
758
2.92k
        },
759
        // patternSigCtx = 3
760
2.92k
        {
761
2.92k
            2, 2, 2, 2,
762
2.92k
            2, 2, 2, 2,
763
2.92k
            2, 2, 2, 2,
764
2.92k
            2, 2, 2, 2,
765
2.92k
        },
766
        // 4x4
767
2.92k
        {
768
2.92k
            0, 1, 4, 5,
769
2.92k
            2, 3, 4, 5,
770
2.92k
            6, 6, 8, 8,
771
2.92k
            7, 7, 8, 8
772
2.92k
        }
773
2.92k
    };
774
775
    /* iterate over coding groups in reverse scan order */
776
5.85k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0; cgScanPos--)
777
2.92k
    {
778
2.92k
        uint32_t ctxSet = (cgScanPos && bIsLuma) ? 2 : 0;
779
2.92k
        const uint32_t cgBlkPos = codeParams.scanCG[cgScanPos];
780
2.92k
        const uint32_t cgPosY   = cgBlkPos >> log2TrSizeCG;
781
2.92k
        const uint32_t cgPosX   = cgBlkPos & ((1 << log2TrSizeCG) - 1);
782
2.92k
        const uint64_t cgBlkPosMask = ((uint64_t)1 << cgBlkPos);
783
2.92k
        const int patternSigCtx = calcPatternSigCtx(sigCoeffGroupFlag64, cgPosX, cgPosY, cgBlkPos, cgStride);
784
2.92k
        const int ctxSigOffset = codeParams.firstSignificanceMapContext + (cgScanPos && bIsLuma ? 3 : 0);
785
786
2.92k
        if (c1 == 0)
787
0
            ctxSet++;
788
2.92k
        c1 = 1;
789
790
2.92k
        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.92k
        coeffGroupRDStats cgRdStats;
859
2.92k
        memset(&cgRdStats, 0, sizeof(coeffGroupRDStats));
860
861
2.92k
        uint32_t subFlagMask = coeffFlag[cgScanPos];
862
2.92k
        int    c2            = 0;
863
2.92k
        uint32_t goRiceParam = 0;
864
2.92k
        uint32_t levelThreshold = 3;
865
2.92k
        uint32_t c1Idx       = 0;
866
2.92k
        uint32_t c2Idx       = 0;
867
        /* iterate over coefficients in each group in reverse scan order */
868
49.7k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
869
46.8k
        {
870
46.8k
            scanPos              = (cgScanPos << MLS_CG_SIZE) + scanPosinCG;
871
46.8k
            uint32_t blkPos      = codeParams.scan[scanPos];
872
46.8k
            uint32_t maxAbsLevel = dstCoeff[blkPos];                  /* abs(quantized coeff) */
873
46.8k
            int signCoef         = m_resiDctCoeff[blkPos];            /* pre-quantization DCT coeff */
874
46.8k
            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
46.8k
            costUncoded[blkPos] = ((int64_t)signCoef * signCoef) << scaleBits;
882
46.8k
            X265_CHECK((!!scanPos ^ !!blkPos) == 0, "failed on (blkPos=0 && scanPos!=0)\n");
883
46.8k
            if (usePsyMask & scanPos)
884
                /* when no residual coefficient is coded, predicted coef == recon coef */
885
43.8k
                costUncoded[blkPos] -= PSYVALUE(predictedCoef);
886
887
46.8k
            totalUncodedCost += costUncoded[blkPos];
888
889
            // coefficient level estimation
890
46.8k
            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
46.8k
            static const uint64_t table_cnt64[4] = {0x0000000100110112ULL, 0x0000000011112222ULL, 0x0012001200120012ULL, 0x2222222222222222ULL};
893
46.8k
            uint64_t ctxCnt = (trSize == 4) ? 0x8877886654325410ULL : table_cnt64[patternSigCtx];
894
46.8k
            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
46.8k
            X265_CHECK(ctxSig == getSigCtxInc(patternSigCtx, log2TrSize, trSize, blkPos, bIsLuma, codeParams.firstSignificanceMapContext), "sigCtx check failure\n");
897
898
            // before find lastest non-zero coeff
899
46.8k
            if (scanPos > (uint32_t)lastScanPos)
900
43.8k
            {
901
                /* coefficients after lastNZ have no distortion signal cost */
902
43.8k
                costCoeff[scanPos] = 0;
903
43.8k
                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
43.8k
                totalRdCost += costUncoded[blkPos];
909
43.8k
            }
910
2.92k
            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.92k
            else
923
2.92k
            {
924
2.92k
                subFlagMask >>= 1;
925
926
2.92k
                const uint32_t c1c2idx = ((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)) + (((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1) * 2;
927
2.92k
                const uint32_t baseLevel = ((uint32_t)0xD9 >> (c1c2idx * 2)) & 3;  // {1, 2, 1, 3}
928
929
2.92k
                X265_CHECK(!!((int)c1Idx < C1FLAG_NUMBER) == (int)((c1Idx - 8) >> (sizeof(int) * CHAR_BIT - 1)), "scan validation 1\n");
930
2.92k
                X265_CHECK(!!(c2Idx == 0) == ((-(int)c2Idx) >> (sizeof(int) * CHAR_BIT - 1)) + 1, "scan validation 2\n");
931
2.92k
                X265_CHECK((int)baseLevel == ((c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx == 0)) : 1), "scan validation 3\n");
932
2.92k
                X265_CHECK(c1c2idx <= 3, "c1c2Idx check failure\n");
933
934
                // coefficient level estimation
935
2.92k
                const int* levelAbsBits = estBitsSbac.levelAbsBits[ctxSet + c2];
936
2.92k
                const uint32_t c1c2Rate = ((c1c2idx & 1) ?  greaterOneBits[1] : 0) + ((c1c2idx == 3) ? levelAbsBits[1] : 0);
937
938
2.92k
                uint32_t level = 0;
939
2.92k
                uint32_t sigCoefBits = 0;
940
2.92k
                costCoeff[scanPos] = MAX_INT64;
941
942
2.92k
                if ((int)scanPos == lastScanPos)
943
2.92k
                    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.92k
                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.92k
                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.92k
                else if (maxAbsLevel)
983
2.92k
                {
984
2.92k
                    uint32_t levelBits0 = getICRateCost(maxAbsLevel,     maxAbsLevel     - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
985
2.92k
                    uint32_t levelBits1 = getICRateCost(maxAbsLevel - 1, maxAbsLevel - 1 - baseLevel, greaterOneBits, levelAbsBits, goRiceParam, c1c2Rate) + IEP_RATE;
986
987
2.92k
                    const uint32_t preDQuantLevelDiff = (unquantScale[blkPos] << per);
988
989
2.92k
                    const int unquantAbsLevel0 = unQuantLevel >> unquantShift;
990
2.92k
                    X265_CHECK(UNQUANT(maxAbsLevel) == (uint32_t)unquantAbsLevel0, "DQuant check failed\n");
991
2.92k
                    int d0 = abs(signCoef) - unquantAbsLevel0;
992
2.92k
                    int64_t curCost0 = RDCOST(d0, sigCoefBits + levelBits0);
993
994
2.92k
                    const int unquantAbsLevel1 = (unQuantLevel - preDQuantLevelDiff) >> unquantShift;
995
2.92k
                    X265_CHECK(UNQUANT(maxAbsLevel - 1) == (uint32_t)unquantAbsLevel1, "DQuant check failed\n");
996
2.92k
                    int d1 = abs(signCoef) - unquantAbsLevel1;
997
2.92k
                    int64_t curCost1 = RDCOST(d1, sigCoefBits + levelBits1);
998
999
                    /* Psy RDOQ: bias in favor of higher AC coefficients in the reconstructed frame */
1000
2.92k
                    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.92k
                    if (curCost0 < costCoeff[scanPos])
1010
2.92k
                    {
1011
2.92k
                        level = maxAbsLevel;
1012
2.92k
                        costCoeff[scanPos] = curCost0;
1013
2.92k
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1014
2.92k
                    }
1015
2.92k
                    if (curCost1 < costCoeff[scanPos])
1016
35
                    {
1017
35
                        level = maxAbsLevel - 1;
1018
35
                        costCoeff[scanPos] = curCost1;
1019
35
                        costSig[scanPos] = SIGCOST(sigCoefBits);
1020
35
                    }
1021
2.92k
                }
1022
1023
2.92k
                dstCoeff[blkPos] = (int16_t)level;
1024
2.92k
                totalRdCost += costCoeff[scanPos];
1025
1026
                /* record costs for sign-hiding performed at the end */
1027
2.92k
                if ((cu.m_slice->m_pps->bSignHideEnabled ? ~0 : 0) & level)
1028
2.92k
                {
1029
2.92k
                    const int32_t diff0 = level - 1 - baseLevel;
1030
2.92k
                    const int32_t diff2 = level + 1 - baseLevel;
1031
2.92k
                    const int32_t maxVlc = g_goRiceRange[goRiceParam];
1032
2.92k
                    int rate0, rate1, rate2;
1033
1034
2.92k
                    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.92k
                    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.92k
                    else
1059
2.92k
                    {
1060
2.92k
                        rate1 = getICRate(level + 0, diff0 + 1, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1061
2.92k
                        rate2 = getICRate(level + 1, diff0 + 2, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1062
2.92k
                        rate0 = getICRate(level - 1, diff0 + 0, greaterOneBits, levelAbsBits, goRiceParam, maxVlc, c1c2Rate);
1063
2.92k
                    }
1064
2.92k
                    rateIncUp[blkPos] = rate2 - rate1;
1065
2.92k
                    rateIncDown[blkPos] = rate0 - rate1;
1066
2.92k
                }
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.92k
                if ((level >= baseLevel) && (goRiceParam < 4) && (level > levelThreshold))
1075
2.92k
                {
1076
2.92k
                    goRiceParam++;
1077
2.92k
                    levelThreshold <<= 1;
1078
2.92k
                }
1079
1080
2.92k
                const uint32_t isNonZero = (uint32_t)(-(int32_t)level) >> 31;
1081
2.92k
                c1Idx += isNonZero;
1082
1083
                /* update bin model */
1084
2.92k
                if (level > 1)
1085
2.92k
                {
1086
2.92k
                    c1 = 0;
1087
2.92k
                    c2 += (uint32_t)(c2 - 2) >> 31;
1088
2.92k
                    c2Idx++;
1089
2.92k
                }
1090
0
                else if (((c1 == 1) | (c1 == 2)) & isNonZero)
1091
0
                    c1++;
1092
1093
2.92k
                if (dstCoeff[blkPos])
1094
2.92k
                {
1095
2.92k
                    sigCoeffGroupFlag64 |= cgBlkPosMask;
1096
2.92k
                    cgRdStats.codedLevelAndDist += costCoeff[scanPos] - costSig[scanPos];
1097
2.92k
                    cgRdStats.uncodedDist += costUncoded[blkPos];
1098
2.92k
                    cgRdStats.nnzBeforePos0 += scanPosinCG;
1099
2.92k
                }
1100
2.92k
            }
1101
1102
46.8k
            cgRdStats.sigCost += costSig[scanPos];
1103
46.8k
        } /* end for (scanPosinCG) */
1104
1105
2.92k
        X265_CHECK((cgScanPos << MLS_CG_SIZE) == (int)scanPos, "scanPos mistake\n");
1106
2.92k
        cgRdStats.sigCost0 = costSig[scanPos];
1107
1108
2.92k
        costCoeffGroupSig[cgScanPos] = 0;
1109
1110
        /* nothing to do at this case */
1111
2.92k
        X265_CHECK(cgLastScanPos >= 0, "cgLastScanPos check failure\n");
1112
1113
2.92k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1114
2.92k
        {
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.92k
        }
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.92k
    } /* end for (cgScanPos) */
1164
1165
2.92k
    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.92k
    int64_t bestCost;
1169
2.92k
    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.92k
    else
1175
2.92k
    {
1176
2.92k
        int ctx = ctxCbf[ttype][cu.m_tuDepth[absPartIdx]];
1177
2.92k
        bestCost = totalUncodedCost + SIGCOST(estBitsSbac.blockCbpBits[ctx][0]);
1178
2.92k
        totalRdCost += SIGCOST(estBitsSbac.blockCbpBits[ctx][1]);
1179
2.92k
    }
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.92k
    int  bestLastIdx = 0;
1187
2.92k
    bool foundLast = false;
1188
5.85k
    for (int cgScanPos = cgLastScanPos; cgScanPos >= 0 && !foundLast; cgScanPos--)
1189
2.92k
    {
1190
2.92k
        if (!cgScanPos || cgScanPos == cgLastScanPos)
1191
2.92k
        {
1192
            /* the presence of these coefficient groups are inferred, they have no bit in
1193
             * sigCoeffGroupFlag64 and no saved costCoeffGroupSig[] cost */
1194
2.92k
        }
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
46.8k
        for (int scanPosinCG = cgSize - 1; scanPosinCG >= 0; scanPosinCG--)
1209
46.8k
        {
1210
46.8k
            scanPos = cgScanPos * cgSize + scanPosinCG;
1211
46.8k
            if ((int)scanPos > lastScanPos)
1212
43.8k
                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.92k
            uint32_t blkPos = codeParams.scan[scanPos];
1218
2.92k
            if (dstCoeff[blkPos])
1219
2.92k
            {
1220
                // Calculates the cost of signaling the last significant coefficient in the block 
1221
2.92k
                uint32_t pos[2] = { (blkPos & (trSize - 1)), (blkPos >> log2TrSize) };
1222
2.92k
                if (codeParams.scanType == SCAN_VER)
1223
0
                    std::swap(pos[0], pos[1]);
1224
2.92k
                uint32_t bitsLastNZ = 0;
1225
1226
8.77k
                for (int i = 0; i < 2; i++)
1227
5.85k
                {
1228
5.85k
                    int temp = g_lastCoeffTable[pos[i]];
1229
5.85k
                    int prefixOnes = temp & 15;
1230
5.85k
                    int suffixLen = temp >> 4;
1231
1232
5.85k
                    bitsLastNZ += m_entropyCoder->m_estBitsSbac.lastBits[i][prefixOnes];
1233
5.85k
                    bitsLastNZ += IEP_RATE * suffixLen;
1234
5.85k
                }
1235
1236
2.92k
                int64_t costAsLast = totalRdCost - costSig[scanPos] + SIGCOST(bitsLastNZ);
1237
1238
2.92k
                if (costAsLast < bestCost)
1239
2.92k
                {
1240
2.92k
                    bestLastIdx = scanPos + 1;
1241
2.92k
                    bestCost = costAsLast;
1242
2.92k
                }
1243
2.92k
                if (dstCoeff[blkPos] > 1 || m_rdoqLevel == 1)
1244
2.92k
                {
1245
2.92k
                    foundLast = true;
1246
2.92k
                    break;
1247
2.92k
                }
1248
1249
0
                totalRdCost -= costCoeff[scanPos];
1250
0
                totalRdCost += costUncoded[blkPos];
1251
0
            }
1252
0
            else
1253
0
                totalRdCost -= costSig[scanPos];
1254
2.92k
        }
1255
2.92k
    }
1256
1257
    /* recount non-zero coefficients and re-apply sign of DCT coef */
1258
2.92k
    numSig = 0;
1259
5.85k
    for (int pos = 0; pos < bestLastIdx; pos++)
1260
2.92k
    {
1261
2.92k
        int blkPos = codeParams.scan[pos];
1262
2.92k
        int level  = dstCoeff[blkPos];
1263
2.92k
        numSig += (level != 0);
1264
1265
2.92k
        uint32_t mask = (int32_t)m_resiDctCoeff[blkPos] >> 31;
1266
2.92k
        dstCoeff[blkPos] = (int16_t)((level ^ mask) - mask);
1267
2.92k
    }
1268
1269
    // Average 49.62 pixels
1270
    /* clean uncoded coefficients */
1271
2.92k
    X265_CHECK((uint32_t)(fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)) < trSize * trSize, "array beyond bound\n");
1272
46.8k
    for (int pos = bestLastIdx; pos <= (fastMin(lastScanPos, bestLastIdx) | (SCAN_SET_SIZE - 1)); pos++)
1273
43.8k
    {
1274
43.8k
        dstCoeff[codeParams.scan[pos]] = 0;
1275
43.8k
    }
1276
2.92k
    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.92k
    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.92k
    return numSig;
1423
27.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