Coverage Report

Created: 2026-05-24 07:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/enc_group.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/enc_group.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <cmath>
12
#include <cstddef>
13
#include <cstdint>
14
#include <cstdlib>
15
16
#include "lib/jxl/base/common.h"
17
#include "lib/jxl/base/status.h"
18
#include "lib/jxl/chroma_from_luma.h"
19
#include "lib/jxl/coeff_order_fwd.h"
20
#include "lib/jxl/enc_ans.h"
21
#include "lib/jxl/enc_bit_writer.h"
22
#include "lib/jxl/frame_dimensions.h"
23
#include "lib/jxl/memory_manager_internal.h"
24
25
#undef HWY_TARGET_INCLUDE
26
#define HWY_TARGET_INCLUDE "lib/jxl/enc_group.cc"
27
#include <hwy/foreach_target.h>
28
#include <hwy/highway.h>
29
30
#include "lib/jxl/ac_strategy.h"
31
#include "lib/jxl/base/bits.h"
32
#include "lib/jxl/base/compiler_specific.h"
33
#include "lib/jxl/base/rect.h"
34
#include "lib/jxl/common.h"  // kMaxNumPasses
35
#include "lib/jxl/dct_util.h"
36
#include "lib/jxl/dec_transforms-inl.h"
37
#include "lib/jxl/enc_aux_out.h"
38
#include "lib/jxl/enc_cache.h"
39
#include "lib/jxl/enc_params.h"
40
#include "lib/jxl/enc_transforms-inl.h"
41
#include "lib/jxl/image.h"
42
#include "lib/jxl/quantizer-inl.h"
43
#include "lib/jxl/quantizer.h"
44
#include "lib/jxl/simd_util.h"
45
HWY_BEFORE_NAMESPACE();
46
namespace jxl {
47
namespace HWY_NAMESPACE {
48
49
// These templates are not found via ADL.
50
using hwy::HWY_NAMESPACE::Abs;
51
using hwy::HWY_NAMESPACE::Ge;
52
using hwy::HWY_NAMESPACE::IfThenElse;
53
using hwy::HWY_NAMESPACE::IfThenElseZero;
54
using hwy::HWY_NAMESPACE::MaskFromVec;
55
using hwy::HWY_NAMESPACE::Round;
56
57
// NOTE: caller takes care of extracting quant from rect of RawQuantField.
58
void QuantizeBlockAC(const Quantizer& quantizer, const bool error_diffusion,
59
                     size_t c, float qm_multiplier, AcStrategyType quant_kind,
60
                     size_t xsize, size_t ysize, float* thresholds,
61
                     const float* JXL_RESTRICT block_in, const int32_t* quant,
62
8.30M
                     int32_t* JXL_RESTRICT block_out) {
63
8.30M
  const float* JXL_RESTRICT qm = quantizer.InvDequantMatrix(quant_kind, c);
64
8.30M
  float qac = quantizer.Scale() * (*quant);
65
  // Not SIMD-ified for now.
66
8.30M
  if (c != 1 && xsize * ysize >= 4) {
67
1.95M
    for (int i = 0; i < 4; ++i) {
68
1.56M
      thresholds[i] -= 0.00744f * xsize * ysize;
69
1.56M
      if (thresholds[i] < 0.5) {
70
310k
        thresholds[i] = 0.5;
71
310k
      }
72
1.56M
    }
73
391k
  }
74
8.30M
  HWY_CAPPED(float, kBlockDim) df;
75
8.30M
  HWY_CAPPED(int32_t, kBlockDim) di;
76
8.30M
  HWY_CAPPED(uint32_t, kBlockDim) du;
77
8.30M
  const auto quantv = Set(df, qac * qm_multiplier);
78
85.3M
  for (size_t y = 0; y < ysize * kBlockDim; y++) {
79
77.0M
    size_t yfix = static_cast<size_t>(y >= ysize * kBlockDim / 2) * 2;
80
77.0M
    const size_t off = y * kBlockDim * xsize;
81
215M
    for (size_t x = 0; x < xsize * kBlockDim; x += Lanes(df)) {
82
138M
      auto threshold = Zero(df);
83
138M
      if (xsize == 1) {
84
56.6M
        HWY_ALIGN uint32_t kMask[kBlockDim] = {0, 0, 0, 0, ~0u, ~0u, ~0u, ~0u};
85
56.6M
        const auto mask = MaskFromVec(BitCast(df, Load(du, kMask + x)));
86
56.6M
        threshold = IfThenElse(mask, Set(df, thresholds[yfix + 1]),
87
56.6M
                               Set(df, thresholds[yfix]));
88
81.7M
      } else {
89
        // Same for all lanes in the vector.
90
81.7M
        threshold = Set(
91
81.7M
            df,
92
81.7M
            thresholds[yfix + static_cast<size_t>(x >= xsize * kBlockDim / 2)]);
93
81.7M
      }
94
138M
      const auto q = Mul(Load(df, qm + off + x), quantv);
95
138M
      const auto in = Load(df, block_in + off + x);
96
138M
      const auto val = Mul(q, in);
97
138M
      const auto nzero_mask = Ge(Abs(val), threshold);
98
138M
      const auto v = ConvertTo(di, IfThenElseZero(nzero_mask, Round(val)));
99
138M
      Store(v, di, block_out + off + x);
100
138M
    }
101
77.0M
  }
102
8.30M
}
Unexecuted instantiation: jxl::N_SSE4::QuantizeBlockAC(jxl::Quantizer const&, bool, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int const*, int*)
jxl::N_AVX2::QuantizeBlockAC(jxl::Quantizer const&, bool, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int const*, int*)
Line
Count
Source
62
8.30M
                     int32_t* JXL_RESTRICT block_out) {
63
8.30M
  const float* JXL_RESTRICT qm = quantizer.InvDequantMatrix(quant_kind, c);
64
8.30M
  float qac = quantizer.Scale() * (*quant);
65
  // Not SIMD-ified for now.
66
8.30M
  if (c != 1 && xsize * ysize >= 4) {
67
1.95M
    for (int i = 0; i < 4; ++i) {
68
1.56M
      thresholds[i] -= 0.00744f * xsize * ysize;
69
1.56M
      if (thresholds[i] < 0.5) {
70
310k
        thresholds[i] = 0.5;
71
310k
      }
72
1.56M
    }
73
391k
  }
74
8.30M
  HWY_CAPPED(float, kBlockDim) df;
75
8.30M
  HWY_CAPPED(int32_t, kBlockDim) di;
76
8.30M
  HWY_CAPPED(uint32_t, kBlockDim) du;
77
8.30M
  const auto quantv = Set(df, qac * qm_multiplier);
78
85.3M
  for (size_t y = 0; y < ysize * kBlockDim; y++) {
79
77.0M
    size_t yfix = static_cast<size_t>(y >= ysize * kBlockDim / 2) * 2;
80
77.0M
    const size_t off = y * kBlockDim * xsize;
81
215M
    for (size_t x = 0; x < xsize * kBlockDim; x += Lanes(df)) {
82
138M
      auto threshold = Zero(df);
83
138M
      if (xsize == 1) {
84
56.6M
        HWY_ALIGN uint32_t kMask[kBlockDim] = {0, 0, 0, 0, ~0u, ~0u, ~0u, ~0u};
85
56.6M
        const auto mask = MaskFromVec(BitCast(df, Load(du, kMask + x)));
86
56.6M
        threshold = IfThenElse(mask, Set(df, thresholds[yfix + 1]),
87
56.6M
                               Set(df, thresholds[yfix]));
88
81.7M
      } else {
89
        // Same for all lanes in the vector.
90
81.7M
        threshold = Set(
91
81.7M
            df,
92
81.7M
            thresholds[yfix + static_cast<size_t>(x >= xsize * kBlockDim / 2)]);
93
81.7M
      }
94
138M
      const auto q = Mul(Load(df, qm + off + x), quantv);
95
138M
      const auto in = Load(df, block_in + off + x);
96
138M
      const auto val = Mul(q, in);
97
138M
      const auto nzero_mask = Ge(Abs(val), threshold);
98
138M
      const auto v = ConvertTo(di, IfThenElseZero(nzero_mask, Round(val)));
99
138M
      Store(v, di, block_out + off + x);
100
138M
    }
101
77.0M
  }
102
8.30M
}
Unexecuted instantiation: jxl::N_AVX3::QuantizeBlockAC(jxl::Quantizer const&, bool, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int const*, int*)
Unexecuted instantiation: jxl::N_AVX3_ZEN4::QuantizeBlockAC(jxl::Quantizer const&, bool, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int const*, int*)
Unexecuted instantiation: jxl::N_AVX3_SPR::QuantizeBlockAC(jxl::Quantizer const&, bool, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int const*, int*)
Unexecuted instantiation: jxl::N_SSE2::QuantizeBlockAC(jxl::Quantizer const&, bool, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int const*, int*)
103
104
void AdjustQuantBlockAC(const Quantizer& quantizer, size_t c,
105
                        float qm_multiplier, AcStrategyType quant_kind,
106
                        size_t xsize, size_t ysize, float* thresholds,
107
8.30M
                        const float* JXL_RESTRICT block_in, int32_t* quant) {
108
  // No quantization adjusting for these small blocks.
109
  // Quantization adjusting attempts to fix some known issues
110
  // with larger blocks and on the 8x8 dct's emerging 8x8 blockiness
111
  // when there are not many non-zeros.
112
8.30M
  constexpr size_t kPartialBlockKinds =
113
8.30M
      (1 << static_cast<size_t>(AcStrategyType::IDENTITY)) |
114
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT2X2)) |
115
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT4X4)) |
116
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT4X8)) |
117
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT8X4)) |
118
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV0)) |
119
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV1)) |
120
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV2)) |
121
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV3));
122
8.30M
  if ((1 << static_cast<size_t>(quant_kind)) & kPartialBlockKinds) {
123
4.32M
    return;
124
4.32M
  }
