Coverage Report

Created: 2026-06-30 07:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/modular/encoding/encoding.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/modular/encoding/encoding.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <array>
12
#include <cstddef>
13
#include <cstdint>
14
#include <cstdlib>
15
#include <queue>
16
#include <utility>
17
#include <vector>
18
19
#include "lib/jxl/base/common.h"
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/printf_macros.h"
22
#include "lib/jxl/base/scope_guard.h"
23
#include "lib/jxl/base/status.h"
24
#include "lib/jxl/dec_ans.h"
25
#include "lib/jxl/dec_bit_reader.h"
26
#include "lib/jxl/fields.h"
27
#include "lib/jxl/frame_dimensions.h"
28
#include "lib/jxl/image_ops.h"
29
#include "lib/jxl/modular/encoding/context_predict.h"
30
#include "lib/jxl/modular/encoding/dec_ma.h"
31
#include "lib/jxl/modular/modular_image.h"
32
#include "lib/jxl/modular/options.h"
33
#include "lib/jxl/modular/transform/transform.h"
34
#include "lib/jxl/pack_signed.h"
35
36
namespace jxl {
37
38
// Removes all nodes that use a static property (i.e. channel or group ID) from
39
// the tree and collapses each node on even levels with its two children to
40
// produce a flatter tree. Also computes whether the resulting tree requires
41
// using the weighted predictor.
42
FlatTree FilterTree(const Tree &global_tree,
43
                    std::array<pixel_type, kNumStaticProperties> &static_props,
44
                    size_t *num_props, bool *use_wp, bool *wp_only,
45
452k
                    bool *gradient_only) {
46
452k
  *num_props = 0;
47
452k
  bool has_wp = false;
48
452k
  bool has_non_wp = false;
49
452k
  *gradient_only = true;
50
1.11M
  const auto mark_property = [&](int32_t p) {
51
1.11M
    if (p == kWPProp) {
52
106k
      has_wp = true;
53
1.00M
    } else if (p >= kNumStaticProperties) {
54
611k
      has_non_wp = true;
55
611k
    }
56
1.11M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
647k
      *gradient_only = false;
58
647k
    }
59
1.11M
  };
60
452k
  FlatTree output;
61
452k
  std::queue<size_t> nodes;
62
452k
  nodes.push(0);
63
  // Produces a trimmed and flattened tree by doing a BFS visit of the original
64
  // tree, ignoring branches that are known to be false and proceeding two
65
  // levels at a time to collapse nodes in a flatter tree; if an inner parent
66
  // node has a leaf as a child, the leaf is duplicated and an implicit fake
67
  // node is added. This allows to reduce the number of branches when traversing
68
  // the resulting flat tree.
69
2.39M
  while (!nodes.empty()) {
70
1.93M
    size_t cur = nodes.front();
71
1.93M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.99M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.62M
           global_tree[cur].property != -1) {
75
58.9k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
30.7k
        cur = global_tree[cur].lchild;
77
30.7k
      } else {
78
28.2k
        cur = global_tree[cur].rchild;
79
28.2k
      }
80
58.9k
    }
81
1.93M
    FlatDecisionNode flat;
82
1.93M
    if (global_tree[cur].property == -1) {
83
1.56M
      flat.property0 = -1;
84
1.56M
      flat.childID = global_tree[cur].lchild;
85
1.56M
      flat.predictor = global_tree[cur].predictor;
86
1.56M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.56M
      flat.multiplier = global_tree[cur].multiplier;
88
1.56M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.56M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.56M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.56M
      output.push_back(flat);
92
1.56M
      continue;
93
1.56M
    }
94
371k
    flat.childID = output.size() + nodes.size() + 1;
95
96
371k
    flat.property0 = global_tree[cur].property;
97
371k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
371k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.11M
    for (size_t i = 0; i < 2; i++) {
101
743k
      size_t cur_child =
102
743k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
765k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
418k
             global_tree[cur_child].property != -1) {
106
21.5k
        if (static_props[global_tree[cur_child].property] >
107
21.5k
            global_tree[cur_child].splitval) {
108
11.0k
          cur_child = global_tree[cur_child].lchild;
109
11.0k
        } else {
110
10.5k
          cur_child = global_tree[cur_child].rchild;
111
10.5k
        }
112
21.5k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
743k
      if (global_tree[cur_child].property == -1) {
116
397k
        flat.properties[i] = 0;
117
397k
        flat.splitvals[i] = 0;
118
397k
        nodes.push(cur_child);
119
397k
        nodes.push(cur_child);
120
397k
      } else {
121
346k
        flat.properties[i] = global_tree[cur_child].property;
122
346k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
346k
        nodes.push(global_tree[cur_child].lchild);
124
346k
        nodes.push(global_tree[cur_child].rchild);
125
346k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
346k
      }
127
743k
    }
128
129
743k
    for (int16_t property : flat.properties) mark_property(property);
130
371k
    mark_property(flat.property0);
131
371k
    output.push_back(flat);
132
371k
  }
133
452k
  if (*num_props > kNumNonrefProperties) {
134
2.46k
    *num_props =
135
2.46k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
2.46k
            kExtraPropsPerChannel +
137
2.46k
        kNumNonrefProperties;
138
450k
  } else {
139
450k
    *num_props = kNumNonrefProperties;
140
450k
  }
141
452k
  *use_wp = has_wp;
142
452k
  *wp_only = has_wp && !has_non_wp;
143
144
452k
  return output;
