Coverage Report

Created: 2025-08-11 08:01

/src/libjxl/lib/jxl/modular/encoding/encoding.cc
Line
Count
Source (jump to first uncovered line)
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
161k
                    bool *gradient_only) {
46
161k
  *num_props = 0;
47
161k
  bool has_wp = false;
48
161k
  bool has_non_wp = false;
49
161k
  *gradient_only = true;
50
443k
  const auto mark_property = [&](int32_t p) {
51
443k
    if (p == kWPProp) {
52
74.7k
      has_wp = true;
53
369k
    } else if (p >= kNumStaticProperties) {
54
198k
      has_non_wp = true;
55
198k
    }
56
443k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
229k
      *gradient_only = false;
58
229k
    }
59
443k
  };
60
161k
  FlatTree output;
61
161k
  std::queue<size_t> nodes;
62
161k
  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
915k
  while (!nodes.empty()) {
70
753k
    size_t cur = nodes.front();
71
753k
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
796k
    while (global_tree[cur].property < kNumStaticProperties &&
74
796k
           global_tree[cur].property != -1) {
75
42.4k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
23.4k
        cur = global_tree[cur].lchild;
77
23.4k
      } else {
78
19.0k
        cur = global_tree[cur].rchild;
79
19.0k
      }
80
42.4k
    }
81
753k
    FlatDecisionNode flat;
82
753k
    if (global_tree[cur].property == -1) {
83
605k
      flat.property0 = -1;
84
605k
      flat.childID = global_tree[cur].lchild;
85
605k
      flat.predictor = global_tree[cur].predictor;
86
605k
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
605k
      flat.multiplier = global_tree[cur].multiplier;
88
605k
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
605k
      has_wp |= flat.predictor == Predictor::Weighted;
90
605k
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
605k
      output.push_back(flat);
92
605k
      continue;
93
605k
    }
94
147k
    flat.childID = output.size() + nodes.size() + 1;
95
96
147k
    flat.property0 = global_tree[cur].property;
97
147k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
147k
    flat.splitval0 = global_tree[cur].splitval;
99
100
443k
    for (size_t i = 0; i < 2; i++) {
101
295k
      size_t cur_child =
102
295k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
316k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
316k
             global_tree[cur_child].property != -1) {
106
20.7k
        if (static_props[global_tree[cur_child].property] >
107
20.7k
            global_tree[cur_child].splitval) {
108
11.6k
          cur_child = global_tree[cur_child].lchild;
109
11.6k
        } else {
110
9.12k
          cur_child = global_tree[cur_child].rchild;
111
9.12k
        }
112
20.7k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
295k
      if (global_tree[cur_child].property == -1) {
116
170k
        flat.properties[i] = 0;
117
170k
        flat.splitvals[i] = 0;
118
170k
        nodes.push(cur_child);
119
170k
        nodes.push(cur_child);
120
170k
      } else {
121
124k
        flat.properties[i] = global_tree[cur_child].property;
122
124k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
124k
        nodes.push(global_tree[cur_child].lchild);
124
124k
        nodes.push(global_tree[cur_child].rchild);
125
124k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
124k
      }
127
295k
    }
128
129
295k
    for (int16_t property : flat.properties) mark_property(property);
130
147k
    mark_property(flat.property0);
131
147k
    output.push_back(flat);
132
147k
  }
133
161k
  if (*num_props > kNumNonrefProperties) {
134
1.46k
    *num_props =
135
1.46k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.46k
            kExtraPropsPerChannel +
137
1.46k
        kNumNonrefProperties;
138
160k
  } else {
139
160k
    *num_props = kNumNonrefProperties;
140
160k
  }
141
161k
  *use_wp = has_wp;
142
161k
  *wp_only = has_wp && !has_non_wp;
143
144
161k
  return output;
145
161k
}
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
142k
                                 uint32_t &fl_v) {
157
142k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
142k
  Channel &channel = image->channel[chan];
159
160
142k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
142k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
142k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
142k
  bool tree_has_wp_prop_or_pred = false;
168
142k
  bool is_wp_only = false;
169
142k
  bool is_gradient_only = false;
170
142k
  size_t num_props;
171
142k
  FlatTree tree =
172
142k
      FilterTree(global_tree, static_props, &num_props,
173
142k
                 &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
385k
  for (auto &node : tree) {
178
385k
    if (node.property0 == -1) {
179
325k
      node.childID = context_map[node.childID];
180
325k
    }
181
385k
  }
182
183
142k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
142k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
89.4M
                             pixel_type_w offset) -> pixel_type {
188
89.4M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
89.4M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
89.4M
    return val * multiplier + offset;
192
89.4M
  };
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
24.9M
                             pixel_type_w offset) -> pixel_type {
188
24.9M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
24.9M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
24.9M
    return val * multiplier + offset;
192
24.9M
  };
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
64.4M
                             pixel_type_w offset) -> pixel_type {
188
64.4M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
64.4M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
64.4M
    return val * multiplier + offset;
192
64.4M
  };
193
194
142k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
128k
    Predictor predictor = tree[0].predictor;
198
128k
    int64_t offset = tree[0].predictor_offset;
199
128k
    int32_t multiplier = tree[0].multiplier;
200
128k
    size_t ctx_id = tree[0].childID;