125
126
3.98M
  const float* JXL_RESTRICT qm = quantizer.InvDequantMatrix(quant_kind, c);
127
3.98M
  float qac = quantizer.Scale() * (*quant);
128
3.98M
  if (xsize > 1 || ysize > 1) {
129
6.13M
    for (int i = 0; i < 4; ++i) {
130
4.90M
      thresholds[i] -= Clamp1(0.003f * xsize * ysize, 0.f, 0.08f);
131
4.90M
      if (thresholds[i] < 0.54) {
132
262k
        thresholds[i] = 0.54;
133
262k
      }
134
4.90M
    }
135
1.22M
  }
136
3.98M
  float sum_of_highest_freq_row_and_column = 0;
137
3.98M
  float sum_of_error = 0;
138
3.98M
  float sum_of_vals = 0;
139
3.98M
  float hfNonZeros[4] = {};
140
3.98M
  float hfMaxError[4] = {};
141
142
46.4M
  for (size_t y = 0; y < ysize * kBlockDim; y++) {
143
872M
    for (size_t x = 0; x < xsize * kBlockDim; x++) {
144
830M
      const size_t pos = y * kBlockDim * xsize + x;
145
830M
      if (x < xsize && y < ysize) {
146
12.9M
        continue;
147
12.9M
      }
148
817M
      const size_t hfix = (static_cast<size_t>(y >= ysize * kBlockDim / 2) * 2 +
149
817M
                           static_cast<size_t>(x >= xsize * kBlockDim / 2));
150
817M
      const float val = block_in[pos] * (qm[pos] * qac * qm_multiplier);
151
817M
      const float v = (std::abs(val) < thresholds[hfix]) ? 0 : rintf(val);
152
817M
      const float error = std::abs(val - v);
153
817M
      sum_of_error += error;
154
817M
      sum_of_vals += std::abs(v);
155
817M
      if (c == 1 && v == 0) {
156
233M
        if (hfMaxError[hfix] < error) {
157
13.7M
          hfMaxError[hfix] = error;
158
13.7M
        }
159
233M
      }
160
817M
      if (v != 0.0f) {
161
61.6M
        hfNonZeros[hfix] += std::abs(v);
162
61.6M
        bool in_corner = y >= 7 * ysize && x >= 7 * xsize;
163
61.6M
        bool on_border =
164
61.6M
            y == ysize * kBlockDim - 1 || x == xsize * kBlockDim - 1;
165
61.6M
        bool in_larger_corner = x >= 4 * xsize && y >= 4 * ysize;
166
61.6M
        if (in_corner || (on_border && in_larger_corner)) {
167
1.83M
          sum_of_highest_freq_row_and_column += std::abs(val);
168
1.83M
        }
169
61.6M
      }
170
817M
    }
171
42.4M
  }
172
3.98M
  if (c == 1 && sum_of_vals * 8 < xsize * ysize) {
173
364k
    static const double kLimit[4] = {
174
364k
        0.46,
175
364k
        0.46,
176
364k
        0.46,
177
364k
        0.46,
178
364k
    };
179
364k
    static const double kMul[4] = {
180
364k
        0.9999,
181
364k
        0.9999,
182
364k
        0.9999,
183
364k
        0.9999,
184
364k
    };
185
364k
    const int32_t orig_quant = *quant;
186
364k
    int32_t new_quant = *quant;
187
1.45M
    for (int i = 1; i < 4; ++i) {
188
1.08M
      if (hfNonZeros[i] == 0.0 && hfMaxError[i] > kLimit[i]) {
189
3.13k
        new_quant = orig_quant + 1;
190
3.13k
        break;
191
3.13k
      }
192
1.08M
    }
193
364k
    *quant = new_quant;
194
364k
    if (hfNonZeros[3] == 0.0 && hfMaxError[3] > kLimit[3]) {
195
473
      thresholds[3] = kMul[3] * hfMaxError[3] * new_quant / orig_quant;
196
364k
    } else if ((hfNonZeros[1] == 0.0 && hfMaxError[1] > kLimit[1]) ||
197
362k
               (hfNonZeros[2] == 0.0 && hfMaxError[2] > kLimit[2])) {
198
2.66k
      thresholds[1] = kMul[1] * std::max(hfMaxError[1], hfMaxError[2]) *
199
2.66k
                      new_quant / orig_quant;
200
2.66k
      thresholds[2] = thresholds[1];
201
361k
    } else if (hfNonZeros[0] == 0.0 && hfMaxError[0] > kLimit[0]) {
202
13.7k
      thresholds[0] = kMul[0] * hfMaxError[0] * new_quant / orig_quant;
203
13.7k
    }
204
364k
  }
205
  // Heuristic for improving accuracy of high-frequency patterns
206
  // occurring in an environment with no medium-frequency masking
207
  // patterns.
208
3.98M
  {
209
3.98M
    float all =
210
3.98M
        hfNonZeros[0] + hfNonZeros[1] + hfNonZeros[2] + hfNonZeros[3] + 1;
211
3.98M
    float mul[3] = {70, 30, 60};
212
3.98M
    if (mul[c] * sum_of_highest_freq_row_and_column >= all) {
213
460k
      *quant += mul[c] * sum_of_highest_freq_row_and_column / all;
214
460k
      if (*quant >= Quantizer::kQuantMax) {
215
0
        *quant = Quantizer::kQuantMax - 1;
216
0
      }
217
460k
    }
218
3.98M
  }
219
3.98M
  if (quant_kind == AcStrategyType::DCT) {
220
    // If this 8x8 block is too flat, increase the adaptive quantization level
221
    // a bit to reduce visible block boundaries and requantize the block.
222
2.75M
    if (hfNonZeros[0] + hfNonZeros[1] + hfNonZeros[2] + hfNonZeros[3] < 11) {
223
1.20M
      *quant += 1;
224
1.20M
      if (*quant >= Quantizer::kQuantMax) {
225
0
        *quant = Quantizer::kQuantMax - 1;
226
0
      }
227
1.20M
    }
228
2.75M
  }