145
452k
}
146
147
namespace detail {
148
template <bool uses_lz77>
149
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
150
                                 const std::vector<uint8_t> &context_map,
151
                                 const Tree &global_tree,
152
                                 const weighted::Header &wp_header,
153
                                 pixel_type chan, size_t group_id,
154
                                 TreeLut<uint8_t, false, false> &tree_lut,
155
                                 Image *image, uint32_t &fl_run,
156
427k
                                 uint32_t &fl_v) {
157
427k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
427k
  Channel &channel = image->channel[chan];
159
160
427k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
427k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
427k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
427k
  bool tree_has_wp_prop_or_pred = false;
168
427k
  bool is_wp_only = false;
169
427k
  bool is_gradient_only = false;
170
427k
  size_t num_props;
171
427k
  FlatTree tree =
172
427k
      FilterTree(global_tree, static_props, &num_props,
173
427k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
602k
  for (auto &node : tree) {
178
602k
    if (node.property0 == -1) {
179
558k
      node.childID = context_map[node.childID];
180
558k
    }
181
602k
  }
182
183
427k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
427k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
246M
                             pixel_type_w offset) -> pixel_type {
188
246M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
246M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
246M
    return val * multiplier + offset;
192
246M
  };
jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda(unsigned long, int, long)#1}::operator()(unsigned long, int, long) const
Line
Count
Source
187
52.5M
                             pixel_type_w offset) -> pixel_type {
188
52.5M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
52.5M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
52.5M
    return val * multiplier + offset;
192
52.5M
  };
jxl::detail::DecodeModularChannelMAANS<false>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda(unsigned long, int, long)#1}::operator()(unsigned long, int, long) const
Line
Count
Source
187
193M
                             pixel_type_w offset) -> pixel_type {
188
193M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
193M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
193M
    return val * multiplier + offset;
192
193M
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
427k
  const bool global_tree_is_all_gradient_noop = [&] {
200
432k
    for (const auto& n : global_tree) {
201
432k
      if (n.property == -1) {
202
415k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
4.74k
            n.multiplier != 1)
204
411k
          return false;
205
415k
      } else if (n.property >= kNumStaticProperties) {
206
13.0k
        return false;
207
13.0k
      }
208
432k
    }
209
2.97k
    return true;
210
427k
  }();
jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda()#1}::operator()() const
Line
Count
Source
199
43.4k
  const bool global_tree_is_all_gradient_noop = [&] {
200
43.8k
    for (const auto& n : global_tree) {
201
43.8k
      if (n.property == -1) {
202
40.6k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
1.96k
            n.multiplier != 1)
204
38.8k
          return false;
205
40.6k
      } else if (n.property >= kNumStaticProperties) {
206
2.74k
        return false;
207
2.74k
      }
208
43.8k
    }
209
1.78k
    return true;
210
43.4k
  }();
jxl::detail::DecodeModularChannelMAANS<false>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda()#1}::operator()() const
Line
Count
Source
199
384k
  const bool global_tree_is_all_gradient_noop = [&] {
200
389k
    for (const auto& n : global_tree) {
201
389k
      if (n.property == -1) {
202
375k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
2.78k
            n.multiplier != 1)
204
372k
          return false;
205
375k
      } else if (n.property >= kNumStaticProperties) {
206
10.3k
        return false;
207
10.3k
      }
208
389k
    }
209
1.19k
    return true;
210
384k
  }();
211
212
427k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
414k
    Predictor predictor = tree[0].predictor;
216
414k
    int64_t offset = tree[0].predictor_offset;
217
414k
    int32_t multiplier = tree[0].multiplier;
218
414k
    size_t ctx_id = tree[0].childID;
219
414k
    if (predictor == Predictor::Zero) {
220
389k
      uint32_t value;
221
389k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
389k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
172k
        JXL_DEBUG_V(8, "Fastest track.");
226
172k
        pixel_type v = make_pixel(value, multiplier, offset);
227
5.28M
        for (size_t y = 0; y < channel.h; y++) {
228
5.10M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
5.10M
          std::fill(r, r + channel.w, v);
230
5.10M
        }
231
216k
      } else {
232
216k
        JXL_DEBUG_V(8, "Fast track.");
233
216k
        if (multiplier == 1 && offset == 0) {
234
3.20M
          for (size_t y = 0; y < channel.h; y++) {
235
3.02M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
234M
            for (size_t x = 0; x < channel.w; x++) {
237
231M
              uint32_t v =
238
231M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
231M
              r[x] = UnpackSigned(v);
240
231M
            }
241
3.02M
          }
242
180k
        } else {
243
1.51M
          for (size_t y = 0; y < channel.h; y++) {
244
1.48M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
161M
            for (size_t x = 0; x < channel.w; x++) {
246
159M
              uint32_t v =
247
159M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
159M
                                                                         br);
249
159M
              r[x] = make_pixel(v, multiplier, offset);
250
159M
            }
251
1.48M
          }
252
36.2k
        }
253
216k
      }
254
389k
      return true;
255
389k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
460
               global_tree_is_all_gradient_noop) {
257
451
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
451
      pixel_type_w sv = UnpackSigned(fl_v);
259
17.4k
      for (size_t y = 0; y < channel.h; y++) {
260
17.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
17.0k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
17.0k
        const pixel_type *JXL_RESTRICT rtopleft =
263
17.0k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
17.0k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
17.0k
        if (fl_run == 0) {
266
5.19k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.19k
                                                     &fl_run);
268
5.19k
          sv = UnpackSigned(fl_v);
269
11.8k
        } else {
270
11.8k
          fl_run--;
271
11.8k
        }
272
17.0k
        r[0] = sv + guess_0;
273
457k
        for (size_t x = 1; x < channel.w; x++) {
274
440k
          pixel_type left = r[x - 1];
275
440k
          pixel_type top = rtop[x];
276
440k
          pixel_type topleft = rtopleft[x];
277
440k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
440k
          if (!fl_run) {
279
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
119k
                                                       &fl_run);
281
119k
            sv = UnpackSigned(fl_v);
282
321k
          } else {
283
321k
            fl_run--;
284
321k
          }
285
440k
          r[x] = sv + guess;
286
440k
        }
287
17.0k
      }
288
451
      return true;