201
128k
    if (predictor == Predictor::Zero) {
202
102k
      uint32_t value;
203
102k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
102k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
43.6k
        JXL_DEBUG_V(8, "Fastest track.");
208
43.6k
        pixel_type v = make_pixel(value, multiplier, offset);
209
935k
        for (size_t y = 0; y < channel.h; y++) {
210
891k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
891k
          std::fill(r, r + channel.w, v);
212
891k
        }
213
58.6k
      } else {
214
58.6k
        JXL_DEBUG_V(8, "Fast track.");
215
58.6k
        if (multiplier == 1 && offset == 0) {
216
707k
          for (size_t y = 0; y < channel.h; y++) {
217
669k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
31.2M
            for (size_t x = 0; x < channel.w; x++) {
219
30.6M
              uint32_t v =
220
30.6M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
30.6M
              r[x] = UnpackSigned(v);
222
30.6M
            }
223
669k
          }
224
38.4k
        } else {
225
458k
          for (size_t y = 0; y < channel.h; y++) {
226
437k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
18.1M
            for (size_t x = 0; x < channel.w; x++) {
228
17.7M
              uint32_t v =
229
17.7M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
17.7M
                                                                         br);
231
17.7M
              r[x] = make_pixel(v, multiplier, offset);
232
17.7M
            }
233
437k
          }
234
20.1k
        }
235
58.6k
      }
236
102k
      return true;
237
102k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
26.5k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
75
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
75
      pixel_type_w sv = UnpackSigned(fl_v);
241
969
      for (size_t y = 0; y < channel.h; y++) {
242
894
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
894
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
894
        const pixel_type *JXL_RESTRICT rtopleft =
245
894
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
894
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
894
        if (fl_run == 0) {
248
894
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
894
                                                     &fl_run);
250
894
          sv = UnpackSigned(fl_v);
251
894
        } else {
252
0
          fl_run--;
253
0
        }
254
894
        r[0] = sv + guess_0;
255
33.3k
        for (size_t x = 1; x < channel.w; x++) {
256
32.4k
          pixel_type left = r[x - 1];
257
32.4k
          pixel_type top = rtop[x];
258
32.4k
          pixel_type topleft = rtopleft[x];
259
32.4k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
32.4k
          if (!fl_run) {
261
32.4k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
32.4k
                                                       &fl_run);
263
32.4k
            sv = UnpackSigned(fl_v);
264
32.4k
          } else {
265
0
            fl_run--;
266
0
          }
267
32.4k
          r[x] = sv + guess;
268
32.4k
        }
269
894
      }
270
75
      return true;
271
26.5k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
26.5k
               multiplier == 1) {
273
813
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
813
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
15.9k
      for (size_t y = 0; y < channel.h; y++) {
276
15.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
646k
        for (size_t x = 0; x < channel.w; x++) {
278
631k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
631k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
631k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
631k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
631k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
631k
              ctx_id, br);
284
631k
          r[x] = make_pixel(v, 1, guess);
285
631k
        }
286
15.1k
      }
287
813
      return true;
288
813
    }
289
128k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
39.4k
  if (is_wp_only) {
294
2.43k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
2.43k
  }
296
39.4k
  if (is_gradient_only) {
297
1.74k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.74k
  }
299
300
39.4k
  if (is_gradient_only) {
301
498
    JXL_DEBUG_V(8, "Gradient fast track.");
302
498
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
13.0k
    for (size_t y = 0; y < channel.h; y++) {
304
12.5k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
426k
      for (size_t x = 0; x < channel.w; x++) {
306
413k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
413k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
413k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
413k
        int32_t guess = ClampedGradient(top, left, topleft);
310
413k
        uint32_t pos =
311
413k
            kPropRangeFast +
312
413k
            std::min<pixel_type_w>(
313
413k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
413k
                kPropRangeFast - 1);
315
413k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
413k
        uint64_t v =
317
413k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
413k
        r[x] = make_pixel(v, 1, guess);
319
413k
      }
320
12.5k
    }
321
38.9k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
855
    JXL_DEBUG_V(8, "WP fast track.");
323
855
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
855
    Properties properties(1);
325
19.6k
    for (size_t y = 0; y < channel.h; y++) {
326
18.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
18.7k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
18.7k
      const pixel_type *JXL_RESTRICT rtoptop =
329
18.7k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
18.7k
      const pixel_type *JXL_RESTRICT rtopleft =
331
18.7k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
18.7k
      const pixel_type *JXL_RESTRICT rtopright =
333
18.7k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
18.7k
      size_t x = 0;
335
18.7k
      {
336
18.7k
        size_t offset = 0;
337
18.7k
        pixel_type_w left = y ? rtop[x] : 0;
338
18.7k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
18.7k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
18.7k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
18.7k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
18.7k
            offset);
343
18.7k
        uint32_t pos =
344
18.7k
            kPropRangeFast +
345
18.7k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
18.7k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
18.7k
        uint64_t v =
348
18.7k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
18.7k
        r[x] = make_pixel(v, 1, guess);
350
18.7k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
18.7k
      }
352
706k
      for (x = 1; x + 1 < channel.w; x++) {
353
687k
        size_t offset = 0;
354
687k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
687k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
687k
            rtoptop[x], &properties, offset);
357
687k
        uint32_t pos =
358
687k
            kPropRangeFast +
359
687k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
687k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
687k
        uint64_t v =
362
687k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
687k
        r[x] = make_pixel(v, 1, guess);
364
687k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
687k
      }