229
3.98M
  {
230
3.98M
    static const double kMul1[4][3] = {
231
3.98M
        {
232
3.98M
            0.22080615753848404,
233
3.98M
            0.45797479824262011,
234
3.98M
            0.29859235095977965,
235
3.98M
        },
236
3.98M
        {
237
3.98M
            0.70109486510286834,
238
3.98M
            0.16185281305512639,
239
3.98M
            0.14387691730035473,
240
3.98M
        },
241
3.98M
        {
242
3.98M
            0.114985964456218638,
243
3.98M
            0.44656840441027695,
244
3.98M
            0.10587658215149048,
245
3.98M
        },
246
3.98M
        {
247
3.98M
            0.46849665264409396,
248
3.98M
            0.41239077937781954,
249
3.98M
            0.088667407767185444,
250
3.98M
        },
251
3.98M
    };
252
3.98M
    static const double kMul2[4][3] = {
253
3.98M
        {
254
3.98M
            0.27450281941822197,
255
3.98M
            1.1255766549984996,
256
3.98M
            0.98950459134128388,
257
3.98M
        },
258
3.98M
        {
259
3.98M
            0.4652168675598285,
260
3.98M
            0.40945807983455818,
261
3.98M
            0.36581899811751367,
262
3.98M
        },
263
3.98M
        {
264
3.98M
            0.28034972424715715,
265
3.98M
            0.9182653201929738,
266
3.98M
            1.5581531543057416,
267
3.98M
        },
268
3.98M
        {
269
3.98M
            0.26873118114033728,
270
3.98M
            0.68863712390392484,
271
3.98M
            1.2082185408666786,
272
3.98M
        },
273
3.98M
    };
274
3.98M
    static const double kQuantNormalizer = 2.2942708343284721;
275
3.98M
    sum_of_error *= kQuantNormalizer;
276
3.98M
    sum_of_vals *= kQuantNormalizer;
277
3.98M
    if (quant_kind >= AcStrategyType::DCT16X16) {
278
1.22M
      int ix = 3;
279
1.22M
      if (quant_kind == AcStrategyType::DCT32X16 ||
280
1.16M
          quant_kind == AcStrategyType::DCT16X32) {
281
171k
        ix = 1;
282
1.05M
      } else if (quant_kind == AcStrategyType::DCT16X16) {
283
153k
        ix = 0;
284
901k
      } else if (quant_kind == AcStrategyType::DCT32X32) {
285
194k
        ix = 2;
286
194k
      }
287
1.22M
      int step =
288
1.22M
          sum_of_error / (kMul1[ix][c] * xsize * ysize * kBlockDim * kBlockDim +
289
1.22M
                          kMul2[ix][c] * sum_of_vals);
290
1.22M
      if (step >= 2) {
291
3.30k
        step = 2;
292
3.30k
      }
293
1.22M
      if (step < 0) {
294
0
        step = 0;
295
0
      }
296
1.22M
      if (sum_of_error > kMul1[ix][c] * xsize * ysize * kBlockDim * kBlockDim +
297
1.22M
                             kMul2[ix][c] * sum_of_vals) {
298
41.7k
        *quant += step;
299
41.7k
        if (*quant >= Quantizer::kQuantMax) {
300
0
          *quant = Quantizer::kQuantMax - 1;
301
0
        }
302
41.7k
      }
303
1.22M
    }
304
3.98M
  }
305
3.98M
  {
306
    // Reduce quant in highly active areas.
307
3.98M
    int32_t div = (xsize * ysize);
308
3.98M
    float min_hf_non_zeros =
309
3.98M
        std::min({hfNonZeros[0], hfNonZeros[1], hfNonZeros[2], hfNonZeros[3]});
310
3.98M
    int32_t activity = 15;
311
3.98M
    if (min_hf_non_zeros < 15.0f * div) {
312
3.84M
      activity = (static_cast<int32_t>(min_hf_non_zeros) + div / 2) / div;
313
3.84M
    }
314
3.98M
    int32_t qp = *quant - activity;
315
3.98M
    if (c == 1) {
316
5.31M
      for (int i = 1; i < 4; ++i) {
317
3.98M
        thresholds[i] += 0.01 * activity;
318
3.98M
      }
319
1.32M
    }
320
3.98M
    int32_t orig_qp_limit = std::max(4, *quant / 2);
321
3.98M
    if (qp < orig_qp_limit) {
322
993k
      qp = orig_qp_limit;
323
993k
    }
324
3.98M
    *quant = qp;
325
3.98M
  }
326
3.98M
}
Unexecuted instantiation: jxl::N_SSE4::AdjustQuantBlockAC(jxl::Quantizer const&, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int*)
jxl::N_AVX2::AdjustQuantBlockAC(jxl::Quantizer const&, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int*)
Line
Count
Source
107
8.30M
                        const float* JXL_RESTRICT block_in, int32_t* quant) {
108
  // No quantization adjusting for these small blocks.
109
  // Quantization adjusting attempts to fix some known issues
110
  // with larger blocks and on the 8x8 dct's emerging 8x8 blockiness
111
  // when there are not many non-zeros.
112
8.30M
  constexpr size_t kPartialBlockKinds =
113
8.30M
      (1 << static_cast<size_t>(AcStrategyType::IDENTITY)) |
114
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT2X2)) |
115
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT4X4)) |
116
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT4X8)) |
117
8.30M
      (1 << static_cast<size_t>(AcStrategyType::DCT8X4)) |
118
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV0)) |
119
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV1)) |
120
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV2)) |
121
8.30M
      (1 << static_cast<size_t>(AcStrategyType::AFV3));
122
8.30M
  if ((1 << static_cast<size_t>(quant_kind)) & kPartialBlockKinds) {
123
4.32M
    return;
124
4.32M
  }
125
126
3.98M
  const float* JXL_RESTRICT qm = quantizer.InvDequantMatrix(quant_kind, c);
127
3.98M
  float qac = quantizer.Scale() * (*quant);
128
3.98M
  if (xsize > 1 || ysize > 1) {
129
6.13M
    for (int i = 0; i < 4; ++i) {
130
4.90M
      thresholds[i] -= Clamp1(0.003f * xsize * ysize, 0.f, 0.08f);
131
4.90M
      if (thresholds[i] < 0.54) {
132
262k
        thresholds[i] = 0.54;
133
262k
      }
134
4.90M
    }
135
1.22M
  }
136
3.98M
  float sum_of_highest_freq_row_and_column = 0;
137
3.98M
  float sum_of_error = 0;
138
3.98M
  float sum_of_vals = 0;
139
3.98M
  float hfNonZeros[4] = {};
140
3.98M
  float hfMaxError[4] = {};
141
142
46.4M
  for (size_t y = 0; y < ysize * kBlockDim; y++) {
143
872M
    for (size_t x = 0; x < xsize * kBlockDim; x++) {
144
830M
      const size_t pos = y * kBlockDim * xsize + x;
145
830M
      if (x < xsize && y < ysize) {
146
12.9M
        continue;
147
12.9M
      }
148
817M
      const size_t hfix = (static_cast<size_t>(y >= ysize * kBlockDim / 2) * 2 +
149
817M
                           static_cast<size_t>(x >= xsize * kBlockDim / 2));
150
817M
      const float val = block_in[pos] * (qm[pos] * qac * qm_multiplier);
151
817M
      const float v = (std::abs(val) < thresholds[hfix]) ? 0 : rintf(val);
152
817M
      const float error = std::abs(val - v);
153
817M
      sum_of_error += error;
154
817M
      sum_of_vals += std::abs(v);
155
817M
      if (c == 1 && v == 0) {
156
233M
        if (hfMaxError[hfix] < error) {
157
13.7M
          hfMaxError[hfix] = error;
158
13.7M
        }
159
233M
      }
160
817M
      if (v != 0.0f) {
161
61.6M
        hfNonZeros[hfix] += std::abs(v);
162
61.6M
        bool in_corner = y >= 7 * ysize && x >= 7 * xsize;
163
61.6M
        bool on_border =
164
61.6M
            y == ysize * kBlockDim - 1 || x == xsize * kBlockDim - 1;
165
61.6M
        bool in_larger_corner = x >= 4 * xsize && y >= 4 * ysize;
166
61.6M
        if (in_corner || (on_border && in_larger_corner)) {
167
1.83M
          sum_of_highest_freq_row_and_column += std::abs(val);
168
1.83M
        }
169
61.6M
      }
170
817M
    }
171
42.4M
  }