289
24.9k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
3.20k
               multiplier == 1) {
291
2.88k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
2.88k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
69.7k
      for (size_t y = 0; y < channel.h; y++) {
294
66.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
3.74M
        for (size_t x = 0; x < channel.w; x++) {
296
3.68M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
3.68M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
3.68M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
3.68M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
3.68M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
3.68M
              ctx_id, br);
302
3.68M
          r[x] = make_pixel(v, 1, guess);
303
3.68M
        }
304
66.8k
      }
305
2.88k
      return true;
306
2.88k
    }
307
414k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
34.8k
  if (is_wp_only) {
312
4.37k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
4.37k
  }
314
34.8k
  if (is_gradient_only) {
315
1.64k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.64k
  }
317
318
34.8k
  if (is_gradient_only) {
319
769
    JXL_DEBUG_V(8, "Gradient fast track.");
320
769
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
16.5k
    for (size_t y = 0; y < channel.h; y++) {
322
15.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
640k
      for (size_t x = 0; x < channel.w; x++) {
324
625k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
625k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
625k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
625k
        int32_t guess = ClampedGradient(top, left, topleft);
328
625k
        uint32_t pos =
329
625k
            kPropRangeFast +
330
625k
            std::min<pixel_type_w>(
331
625k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
625k
                kPropRangeFast - 1);
333
625k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
625k
        uint64_t v =
335
625k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
625k
        r[x] = make_pixel(v, 1, guess);
337
625k
      }
338
15.7k
    }
339
34.0k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
935
    JXL_DEBUG_V(8, "WP fast track.");
341
935
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
935
    Properties properties(1);
343
23.8k
    for (size_t y = 0; y < channel.h; y++) {
344
22.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
22.8k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
22.8k
      const pixel_type *JXL_RESTRICT rtoptop =
347
22.8k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
22.8k
      const pixel_type *JXL_RESTRICT rtopleft =
349
22.8k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
22.8k
      const pixel_type *JXL_RESTRICT rtopright =
351
22.8k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
22.8k
      size_t x = 0;
353
22.8k
      {
354
22.8k
        size_t offset = 0;
355
22.8k
        pixel_type_w left = y ? rtop[x] : 0;
356
22.8k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
22.8k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
22.8k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
22.8k
            offset);
361
22.8k
        uint32_t pos =
362
22.8k
            kPropRangeFast +
363
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
22.8k
        uint64_t v =
366
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
22.8k
        r[x] = make_pixel(v, 1, guess);
368
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
22.8k
      }
370
2.12M
      for (x = 1; x + 1 < channel.w; x++) {
371
2.10M
        size_t offset = 0;
372
2.10M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
2.10M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
2.10M
            rtoptop[x], &properties, offset);
375
2.10M
        uint32_t pos =
376
2.10M
            kPropRangeFast +
377
2.10M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
2.10M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
2.10M
        uint64_t v =
380
2.10M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
2.10M
        r[x] = make_pixel(v, 1, guess);
382
2.10M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
2.10M
      }
384
22.8k
      {
385
22.8k
        size_t offset = 0;
386
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
22.8k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
22.8k
            rtoptop[x], &properties, offset);
389
22.8k
        uint32_t pos =
390
22.8k
            kPropRangeFast +
391
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
22.8k
        uint64_t v =
394
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
22.8k
        r[x] = make_pixel(v, 1, guess);
396
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
22.8k
      }
398
22.8k
    }
399
33.1k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
23.0k
    JXL_DEBUG_V(8, "Slow track.");
403
23.0k
    MATreeLookup tree_lookup(tree);
404
23.0k
    Properties properties = Properties(num_props);
405
23.0k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
23.0k
    JXL_ASSIGN_OR_RETURN(
407
23.0k
        Channel references,
408
23.0k
        Channel::Create(memory_manager,
409
23.0k
                        properties.size() - kNumNonrefProperties, channel.w));
410
682k
    for (size_t y = 0; y < channel.h; y++) {
411
659k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
659k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
659k
      InitPropsRow(&properties, static_props, y);
414
659k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.63M
        for (size_t x = 0; x < 2; x++) {
416
1.09M
          PredictionResult res =
417
1.09M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
1.09M
                              tree_lookup, references);
419
1.09M
          uint64_t v =
420
1.09M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
1.09M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
1.09M
        }
423
57.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
56.7M
          PredictionResult res =
425
56.7M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
56.7M
                                 tree_lookup, references);
427
56.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
56.7M
              res.context, br);
429
56.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
56.7M
        }
431
1.63M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
1.09M
          PredictionResult res =
433
1.09M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
1.09M
                              tree_lookup, references);
435
1.09M
          uint64_t v =
436
1.09M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
1.09M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
1.09M
        }
439
546k
      } else {
440
2.49M
        for (size_t x = 0; x < channel.w; x++) {
441
2.37M
          PredictionResult res =
442
2.37M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
2.37M
                              tree_lookup, references);
444
2.37M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
2.37M
              res.context, br);
446
2.37M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
2.37M
        }
448
113k
      }
449
659k
    }
450
23.0k
  } else {
451
10.0k
    JXL_DEBUG_V(8, "Slowest track.");
452
10.0k
    MATreeLookup tree_lookup(tree);
453
10.0k
    Properties properties = Properties(num_props);
454
10.0k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
10.0k
    JXL_ASSIGN_OR_RETURN(
456
10.0k
        Channel references,
457
10.0k
        Channel::Create(memory_manager,
458
10.0k
                        properties.size() - kNumNonrefProperties, channel.w));
459
10.0k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
268k
    for (size_t y = 0; y < channel.h; y++) {
461
257k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
257k
      InitPropsRow(&properties, static_props, y);
463
257k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
257k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
620k
        for (size_t x = 0; x < 2; x++) {
466
413k
          PredictionResult res =
467
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
413k
                            tree_lookup, references, &wp_state);
469
413k
          uint64_t v =
470
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
413k
        }
474
16.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
15.8M
          PredictionResult res =
476
15.8M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
15.8M
                               tree_lookup, references, &wp_state);
478
15.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
15.8M
              res.context, br);
480
15.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
15.8M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
15.8M
        }
483
620k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
413k
          PredictionResult res =