366
18.7k
      {
367
18.7k
        size_t offset = 0;
368
18.7k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
18.7k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
18.7k
            rtoptop[x], &properties, offset);
371
18.7k
        uint32_t pos =
372
18.7k
            kPropRangeFast +
373
18.7k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
18.7k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
18.7k
        uint64_t v =
376
18.7k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
18.7k
        r[x] = make_pixel(v, 1, guess);
378
18.7k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
18.7k
      }
380
18.7k
    }
381
38.0k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
30.2k
    JXL_DEBUG_V(8, "Slow track.");
385
30.2k
    MATreeLookup tree_lookup(tree);
386
30.2k
    Properties properties = Properties(num_props);
387
30.2k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
30.2k
    JXL_ASSIGN_OR_RETURN(
389
30.2k
        Channel references,
390
30.2k
        Channel::Create(memory_manager,
391
30.2k
                        properties.size() - kNumNonrefProperties, channel.w));
392
629k
    for (size_t y = 0; y < channel.h; y++) {
393
599k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
599k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
599k
      InitPropsRow(&properties, static_props, y);
396
599k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.41M
        for (size_t x = 0; x < 2; x++) {
398
944k
          PredictionResult res =
399
944k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
944k
                              tree_lookup, references);
401
944k
          uint64_t v =
402
944k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
944k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
944k
        }
405
33.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
32.5M
          PredictionResult res =
407
32.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
32.5M
                                 tree_lookup, references);
409
32.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
32.5M
              res.context, br);
411
32.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
32.5M
        }
413
1.41M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
944k
          PredictionResult res =
415
944k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
944k
                              tree_lookup, references);
417
944k
          uint64_t v =
418
944k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
944k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
944k
        }
421
472k
      } else {
422
3.55M
        for (size_t x = 0; x < channel.w; x++) {
423
3.42M
          PredictionResult res =
424
3.42M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
3.42M
                              tree_lookup, references);
426
3.42M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
3.42M
              res.context, br);
428
3.42M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
3.42M
        }
430
127k
      }
431
599k
    }
432
30.2k
  } else {
433
7.76k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.76k
    MATreeLookup tree_lookup(tree);
435
7.76k
    Properties properties = Properties(num_props);
436
7.76k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
7.76k
    JXL_ASSIGN_OR_RETURN(
438
7.76k
        Channel references,
439
7.76k
        Channel::Create(memory_manager,
440
7.76k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.76k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
343k
    for (size_t y = 0; y < channel.h; y++) {
443
335k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
335k
      InitPropsRow(&properties, static_props, y);
445
335k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
335k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
836k
        for (size_t x = 0; x < 2; x++) {
448
557k
          PredictionResult res =
449
557k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
557k
                            tree_lookup, references, &wp_state);
451
557k
          uint64_t v =
452
557k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
557k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
557k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
557k
        }
456
29.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
29.1M
          PredictionResult res =
458
29.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
29.1M
                               tree_lookup, references, &wp_state);
460
29.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
29.1M
              res.context, br);
462
29.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
29.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
29.1M
        }
465
836k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
557k
          PredictionResult res =
467
557k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
557k
                            tree_lookup, references, &wp_state);
469
557k
          uint64_t v =
470
557k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
557k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
557k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
557k
        }
474
278k
      } else {
475
1.76M
        for (size_t x = 0; x < channel.w; x++) {
476
1.70M
          PredictionResult res =
477
1.70M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.70M
                            tree_lookup, references, &wp_state);
479
1.70M
          uint64_t v =
480
1.70M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.70M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.70M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.70M
        }
484
56.7k
      }
485
335k
    }
486
7.76k
  }
487
39.4k
  return true;
488
39.4k
}
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
48.3k
                                 uint32_t &fl_v) {
157
48.3k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
48.3k
  Channel &channel = image->channel[chan];
159
160
48.3k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
48.3k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
48.3k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
48.3k
  bool tree_has_wp_prop_or_pred = false;
168
48.3k
  bool is_wp_only = false;
169
48.3k
  bool is_gradient_only = false;
170
48.3k
  size_t num_props;
171
48.3k
  FlatTree tree =
172
48.3k
      FilterTree(global_tree, static_props, &num_props,
173
48.3k
                 &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
58.9k
  for (auto &node : tree) {
178
58.9k
    if (node.property0 == -1) {
179
56.2k
      node.childID = context_map[node.childID];
180
56.2k
    }
181
58.9k
  }
182
183
48.3k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
48.3k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
48.3k
                             pixel_type_w offset) -> pixel_type {
188
48.3k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
48.3k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
48.3k
    return val * multiplier + offset;
192
48.3k
  };
193
194
48.3k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
46.1k
    Predictor predictor = tree[0].predictor;
198
46.1k
    int64_t offset = tree[0].predictor_offset;
199
46.1k
    int32_t multiplier = tree[0].multiplier;
200
46.1k
    size_t ctx_id = tree[0].childID;
201
46.1k
    if (predictor == Predictor::Zero) {
202
36.3k
      uint32_t value;
203
36.3k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
36.3k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
24.0k
        JXL_DEBUG_V(8, "Fastest track.");
208
24.0k
        pixel_type v = make_pixel(value, multiplier, offset);
209
475k
        for (size_t y = 0; y < channel.h; y++) {
210
451k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
451k
          std::fill(r, r + channel.w, v);
212
451k
        }
213
24.0k
      } else {
214
12.3k
        JXL_DEBUG_V(8, "Fast track.");
215
12.3k
        if (multiplier == 1 && offset == 0) {
216
52.4k
          for (size_t y = 0; y < channel.h; y++) {
217
48.6k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
3.09M
            for (size_t x = 0; x < channel.w; x++) {
219
3.04M
              uint32_t v =
220
3.04M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
3.04M
              r[x] = UnpackSigned(v);
222
3.04M
            }
223
48.6k
          }
224
8.59k
        } else {
225
209k
          for (size_t y = 0; y < channel.h; y++) {
226
200k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
9.29M
            for (size_t x = 0; x < channel.w; x++) {
228
9.09M
              uint32_t v =
229
9.09M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
9.09M
                                                                         br);
231
9.09M
              r[x] = make_pixel(v, multiplier, offset);
232
9.09M
            }
233
200k
          }
234
8.59k
        }
235
12.3k
      }