172
3.98M
  if (c == 1 && sum_of_vals * 8 < xsize * ysize) {
173
364k
    static const double kLimit[4] = {
174
364k
        0.46,
175
364k
        0.46,
176
364k
        0.46,
177
364k
        0.46,
178
364k
    };
179
364k
    static const double kMul[4] = {
180
364k
        0.9999,
181
364k
        0.9999,
182
364k
        0.9999,
183
364k
        0.9999,
184
364k
    };
185
364k
    const int32_t orig_quant = *quant;
186
364k
    int32_t new_quant = *quant;
187
1.45M
    for (int i = 1; i < 4; ++i) {
188
1.08M
      if (hfNonZeros[i] == 0.0 && hfMaxError[i] > kLimit[i]) {
189
3.13k
        new_quant = orig_quant + 1;
190
3.13k
        break;
191
3.13k
      }
192
1.08M
    }
193
364k
    *quant = new_quant;
194
364k
    if (hfNonZeros[3] == 0.0 && hfMaxError[3] > kLimit[3]) {
195
473
      thresholds[3] = kMul[3] * hfMaxError[3] * new_quant / orig_quant;
196
364k
    } else if ((hfNonZeros[1] == 0.0 && hfMaxError[1] > kLimit[1]) ||
197
362k
               (hfNonZeros[2] == 0.0 && hfMaxError[2] > kLimit[2])) {
198
2.66k
      thresholds[1] = kMul[1] * std::max(hfMaxError[1], hfMaxError[2]) *
199
2.66k
                      new_quant / orig_quant;
200
2.66k
      thresholds[2] = thresholds[1];
201
361k
    } else if (hfNonZeros[0] == 0.0 && hfMaxError[0] > kLimit[0]) {
202
13.7k
      thresholds[0] = kMul[0] * hfMaxError[0] * new_quant / orig_quant;
203
13.7k
    }
204
364k
  }
205
  // Heuristic for improving accuracy of high-frequency patterns
206
  // occurring in an environment with no medium-frequency masking
207
  // patterns.
208
3.98M
  {
209
3.98M
    float all =
210
3.98M
        hfNonZeros[0] + hfNonZeros[1] + hfNonZeros[2] + hfNonZeros[3] + 1;
211
3.98M
    float mul[3] = {70, 30, 60};
212
3.98M
    if (mul[c] * sum_of_highest_freq_row_and_column >= all) {
213
460k
      *quant += mul[c] * sum_of_highest_freq_row_and_column / all;
214
460k
      if (*quant >= Quantizer::kQuantMax) {
215
0
        *quant = Quantizer::kQuantMax - 1;
216
0
      }
217
460k
    }
218
3.98M
  }
219
3.98M
  if (quant_kind == AcStrategyType::DCT) {
220
    // If this 8x8 block is too flat, increase the adaptive quantization level
221
    // a bit to reduce visible block boundaries and requantize the block.
222
2.75M
    if (hfNonZeros[0] + hfNonZeros[1] + hfNonZeros[2] + hfNonZeros[3] < 11) {
223
1.20M
      *quant += 1;
224
1.20M
      if (*quant >= Quantizer::kQuantMax) {
225
0
        *quant = Quantizer::kQuantMax - 1;
226
0
      }
227
1.20M
    }
228
2.75M
  }
229
3.98M
  {
230
3.98M
    static const double kMul1[4][3] = {
231
3.98M
        {
232
3.98M
            0.22080615753848404,
233
3.98M
            0.45797479824262011,
234
3.98M
            0.29859235095977965,
235
3.98M
        },
236
3.98M
        {
237
3.98M
            0.70109486510286834,
238
3.98M
            0.16185281305512639,
239
3.98M
            0.14387691730035473,
240
3.98M
        },
241
3.98M
        {
242
3.98M
            0.114985964456218638,
243
3.98M
            0.44656840441027695,
244
3.98M
            0.10587658215149048,
245
3.98M
        },
246
3.98M
        {
247
3.98M
            0.46849665264409396,
248
3.98M
            0.41239077937781954,
249
3.98M
            0.088667407767185444,
250
3.98M
        },
251
3.98M
    };
252
3.98M
    static const double kMul2[4][3] = {
253
3.98M
        {
254
3.98M
            0.27450281941822197,
255
3.98M
            1.1255766549984996,
256
3.98M
            0.98950459134128388,
257
3.98M
        },
258
3.98M
        {
259
3.98M
            0.4652168675598285,
260
3.98M
            0.40945807983455818,
261
3.98M
            0.36581899811751367,
262
3.98M
        },
263
3.98M
        {
264
3.98M
            0.28034972424715715,
265
3.98M
            0.9182653201929738,
266
3.98M
            1.5581531543057416,
267
3.98M
        },
268
3.98M
        {
269
3.98M
            0.26873118114033728,
270
3.98M
            0.68863712390392484,
271
3.98M
            1.2082185408666786,
272
3.98M
        },
273
3.98M
    };
274
3.98M
    static const double kQuantNormalizer = 2.2942708343284721;
275
3.98M
    sum_of_error *= kQuantNormalizer;
276
3.98M
    sum_of_vals *= kQuantNormalizer;
277
3.98M
    if (quant_kind >= AcStrategyType::DCT16X16) {
278
1.22M
      int ix = 3;
279
1.22M
      if (quant_kind == AcStrategyType::DCT32X16 ||
280
1.16M
          quant_kind == AcStrategyType::DCT16X32) {
281
171k
        ix = 1;
282
1.05M
      } else if (quant_kind == AcStrategyType::DCT16X16) {
283
153k
        ix = 0;
284
901k
      } else if (quant_kind == AcStrategyType::DCT32X32) {
285
194k
        ix = 2;
286
194k
      }
287
1.22M
      int step =
288
1.22M
          sum_of_error / (kMul1[ix][c] * xsize * ysize * kBlockDim * kBlockDim +
289
1.22M
                          kMul2[ix][c] * sum_of_vals);
290
1.22M
      if (step >= 2) {
291
3.30k
        step = 2;
292
3.30k
      }
293
1.22M
      if (step < 0) {
294
0
        step = 0;
295
0
      }
296
1.22M
      if (sum_of_error > kMul1[ix][c] * xsize * ysize * kBlockDim * kBlockDim +
297
1.22M
                             kMul2[ix][c] * sum_of_vals) {
298
41.7k
        *quant += step;
299
41.7k
        if (*quant >= Quantizer::kQuantMax) {
300
0
          *quant = Quantizer::kQuantMax - 1;
301
0
        }
302
41.7k
      }
303
1.22M
    }
304
3.98M
  }