485
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
413k
                            tree_lookup, references, &wp_state);
487
413k
          uint64_t v =
488
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
413k
        }
492
206k
      } else {
493
2.09M
        for (size_t x = 0; x < channel.w; x++) {
494
2.04M
          PredictionResult res =
495
2.04M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.04M
                            tree_lookup, references, &wp_state);
497
2.04M
          uint64_t v =
498
2.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.04M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.04M
        }
502
51.2k
      }
503
257k
    }
504
10.0k
  }
505
34.8k
  return true;
506
34.8k
}
jxl::Status jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)
Line
Count
Source
156
43.4k
                                 uint32_t &fl_v) {
157
43.4k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
43.4k
  Channel &channel = image->channel[chan];
159
160
43.4k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
43.4k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
43.4k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
43.4k
  bool tree_has_wp_prop_or_pred = false;
168
43.4k
  bool is_wp_only = false;
169
43.4k
  bool is_gradient_only = false;
170
43.4k
  size_t num_props;
171
43.4k
  FlatTree tree =
172
43.4k
      FilterTree(global_tree, static_props, &num_props,
173
43.4k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
57.4k
  for (auto &node : tree) {
178
57.4k
    if (node.property0 == -1) {
179
53.9k
      node.childID = context_map[node.childID];
180
53.9k
    }
181
57.4k
  }
182
183
43.4k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
43.4k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
43.4k
                             pixel_type_w offset) -> pixel_type {
188
43.4k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
43.4k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
43.4k
    return val * multiplier + offset;
192
43.4k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
43.4k
  const bool global_tree_is_all_gradient_noop = [&] {
200
43.4k
    for (const auto& n : global_tree) {
201
43.4k
      if (n.property == -1) {
202
43.4k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
43.4k
            n.multiplier != 1)
204
43.4k
          return false;
205
43.4k
      } else if (n.property >= kNumStaticProperties) {
206
43.4k
        return false;
207
43.4k
      }
208
43.4k
    }
209
43.4k
    return true;
210
43.4k
  }();
211
212
43.4k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
40.6k
    Predictor predictor = tree[0].predictor;
216
40.6k
    int64_t offset = tree[0].predictor_offset;
217
40.6k
    int32_t multiplier = tree[0].multiplier;
218
40.6k
    size_t ctx_id = tree[0].childID;
219
40.6k
    if (predictor == Predictor::Zero) {
220
32.5k
      uint32_t value;
221
32.5k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
32.5k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
10.9k
        JXL_DEBUG_V(8, "Fastest track.");
226
10.9k
        pixel_type v = make_pixel(value, multiplier, offset);
227
362k
        for (size_t y = 0; y < channel.h; y++) {
228
351k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
351k
          std::fill(r, r + channel.w, v);
230
351k
        }
231
21.5k
      } else {
232
21.5k
        JXL_DEBUG_V(8, "Fast track.");
233
21.5k
        if (multiplier == 1 && offset == 0) {
234
429k
          for (size_t y = 0; y < channel.h; y++) {
235
422k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
67.9M
            for (size_t x = 0; x < channel.w; x++) {
237
67.5M
              uint32_t v =
238
67.5M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
67.5M
              r[x] = UnpackSigned(v);
240
67.5M
            }
241
422k
          }
242
14.6k
        } else {
243
459k
          for (size_t y = 0; y < channel.h; y++) {
244
445k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
29.8M
            for (size_t x = 0; x < channel.w; x++) {
246
29.3M
              uint32_t v =
247
29.3M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
29.3M
                                                                         br);
249
29.3M
              r[x] = make_pixel(v, multiplier, offset);
250
29.3M
            }
251
445k
          }
252
14.6k
        }
253
21.5k
      }
254
32.5k
      return true;
255
32.5k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
460
               global_tree_is_all_gradient_noop) {
257
451
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
451
      pixel_type_w sv = UnpackSigned(fl_v);
259
17.4k
      for (size_t y = 0; y < channel.h; y++) {
260
17.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
17.0k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
17.0k
        const pixel_type *JXL_RESTRICT rtopleft =
263
17.0k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
17.0k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
17.0k
        if (fl_run == 0) {
266
5.19k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.19k
                                                     &fl_run);
268
5.19k
          sv = UnpackSigned(fl_v);
269
11.8k
        } else {
270
11.8k
          fl_run--;
271
11.8k
        }
272
17.0k
        r[0] = sv + guess_0;
273
457k
        for (size_t x = 1; x < channel.w; x++) {
274
440k
          pixel_type left = r[x - 1];
275
440k
          pixel_type top = rtop[x];
276
440k
          pixel_type topleft = rtopleft[x];
277
440k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
440k
          if (!fl_run) {
279
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
119k
                                                       &fl_run);
281
119k
            sv = UnpackSigned(fl_v);
282
321k
          } else {
283
321k
            fl_run--;
284
321k
          }
285
440k
          r[x] = sv + guess;
286
440k
        }
287
17.0k
      }
288
451
      return true;
289
7.64k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
1.50k
               multiplier == 1) {
291
1.33k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
1.33k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
28.0k
      for (size_t y = 0; y < channel.h; y++) {
294
26.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
1.30M
        for (size_t x = 0; x < channel.w; x++) {
296
1.28M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
1.28M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
1.28M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
1.28M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
1.28M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
1.28M
              ctx_id, br);
302
1.28M
          r[x] = make_pixel(v, 1, guess);
303
1.28M
        }
304
26.7k
      }
305
1.33k
      return true;
306
1.33k
    }
307
40.6k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
9.05k
  if (is_wp_only) {
312
357
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
357
  }
314
9.05k
  if (is_gradient_only) {
315
557
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
557
  }