236
36.3k
      return true;
237
36.3k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
9.78k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
75
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
75
      pixel_type_w sv = UnpackSigned(fl_v);
241
969
      for (size_t y = 0; y < channel.h; y++) {
242
894
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
894
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
894
        const pixel_type *JXL_RESTRICT rtopleft =
245
894
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
894
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
894
        if (fl_run == 0) {
248
894
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
894
                                                     &fl_run);
250
894
          sv = UnpackSigned(fl_v);
251
894
        } else {
252
0
          fl_run--;
253
0
        }
254
894
        r[0] = sv + guess_0;
255
33.3k
        for (size_t x = 1; x < channel.w; x++) {
256
32.4k
          pixel_type left = r[x - 1];
257
32.4k
          pixel_type top = rtop[x];
258
32.4k
          pixel_type topleft = rtopleft[x];
259
32.4k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
32.4k
          if (!fl_run) {
261
32.4k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
32.4k
                                                       &fl_run);
263
32.4k
            sv = UnpackSigned(fl_v);
264
32.4k
          } else {
265
0
            fl_run--;
266
0
          }
267
32.4k
          r[x] = sv + guess;
268
32.4k
        }
269
894
      }
270
75
      return true;
271
9.71k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
9.71k
               multiplier == 1) {
273
266
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
266
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
5.47k
      for (size_t y = 0; y < channel.h; y++) {
276
5.21k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
139k
        for (size_t x = 0; x < channel.w; x++) {
278
134k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
134k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
134k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
134k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
134k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
134k
              ctx_id, br);
284
134k
          r[x] = make_pixel(v, 1, guess);
285
134k
        }
286
5.21k
      }
287
266
      return true;
288
266
    }
289
46.1k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
11.6k
  if (is_wp_only) {
294
687
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
687
  }
296
11.6k
  if (is_gradient_only) {
297
663
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
663
  }
299
300
11.6k
  if (is_gradient_only) {
301
3
    JXL_DEBUG_V(8, "Gradient fast track.");
302
3
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
36
    for (size_t y = 0; y < channel.h; y++) {
304
33
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
330
      for (size_t x = 0; x < channel.w; x++) {
306
297
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
297
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
297
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
297
        int32_t guess = ClampedGradient(top, left, topleft);
310
297
        uint32_t pos =
311
297
            kPropRangeFast +
312
297
            std::min<pixel_type_w>(
313
297
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
297
                kPropRangeFast - 1);
315
297
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
297
        uint64_t v =
317
297
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
297
        r[x] = make_pixel(v, 1, guess);
319
297
      }
320
33
    }
321
11.6k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
0
    JXL_DEBUG_V(8, "WP fast track.");
323
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
0
    Properties properties(1);
325
0
    for (size_t y = 0; y < channel.h; y++) {
326
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
0
      const pixel_type *JXL_RESTRICT rtoptop =
329
0
          (y > 1 ? channel.Row(y - 2) : rtop);
330
0
      const pixel_type *JXL_RESTRICT rtopleft =
331
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
0
      const pixel_type *JXL_RESTRICT rtopright =
333
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
0
      size_t x = 0;
335
0
      {
336
0
        size_t offset = 0;
337
0
        pixel_type_w left = y ? rtop[x] : 0;
338
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
0
            offset);
343
0
        uint32_t pos =
344
0
            kPropRangeFast +
345
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
0
        uint64_t v =
348
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
0
        r[x] = make_pixel(v, 1, guess);
350
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
0
      }
352
0
      for (x = 1; x + 1 < channel.w; x++) {
353
0
        size_t offset = 0;
354
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
0
            rtoptop[x], &properties, offset);
357
0
        uint32_t pos =
358
0
            kPropRangeFast +
359
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
0
        uint64_t v =
362
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
0
        r[x] = make_pixel(v, 1, guess);
364
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
0
      }
366
0
      {
367
0
        size_t offset = 0;
368
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
0
            rtoptop[x], &properties, offset);
371
0
        uint32_t pos =
372
0
            kPropRangeFast +
373
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
0
        uint64_t v =
376
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
0
        r[x] = make_pixel(v, 1, guess);
378
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
0
      }
380
0
    }
381
11.6k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
10.6k
    JXL_DEBUG_V(8, "Slow track.");