305
3.98M
  {
306
    // Reduce quant in highly active areas.
307
3.98M
    int32_t div = (xsize * ysize);
308
3.98M
    float min_hf_non_zeros =
309
3.98M
        std::min({hfNonZeros[0], hfNonZeros[1], hfNonZeros[2], hfNonZeros[3]});
310
3.98M
    int32_t activity = 15;
311
3.98M
    if (min_hf_non_zeros < 15.0f * div) {
312
3.84M
      activity = (static_cast<int32_t>(min_hf_non_zeros) + div / 2) / div;
313
3.84M
    }
314
3.98M
    int32_t qp = *quant - activity;
315
3.98M
    if (c == 1) {
316
5.31M
      for (int i = 1; i < 4; ++i) {
317
3.98M
        thresholds[i] += 0.01 * activity;
318
3.98M
      }
319
1.32M
    }
320
3.98M
    int32_t orig_qp_limit = std::max(4, *quant / 2);
321
3.98M
    if (qp < orig_qp_limit) {
322
993k
      qp = orig_qp_limit;
323
993k
    }
324
3.98M
    *quant = qp;
325
3.98M
  }
326
3.98M
}
Unexecuted instantiation: jxl::N_AVX3::AdjustQuantBlockAC(jxl::Quantizer const&, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int*)
Unexecuted instantiation: jxl::N_AVX3_ZEN4::AdjustQuantBlockAC(jxl::Quantizer const&, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int*)
Unexecuted instantiation: jxl::N_AVX3_SPR::AdjustQuantBlockAC(jxl::Quantizer const&, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int*)
Unexecuted instantiation: jxl::N_SSE2::AdjustQuantBlockAC(jxl::Quantizer const&, unsigned long, float, jxl::AcStrategyType, unsigned long, unsigned long, float*, float const*, int*)
327
328
// NOTE: caller takes care of extracting quant from rect of RawQuantField.
329
void QuantizeRoundtripYBlockAC(PassesEncoderState* enc_state, const size_t size,
330
                               const Quantizer& quantizer,
331
                               const bool error_diffusion,
332
                               AcStrategyType quant_kind, size_t xsize,
333
                               size_t ysize, const float* JXL_RESTRICT biases,
334
                               int32_t* quant, float* JXL_RESTRICT inout,
335
2.76M
                               int32_t* JXL_RESTRICT quantized) {
336
2.76M
  float thres_y[4] = {0.58f, 0.64f, 0.64f, 0.64f};
337
2.76M
  if (enc_state->cparams.speed_tier <= SpeedTier::kHare) {
338
2.76M
    int32_t max_quant = 0;
339
2.76M
    int quant_orig = *quant;
340
2.76M
    float val[3] = {enc_state->x_qm_multiplier, 1.0f,
341
2.76M
                    enc_state->b_qm_multiplier};
342
8.30M
    for (int c : {1, 0, 2}) {
343
8.30M
      float thres[4] = {0.58f, 0.64f, 0.64f, 0.64f};
344
8.30M
      *quant = quant_orig;
345
8.30M
      AdjustQuantBlockAC(quantizer, c, val[c], quant_kind, xsize, ysize,
346
8.30M
                         &thres[0], inout + c * size, quant);
347
      // Dead zone adjustment
348
8.30M
      if (c == 1) {
349
13.8M
        for (int k = 0; k < 4; ++k) {
350
11.0M
          thres_y[k] = thres[k];
351
11.0M
        }
352
2.76M
      }
353
8.30M
      max_quant = std::max(*quant, max_quant);
354
8.30M
    }
355
2.76M
    *quant = max_quant;
356
2.76M
  } else {
357
0
    thres_y[0] = 0.56;
358
0
    thres_y[1] = 0.62;
359
0
    thres_y[2] = 0.62;
360
0
    thres_y[3] = 0.62;
361
0
  }
362
363
2.76M
  QuantizeBlockAC(quantizer, error_diffusion, 1, 1.0f, quant_kind, xsize, ysize,
364
2.76M
                  &thres_y[0], inout + size, quant, quantized + size);
365
366
2.76M
  const float* JXL_RESTRICT dequant_matrix =
367
2.76M
      quantizer.DequantMatrix(quant_kind, 1);
368
369
2.76M
  HWY_CAPPED(float, kDCTBlockSize) df;
370
2.76M
  HWY_CAPPED(int32_t, kDCTBlockSize) di;
371
2.76M
  const auto inv_qac = Set(df, quantizer.inv_quant_ac(*quant));
372
48.9M
  for (size_t k = 0; k < kDCTBlockSize * xsize * ysize; k += Lanes(df)) {
373
46.1M
    const auto oquant = Load(di, quantized + size + k);
374
46.1M
    const auto adj_quant = AdjustQuantBias(di, 1, oquant, biases);
375
46.1M
    const auto dequantm = Load(df, dequant_matrix + k);
376
46.1M
    Store(Mul(Mul(adj_quant, dequantm), inv_qac), df, inout + size + k);
377
46.1M
  }
378
2.76M
}
Unexecuted instantiation: jxl::N_SSE4::QuantizeRoundtripYBlockAC(jxl::PassesEncoderState*, unsigned long, jxl::Quantizer const&, bool, jxl::AcStrategyType, unsigned long, unsigned long, float const*, int*, float*, int*)
jxl::N_AVX2::QuantizeRoundtripYBlockAC(jxl::PassesEncoderState*, unsigned long, jxl::Quantizer const&, bool, jxl::AcStrategyType, unsigned long, unsigned long, float const*, int*, float*, int*)
Line
Count
Source
335
2.76M
                               int32_t* JXL_RESTRICT quantized) {
336
2.76M
  float thres_y[4] = {0.58f, 0.64f, 0.64f, 0.64f};
337
2.76M
  if (enc_state->cparams.speed_tier <= SpeedTier::kHare) {
338
2.76M
    int32_t max_quant = 0;
339
2.76M
    int quant_orig = *quant;
340
2.76M
    float val[3] = {enc_state->x_qm_multiplier, 1.0f,
341
2.76M
                    enc_state->b_qm_multiplier};
342
8.30M
    for (int c : {1, 0, 2}) {
343
8.30M
      float thres[4] = {0.58f, 0.64f, 0.64f, 0.64f};
344
8.30M
      *quant = quant_orig;
345
8.30M
      AdjustQuantBlockAC(quantizer, c, val[c], quant_kind, xsize, ysize,
346
8.30M
                         &thres[0], inout + c * size, quant);
347
      // Dead zone adjustment
348
8.30M
      if (c == 1) {
349
13.8M
        for (int k = 0; k < 4; ++k) {
350
11.0M
          thres_y[k] = thres[k];
351
11.0M
        }
352
2.76M
      }
353
8.30M
      max_quant = std::max(*quant, max_quant);
354
8.30M
    }
355
2.76M
    *quant = max_quant;
356
2.76M
  } else {
357
0
    thres_y[0] = 0.56;
358
0
    thres_y[1] = 0.62;
359
0
    thres_y[2] = 0.62;
360
0
    thres_y[3] = 0.62;
361
0
  }
362
363
2.76M
  QuantizeBlockAC(quantizer, error_diffusion, 1, 1.0f, quant_kind, xsize, ysize,
364
2.76M
                  &thres_y[0], inout + size, quant, quantized + size);
365
366
2.76M
  const float* JXL_RESTRICT dequant_matrix =
367
2.76M
      quantizer.DequantMatrix(quant_kind, 1);
368
369
2.76M
  HWY_CAPPED(float, kDCTBlockSize) df;
370
2.76M
  HWY_CAPPED(int32_t, kDCTBlockSize) di;
371
2.76M
  const auto inv_qac = Set(df, quantizer.inv_quant_ac(*quant));
372
48.9M
  for (size_t k = 0; k < kDCTBlockSize * xsize * ysize; k += Lanes(df)) {
373
46.1M
    const auto oquant = Load(di, quantized + size + k);
374
46.1M
    const auto adj_quant = AdjustQuantBias(di, 1, oquant, biases);
375
46.1M
    const auto dequantm = Load(df, dequant_matrix + k);
376
46.1M
    Store(Mul(Mul(adj_quant, dequantm), inv_qac), df, inout + size + k);
377
46.1M
  }
378
2.76M
}
Unexecuted instantiation: jxl::N_AVX3::QuantizeRoundtripYBlockAC(jxl::PassesEncoderState*, unsigned long, jxl::Quantizer const&, bool, jxl::AcStrategyType, unsigned long, unsigned long, float const*, int*, float*, int*)
Unexecuted instantiation: jxl::N_AVX3_ZEN4::QuantizeRoundtripYBlockAC(jxl::PassesEncoderState*, unsigned long, jxl::Quantizer const&, bool, jxl::AcStrategyType, unsigned long, unsigned long, float const*, int*, float*, int*)
Unexecuted instantiation: jxl::N_AVX3_SPR::QuantizeRoundtripYBlockAC(jxl::PassesEncoderState*, unsigned long, jxl::Quantizer const&, bool, jxl::AcStrategyType, unsigned long, unsigned long, float const*, int*, float*, int*)
Unexecuted instantiation: jxl::N_SSE2::QuantizeRoundtripYBlockAC(jxl::PassesEncoderState*, unsigned long, jxl::Quantizer const&, bool, jxl::AcStrategyType, unsigned long, unsigned long, float const*, int*, float*, int*)
379
380
Status ComputeCoefficients(size_t group_idx, PassesEncoderState* enc_state,
381
                           const Image3F& opsin, const Rect& rect,
382
9.40k
                           Image3F* dc) {
383
9.40k
  JxlMemoryManager* memory_manager = opsin.memory_manager();
384
9.40k
  const Rect block_group_rect =
385
9.40k
      enc_state->shared.frame_dim.BlockGroupRect(group_idx);
386
9.40k
  const Rect cmap_rect(
387
9.40k
      block_group_rect.x0() / kColorTileDimInBlocks,
388
9.40k
      block_group_rect.y0() / kColorTileDimInBlocks,
389
9.40k
      DivCeil(block_group_rect.xsize(), kColorTileDimInBlocks),
390
9.40k
      DivCeil(block_group_rect.ysize(), kColorTileDimInBlocks));
391
9.40k
  const Rect group_rect =
392
9.40k
      enc_state->shared.frame_dim.GroupRect(group_idx).Translate(rect.x0(),
393
9.40k
                                                                 rect.y0());
394
395
9.40k
  const size_t xsize_blocks = block_group_rect.xsize();
396
9.40k
  const size_t ysize_blocks = block_group_rect.ysize();
397
398
9.40k
  const size_t dc_stride = static_cast<size_t>(dc->PixelsPerRow());
399
9.40k
  const size_t opsin_stride = static_cast<size_t>(opsin.PixelsPerRow());
400
401
9.40k
  ImageI& full_quant_field = enc_state->shared.raw_quant_field;
402
9.40k
  const CompressParams& cparams = enc_state->cparams;
403
404
9.40k
  const size_t dct_scratch_size =
405
9.40k
      3 * (MaxVectorSize() / sizeof(float)) * AcStrategy::kMaxBlockDim;
406
407
  // TODO(veluca): consider strategies to reduce this memory.
408
9.40k
  size_t mem_bytes = 3 * AcStrategy::kMaxCoeffArea * sizeof(int32_t);
409
9.40k
  JXL_ASSIGN_OR_RETURN(auto mem,
410
9.40k
                       AlignedMemory::Create(memory_manager, mem_bytes));
411
9.40k
  size_t fmem_bytes =
412
9.40k
      (5 * AcStrategy::kMaxCoeffArea + dct_scratch_size) * sizeof(float);
413
9.40k
  JXL_ASSIGN_OR_RETURN(auto fmem,
414
9.40k
                       AlignedMemory::Create(memory_manager, fmem_bytes));
415
9.40k
  float* JXL_RESTRICT scratch_space =
416
9.40k
      fmem.address<float>() + 3 * AcStrategy::kMaxCoeffArea;
417
9.40k
  {
418
    // Only use error diffusion in Squirrel mode or slower.
419
9.40k
    const bool error_diffusion = cparams.speed_tier <= SpeedTier::kSquirrel;
420
9.40k
    constexpr HWY_CAPPED(float, kDCTBlockSize) d;
421
422
9.40k
    int32_t* JXL_RESTRICT coeffs[3][kMaxNumPasses] = {};
423
9.40k
    size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
424
9.40k
    JXL_ENSURE(num_passes > 0);
425
18.8k
    for (size_t i = 0; i < num_passes; i++) {
426
      // TODO(veluca): 16-bit quantized coeffs are not implemented yet.
427
9.40k
      JXL_ENSURE(enc_state->coeffs[i]->Type() == ACType::k32);
428
37.6k
      for (size_t c = 0; c < 3; c++) {
429
28.2k
        coeffs[c][i] = enc_state->coeffs[i]->PlaneRow(c, group_idx, 0).ptr32;
430
28.2k
      }
431
9.40k
    }
432
433
9.40k
    HWY_ALIGN float* coeffs_in = fmem.address<float>();
434
9.40k
    HWY_ALIGN int32_t* quantized = mem.address<int32_t>();
435
436
244k
    for (size_t by = 0; by < ysize_blocks; ++by) {
437
234k
      int32_t* JXL_RESTRICT row_quant_ac =
438
234k
          block_group_rect.Row(&full_quant_field, by);
439
234k
      size_t ty = by / kColorTileDimInBlocks;
440
234k
      const int8_t* JXL_RESTRICT row_cmap[3] = {
441
234k
          cmap_rect.ConstRow(enc_state->shared.cmap.ytox_map, ty),
442
234k
          nullptr,
443
234k
          cmap_rect.ConstRow(enc_state->shared.cmap.ytob_map, ty),
444
234k
      };
445
234k
      const float* JXL_RESTRICT opsin_rows[3] = {
446
234k
          group_rect.ConstPlaneRow(opsin, 0, by * kBlockDim),
447
234k
          group_rect.ConstPlaneRow(opsin, 1, by * kBlockDim),
448
234k
          group_rect.ConstPlaneRow(opsin, 2, by * kBlockDim),
449
234k
      };
450
234k
      float* JXL_RESTRICT dc_rows[3] = {
451
234k
          block_group_rect.PlaneRow(dc, 0, by),
452
234k
          block_group_rect.PlaneRow(dc, 1, by),
453
234k
          block_group_rect.PlaneRow(dc, 2, by),
454
234k
      };
455
234k
      AcStrategyRow ac_strategy_row =
456
234k
          enc_state->shared.ac_strategy.ConstRow(block_group_rect, by);
457
1.01M
      for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
458
779k
           tx++) {
459
779k
        const auto x_factor =
460
779k
            Set(d, enc_state->shared.cmap.base().YtoXRatio(row_cmap[0][tx]));
461
779k
        const auto b_factor =
462
779k
            Set(d, enc_state->shared.cmap.base().YtoBRatio(row_cmap[2][tx]));
463
779k
        for (size_t bx = tx * kColorTileDimInBlocks;
464
6.54M
             bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks; ++bx) {
465
5.76M
          const AcStrategy acs = ac_strategy_row[bx];
466
5.76M
          if (!acs.IsFirstBlock()) continue;
467
468
2.76M
          size_t xblocks = acs.covered_blocks_x();
469
2.76M
          size_t yblocks = acs.covered_blocks_y();
470
471
2.76M
          CoefficientLayout(&yblocks, &xblocks);
472
473
2.76M
          size_t size = kDCTBlockSize * xblocks * yblocks;
474
475
          // DCT Y channel, roundtrip-quantize it and set DC.
476
2.76M
          int32_t quant_ac = row_quant_ac[bx];
477
8.30M
          for (size_t c : {0, 1, 2}) {
478
8.30M
            TransformFromPixels(acs.Strategy(), opsin_rows[c] + bx * kBlockDim,
479
8.30M
                                opsin_stride, coeffs_in + c * size,
480
8.30M
                                scratch_space);
481
8.30M
          }
482
2.76M
          DCFromLowestFrequencies(acs.Strategy(), coeffs_in + size,
483
2.76M
                                  dc_rows[1] + bx, dc_stride, scratch_space);
484
485
2.76M
          QuantizeRoundtripYBlockAC(
486
2.76M
              enc_state, size, enc_state->shared.quantizer, error_diffusion,
487
2.76M
              acs.Strategy(), xblocks, yblocks, kDefaultQuantBias, &quant_ac,
488
2.76M
              coeffs_in, quantized);
489
490
          // Unapply color correlation
491
48.9M
          for (size_t k = 0; k < size; k += Lanes(d)) {
492
46.1M
            const auto in_x = Load(d, coeffs_in + k);
493
46.1M
            const auto in_y = Load(d, coeffs_in + size + k);
494
46.1M
            const auto in_b = Load(d, coeffs_in + 2 * size + k);
495
46.1M
            const auto out_x = NegMulAdd(x_factor, in_y, in_x);
496
46.1M
            const auto out_b = NegMulAdd(b_factor, in_y, in_b);
497
46.1M
            Store(out_x, d, coeffs_in + k);
498
46.1M
            Store(out_b, d, coeffs_in + 2 * size + k);
499
46.1M
          }
500
501
          // Quantize X and B channels and set DC.
502
5.53M
          for (size_t c : {0, 2}) {
503
5.53M
            float thres[4] = {0.58f, 0.62f, 0.62f, 0.62f};
504
5.53M
            QuantizeBlockAC(enc_state->shared.quantizer, error_diffusion, c,
505
5.53M
                            c == 0 ? enc_state->x_qm_multiplier
506
5.53M
                                   : enc_state->b_qm_multiplier,
507
5.53M
                            acs.Strategy(), xblocks, yblocks, &thres[0],
508
5.53M
                            coeffs_in + c * size, &quant_ac,
509
5.53M
                            quantized + c * size);
510
5.53M
            DCFromLowestFrequencies(acs.Strategy(), coeffs_in + c * size,
511
5.53M
                                    dc_rows[c] + bx, dc_stride, scratch_space);
512
5.53M
          }
513
2.76M
          row_quant_ac[bx] = quant_ac;
514
11.0M
          for (size_t c = 0; c < 3; c++) {
515
8.30M
            enc_state->progressive_splitter.SplitACCoefficients(
516
8.30M
                quantized + c * size, acs, bx, by, coeffs[c]);
517
16.6M
            for (size_t p = 0; p < num_passes; p++) {
518
8.30M
              coeffs[c][p] += size;
519
8.30M
            }
520
8.30M
          }
521
2.76M
        }
522
779k
      }
523
234k
    }
524
9.40k
  }