317
318
9.05k
  if (is_gradient_only) {
319
140
    JXL_DEBUG_V(8, "Gradient fast track.");
320
140
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
2.49k
    for (size_t y = 0; y < channel.h; y++) {
322
2.35k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
167k
      for (size_t x = 0; x < channel.w; x++) {
324
165k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
165k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
165k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
165k
        int32_t guess = ClampedGradient(top, left, topleft);
328
165k
        uint32_t pos =
329
165k
            kPropRangeFast +
330
165k
            std::min<pixel_type_w>(
331
165k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
165k
                kPropRangeFast - 1);
333
165k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
165k
        uint64_t v =
335
165k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
165k
        r[x] = make_pixel(v, 1, guess);
337
165k
      }
338
2.35k
    }
339
8.91k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
0
    JXL_DEBUG_V(8, "WP fast track.");
341
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
0
    Properties properties(1);
343
0
    for (size_t y = 0; y < channel.h; y++) {
344
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
0
      const pixel_type *JXL_RESTRICT rtoptop =
347
0
          (y > 1 ? channel.Row(y - 2) : rtop);
348
0
      const pixel_type *JXL_RESTRICT rtopleft =
349
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
0
      const pixel_type *JXL_RESTRICT rtopright =
351
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
0
      size_t x = 0;
353
0
      {
354
0
        size_t offset = 0;
355
0
        pixel_type_w left = y ? rtop[x] : 0;
356
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
0
            offset);
361
0
        uint32_t pos =
362
0
            kPropRangeFast +
363
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
0
        uint64_t v =
366
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
0
        r[x] = make_pixel(v, 1, guess);
368
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
0
      }
370
0
      for (x = 1; x + 1 < channel.w; x++) {
371
0
        size_t offset = 0;
372
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
0
            rtoptop[x], &properties, offset);
375
0
        uint32_t pos =
376
0
            kPropRangeFast +
377
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
0
        uint64_t v =
380
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
0
        r[x] = make_pixel(v, 1, guess);
382
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
0
      }
384
0
      {
385
0
        size_t offset = 0;
386
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
0
            rtoptop[x], &properties, offset);
389
0
        uint32_t pos =
390
0
            kPropRangeFast +
391
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
0
        uint64_t v =
394
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
0
        r[x] = make_pixel(v, 1, guess);
396
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
0
      }
398
0
    }
399
8.91k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
7.92k
    JXL_DEBUG_V(8, "Slow track.");
403
7.92k
    MATreeLookup tree_lookup(tree);
404
7.92k
    Properties properties = Properties(num_props);
405
7.92k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
7.92k
    JXL_ASSIGN_OR_RETURN(
407
7.92k
        Channel references,
408
7.92k
        Channel::Create(memory_manager,
409
7.92k
                        properties.size() - kNumNonrefProperties, channel.w));
410
194k
    for (size_t y = 0; y < channel.h; y++) {
411
186k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
186k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
186k
      InitPropsRow(&properties, static_props, y);
414
186k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
472k
        for (size_t x = 0; x < 2; x++) {
416
314k
          PredictionResult res =
417
314k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
314k
                              tree_lookup, references);
419
314k
          uint64_t v =
420
314k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
314k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
314k
        }
423
20.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
20.1M
          PredictionResult res =
425
20.1M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
20.1M
                                 tree_lookup, references);
427
20.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
20.1M
              res.context, br);
429
20.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
20.1M
        }
431
472k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
314k
          PredictionResult res =
433
314k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
314k
                              tree_lookup, references);
435
314k
          uint64_t v =
436
314k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
314k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
314k
        }
439
157k
      } else {
440
515k
        for (size_t x = 0; x < channel.w; x++) {
441
486k
          PredictionResult res =
442
486k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
486k
                              tree_lookup, references);
444
486k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
486k
              res.context, br);
446
486k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
486k
        }
448
28.9k
      }
449
186k
    }
450
7.92k
  } else {
451
984
    JXL_DEBUG_V(8, "Slowest track.");
452
984
    MATreeLookup tree_lookup(tree);
453
984
    Properties properties = Properties(num_props);
454
984
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
984
    JXL_ASSIGN_OR_RETURN(
456
984
        Channel references,
457
984
        Channel::Create(memory_manager,
458
984
                        properties.size() - kNumNonrefProperties, channel.w));
459
984
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
13.3k
    for (size_t y = 0; y < channel.h; y++) {
461
12.3k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
12.3k
      InitPropsRow(&properties, static_props, y);
463
12.3k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
12.3k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
0
        for (size_t x = 0; x < 2; x++) {
466
0
          PredictionResult res =
467
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
0
                            tree_lookup, references, &wp_state);
469
0
          uint64_t v =
470
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
0
        }
474
0
        for (size_t x = 2; x < channel.w - 2; x++) {
475
0
          PredictionResult res =
476
0
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
0
                               tree_lookup, references, &wp_state);
478
0
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
0
              res.context, br);
480
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
0
        }
483
0
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
0
          PredictionResult res =
485
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
0
                            tree_lookup, references, &wp_state);
487
0
          uint64_t v =
488
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
0
        }
492
12.3k
      } else {
493
501k
        for (size_t x = 0; x < channel.w; x++) {
494
488k
          PredictionResult res =
495
488k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
488k
                            tree_lookup, references, &wp_state);
497
488k
          uint64_t v =
498
488k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
488k
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
488k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
488k
        }
502
12.3k
      }
503
12.3k
    }
504
984
  }
505
9.05k
  return true;