385
10.6k
    MATreeLookup tree_lookup(tree);
386
10.6k
    Properties properties = Properties(num_props);
387
10.6k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
10.6k
    JXL_ASSIGN_OR_RETURN(
389
10.6k
        Channel references,
390
10.6k
        Channel::Create(memory_manager,
391
10.6k
                        properties.size() - kNumNonrefProperties, channel.w));
392
234k
    for (size_t y = 0; y < channel.h; y++) {
393
223k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
223k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
223k
      InitPropsRow(&properties, static_props, y);
396
223k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
568k
        for (size_t x = 0; x < 2; x++) {
398
378k
          PredictionResult res =
399
378k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
378k
                              tree_lookup, references);
401
378k
          uint64_t v =
402
378k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
378k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
378k
        }
405
13.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
12.9M
          PredictionResult res =
407
12.9M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
12.9M
                                 tree_lookup, references);
409
12.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
12.9M
              res.context, br);
411
12.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
12.9M
        }
413
568k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
378k
          PredictionResult res =
415
378k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
378k
                              tree_lookup, references);
417
378k
          uint64_t v =
418
378k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
378k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
378k
        }
421
189k
      } else {
422
1.46M
        for (size_t x = 0; x < channel.w; x++) {
423
1.43M
          PredictionResult res =
424
1.43M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.43M
                              tree_lookup, references);
426
1.43M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.43M
              res.context, br);
428
1.43M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.43M
        }
430
34.3k
      }
431
223k
    }
432
10.6k
  } else {
433
981
    JXL_DEBUG_V(8, "Slowest track.");
434
981
    MATreeLookup tree_lookup(tree);
435
981
    Properties properties = Properties(num_props);
436
981
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
981
    JXL_ASSIGN_OR_RETURN(
438
981
        Channel references,
439
981
        Channel::Create(memory_manager,
440
981
                        properties.size() - kNumNonrefProperties, channel.w));
441
981
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
23.5k
    for (size_t y = 0; y < channel.h; y++) {
443
22.5k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
22.5k
      InitPropsRow(&properties, static_props, y);
445
22.5k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
22.5k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
0
        for (size_t x = 0; x < 2; x++) {
448
0
          PredictionResult res =
449
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
0
                            tree_lookup, references, &wp_state);
451
0
          uint64_t v =
452
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
0
        }
456
0
        for (size_t x = 2; x < channel.w - 2; x++) {
457
0
          PredictionResult res =
458
0
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
0
                               tree_lookup, references, &wp_state);
460
0
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
0
              res.context, br);
462
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
0
        }
465
0
        for (size_t x = channel.w - 2; x < channel.w; 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
22.5k
      } else {
475
606k
        for (size_t x = 0; x < channel.w; x++) {
476
584k
          PredictionResult res =
477
584k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
584k
                            tree_lookup, references, &wp_state);
479
584k
          uint64_t v =
480
584k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
584k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
584k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
584k
        }
484
22.5k
      }
485
22.5k
    }
486
981
  }
487
11.6k
  return true;
488
11.6k
}
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
94.2k
                                 uint32_t &fl_v) {
157
94.2k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
94.2k
  Channel &channel = image->channel[chan];
159
160
94.2k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
94.2k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
94.2k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
94.2k
  bool tree_has_wp_prop_or_pred = false;
168
94.2k
  bool is_wp_only = false;
169
94.2k
  bool is_gradient_only = false;
170
94.2k
  size_t num_props;
171
94.2k
  FlatTree tree =
172
94.2k
      FilterTree(global_tree, static_props, &num_props,
173
94.2k
                 &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
326k
  for (auto &node : tree) {
178
326k
    if (node.property0 == -1) {
179
268k
      node.childID = context_map[node.childID];
180
268k
    }
181
326k
  }
182
183
94.2k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
94.2k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
94.2k
                             pixel_type_w offset) -> pixel_type {
188
94.2k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
94.2k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
94.2k
    return val * multiplier + offset;
192
94.2k
  };
193
194
94.2k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
82.7k
    Predictor predictor = tree[0].predictor;
198
82.7k
    int64_t offset = tree[0].predictor_offset;
199
82.7k
    int32_t multiplier = tree[0].multiplier;
200
82.7k
    size_t ctx_id = tree[0].childID;
201
82.7k
    if (predictor == Predictor::Zero) {
202
65.9k
      uint32_t value;
203
65.9k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
65.9k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
19.6k
        JXL_DEBUG_V(8, "Fastest track.");
208
19.6k
        pixel_type v = make_pixel(value, multiplier, offset);
209
459k
        for (size_t y = 0; y < channel.h; y++) {
210
439k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
439k
          std::fill(r, r + channel.w, v);
212
439k
        }
213
46.2k
      } else {
214
46.2k
        JXL_DEBUG_V(8, "Fast track.");
215
46.2k
        if (multiplier == 1 && offset == 0) {
216
655k
          for (size_t y = 0; y < channel.h; y++) {
217
620k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
28.2M
            for (size_t x = 0; x < channel.w; x++) {
219
27.5M
              uint32_t v =
220
27.5M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
27.5M
              r[x] = UnpackSigned(v);
222
27.5M
            }
223
620k
          }
224
34.6k
        } else {
225
248k
          for (size_t y = 0; y < channel.h; y++) {
226
237k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
8.88M
            for (size_t x = 0; x < channel.w; x++) {
228
8.64M
              uint32_t v =
229
8.64M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
8.64M
                                                                         br);
231
8.64M
              r[x] = make_pixel(v, multiplier, offset);
232
8.64M
            }
233
237k
          }
234
11.6k
        }
235
46.2k
      }