525
0
  return true;
526
9.40k
}
Unexecuted instantiation: jxl::N_SSE4::ComputeCoefficients(unsigned long, jxl::PassesEncoderState*, jxl::Image3<float> const&, jxl::RectT<unsigned long> const&, jxl::Image3<float>*)
jxl::N_AVX2::ComputeCoefficients(unsigned long, jxl::PassesEncoderState*, jxl::Image3<float> const&, jxl::RectT<unsigned long> const&, jxl::Image3<float>*)
Line
Count
Source
382
9.40k
                           Image3F* dc) {
383
9.40k
  JxlMemoryManager* memory_manager = opsin.memory_manager();
384
9.40k
  const Rect block_group_rect =
385
9.40k
      enc_state->shared.frame_dim.BlockGroupRect(group_idx);
386
9.40k
  const Rect cmap_rect(
387
9.40k
      block_group_rect.x0() / kColorTileDimInBlocks,
388
9.40k
      block_group_rect.y0() / kColorTileDimInBlocks,
389
9.40k
      DivCeil(block_group_rect.xsize(), kColorTileDimInBlocks),
390
9.40k
      DivCeil(block_group_rect.ysize(), kColorTileDimInBlocks));
391
9.40k
  const Rect group_rect =
392
9.40k
      enc_state->shared.frame_dim.GroupRect(group_idx).Translate(rect.x0(),
393
9.40k
                                                                 rect.y0());
394
395
9.40k
  const size_t xsize_blocks = block_group_rect.xsize();
396
9.40k
  const size_t ysize_blocks = block_group_rect.ysize();
397
398
9.40k
  const size_t dc_stride = static_cast<size_t>(dc->PixelsPerRow());
399
9.40k
  const size_t opsin_stride = static_cast<size_t>(opsin.PixelsPerRow());
400
401
9.40k
  ImageI& full_quant_field = enc_state->shared.raw_quant_field;
402
9.40k
  const CompressParams& cparams = enc_state->cparams;
403
404
9.40k
  const size_t dct_scratch_size =
405
9.40k
      3 * (MaxVectorSize() / sizeof(float)) * AcStrategy::kMaxBlockDim;
406
407
  // TODO(veluca): consider strategies to reduce this memory.
408
9.40k
  size_t mem_bytes = 3 * AcStrategy::kMaxCoeffArea * sizeof(int32_t);
409
9.40k
  JXL_ASSIGN_OR_RETURN(auto mem,
410
9.40k
                       AlignedMemory::Create(memory_manager, mem_bytes));
411
9.40k
  size_t fmem_bytes =
412
9.40k
      (5 * AcStrategy::kMaxCoeffArea + dct_scratch_size) * sizeof(float);
413
9.40k
  JXL_ASSIGN_OR_RETURN(auto fmem,
414
9.40k
                       AlignedMemory::Create(memory_manager, fmem_bytes));
415
9.40k
  float* JXL_RESTRICT scratch_space =
416
9.40k
      fmem.address<float>() + 3 * AcStrategy::kMaxCoeffArea;
417
9.40k
  {
418
    // Only use error diffusion in Squirrel mode or slower.
419
9.40k
    const bool error_diffusion = cparams.speed_tier <= SpeedTier::kSquirrel;
420
9.40k
    constexpr HWY_CAPPED(float, kDCTBlockSize) d;
421
422
9.40k
    int32_t* JXL_RESTRICT coeffs[3][kMaxNumPasses] = {};
423
9.40k
    size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
424
9.40k
    JXL_ENSURE(num_passes > 0);
425
18.8k
    for (size_t i = 0; i < num_passes; i++) {
426
      // TODO(veluca): 16-bit quantized coeffs are not implemented yet.
427
9.40k
      JXL_ENSURE(enc_state->coeffs[i]->Type() == ACType::k32);
428
37.6k
      for (size_t c = 0; c < 3; c++) {
429
28.2k
        coeffs[c][i] = enc_state->coeffs[i]->PlaneRow(c, group_idx, 0).ptr32;
430
28.2k
      }
431
9.40k
    }
432
433
9.40k
    HWY_ALIGN float* coeffs_in = fmem.address<float>();
434
9.40k
    HWY_ALIGN int32_t* quantized = mem.address<int32_t>();
435
436
244k
    for (size_t by = 0; by < ysize_blocks; ++by) {
437
234k
      int32_t* JXL_RESTRICT row_quant_ac =
438
234k
          block_group_rect.Row(&full_quant_field, by);
439
234k
      size_t ty = by / kColorTileDimInBlocks;
440
234k
      const int8_t* JXL_RESTRICT row_cmap[3] = {
441
234k
          cmap_rect.ConstRow(enc_state->shared.cmap.ytox_map, ty),
442
234k
          nullptr,
443
234k
          cmap_rect.ConstRow(enc_state->shared.cmap.ytob_map, ty),
444
234k
      };
445
234k
      const float* JXL_RESTRICT opsin_rows[3] = {
446
234k
          group_rect.ConstPlaneRow(opsin, 0, by * kBlockDim),
447
234k
          group_rect.ConstPlaneRow(opsin, 1, by * kBlockDim),
448
234k
          group_rect.ConstPlaneRow(opsin, 2, by * kBlockDim),
449
234k
      };
450
234k
      float* JXL_RESTRICT dc_rows[3] = {
451
234k
          block_group_rect.PlaneRow(dc, 0, by),
452
234k
          block_group_rect.PlaneRow(dc, 1, by),
453
234k
          block_group_rect.PlaneRow(dc, 2, by),
454
234k
      };
455
234k
      AcStrategyRow ac_strategy_row =
456
234k
          enc_state->shared.ac_strategy.ConstRow(block_group_rect, by);
457
1.01M
      for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
458
779k
           tx++) {
459
779k
        const auto x_factor =
460
779k
            Set(d, enc_state->shared.cmap.base().YtoXRatio(row_cmap[0][tx]));
461
779k
        const auto b_factor =
462
779k
            Set(d, enc_state->shared.cmap.base().YtoBRatio(row_cmap[2][tx]));
463
779k
        for (size_t bx = tx * kColorTileDimInBlocks;
464
6.54M
             bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks; ++bx) {
465
5.76M
          const AcStrategy acs = ac_strategy_row[bx];
466
5.76M
          if (!acs.IsFirstBlock()) continue;
467
468
2.76M
          size_t xblocks = acs.covered_blocks_x();
469
2.76M
          size_t yblocks = acs.covered_blocks_y();
470
471
2.76M
          CoefficientLayout(&yblocks, &xblocks);
472
473
2.76M
          size_t size = kDCTBlockSize * xblocks * yblocks;
474
475
          // DCT Y channel, roundtrip-quantize it and set DC.
476
2.76M
          int32_t quant_ac = row_quant_ac[bx];
477
8.30M
          for (size_t c : {0, 1, 2}) {
478
8.30M
            TransformFromPixels(acs.Strategy(), opsin_rows[c] + bx * kBlockDim,
479
8.30M
                                opsin_stride, coeffs_in + c * size,
480
8.30M
                                scratch_space);
481
8.30M
          }
482
2.76M
          DCFromLowestFrequencies(acs.Strategy(), coeffs_in + size,
483
2.76M
                                  dc_rows[1] + bx, dc_stride, scratch_space);
484
485
2.76M
          QuantizeRoundtripYBlockAC(
486
2.76M
              enc_state, size, enc_state->shared.quantizer, error_diffusion,
487
2.76M
              acs.Strategy(), xblocks, yblocks, kDefaultQuantBias, &quant_ac,
488
2.76M
              coeffs_in, quantized);
489
490
          // Unapply color correlation
491
48.9M
          for (size_t k = 0; k < size; k += Lanes(d)) {
492
46.1M
            const auto in_x = Load(d, coeffs_in + k);
493
46.1M
            const auto in_y = Load(d, coeffs_in + size + k);
494
46.1M
            const auto in_b = Load(d, coeffs_in + 2 * size + k);
495
46.1M
            const auto out_x = NegMulAdd(x_factor, in_y, in_x);
496
46.1M
            const auto out_b = NegMulAdd(b_factor, in_y, in_b);
497
46.1M
            Store(out_x, d, coeffs_in + k);
498
46.1M
            Store(out_b, d, coeffs_in + 2 * size + k);
499
46.1M
          }
500
501
          // Quantize X and B channels and set DC.
502
5.53M
          for (size_t c : {0, 2}) {
503
5.53M
            float thres[4] = {0.58f, 0.62f, 0.62f, 0.62f};
504
5.53M
            QuantizeBlockAC(enc_state->shared.quantizer, error_diffusion, c,
505
5.53M
                            c == 0 ? enc_state->x_qm_multiplier
506
5.53M
                                   : enc_state->b_qm_multiplier,
507
5.53M
                            acs.Strategy(), xblocks, yblocks, &thres[0],
508
5.53M
                            coeffs_in + c * size, &quant_ac,
509
5.53M
                            quantized + c * size);
510
5.53M
            DCFromLowestFrequencies(acs.Strategy(), coeffs_in + c * size,
511
5.53M
                                    dc_rows[c] + bx, dc_stride, scratch_space);
512
5.53M
          }
513
2.76M
          row_quant_ac[bx] = quant_ac;
514
11.0M
          for (size_t c = 0; c < 3; c++) {
515
8.30M
            enc_state->progressive_splitter.SplitACCoefficients(
516
8.30M
                quantized + c * size, acs, bx, by, coeffs[c]);
517
16.6M
            for (size_t p = 0; p < num_passes; p++) {
518
8.30M
              coeffs[c][p] += size;
519
8.30M
            }
520
8.30M
          }
521
2.76M
        }
522
779k
      }
523
234k
    }
524
9.40k
  }