506
9.05k
}
jxl::Status jxl::detail::DecodeModularChannelMAANS<false>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)
Line
Count
Source
156
384k
                                 uint32_t &fl_v) {
157
384k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
384k
  Channel &channel = image->channel[chan];
159
160
384k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
384k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
384k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
384k
  bool tree_has_wp_prop_or_pred = false;
168
384k
  bool is_wp_only = false;
169
384k
  bool is_gradient_only = false;
170
384k
  size_t num_props;
171
384k
  FlatTree tree =
172
384k
      FilterTree(global_tree, static_props, &num_props,
173
384k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
544k
  for (auto &node : tree) {
178
544k
    if (node.property0 == -1) {
179
504k
      node.childID = context_map[node.childID];
180
504k
    }
181
544k
  }
182
183
384k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
384k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
384k
                             pixel_type_w offset) -> pixel_type {
188
384k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
384k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
384k
    return val * multiplier + offset;
192
384k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
384k
  const bool global_tree_is_all_gradient_noop = [&] {
200
384k
    for (const auto& n : global_tree) {
201
384k
      if (n.property == -1) {
202
384k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
384k
            n.multiplier != 1)
204
384k
          return false;
205
384k
      } else if (n.property >= kNumStaticProperties) {
206
384k
        return false;
207
384k
      }
208
384k
    }
209
384k
    return true;
210
384k
  }();
211
212
384k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
374k
    Predictor predictor = tree[0].predictor;
216
374k
    int64_t offset = tree[0].predictor_offset;
217
374k
    int32_t multiplier = tree[0].multiplier;
218
374k
    size_t ctx_id = tree[0].childID;
219
374k
    if (predictor == Predictor::Zero) {
220
356k
      uint32_t value;
221
356k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
356k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
161k
        JXL_DEBUG_V(8, "Fastest track.");
226
161k
        pixel_type v = make_pixel(value, multiplier, offset);
227
4.91M
        for (size_t y = 0; y < channel.h; y++) {
228
4.75M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
4.75M
          std::fill(r, r + channel.w, v);
230
4.75M
        }
231
195k
      } else {
232
195k
        JXL_DEBUG_V(8, "Fast track.");
233
195k
        if (multiplier == 1 && offset == 0) {
234
2.77M
          for (size_t y = 0; y < channel.h; y++) {
235
2.59M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
166M
            for (size_t x = 0; x < channel.w; x++) {
237
164M
              uint32_t v =
238
164M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
164M
              r[x] = UnpackSigned(v);
240
164M
            }
241
2.59M
          }
242
173k
        } else {
243
1.05M
          for (size_t y = 0; y < channel.h; y++) {
244
1.03M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
131M
            for (size_t x = 0; x < channel.w; x++) {
246
130M
              uint32_t v =
247
130M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
130M
                                                                         br);
249
130M
              r[x] = make_pixel(v, multiplier, offset);
250
130M
            }
251
1.03M
          }
252
21.6k
        }
253
195k
      }
254
356k
      return true;
255
356k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
0
               global_tree_is_all_gradient_noop) {
257
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
0
      pixel_type_w sv = UnpackSigned(fl_v);
259
0
      for (size_t y = 0; y < channel.h; y++) {
260
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
0
        const pixel_type *JXL_RESTRICT rtopleft =
263
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
0
        if (fl_run == 0) {
266
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
0
                                                     &fl_run);
268
0
          sv = UnpackSigned(fl_v);
269
0
        } else {
270
0
          fl_run--;
271
0
        }
272
0
        r[0] = sv + guess_0;
273
0
        for (size_t x = 1; x < channel.w; x++) {
274
0
          pixel_type left = r[x - 1];
275
0
          pixel_type top = rtop[x];
276
0
          pixel_type topleft = rtopleft[x];
277
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
0
          if (!fl_run) {
279
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
0
                                                       &fl_run);
281
0
            sv = UnpackSigned(fl_v);
282
0
          } else {
283
0
            fl_run--;
284
0
          }
285
0
          r[x] = sv + guess;
286
0
        }
287
0
      }
288
0
      return true;
289
17.3k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
1.69k
               multiplier == 1) {
291
1.54k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
1.54k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
41.7k
      for (size_t y = 0; y < channel.h; y++) {
294
40.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
2.44M
        for (size_t x = 0; x < channel.w; x++) {
296
2.40M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.40M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.40M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.40M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.40M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.40M
              ctx_id, br);
302
2.40M
          r[x] = make_pixel(v, 1, guess);
303
2.40M
        }
304
40.1k
      }
305
1.54k
      return true;
306
1.54k
    }
307
374k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
25.7k
  if (is_wp_only) {
312
4.01k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
4.01k
  }
314
25.7k
  if (is_gradient_only) {
315
1.08k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.08k
  }
317
318
25.7k
  if (is_gradient_only) {
319
629
    JXL_DEBUG_V(8, "Gradient fast track.");
320
629
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
14.0k
    for (size_t y = 0; y < channel.h; y++) {
322
13.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
473k
      for (size_t x = 0; x < channel.w; x++) {
324
459k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
459k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
459k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
459k
        int32_t guess = ClampedGradient(top, left, topleft);
328
459k
        uint32_t pos =
329
459k
            kPropRangeFast +
330
459k
            std::min<pixel_type_w>(
331
459k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
459k
                kPropRangeFast - 1);
333
459k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
459k
        uint64_t v =
335
459k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
459k
        r[x] = make_pixel(v, 1, guess);
337
459k
      }
338
13.3k
    }
339
25.1k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
935
    JXL_DEBUG_V(8, "WP fast track.");
341
935
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
935
    Properties properties(1);
343
23.8k
    for (size_t y = 0; y < channel.h; y++) {
344
22.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
22.8k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
22.8k
      const pixel_type *JXL_RESTRICT rtoptop =
347
22.8k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
22.8k
      const pixel_type *JXL_RESTRICT rtopleft =
349
22.8k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
22.8k
      const pixel_type *JXL_RESTRICT rtopright =
351
22.8k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
22.8k
      size_t x = 0;
353
22.8k
      {
354
22.8k
        size_t offset = 0;
355
22.8k
        pixel_type_w left = y ? rtop[x] : 0;
356
22.8k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
22.8k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
22.8k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
22.8k
            offset);
361
22.8k
        uint32_t pos =
362
22.8k
            kPropRangeFast +
363
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
22.8k
        uint64_t v =
366
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
22.8k
        r[x] = make_pixel(v, 1, guess);
368
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
22.8k
      }
370
2.12M
      for (x = 1; x + 1 < channel.w; x++) {
371
2.10M
        size_t offset = 0;
372
2.10M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
2.10M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
2.10M
            rtoptop[x], &properties, offset);
375
2.10M
        uint32_t pos =
376
2.10M
            kPropRangeFast +
377
2.10M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
2.10M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
2.10M
        uint64_t v =
380
2.10M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
2.10M
        r[x] = make_pixel(v, 1, guess);
382
2.10M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
2.10M
      }