236
65.9k
      return true;
237
65.9k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
16.7k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
0
      pixel_type_w sv = UnpackSigned(fl_v);
241
0
      for (size_t y = 0; y < channel.h; y++) {
242
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
0
        const pixel_type *JXL_RESTRICT rtopleft =
245
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
0
        if (fl_run == 0) {
248
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
0
                                                     &fl_run);
250
0
          sv = UnpackSigned(fl_v);
251
0
        } else {
252
0
          fl_run--;
253
0
        }
254
0
        r[0] = sv + guess_0;
255
0
        for (size_t x = 1; x < channel.w; x++) {
256
0
          pixel_type left = r[x - 1];
257
0
          pixel_type top = rtop[x];
258
0
          pixel_type topleft = rtopleft[x];
259
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
0
          if (!fl_run) {
261
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
0
                                                       &fl_run);
263
0
            sv = UnpackSigned(fl_v);
264
0
          } else {
265
0
            fl_run--;
266
0
          }
267
0
          r[x] = sv + guess;
268
0
        }
269
0
      }
270
0
      return true;
271
16.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
16.7k
               multiplier == 1) {
273
547
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
547
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
10.4k
      for (size_t y = 0; y < channel.h; y++) {
276
9.91k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
506k
        for (size_t x = 0; x < channel.w; x++) {
278
496k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
496k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
496k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
496k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
496k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
496k
              ctx_id, br);
284
496k
          r[x] = make_pixel(v, 1, guess);
285
496k
        }
286
9.91k
      }
287
547
      return true;
288
547
    }
289
82.7k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
27.7k
  if (is_wp_only) {
294
1.74k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
1.74k
  }
296
27.7k
  if (is_gradient_only) {
297
1.08k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.08k
  }
299
300
27.7k
  if (is_gradient_only) {
301
495
    JXL_DEBUG_V(8, "Gradient fast track.");
302
495
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
13.0k
    for (size_t y = 0; y < channel.h; y++) {
304
12.5k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
425k
      for (size_t x = 0; x < channel.w; x++) {
306
413k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
413k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
413k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
413k
        int32_t guess = ClampedGradient(top, left, topleft);
310
413k
        uint32_t pos =
311
413k
            kPropRangeFast +
312
413k
            std::min<pixel_type_w>(
313
413k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
413k
                kPropRangeFast - 1);
315
413k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
413k
        uint64_t v =
317
413k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
413k
        r[x] = make_pixel(v, 1, guess);
319
413k
      }
320
12.5k
    }
321
27.2k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
855
    JXL_DEBUG_V(8, "WP fast track.");
323
855
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
855
    Properties properties(1);
325
19.6k
    for (size_t y = 0; y < channel.h; y++) {
326
18.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
18.7k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
18.7k
      const pixel_type *JXL_RESTRICT rtoptop =
329
18.7k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
18.7k
      const pixel_type *JXL_RESTRICT rtopleft =
331
18.7k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
18.7k
      const pixel_type *JXL_RESTRICT rtopright =
333
18.7k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
18.7k
      size_t x = 0;
335
18.7k
      {
336
18.7k
        size_t offset = 0;
337
18.7k
        pixel_type_w left = y ? rtop[x] : 0;
338
18.7k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
18.7k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
18.7k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
18.7k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
18.7k
            offset);
343
18.7k
        uint32_t pos =
344
18.7k
            kPropRangeFast +
345
18.7k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
18.7k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
18.7k
        uint64_t v =
348
18.7k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
18.7k
        r[x] = make_pixel(v, 1, guess);
350
18.7k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
18.7k
      }
352
706k
      for (x = 1; x + 1 < channel.w; x++) {
353
687k
        size_t offset = 0;
354
687k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
687k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
687k
            rtoptop[x], &properties, offset);
357
687k
        uint32_t pos =
358
687k
            kPropRangeFast +
359
687k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
687k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
687k
        uint64_t v =
362
687k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
687k
        r[x] = make_pixel(v, 1, guess);
364
687k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
687k
      }
366
18.7k
      {
367
18.7k
        size_t offset = 0;
368
18.7k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
18.7k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
18.7k
            rtoptop[x], &properties, offset);
371
18.7k
        uint32_t pos =
372
18.7k
            kPropRangeFast +
373
18.7k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
18.7k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
18.7k
        uint64_t v =
376
18.7k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
18.7k
        r[x] = make_pixel(v, 1, guess);
378
18.7k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
18.7k
      }
380
18.7k
    }
381
26.3k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
19.6k
    JXL_DEBUG_V(8, "Slow track.");
385
19.6k
    MATreeLookup tree_lookup(tree);
386
19.6k
    Properties properties = Properties(num_props);
387
19.6k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
19.6k
    JXL_ASSIGN_OR_RETURN(
389
19.6k
        Channel references,
390
19.6k
        Channel::Create(memory_manager,
391
19.6k
                        properties.size() - kNumNonrefProperties, channel.w));
