Coverage Report

Created: 2026-09-14 07:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/enc_coeff_order.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 <jxl/memory_manager.h>
7
8
#include <algorithm>
9
#include <cmath>
10
#include <cstddef>
11
#include <cstdint>
12
#include <cstring>
13
#include <limits>
14
#include <utility>
15
#include <vector>
16
17
#include "lib/jxl/ac_strategy.h"
18
#include "lib/jxl/base/compiler_specific.h"
19
#include "lib/jxl/base/rect.h"
20
#include "lib/jxl/base/status.h"
21
#include "lib/jxl/coeff_order.h"
22
#include "lib/jxl/coeff_order_fwd.h"
23
#include "lib/jxl/common.h"
24
#include "lib/jxl/dct_util.h"
25
#include "lib/jxl/enc_ans.h"
26
#include "lib/jxl/enc_ans_params.h"
27
#include "lib/jxl/enc_bit_writer.h"
28
#include "lib/jxl/frame_dimensions.h"
29
#include "lib/jxl/lehmer_code.h"
30
#include "lib/jxl/memory_manager_internal.h"
31
32
namespace jxl {
33
34
struct AuxOut;
35
enum class LayerType : uint8_t;
36
37
std::pair<uint32_t, uint32_t> ComputeUsedOrders(
38
    const SpeedTier speed, const AcStrategyImage& ac_strategy,
39
5.00k
    const Rect& rect) {
40
  // No coefficient reordering in Falcon or faster.
41
  // Only uses DCT8 = 0, so bitfield = 1.
42
5.00k
  if (speed >= SpeedTier::kFalcon) return {1, 1};
43
44
5.00k
  uint32_t ret = 0;
45
5.00k
  uint32_t ret_customize = 0;
46
5.00k
  size_t xsize_blocks = rect.xsize();
47
5.00k
  size_t ysize_blocks = rect.ysize();
48
  // TODO(veluca): precompute when doing DCT.
49
223k
  for (size_t by = 0; by < ysize_blocks; ++by) {
50
218k
    AcStrategyRow acs_row = ac_strategy.ConstRow(rect, by);
51
7.88M
    for (size_t bx = 0; bx < xsize_blocks; ++bx) {
52
7.66M
      int ord = kStrategyOrder[acs_row[bx].RawStrategy()];
53
      // Do not customize coefficient orders for blocks bigger than 32x32.
54
7.66M
      ret |= 1u << ord;
55
7.66M
      if (ord > 6) {
56
1.71M
        continue;
57
1.71M
      }
58
5.95M
      ret_customize |= 1u << ord;
59
5.95M
    }
60
218k
  }
61
  // Use default orders for small images.
62
5.00k
  if (ac_strategy.xsize() < 5 && ac_strategy.ysize() < 5) return {ret, 0};
63
4.82k
  return {ret, ret_customize};
64
5.00k
}
65
66
Status ComputeCoeffOrder(SpeedTier speed, const ACImage& ac_image,
67
                         const AcStrategyImage& ac_strategy,
68
                         const FrameDimensions& frame_dim,
69
                         uint32_t& all_used_orders, uint32_t prev_used_acs,
70
                         uint32_t current_used_acs,
71
                         uint32_t current_used_orders,
72
5.00k
                         coeff_order_t* JXL_RESTRICT order) {
73
5.00k
  JxlMemoryManager* memory_manager = ac_strategy.memory_manager();
74
5.00k
  std::vector<int64_t> num_zeros(kCoeffOrderMaxSize);
75
  // If compressing at high speed and only using 8x8 DCTs, only consider a
76
  // subset of blocks.
77
5.00k
  double block_fraction = 1.0f;
78
  // TODO(veluca): figure out why sampling blocks if non-8x8s are used makes
79
  // encoding significantly less dense.
80
5.00k
  if (speed >= SpeedTier::kSquirrel && current_used_orders == 1) {
81
6
    block_fraction = 0.5f;
82
6
  }
83
  // No need to compute number of zero coefficients if all orders are the
84
  // default.
85
5.00k
  if (current_used_orders != 0) {
86
4.80k
    uint64_t threshold =
87
4.80k
        (std::numeric_limits<uint64_t>::max() >> 32) * block_fraction;
88
4.80k
    uint64_t s[2] = {static_cast<uint64_t>(0x94D049BB133111EBull),
89
4.80k
                     static_cast<uint64_t>(0xBF58476D1CE4E5B9ull)};
90
    // Xorshift128+ adapted from xorshift128+-inl.h
91
3.58M
    auto use_sample = [&]() {
92
3.58M
      auto s1 = s[0];
93
3.58M
      const auto s0 = s[1];
94
3.58M
      const auto bits = s1 + s0;  // b, c
95
3.58M
      s[0] = s0;
96
3.58M
      s1 ^= s1 << 23;
97
3.58M
      s1 ^= s0 ^ (s1 >> 18) ^ (s0 >> 5);
98
3.58M
      s[1] = s1;
99
3.58M
      return (bits >> 32) <= threshold;
100
3.58M
    };
101
102
    // Count number of zero coefficients, separately for each DCT band.
103
    // TODO(veluca): precompute when doing DCT.
104
16.8k
    for (size_t group_index = 0; group_index < frame_dim.num_groups;
105
12.0k
         group_index++) {
106
12.0k
      const size_t gx = group_index % frame_dim.xsize_groups;
107
12.0k
      const size_t gy = group_index / frame_dim.xsize_groups;
108
12.0k
      const Rect rect(gx * kGroupDimInBlocks, gy * kGroupDimInBlocks,
109
12.0k
                      kGroupDimInBlocks, kGroupDimInBlocks,
110
12.0k
                      frame_dim.xsize_blocks, frame_dim.ysize_blocks);
111
12.0k
      ConstACPtr rows[3];
112
12.0k
      ACType type = ac_image.Type();
113
48.2k
      for (size_t c = 0; c < 3; c++) {
114
36.1k
        rows[c] = ac_image.PlaneRow(c, group_index, 0);
115
36.1k
      }
116
12.0k
      size_t ac_offset = 0;
117
118
      // TODO(veluca): SIMDfy.
119
323k
      for (size_t by = 0; by < rect.ysize(); ++by) {
120
311k
        AcStrategyRow acs_row = ac_strategy.ConstRow(rect, by);
121
7.96M
        for (size_t bx = 0; bx < rect.xsize(); ++bx) {
122
7.64M
          AcStrategy acs = acs_row[bx];
123
7.64M
          if (!acs.IsFirstBlock()) continue;
124
3.58M
          if (!use_sample()) continue;
125
3.58M
          size_t size = kDCTBlockSize << acs.log2_covered_blocks();
126
14.3M
          for (size_t c = 0; c < 3; ++c) {
127
10.7M
            const size_t order_offset =
128
10.7M
                CoeffOrderOffset(kStrategyOrder[acs.RawStrategy()], c);
129
10.7M
            if (type == ACType::k16) {
130
0
              for (size_t k = 0; k < size; k++) {
131
0
                bool is_zero = rows[c].ptr16[ac_offset + k] == 0;
132
0
                num_zeros[order_offset + k] += is_zero ? 1 : 0;
133
0
              }
134
10.7M
            } else {
135
1.47G
              for (size_t k = 0; k < size; k++) {
136
1.46G
                bool is_zero = rows[c].ptr32[ac_offset + k] == 0;
137
1.46G
                num_zeros[order_offset + k] += is_zero ? 1 : 0;
138
1.46G
              }
139
10.7M
            }
140
            // Ensure LLFs are first in the order.
141
10.7M
            size_t cx = acs.covered_blocks_x();
142
10.7M
            size_t cy = acs.covered_blocks_y();
143
10.7M
            CoefficientLayout(&cy, &cx);
144
23.3M
            for (size_t iy = 0; iy < cy; iy++) {
145
35.5M
              for (size_t ix = 0; ix < cx; ix++) {
146
22.9M
                num_zeros[order_offset + iy * kBlockDim * cx + ix] = -1;
147
22.9M
              }
148
12.5M
            }
149
10.7M
          }
150
3.58M
          ac_offset += size;
151
3.58M
        }
152
311k
      }
153
12.0k
    }
154
4.80k
  }
155
5.00k
  struct PosAndCount {
156
5.00k
    uint32_t pos;
157
    // Saving index breaks the ties for non-stable sort
158
5.00k
    uint64_t count_and_idx;
159
5.00k
  };
160
5.00k
  size_t mem_bytes = AcStrategy::kMaxCoeffArea * sizeof(PosAndCount);
161
5.00k
  JXL_ASSIGN_OR_RETURN(auto mem,
162
5.00k
                       AlignedMemory::Create(memory_manager, mem_bytes));
163
164
5.00k
  std::vector<coeff_order_t> natural_order_buffer;
165
166
5.00k
  uint16_t computed = 0;
167
140k
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
168
135k
    uint8_t ord = kStrategyOrder[o];
169
135k
    if (computed & (1 << ord)) continue;
170
65.0k
    computed |= 1 << ord;
171
65.0k
    AcStrategy acs = AcStrategy::FromRawStrategy(o);
172
65.0k
    size_t sz = kDCTBlockSize * acs.covered_blocks_x() * acs.covered_blocks_y();
173
    // Expected maximal size is 256 x 256.
174
65.0k
    JXL_DASSERT(sz <= (1 << 16));
175
176
    // Do nothing for transforms that don't appear.
177
65.0k
    if ((1 << ord) & ~current_used_acs) continue;
178
179
    // Do nothing if we already committed to this custom order previously.
180
25.6k
    if ((1 << ord) & prev_used_acs) continue;
181
25.6k
    if ((1 << ord) & all_used_orders) continue;
182
183
25.6k
    if (natural_order_buffer.size() < sz) natural_order_buffer.resize(sz);
184
25.6k
    acs.ComputeNaturalCoeffOrder(natural_order_buffer.data());
185
186
    // Ensure natural coefficient order is not permuted if the order is
187
    // not transmitted.
188
25.6k
    if ((1 << ord) & ~current_used_orders) {
189
8.94k
      for (size_t c = 0; c < 3; c++) {
190
6.70k
        size_t offset = CoeffOrderOffset(ord, c);
191
6.70k
        JXL_ENSURE(CoeffOrderOffset(ord, c + 1) - offset == sz);
192
6.70k
        memcpy(&order[offset], natural_order_buffer.data(),
193
6.70k
               sz * sizeof(*order));
194
6.70k
      }
195
2.23k
      continue;
196
2.23k
    }
197
198
23.4k
    bool is_nondefault = false;
199
93.6k
    for (uint8_t c = 0; c < 3; c++) {
200
      // Apply zig-zag order.
201
70.2k
      PosAndCount* pos_and_val = mem.address<PosAndCount>();
202
70.2k
      size_t offset = CoeffOrderOffset(ord, c);
203
70.2k
      JXL_ENSURE(CoeffOrderOffset(ord, c + 1) - offset == sz);
204
70.2k
      float inv_sqrt_sz = 1.0f / std::sqrt(sz);
205
22.3M
      for (size_t i = 0; i < sz; ++i) {
206
22.2M
        size_t pos = natural_order_buffer[i];
207
22.2M
        pos_and_val[i].pos = pos;
208
        // We don't care for the exact number -> quantize number of zeros,
209
        // to get less permuted order.
210
22.2M
        uint64_t count = num_zeros[offset + pos] * inv_sqrt_sz + 0.1f;
211
        // Worst case: all dct8x8, all zeroes: count <= nb_pixels/64/8
212
        // nb_pixels is limited to 2^40 (Level 10 limit)
213
        // so count is limited to 2^31
214
22.2M
        JXL_DASSERT(count < (uint64_t{1} << 48));
215
22.2M
        pos_and_val[i].count_and_idx = (count << 16) | i;
216
22.2M
      }
217
218
      // Stable-sort -> elements with same number of zeros will preserve their
219
      // order.
220
67.0M
      auto comparator = [](const PosAndCount& a, const PosAndCount& b) -> bool {
221
67.0M
        return a.count_and_idx < b.count_and_idx;
222
67.0M
      };
223
70.2k
      std::sort(pos_and_val, pos_and_val + sz, comparator);
224
225
      // Grab indices.
226
22.3M
      for (size_t i = 0; i < sz; ++i) {
227
22.2M
        order[offset + i] = pos_and_val[i].pos;
228
22.2M
        is_nondefault |= natural_order_buffer[i] != pos_and_val[i].pos;
229
22.2M
      }
230
70.2k
    }
231
23.4k
    if (!is_nondefault) {
232
10.1k
      current_used_orders &= ~(1 << ord);
233
10.1k
    }
234
23.4k
  }
235
5.00k
  all_used_orders |= current_used_orders;
236
5.00k
  return true;
237
5.00k
}
238
239
namespace {
240
241
Status TokenizePermutation(const coeff_order_t* JXL_RESTRICT order, size_t skip,
242
39.8k
                           size_t size, std::vector<Token>* tokens) {
243
39.8k
  std::vector<LehmerT> lehmer(size);
244
39.8k
  std::vector<uint32_t> temp(size + 1);
245
39.8k
  JXL_RETURN_IF_ERROR(
246
39.8k
      ComputeLehmerCode(order, temp.data(), size, lehmer.data()));
247
39.8k
  size_t end = size;
248
7.09M
  while (end > skip && lehmer[end - 1] == 0) {
249
7.05M
    --end;
250
7.05M
  }
251
39.8k
  tokens->emplace_back(CoeffOrderContext(size),
252
39.8k
                       static_cast<uint32_t>(end - skip));
253
39.8k
  uint32_t last = 0;
254
1.44M
  for (size_t i = skip; i < end; ++i) {
255
1.40M
    tokens->emplace_back(CoeffOrderContext(last), lehmer[i]);
256
1.40M
    last = lehmer[i];
257
1.40M
  }
258
39.8k
  return true;
259
39.8k
}
260
261
}  // namespace
262
263
Status EncodePermutation(const coeff_order_t* JXL_RESTRICT order, size_t skip,
264
                         size_t size, BitWriter* writer, LayerType layer,
265
0
                         AuxOut* aux_out) {
266
0
  JxlMemoryManager* memory_manager = writer->memory_manager();
267
0
  std::vector<std::vector<Token>> tokens(1);
268
0
  JXL_RETURN_IF_ERROR(TokenizePermutation(order, skip, size, tokens.data()));
269
0
  EntropyEncodingData codes;
270
0
  JXL_ASSIGN_OR_RETURN(
271
0
      size_t cost, BuildAndEncodeHistograms(memory_manager, HistogramParams(),
272
0
                                            kPermutationContexts, tokens,
273
0
                                            &codes, writer, layer, aux_out));
274
0
  (void)cost;
275
0
  JXL_RETURN_IF_ERROR(WriteTokens(tokens[0], codes, 0, writer, layer, aux_out));
276
0
  return true;
277
0
}
278
279
namespace {
280
Status EncodeCoeffOrder(const coeff_order_t* JXL_RESTRICT order, AcStrategy acs,
281
                        std::vector<Token>* tokens, coeff_order_t* order_zigzag,
282
39.8k
                        std::vector<coeff_order_t>& natural_order_lut) {
283
39.8k
  const size_t llf = acs.covered_blocks_x() * acs.covered_blocks_y();
284
39.8k
  const size_t size = kDCTBlockSize * llf;
285
8.62M
  for (size_t i = 0; i < size; ++i) {
286
8.58M
    order_zigzag[i] = natural_order_lut[order[i]];
287
8.58M
  }
288
39.8k
  JXL_RETURN_IF_ERROR(TokenizePermutation(order_zigzag, llf, size, tokens));
289
39.8k
  return true;
290
39.8k
}
291
}  // namespace
292
293
Status EncodeCoeffOrders(uint16_t used_orders,
294
                         const coeff_order_t* JXL_RESTRICT order,
295
                         BitWriter* writer, LayerType layer,
296
5.00k
                         AuxOut* JXL_RESTRICT aux_out) {
297
5.00k
  JxlMemoryManager* memory_manager = writer->memory_manager();
298
5.00k
  size_t mem_bytes = AcStrategy::kMaxCoeffArea * sizeof(coeff_order_t);
299
5.00k
  JXL_ASSIGN_OR_RETURN(auto mem,
300
5.00k
                       AlignedMemory::Create(memory_manager, mem_bytes));
301
5.00k
  uint16_t computed = 0;
302
5.00k
  std::vector<std::vector<Token>> tokens(1);
303
5.00k
  std::vector<coeff_order_t> natural_order_lut;
304
140k
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
305
135k
    uint8_t ord = kStrategyOrder[o];
306
135k
    if (computed & (1 << ord)) continue;
307
65.0k
    computed |= 1 << ord;
308
65.0k
    if ((used_orders & (1 << ord)) == 0) continue;
309
13.2k
    AcStrategy acs = AcStrategy::FromRawStrategy(o);
310
13.2k
    const size_t llf = acs.covered_blocks_x() * acs.covered_blocks_y();
311
13.2k
    const size_t size = kDCTBlockSize * llf;
312
13.2k
    if (natural_order_lut.size() < size) natural_order_lut.resize(size);
313
13.2k
    acs.ComputeNaturalCoeffOrderLut(natural_order_lut.data());
314
53.1k
    for (size_t c = 0; c < 3; c++) {
315
39.8k
      JXL_RETURN_IF_ERROR(
316
39.8k
          EncodeCoeffOrder(&order[CoeffOrderOffset(ord, c)], acs, tokens.data(),
317
39.8k
                           mem.address<coeff_order_t>(), natural_order_lut));
318
39.8k
    }
319
13.2k
  }
320
  // Do not write anything if no order is used.
321
5.00k
  if (used_orders != 0) {
322
4.12k
    EntropyEncodingData codes;
323
4.12k
    JXL_ASSIGN_OR_RETURN(
324
4.12k
        size_t cost, BuildAndEncodeHistograms(memory_manager, HistogramParams(),
325
4.12k
                                              kPermutationContexts, tokens,
326
4.12k
                                              &codes, writer, layer, aux_out));
327
4.12k
    (void)cost;
328
4.12k
    JXL_RETURN_IF_ERROR(
329
4.12k
        WriteTokens(tokens[0], codes, 0, writer, layer, aux_out));
330
4.12k
  }
331
5.00k
  return true;
332
5.00k
}
333
334
}  // namespace jxl