384
22.8k
      {
385
22.8k
        size_t offset = 0;
386
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
22.8k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
22.8k
            rtoptop[x], &properties, offset);
389
22.8k
        uint32_t pos =
390
22.8k
            kPropRangeFast +
391
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
22.8k
        uint64_t v =
394
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
22.8k
        r[x] = make_pixel(v, 1, guess);
396
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
22.8k
      }
398
22.8k
    }
399
24.1k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
15.0k
    JXL_DEBUG_V(8, "Slow track.");
403
15.0k
    MATreeLookup tree_lookup(tree);
404
15.0k
    Properties properties = Properties(num_props);
405
15.0k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
15.0k
    JXL_ASSIGN_OR_RETURN(
407
15.0k
        Channel references,
408
15.0k
        Channel::Create(memory_manager,
409
15.0k
                        properties.size() - kNumNonrefProperties, channel.w));
410
488k
    for (size_t y = 0; y < channel.h; y++) {
411
473k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
473k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
473k
      InitPropsRow(&properties, static_props, y);
414
473k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.16M
        for (size_t x = 0; x < 2; x++) {
416
777k
          PredictionResult res =
417
777k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
777k
                              tree_lookup, references);
419
777k
          uint64_t v =
420
777k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
777k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
777k
        }
423
37.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
36.6M
          PredictionResult res =
425
36.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
36.6M
                                 tree_lookup, references);
427
36.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
36.6M
              res.context, br);
429
36.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
36.6M
        }
431
1.16M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
777k
          PredictionResult res =
433
777k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
777k
                              tree_lookup, references);
435
777k
          uint64_t v =
436
777k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
777k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
777k
        }
439
388k
      } else {
440
1.97M
        for (size_t x = 0; x < channel.w; x++) {
441
1.89M
          PredictionResult res =
442
1.89M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
1.89M
                              tree_lookup, references);
444
1.89M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
1.89M
              res.context, br);
446
1.89M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
1.89M
        }
448
84.3k
      }
449
473k
    }
450
15.0k
  } else {
451
9.09k
    JXL_DEBUG_V(8, "Slowest track.");
452
9.09k
    MATreeLookup tree_lookup(tree);
453
9.09k
    Properties properties = Properties(num_props);
454
9.09k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
9.09k
    JXL_ASSIGN_OR_RETURN(
456
9.09k
        Channel references,
457
9.09k
        Channel::Create(memory_manager,
458
9.09k
                        properties.size() - kNumNonrefProperties, channel.w));
459
9.09k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
254k
    for (size_t y = 0; y < channel.h; y++) {
461
245k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
245k
      InitPropsRow(&properties, static_props, y);
463
245k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
245k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
620k
        for (size_t x = 0; x < 2; x++) {
466
413k
          PredictionResult res =
467
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
413k
                            tree_lookup, references, &wp_state);
469
413k
          uint64_t v =
470
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
413k
        }
474
16.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
15.8M
          PredictionResult res =
476
15.8M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
15.8M
                               tree_lookup, references, &wp_state);
478
15.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
15.8M
              res.context, br);
480
15.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
15.8M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
15.8M
        }
483
620k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
413k
          PredictionResult res =
485
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
413k
                            tree_lookup, references, &wp_state);
487
413k
          uint64_t v =
488
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
413k
        }
492
206k
      } else {
493
1.59M
        for (size_t x = 0; x < channel.w; x++) {
494
1.55M
          PredictionResult res =
495
1.55M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
1.55M
                            tree_lookup, references, &wp_state);
497
1.55M
          uint64_t v =
498
1.55M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
1.55M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
1.55M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
1.55M
        }
502
38.9k
      }
503
245k
    }
504
9.09k
  }
505
25.7k
  return true;
506
25.7k
}
507
}  // namespace detail
508
509
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
510
                                 const std::vector<uint8_t> &context_map,
511
                                 const Tree &global_tree,
512
                                 const weighted::Header &wp_header,
513
                                 pixel_type chan, size_t group_id,
514
                                 TreeLut<uint8_t, false, false> &tree_lut,
515
                                 Image *image, uint32_t &fl_run,
516
427k
                                 uint32_t &fl_v) {
517
427k
  if (reader->UsesLZ77()) {
518
43.4k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
43.4k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
43.4k
        tree_lut, image, fl_run, fl_v);
521
384k
  } else {
522
384k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
384k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
384k
        tree_lut, image, fl_run, fl_v);
525
384k
  }
526
427k
}
527
528
193k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
49.5k
                                 const ModularOptions &options) {
532
49.5k
  size_t nb_channels = image.channel.size();
533
99.1k
  for (bool is_dc : {true, false}) {
534
99.1k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
99.1k
    size_t c = image.nb_meta_channels;
536
988k
    for (; c < nb_channels; c++) {
537
892k
      const Channel &ch = image.channel[c];
538
892k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
892k
    }
540
124k
    for (; c < nb_channels; c++) {
541
25.0k
      const Channel &ch = image.channel[c];
542
25.0k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
24.3k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
24.3k
      if (is_dc_channel != is_dc) continue;
545
12.1k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
12.1k
      if (tile_dim == 0) {
547
3
        return JXL_FAILURE("Inconsistent transforms");
548
3
      }
549
12.1k
    }
550
99.1k
  }
551
49.5k
  return true;
552
49.5k
}
553
554
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
555
                     size_t group_id, ModularOptions *options,
556
                     const Tree *global_tree, const ANSCode *global_code,
557
                     const std::vector<uint8_t> *global_ctx_map,