392
395k
    for (size_t y = 0; y < channel.h; y++) {
393
375k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
375k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
375k
      InitPropsRow(&properties, static_props, y);
396
375k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
848k
        for (size_t x = 0; x < 2; x++) {
398
565k
          PredictionResult res =
399
565k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
565k
                              tree_lookup, references);
401
565k
          uint64_t v =
402
565k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
565k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
565k
        }
405
19.8M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
19.5M
          PredictionResult res =
407
19.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
19.5M
                                 tree_lookup, references);
409
19.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
19.5M
              res.context, br);
411
19.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
19.5M
        }
413
848k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
565k
          PredictionResult res =
415
565k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
565k
                              tree_lookup, references);
417
565k
          uint64_t v =
418
565k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
565k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
565k
        }
421
282k
      } else {
422
2.08M
        for (size_t x = 0; x < channel.w; x++) {
423
1.99M
          PredictionResult res =
424
1.99M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.99M
                              tree_lookup, references);
426
1.99M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.99M
              res.context, br);
428
1.99M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.99M
        }
430
93.0k
      }
431
375k
    }
432
19.6k
  } else {
433
6.77k
    JXL_DEBUG_V(8, "Slowest track.");
434
6.77k
    MATreeLookup tree_lookup(tree);
435
6.77k
    Properties properties = Properties(num_props);
436
6.77k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
6.77k
    JXL_ASSIGN_OR_RETURN(
438
6.77k
        Channel references,
439
6.77k
        Channel::Create(memory_manager,
440
6.77k
                        properties.size() - kNumNonrefProperties, channel.w));
441
6.77k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
319k
    for (size_t y = 0; y < channel.h; y++) {
443
312k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
312k
      InitPropsRow(&properties, static_props, y);
445
312k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
312k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
836k
        for (size_t x = 0; x < 2; x++) {
448
557k
          PredictionResult res =
449
557k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
557k
                            tree_lookup, references, &wp_state);
451
557k
          uint64_t v =
452
557k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
557k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
557k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
557k
        }
456
29.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
29.1M
          PredictionResult res =
458
29.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
29.1M
                               tree_lookup, references, &wp_state);
460
29.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
29.1M
              res.context, br);
462
29.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
29.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
29.1M
        }
465
836k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
557k
          PredictionResult res =
467
557k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
557k
                            tree_lookup, references, &wp_state);
469
557k
          uint64_t v =
470
557k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
557k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
557k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
557k
        }
474
278k
      } else {
475
1.15M
        for (size_t x = 0; x < channel.w; x++) {
476
1.12M
          PredictionResult res =
477
1.12M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.12M
                            tree_lookup, references, &wp_state);
479
1.12M
          uint64_t v =
480
1.12M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.12M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.12M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.12M
        }
484
34.1k
      }
485
312k
    }
486
6.77k
  }
487
27.7k
  return true;
488
27.7k
}
489
}  // namespace detail
490
491
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
492
                                 const std::vector<uint8_t> &context_map,
493
                                 const Tree &global_tree,
494
                                 const weighted::Header &wp_header,
495
                                 pixel_type chan, size_t group_id,
496
                                 TreeLut<uint8_t, false, false> &tree_lut,
497
                                 Image *image, uint32_t &fl_run,
498
142k
                                 uint32_t &fl_v) {
499
142k
  if (reader->UsesLZ77()) {
500
48.3k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
48.3k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
48.3k
        tree_lut, image, fl_run, fl_v);
503
94.2k
  } else {
504
94.2k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
94.2k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
94.2k
        tree_lut, image, fl_run, fl_v);
507
94.2k
  }
508
142k
}
509
510
142k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
29.1k
                                 const ModularOptions &options) {
514
29.1k
  size_t nb_channels = image.channel.size();
515
58.3k
  for (bool is_dc : {true, false}) {
516
58.3k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
58.3k
    size_t c = image.nb_meta_channels;
518
369k
    for (; c < nb_channels; c++) {
519
312k
      const Channel &ch = image.channel[c];
520
312k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
312k
    }
522
62.5k
    for (; c < nb_channels; c++) {
523
4.22k
      const Channel &ch = image.channel[c];
524
4.22k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
3.78k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
3.78k
      if (is_dc_channel != is_dc) continue;
527
1.90k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
1.90k
      if (tile_dim == 0) {
529
6
        return JXL_FAILURE("Inconsistent transforms");
530
6
      }
531
1.90k
    }
532
58.3k
  }
533
29.1k
  return true;
534
29.1k
}
535
536
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
537
                     size_t group_id, ModularOptions *options,
538
                     const Tree *global_tree, const ANSCode *global_code,
539
                     const std::vector<uint8_t> *global_ctx_map,
540
32.4k
                     const bool allow_truncated_group) {
541
32.4k
  if (image.channel.empty()) return true;
542
29.0k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
29.0k
  Status status = Bundle::Read(br, &header);
546
29.0k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
28.2k
  if (status.IsFatalError()) return status;
548
28.2k
  if (!br->AllReadsWithinBounds()) {
549
    // Don't do/undo transforms if header is incomplete.
550
0
    header.transforms.clear();
551
0
    image.transform = header.transforms;
552
0
    for (auto &ch : image.channel) {
553
0
      ZeroFillImage(&ch.plane);
554
0
    }
555
0
    return JXL_NOT_ENOUGH_BYTES("Read overrun before ModularDecode");
556
0
  }
557
558
28.2k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
28.2k
              header.transforms.size());