525
0
  return true;
526
9.40k
}
Unexecuted instantiation: jxl::N_AVX3::ComputeCoefficients(unsigned long, jxl::PassesEncoderState*, jxl::Image3<float> const&, jxl::RectT<unsigned long> const&, jxl::Image3<float>*)
Unexecuted instantiation: jxl::N_AVX3_ZEN4::ComputeCoefficients(unsigned long, jxl::PassesEncoderState*, jxl::Image3<float> const&, jxl::RectT<unsigned long> const&, jxl::Image3<float>*)
Unexecuted instantiation: jxl::N_AVX3_SPR::ComputeCoefficients(unsigned long, jxl::PassesEncoderState*, jxl::Image3<float> const&, jxl::RectT<unsigned long> const&, jxl::Image3<float>*)
Unexecuted instantiation: jxl::N_SSE2::ComputeCoefficients(unsigned long, jxl::PassesEncoderState*, jxl::Image3<float> const&, jxl::RectT<unsigned long> const&, jxl::Image3<float>*)
527
528
// NOLINTNEXTLINE(google-readability-namespace-comments)
529
}  // namespace HWY_NAMESPACE
530
}  // namespace jxl
531
HWY_AFTER_NAMESPACE();
532
533
#if HWY_ONCE
534
namespace jxl {
535
HWY_EXPORT(ComputeCoefficients);
536
Status ComputeCoefficients(size_t group_idx, PassesEncoderState* enc_state,
537
                           const Image3F& opsin, const Rect& rect,
538
9.40k
                           Image3F* dc) {
539
9.40k
  return HWY_DYNAMIC_DISPATCH(ComputeCoefficients)(group_idx, enc_state, opsin,
540
9.40k
                                                   rect, dc);
541
9.40k
}
542
543
Status EncodeGroupTokenizedCoefficients(size_t group_idx, size_t pass_idx,
544
                                        size_t histogram_idx,
545
                                        const PassesEncoderState& enc_state,
546
9.40k
                                        BitWriter* writer, AuxOut* aux_out) {
547
  // Select which histogram to use among those of the current pass.
548
9.40k
  const size_t num_histograms = enc_state.shared.num_histograms;
549
  // num_histograms is 0 only for lossless.
550
9.40k
  JXL_ENSURE(num_histograms == 0 || histogram_idx < num_histograms);
551
9.40k
  size_t histo_selector_bits = CeilLog2Nonzero(num_histograms);
552
553
9.40k
  if (histo_selector_bits != 0) {
554
0
    JXL_RETURN_IF_ERROR(
555
0
        writer->WithMaxBits(histo_selector_bits, LayerType::Ac, aux_out, [&] {
556
0
          writer->Write(histo_selector_bits, histogram_idx);
557
0
          return true;
558
0
        }));
559
0
  }
560
9.40k
  size_t context_offset =
561
9.40k
      histogram_idx * enc_state.shared.block_ctx_map.NumACContexts();
562
9.40k
  JXL_RETURN_IF_ERROR(
563
9.40k
      WriteTokens(enc_state.passes[pass_idx].ac_tokens[group_idx],
564
9.40k
                  enc_state.passes[pass_idx].codes, context_offset, writer,
565
9.40k
                  LayerType::AcTokens, aux_out));
566
567
9.40k
  return true;
568
9.40k
}
569
570
}  // namespace jxl
571
#endif  // HWY_ONCE