558
56.4k
                     const bool allow_truncated_group) {
559
56.4k
  if (image.channel.empty()) return true;
560
49.1k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
49.1k
  Status status = Bundle::Read(br, &header);
564
49.1k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
48.0k
  if (status.IsFatalError()) return status;
566
48.0k
  if (!br->AllReadsWithinBounds()) {
567
    // Don't do/undo transforms if header is incomplete.
568
0
    header.transforms.clear();
569
0
    image.transform = header.transforms;
570
0
    for (auto &ch : image.channel) {
571
0
      ZeroFillImage(&ch.plane);
572
0
    }
573
0
    return JXL_NOT_ENOUGH_BYTES("Read overrun before ModularDecode");
574
0
  }
575
576
48.0k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
48.0k
              header.transforms.size());
578
48.0k
  image.transform = header.transforms;
579
48.0k
  for (Transform &transform : image.transform) {
580
29.9k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
29.9k
  }
582
47.8k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
47.8k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
47.8k
  size_t nb_channels = image.channel.size();
588
589
47.8k
  size_t num_chans = 0;
590
47.8k
  size_t distance_multiplier = 0;
591
493k
  for (size_t i = 0; i < nb_channels; i++) {
592
447k
    Channel &channel = image.channel[i];
593
447k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
441k
                                        channel.h > options->max_chan_size)) {
595
1.36k
      break;
596
1.36k
    }
597
445k
    if (!channel.w || !channel.h) {
598
5.61k
      continue;  // skip empty channels
599
5.61k
    }
600
440k
    if (channel.w > distance_multiplier) {
601
77.4k
      distance_multiplier = channel.w;
602
77.4k
    }
603
440k
    num_chans++;
604
440k
  }
605
47.8k
  if (num_chans == 0) return true;
606
607
47.4k
  size_t next_channel = 0;
608
47.4k
  auto scope_guard = MakeScopeGuard([&]() {
609
18.8k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
15.9k
      ZeroFillImage(&image.channel[c].plane);
611
15.9k
    }
612
2.95k
  });
613
  // Do not do anything if truncated groups are not allowed.
614
47.4k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
47.4k
  Tree tree_storage;
618
47.4k
  std::vector<uint8_t> context_map_storage;
619
47.4k
  ANSCode code_storage;
620
47.4k
  const Tree *tree = &tree_storage;
621
47.4k
  const ANSCode *code = &code_storage;
622
47.4k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
47.4k
  if (!header.use_global_tree) {
624
28.2k
    uint64_t max_tree_size = 1024;
625
348k
    for (size_t i = 0; i < nb_channels; i++) {
626
320k
      Channel &channel = image.channel[i];
627
320k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
318k
                                          channel.h > options->max_chan_size)) {
629
48
        break;
630
48
      }
631
320k
      uint64_t pixels = channel.w * channel.h;
632
320k
      max_tree_size += pixels;
633
320k
    }
634
28.2k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
28.2k
    JXL_RETURN_IF_ERROR(
636
28.2k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
27.8k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
27.8k
                                         (tree_storage.size() + 1) / 2,
639
27.8k
                                         &code_storage, &context_map_storage));
640
27.8k
  } else {
641
19.1k
    if (!global_tree || !global_code || !global_ctx_map ||
642
19.1k
        global_tree->empty()) {
643
72
      return JXL_FAILURE("No global tree available but one was requested");
644
72
    }
645
19.0k
    tree = global_tree;
646
19.0k
    code = global_code;
647
19.0k
    context_map = global_ctx_map;
648
19.0k
  }
649
650
  // Read channels
651
93.8k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
93.8k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
93.8k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
93.8k
  uint32_t fl_run = 0;
655
93.8k
  uint32_t fl_v = 0;
656
477k
  for (; next_channel < nb_channels; next_channel++) {
657
433k
    Channel &channel = image.channel[next_channel];
658
433k
    if (next_channel >= image.nb_meta_channels &&
659
428k
        (channel.w > options->max_chan_size ||
660
428k
         channel.h > options->max_chan_size)) {
661
893
      break;
662
893
    }
663
432k
    if (!channel.w || !channel.h) {
664
5.25k
      continue;  // skip empty channels
665
5.25k
    }
666
427k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
427k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
427k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
427k
    if (!br->AllReadsWithinBounds()) {
672
2.46k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
2.46k
    }
675
427k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
44.4k
  scope_guard.Disarm();
679
680
44.4k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
44.4k
  return true;
684
44.4k
}
685
686
Status ModularGenericDecompress(BitReader *br, Image &image,
687
                                GroupHeader *header, size_t group_id,
688
                                ModularOptions *options, bool undo_transforms,
689
                                const Tree *tree, const ANSCode *code,
690
                                const std::vector<uint8_t> *ctx_map,
691
56.4k
                                bool allow_truncated_group) {
692
56.4k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
56.4k
  req_sizes.reserve(image.channel.size());
694
178k
  for (const auto &c : image.channel) {
695
178k
    req_sizes.emplace_back(c.w, c.h);
696
178k
  }
697
56.4k
  GroupHeader local_header;
698
56.4k
  if (header == nullptr) header = &local_header;
699
56.4k
  size_t bit_pos = br->TotalBitsConsumed();
700
56.4k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
56.4k
                                  code, ctx_map, allow_truncated_group);
702
56.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
52.2k
  if (dec_status.IsFatalError()) return dec_status;
704
52.2k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
52.2k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
52.2k
  JXL_DEBUG_V(4,
707
52.2k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
52.2k
              " image from %" PRIuS " bytes",
709
52.2k
              image.w, image.h, image.channel.size(),
710
52.2k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
52.2k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
52.2k
  (void)bit_pos;
713
  // Check that after applying all transforms we are back to the requested
714
  // image sizes, otherwise there's a programming error with the
715
  // transformations.
716
52.2k
  if (undo_transforms) {
717
14.5k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
72.5k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
57.9k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
57.9k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
57.9k
    }
722
14.5k
  }
723
52.2k
  return dec_status;
724
52.2k
}
725
726
}  // namespace jxl