560
28.2k
  image.transform = header.transforms;
561
28.2k
  for (Transform &transform : image.transform) {
562
8.92k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
8.92k
  }
564
28.1k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
28.1k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
28.1k
  size_t nb_channels = image.channel.size();
570
571
28.1k
  size_t num_chans = 0;
572
28.1k
  size_t distance_multiplier = 0;
573
181k
  for (size_t i = 0; i < nb_channels; i++) {
574
153k
    Channel &channel = image.channel[i];
575
153k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
152k
                                        channel.h > options->max_chan_size)) {
577
341
      break;
578
341
    }
579
153k
    if (!channel.w || !channel.h) {
580
1.13k
      continue;  // skip empty channels
581
1.13k
    }
582
152k
    if (channel.w > distance_multiplier) {
583
37.3k
      distance_multiplier = channel.w;
584
37.3k
    }
585
152k
    num_chans++;
586
152k
  }
587
28.1k
  if (num_chans == 0) return true;
588
589
27.8k
  size_t next_channel = 0;
590
27.8k
  auto scope_guard = MakeScopeGuard([&]() {
591
15.6k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
12.4k
      ZeroFillImage(&image.channel[c].plane);
593
12.4k
    }
594
3.13k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
27.8k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
27.8k
  Tree tree_storage;
600
27.8k
  std::vector<uint8_t> context_map_storage;
601
27.8k
  ANSCode code_storage;
602
27.8k
  const Tree *tree = &tree_storage;
603
27.8k
  const ANSCode *code = &code_storage;
604
27.8k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
27.8k
  if (!header.use_global_tree) {
606
23.3k
    uint64_t max_tree_size = 1024;
607
151k
    for (size_t i = 0; i < nb_channels; i++) {
608
128k
      Channel &channel = image.channel[i];
609
128k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
127k
                                          channel.h > options->max_chan_size)) {
611
39
        break;
612
39
      }
613
128k
      uint64_t pixels = channel.w * channel.h;
614
128k
      max_tree_size += pixels;
615
128k
    }
616
23.3k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
23.3k
    JXL_RETURN_IF_ERROR(
618
23.3k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
22.9k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
22.9k
                                         (tree_storage.size() + 1) / 2,
621
22.9k
                                         &code_storage, &context_map_storage));
622
22.9k
  } else {
623
4.52k
    if (!global_tree || !global_code || !global_ctx_map ||
624
4.52k
        global_tree->empty()) {
625
200
      return JXL_FAILURE("No global tree available but one was requested");
626
200
    }
627
4.32k
    tree = global_tree;
628
4.32k
    code = global_code;
629
4.32k
    context_map = global_ctx_map;
630
4.32k
  }
631
632
  // Read channels
633
54.4k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
54.4k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
54.4k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
54.4k
  uint32_t fl_run = 0;
637
54.4k
  uint32_t fl_v = 0;
638
168k
  for (; next_channel < nb_channels; next_channel++) {
639
143k
    Channel &channel = image.channel[next_channel];
640
143k
    if (next_channel >= image.nb_meta_channels &&
641
143k
        (channel.w > options->max_chan_size ||
642
142k
         channel.h > options->max_chan_size)) {
643
63
      break;
644
63
    }
645
143k
    if (!channel.w || !channel.h) {
646
872
      continue;  // skip empty channels
647
872
    }
648
142k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
142k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
142k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
142k
    if (!br->AllReadsWithinBounds()) {
654
2.50k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
2.50k
    }
657
142k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
24.7k
  scope_guard.Disarm();
661
662
24.7k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
24.7k
  return true;
666
24.7k
}
667
668
Status ModularGenericDecompress(BitReader *br, Image &image,
669
                                GroupHeader *header, size_t group_id,
670
                                ModularOptions *options, bool undo_transforms,
671
                                const Tree *tree, const ANSCode *code,
672
                                const std::vector<uint8_t> *ctx_map,
673
32.4k
                                bool allow_truncated_group) {
674
32.4k
  std::vector<std::pair<uint32_t, uint32_t>> req_sizes;
675
32.4k
  req_sizes.reserve(image.channel.size());
676
92.2k
  for (const auto &c : image.channel) {
677
92.2k
    req_sizes.emplace_back(c.w, c.h);
678
92.2k
  }
679
32.4k
  GroupHeader local_header;
680
32.4k
  if (header == nullptr) header = &local_header;
681
32.4k
  size_t bit_pos = br->TotalBitsConsumed();
682
32.4k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
32.4k
                                  code, ctx_map, allow_truncated_group);
684
32.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
28.4k
  if (dec_status.IsFatalError()) return dec_status;
686
28.4k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
28.4k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
28.4k
  JXL_DEBUG_V(4,
689
28.4k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
28.4k
              " image from %" PRIuS " bytes",
691
28.4k
              image.w, image.h, image.channel.size(),
692
28.4k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
28.4k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
28.4k
  (void)bit_pos;
695
  // Check that after applying all transforms we are back to the requested
696
  // image sizes, otherwise there's a programming error with the
697
  // transformations.
698
28.4k
  if (undo_transforms) {
699
5.61k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
24.9k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
19.3k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
19.3k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
19.3k
    }
704
5.61k
  }
705
28.4k
  return dec_status;
706
28.4k
}
707
708
}  // namespace jxl