Coverage Report

Created: 2026-02-14 07:09

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
141k
                    bool *gradient_only) {
46
141k
  *num_props = 0;
47
141k
  bool has_wp = false;
48
141k
  bool has_non_wp = false;
49
141k
  *gradient_only = true;
50
192k
  const auto mark_property = [&](int32_t p) {
51
192k
    if (p == kWPProp) {
52
10.2k
      has_wp = true;
53
182k
    } else if (p >= kNumStaticProperties) {
54
115k
      has_non_wp = true;
55
115k
    }
56
192k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
110k
      *gradient_only = false;
58
110k
    }
59
192k
  };
60
141k
  FlatTree output;
61
141k
  std::queue<size_t> nodes;
62
141k
  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
542k
  while (!nodes.empty()) {
70
401k
    size_t cur = nodes.front();
71
401k
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
426k
    while (global_tree[cur].property < kNumStaticProperties &&
74
363k
           global_tree[cur].property != -1) {
75
25.0k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
13.8k
        cur = global_tree[cur].lchild;
77
13.8k
      } else {
78
11.1k
        cur = global_tree[cur].rchild;
79
11.1k
      }
80
25.0k
    }
81
401k
    FlatDecisionNode flat;
82
401k
    if (global_tree[cur].property == -1) {
83
341k
      flat.property0 = -1;
84
341k
      flat.childID = global_tree[cur].lchild;
85
341k
      flat.predictor = global_tree[cur].predictor;
86
341k
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
341k
      flat.multiplier = global_tree[cur].multiplier;
88
341k
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
341k
      has_wp |= flat.predictor == Predictor::Weighted;
90
341k
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
341k
      output.push_back(flat);
92
341k
      continue;
93
341k
    }
94
59.8k
    flat.childID = output.size() + nodes.size() + 1;
95
96
59.8k
    flat.property0 = global_tree[cur].property;
97
59.8k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
59.8k
    flat.splitval0 = global_tree[cur].splitval;
99
100
192k
    for (size_t i = 0; i < 2; i++) {
101
132k
      size_t cur_child =
102
132k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
152k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
90.5k
             global_tree[cur_child].property != -1) {
106
19.7k
        if (static_props[global_tree[cur_child].property] >
107
19.7k
            global_tree[cur_child].splitval) {
108
12.2k
          cur_child = global_tree[cur_child].lchild;
109
12.2k
        } else {
110
7.58k
          cur_child = global_tree[cur_child].rchild;
111
7.58k
        }
112
19.7k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
132k
      if (global_tree[cur_child].property == -1) {
116
72.3k
        flat.properties[i] = 0;
117
72.3k
        flat.splitvals[i] = 0;
118
72.3k
        nodes.push(cur_child);
119
72.3k
        nodes.push(cur_child);
120
72.3k
      } else {
121
59.9k
        flat.properties[i] = global_tree[cur_child].property;
122
59.9k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
59.9k
        nodes.push(global_tree[cur_child].lchild);
124
59.9k
        nodes.push(global_tree[cur_child].rchild);
125
59.9k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
59.9k
      }
127
132k
    }
128
129
129k
    for (int16_t property : flat.properties) mark_property(property);
130
59.8k
    mark_property(flat.property0);
131
59.8k
    output.push_back(flat);
132
59.8k
  }
133
141k
  if (*num_props > kNumNonrefProperties) {
134
9
    *num_props =
135
9
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
9
            kExtraPropsPerChannel +
137
9
        kNumNonrefProperties;
138
141k
  } else {
139
141k
    *num_props = kNumNonrefProperties;
140
141k
  }
141
141k
  *use_wp = has_wp;
142
141k
  *wp_only = has_wp && !has_non_wp;
143
144
141k
  return output;
145
141k
}
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
141k
                                 uint32_t &fl_v) {
157
141k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
141k
  Channel &channel = image->channel[chan];
159
160
141k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
141k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
141k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
141k
  bool tree_has_wp_prop_or_pred = false;
168
141k
  bool is_wp_only = false;
169
141k
  bool is_gradient_only = false;
170
141k
  size_t num_props;
171
141k
  FlatTree tree =
172
141k
      FilterTree(global_tree, static_props, &num_props,
173
141k
                 &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
420k
  for (auto &node : tree) {
178
420k
    if (node.property0 == -1) {
179
351k
      node.childID = context_map[node.childID];
180
351k
    }
181
420k
  }
182
183
141k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
141k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
37.1M
                             pixel_type_w offset) -> pixel_type {
188
37.1M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
37.1M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
37.1M
    return val * multiplier + offset;
192
37.1M
  };
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
7.71M
                             pixel_type_w offset) -> pixel_type {
188
7.71M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
7.71M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
7.71M
    return val * multiplier + offset;
192
7.71M
  };
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
29.4M
                             pixel_type_w offset) -> pixel_type {
188
29.4M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
29.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
29.4M
    return val * multiplier + offset;
192
29.4M
  };
193
194
141k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
136k
    Predictor predictor = tree[0].predictor;
198
136k
    int64_t offset = tree[0].predictor_offset;
199
136k
    int32_t multiplier = tree[0].multiplier;
200
136k
    size_t ctx_id = tree[0].childID;
201
136k
    if (predictor == Predictor::Zero) {
202
135k
      uint32_t value;
203
135k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
135k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
16.5k
        JXL_DEBUG_V(8, "Fastest track.");
208
16.5k
        pixel_type v = make_pixel(value, multiplier, offset);
209
907k
        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
118k
      } else {
214
118k
        JXL_DEBUG_V(8, "Fast track.");
215
118k
        if (multiplier == 1 && offset == 0) {
216
1.96M
          for (size_t y = 0; y < channel.h; y++) {
217
1.84M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
45.9M
            for (size_t x = 0; x < channel.w; x++) {
219
44.0M
              uint32_t v =
220
44.0M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
44.0M
              r[x] = UnpackSigned(v);
222
44.0M
            }
223
1.84M
          }
224
118k
        } else {
225
121
          for (size_t y = 0; y < channel.h; y++) {
226
97
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
2.46k
            for (size_t x = 0; x < channel.w; x++) {
228
2.36k
              uint32_t v =
229
2.36k
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
2.36k
                                                                         br);
231
2.36k
              r[x] = make_pixel(v, multiplier, offset);
232
2.36k
            }
233
97
          }
234
24
        }
235
118k
      }
236
135k
      return true;
237
135k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
0
               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
1.18k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
500
               multiplier == 1) {
273
500
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
500
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
5.13k
      for (size_t y = 0; y < channel.h; y++) {
276
4.63k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
65.9k
        for (size_t x = 0; x < channel.w; x++) {
278
61.3k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
61.3k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
61.3k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
61.3k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
61.3k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
61.3k
              ctx_id, br);
284
61.3k
          r[x] = make_pixel(v, 1, guess);
285
61.3k
        }
286
4.63k
      }
287
500
      return true;
288
500
    }
289
136k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
5.49k
  if (is_wp_only) {
294
216
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
216
  }
296
5.49k
  if (is_gradient_only) {
297
51
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
51
  }
299
300
5.49k
  if (is_gradient_only) {
301
0
    JXL_DEBUG_V(8, "Gradient fast track.");
302
0
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
0
    for (size_t y = 0; y < channel.h; y++) {
304
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
0
      for (size_t x = 0; x < channel.w; x++) {
306
0
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
0
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
0
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
0
        int32_t guess = ClampedGradient(top, left, topleft);
310
0
        uint32_t pos =
311
0
            kPropRangeFast +
312
0
            std::min<pixel_type_w>(
313
0
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
0
                kPropRangeFast - 1);
315
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
0
        uint64_t v =
317
0
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
0
        r[x] = make_pixel(v, 1, guess);
319
0
      }
320
0
    }
321
5.49k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
200
    JXL_DEBUG_V(8, "WP fast track.");
323
200
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
200
    Properties properties(1);
325
1.59k
    for (size_t y = 0; y < channel.h; y++) {
326
1.39k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
1.39k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
1.39k
      const pixel_type *JXL_RESTRICT rtoptop =
329
1.39k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
1.39k
      const pixel_type *JXL_RESTRICT rtopleft =
331
1.39k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
1.39k
      const pixel_type *JXL_RESTRICT rtopright =
333
1.39k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
1.39k
      size_t x = 0;
335
1.39k
      {
336
1.39k
        size_t offset = 0;
337
1.39k
        pixel_type_w left = y ? rtop[x] : 0;
338
1.39k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
1.39k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
1.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
1.39k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
1.39k
            offset);
343
1.39k
        uint32_t pos =
344
1.39k
            kPropRangeFast +
345
1.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
1.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
1.39k
        uint64_t v =
348
1.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
1.39k
        r[x] = make_pixel(v, 1, guess);
350
1.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
1.39k
      }
352
68.8k
      for (x = 1; x + 1 < channel.w; x++) {
353
67.4k
        size_t offset = 0;
354
67.4k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
67.4k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
67.4k
            rtoptop[x], &properties, offset);
357
67.4k
        uint32_t pos =
358
67.4k
            kPropRangeFast +
359
67.4k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
67.4k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
67.4k
        uint64_t v =
362
67.4k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
67.4k
        r[x] = make_pixel(v, 1, guess);
364
67.4k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
67.4k
      }
366
1.39k
      {
367
1.39k
        size_t offset = 0;
368
1.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
1.39k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
1.39k
            rtoptop[x], &properties, offset);
371
1.39k
        uint32_t pos =
372
1.39k
            kPropRangeFast +
373
1.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
1.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
1.39k
        uint64_t v =
376
1.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
1.39k
        r[x] = make_pixel(v, 1, guess);
378
1.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
1.39k
      }
380
1.39k
    }
381
5.29k
  } 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
3.57k
    JXL_DEBUG_V(8, "Slow track.");
385
3.57k
    MATreeLookup tree_lookup(tree);
386
3.57k
    Properties properties = Properties(num_props);
387
3.57k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
3.57k
    JXL_ASSIGN_OR_RETURN(
389
3.57k
        Channel references,
390
3.57k
        Channel::Create(memory_manager,
391
3.57k
                        properties.size() - kNumNonrefProperties, channel.w));
392
160k
    for (size_t y = 0; y < channel.h; y++) {
393
156k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
156k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
156k
      InitPropsRow(&properties, static_props, y);
396
156k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
438k
        for (size_t x = 0; x < 2; x++) {
398
292k
          PredictionResult res =
399
292k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
292k
                              tree_lookup, references);
401
292k
          uint64_t v =
402
292k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
292k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
292k
        }
405
22.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
22.5M
          PredictionResult res =
407
22.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
22.5M
                                 tree_lookup, references);
409
22.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
22.5M
              res.context, br);
411
22.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
22.5M
        }
413
438k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
292k
          PredictionResult res =
415
292k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
292k
                              tree_lookup, references);
417
292k
          uint64_t v =
418
292k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
292k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
292k
        }
421
146k
      } else {
422
532k
        for (size_t x = 0; x < channel.w; x++) {
423
522k
          PredictionResult res =
424
522k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
522k
                              tree_lookup, references);
426
522k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
522k
              res.context, br);
428
522k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
522k
        }
430
10.3k
      }
431
156k
    }
432
3.57k
  } else {
433
1.72k
    JXL_DEBUG_V(8, "Slowest track.");
434
1.72k
    MATreeLookup tree_lookup(tree);
435
1.72k
    Properties properties = Properties(num_props);
436
1.72k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
1.72k
    JXL_ASSIGN_OR_RETURN(
438
1.72k
        Channel references,
439
1.72k
        Channel::Create(memory_manager,
440
1.72k
                        properties.size() - kNumNonrefProperties, channel.w));
441
1.72k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
119k
    for (size_t y = 0; y < channel.h; y++) {
443
117k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
117k
      InitPropsRow(&properties, static_props, y);
445
117k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
117k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
340k
        for (size_t x = 0; x < 2; x++) {
448
227k
          PredictionResult res =
449
227k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
227k
                            tree_lookup, references, &wp_state);
451
227k
          uint64_t v =
452
227k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
227k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
227k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
227k
        }
456
14.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
14.8M
          PredictionResult res =
458
14.8M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
14.8M
                               tree_lookup, references, &wp_state);
460
14.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
14.8M
              res.context, br);
462
14.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
14.8M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
14.8M
        }
465
340k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
226k
          PredictionResult res =
467
226k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
226k
                            tree_lookup, references, &wp_state);
469
226k
          uint64_t v =
470
226k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
226k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
226k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
226k
        }
474
113k
      } else {
475
923k
        for (size_t x = 0; x < channel.w; x++) {
476
919k
          PredictionResult res =
477
919k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
919k
                            tree_lookup, references, &wp_state);
479
919k
          uint64_t v =
480
919k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
919k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
919k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
919k
        }
484
3.57k
      }
485
117k
    }
486
1.72k
  }
487
5.49k
  return true;
488
5.49k
}
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
8.59k
                                 uint32_t &fl_v) {
157
8.59k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
8.59k
  Channel &channel = image->channel[chan];
159
160
8.59k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
8.59k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
8.59k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
8.59k
  bool tree_has_wp_prop_or_pred = false;
168
8.59k
  bool is_wp_only = false;
169
8.59k
  bool is_gradient_only = false;
170
8.59k
  size_t num_props;
171
8.59k
  FlatTree tree =
172
8.59k
      FilterTree(global_tree, static_props, &num_props,
173
8.59k
                 &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
8.59k
  for (auto &node : tree) {
178
8.59k
    if (node.property0 == -1) {
179
8.59k
      node.childID = context_map[node.childID];
180
8.59k
    }
181
8.59k
  }
182
183
8.59k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
8.59k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
8.59k
                             pixel_type_w offset) -> pixel_type {
188
8.59k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
8.59k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
8.59k
    return val * multiplier + offset;
192
8.59k
  };
193
194
8.60k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
8.60k
    Predictor predictor = tree[0].predictor;
198
8.60k
    int64_t offset = tree[0].predictor_offset;
199
8.60k
    int32_t multiplier = tree[0].multiplier;
200
8.60k
    size_t ctx_id = tree[0].childID;
201
8.60k
    if (predictor == Predictor::Zero) {
202
8.17k
      uint32_t value;
203
8.17k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
8.17k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
1.71k
        JXL_DEBUG_V(8, "Fastest track.");
208
1.71k
        pixel_type v = make_pixel(value, multiplier, offset);
209
181k
        for (size_t y = 0; y < channel.h; y++) {
210
180k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
180k
          std::fill(r, r + channel.w, v);
212
180k
        }
213
6.46k
      } else {
214
6.46k
        JXL_DEBUG_V(8, "Fast track.");
215
6.46k
        if (multiplier == 1 && offset == 0) {
216
782k
          for (size_t y = 0; y < channel.h; y++) {
217
776k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
16.8M
            for (size_t x = 0; x < channel.w; x++) {
219
16.1M
              uint32_t v =
220
16.1M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
16.1M
              r[x] = UnpackSigned(v);
222
16.1M
            }
223
776k
          }
224
6.46k
        } else {
225
1
          for (size_t y = 0; y < channel.h; y++) {
226
0
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
0
            for (size_t x = 0; x < channel.w; x++) {
228
0
              uint32_t v =
229
0
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
0
                                                                         br);
231
0
              r[x] = make_pixel(v, multiplier, offset);
232
0
            }
233
0
          }
234
1
        }
235
6.46k
      }
236
8.17k
      return true;
237
8.17k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
0
               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
426
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
0
               multiplier == 1) {
273
0
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
0
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
0
      for (size_t y = 0; y < channel.h; y++) {
276
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
0
        for (size_t x = 0; x < channel.w; x++) {
278
0
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
0
          pixel_type top = (y ? *(r + x - onerow) : left);
280
0
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
0
          pixel_type guess = ClampedGradient(top, left, topleft);
282
0
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
0
              ctx_id, br);
284
0
          r[x] = make_pixel(v, 1, guess);
285
0
        }
286
0
      }
287
0
      return true;
288
0
    }
289
8.60k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
415
  if (is_wp_only) {
294
0
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
0
  }
296
415
  if (is_gradient_only) {
297
0
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
0
  }
299
300
415
  if (is_gradient_only) {
301
0
    JXL_DEBUG_V(8, "Gradient fast track.");
302
0
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
0
    for (size_t y = 0; y < channel.h; y++) {
304
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
0
      for (size_t x = 0; x < channel.w; x++) {
306
0
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
0
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
0
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
0
        int32_t guess = ClampedGradient(top, left, topleft);
310
0
        uint32_t pos =
311
0
            kPropRangeFast +
312
0
            std::min<pixel_type_w>(
313
0
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
0
                kPropRangeFast - 1);
315
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
0
        uint64_t v =
317
0
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
0
        r[x] = make_pixel(v, 1, guess);
319
0
      }
320
0
    }
321
415
  } 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
427
  } 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
427
    JXL_DEBUG_V(8, "Slow track.");
385
427
    MATreeLookup tree_lookup(tree);
386
427
    Properties properties = Properties(num_props);
387
427
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
427
    JXL_ASSIGN_OR_RETURN(
389
427
        Channel references,
390
427
        Channel::Create(memory_manager,
391
427
                        properties.size() - kNumNonrefProperties, channel.w));
392
28.5k
    for (size_t y = 0; y < channel.h; y++) {
393
28.1k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
28.1k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
28.1k
      InitPropsRow(&properties, static_props, y);
396
28.1k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
81.2k
        for (size_t x = 0; x < 2; x++) {
398
54.1k
          PredictionResult res =
399
54.1k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
54.1k
                              tree_lookup, references);
401
54.1k
          uint64_t v =
402
54.1k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
54.1k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
54.1k
        }
405
7.56M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
7.53M
          PredictionResult res =
407
7.53M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
7.53M
                                 tree_lookup, references);
409
7.53M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
7.53M
              res.context, br);
411
7.53M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
7.53M
        }
413
81.2k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
54.1k
          PredictionResult res =
415
54.1k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
54.1k
                              tree_lookup, references);
417
54.1k
          uint64_t v =
418
54.1k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
54.1k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
54.1k
        }
421
27.0k
      } else {
422
76.0k
        for (size_t x = 0; x < channel.w; x++) {
423
75.0k
          PredictionResult res =
424
75.0k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
75.0k
                              tree_lookup, references);
426
75.0k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
75.0k
              res.context, br);
428
75.0k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
75.0k
        }
430
1.04k
      }
431
28.1k
    }
432
18.4E
  } else {
433
18.4E
    JXL_DEBUG_V(8, "Slowest track.");
434
18.4E
    MATreeLookup tree_lookup(tree);
435
18.4E
    Properties properties = Properties(num_props);
436
18.4E
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
18.4E
    JXL_ASSIGN_OR_RETURN(
438
18.4E
        Channel references,
439
18.4E
        Channel::Create(memory_manager,
440
18.4E
                        properties.size() - kNumNonrefProperties, channel.w));
441
18.4E
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
18.4E
    for (size_t y = 0; y < channel.h; y++) {
443
0
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
0
      InitPropsRow(&properties, static_props, y);
445
0
      PrecomputeReferences(channel, y, *image, chan, &references);
446
0
      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
0
      } else {
475
0
        for (size_t x = 0; x < channel.w; x++) {
476
0
          PredictionResult res =
477
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
0
                            tree_lookup, references, &wp_state);
479
0
          uint64_t v =
480
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
0
        }
484
0
      }
485
0
    }
486
18.4E
  }
487
415
  return true;
488
415
}
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
132k
                                 uint32_t &fl_v) {
157
132k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
132k
  Channel &channel = image->channel[chan];
159
160
132k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
132k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
132k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
132k
  bool tree_has_wp_prop_or_pred = false;
168
132k
  bool is_wp_only = false;
169
132k
  bool is_gradient_only = false;
170
132k
  size_t num_props;
171
132k
  FlatTree tree =
172
132k
      FilterTree(global_tree, static_props, &num_props,
173
132k
                 &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
411k
  for (auto &node : tree) {
178
411k
    if (node.property0 == -1) {
179
342k
      node.childID = context_map[node.childID];
180
342k
    }
181
411k
  }
182
183
132k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
132k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
132k
                             pixel_type_w offset) -> pixel_type {
188
132k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
132k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
132k
    return val * multiplier + offset;
192
132k
  };
193
194
132k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
127k
    Predictor predictor = tree[0].predictor;
198
127k
    int64_t offset = tree[0].predictor_offset;
199
127k
    int32_t multiplier = tree[0].multiplier;
200
127k
    size_t ctx_id = tree[0].childID;
201
127k
    if (predictor == Predictor::Zero) {
202
127k
      uint32_t value;
203
127k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
127k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
14.8k
        JXL_DEBUG_V(8, "Fastest track.");
208
14.8k
        pixel_type v = make_pixel(value, multiplier, offset);
209
725k
        for (size_t y = 0; y < channel.h; y++) {
210
711k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
711k
          std::fill(r, r + channel.w, v);
212
711k
        }
213
112k
      } else {
214
112k
        JXL_DEBUG_V(8, "Fast track.");
215
112k
        if (multiplier == 1 && offset == 0) {
216
1.17M
          for (size_t y = 0; y < channel.h; y++) {
217
1.06M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
29.0M
            for (size_t x = 0; x < channel.w; x++) {
219
27.9M
              uint32_t v =
220
27.9M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
27.9M
              r[x] = UnpackSigned(v);
222
27.9M
            }
223
1.06M
          }
224
112k
        } else {
225
120
          for (size_t y = 0; y < channel.h; y++) {
226
97
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
2.46k
            for (size_t x = 0; x < channel.w; x++) {
228
2.36k
              uint32_t v =
229
2.36k
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
2.36k
                                                                         br);
231
2.36k
              r[x] = make_pixel(v, multiplier, offset);
232
2.36k
            }
233
97
          }
234
23
        }
235
112k
      }
236
127k
      return true;
237
127k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
0
               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
757
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
500
               multiplier == 1) {
273
500
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
500
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
5.13k
      for (size_t y = 0; y < channel.h; y++) {
276
4.63k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
65.9k
        for (size_t x = 0; x < channel.w; x++) {
278
61.3k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
61.3k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
61.3k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
61.3k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
61.3k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
61.3k
              ctx_id, br);
284
61.3k
          r[x] = make_pixel(v, 1, guess);
285
61.3k
        }
286
4.63k
      }
287
500
      return true;
288
500
    }
289
127k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
5.08k
  if (is_wp_only) {
294
216
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
216
  }
296
5.08k
  if (is_gradient_only) {
297
51
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
51
  }
299
300
5.08k
  if (is_gradient_only) {
301
0
    JXL_DEBUG_V(8, "Gradient fast track.");
302
0
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
0
    for (size_t y = 0; y < channel.h; y++) {
304
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
0
      for (size_t x = 0; x < channel.w; x++) {
306
0
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
0
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
0
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
0
        int32_t guess = ClampedGradient(top, left, topleft);
310
0
        uint32_t pos =
311
0
            kPropRangeFast +
312
0
            std::min<pixel_type_w>(
313
0
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
0
                kPropRangeFast - 1);
315
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
0
        uint64_t v =
317
0
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
0
        r[x] = make_pixel(v, 1, guess);
319
0
      }
320
0
    }
321
5.11k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
200
    JXL_DEBUG_V(8, "WP fast track.");
323
200
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
200
    Properties properties(1);
325
1.59k
    for (size_t y = 0; y < channel.h; y++) {
326
1.39k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
1.39k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
1.39k
      const pixel_type *JXL_RESTRICT rtoptop =
329
1.39k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
1.39k
      const pixel_type *JXL_RESTRICT rtopleft =
331
1.39k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
1.39k
      const pixel_type *JXL_RESTRICT rtopright =
333
1.39k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
1.39k
      size_t x = 0;
335
1.39k
      {
336
1.39k
        size_t offset = 0;
337
1.39k
        pixel_type_w left = y ? rtop[x] : 0;
338
1.39k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
1.39k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
1.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
1.39k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
1.39k
            offset);
343
1.39k
        uint32_t pos =
344
1.39k
            kPropRangeFast +
345
1.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
1.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
1.39k
        uint64_t v =
348
1.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
1.39k
        r[x] = make_pixel(v, 1, guess);
350
1.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
1.39k
      }
352
68.8k
      for (x = 1; x + 1 < channel.w; x++) {
353
67.4k
        size_t offset = 0;
354
67.4k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
67.4k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
67.4k
            rtoptop[x], &properties, offset);
357
67.4k
        uint32_t pos =
358
67.4k
            kPropRangeFast +
359
67.4k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
67.4k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
67.4k
        uint64_t v =
362
67.4k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
67.4k
        r[x] = make_pixel(v, 1, guess);
364
67.4k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
67.4k
      }
366
1.39k
      {
367
1.39k
        size_t offset = 0;
368
1.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
1.39k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
1.39k
            rtoptop[x], &properties, offset);
371
1.39k
        uint32_t pos =
372
1.39k
            kPropRangeFast +
373
1.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
1.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
1.39k
        uint64_t v =
376
1.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
1.39k
        r[x] = make_pixel(v, 1, guess);
378
1.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
1.39k
      }
380
1.39k
    }
381
4.88k
  } 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
3.14k
    JXL_DEBUG_V(8, "Slow track.");
385
3.14k
    MATreeLookup tree_lookup(tree);
386
3.14k
    Properties properties = Properties(num_props);
387
3.14k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
3.14k
    JXL_ASSIGN_OR_RETURN(
389
3.14k
        Channel references,
390
3.14k
        Channel::Create(memory_manager,
391
3.14k
                        properties.size() - kNumNonrefProperties, channel.w));
392
131k
    for (size_t y = 0; y < channel.h; y++) {
393
128k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
128k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
128k
      InitPropsRow(&properties, static_props, y);
396
128k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
357k
        for (size_t x = 0; x < 2; x++) {
398
238k
          PredictionResult res =
399
238k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
238k
                              tree_lookup, references);
401
238k
          uint64_t v =
402
238k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
238k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
238k
        }
405
15.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
15.0M
          PredictionResult res =
407
15.0M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
15.0M
                                 tree_lookup, references);
409
15.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
15.0M
              res.context, br);
411
15.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
15.0M
        }
413
357k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
238k
          PredictionResult res =
415
238k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
238k
                              tree_lookup, references);
417
238k
          uint64_t v =
418
238k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
238k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
238k
        }
421
119k
      } else {
422
456k
        for (size_t x = 0; x < channel.w; x++) {
423
447k
          PredictionResult res =
424
447k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
447k
                              tree_lookup, references);
426
447k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
447k
              res.context, br);
428
447k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
447k
        }
430
9.30k
      }
431
128k
    }
432
3.14k
  } else {
433
1.73k
    JXL_DEBUG_V(8, "Slowest track.");
434
1.73k
    MATreeLookup tree_lookup(tree);
435
1.73k
    Properties properties = Properties(num_props);
436
1.73k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
1.73k
    JXL_ASSIGN_OR_RETURN(
438
1.73k
        Channel references,
439
1.73k
        Channel::Create(memory_manager,
440
1.73k
                        properties.size() - kNumNonrefProperties, channel.w));
441
1.73k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
119k
    for (size_t y = 0; y < channel.h; y++) {
443
117k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
117k
      InitPropsRow(&properties, static_props, y);
445
117k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
117k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
340k
        for (size_t x = 0; x < 2; x++) {
448
227k
          PredictionResult res =
449
227k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
227k
                            tree_lookup, references, &wp_state);
451
227k
          uint64_t v =
452
227k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
227k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
227k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
227k
        }
456
14.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
14.8M
          PredictionResult res =
458
14.8M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
14.8M
                               tree_lookup, references, &wp_state);
460
14.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
14.8M
              res.context, br);
462
14.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
14.8M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
14.8M
        }
465
340k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
226k
          PredictionResult res =
467
226k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
226k
                            tree_lookup, references, &wp_state);
469
226k
          uint64_t v =
470
226k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
226k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
226k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
226k
        }
474
113k
      } else {
475
923k
        for (size_t x = 0; x < channel.w; x++) {
476
919k
          PredictionResult res =
477
919k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
919k
                            tree_lookup, references, &wp_state);
479
919k
          uint64_t v =
480
919k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
919k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
919k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
919k
        }
484
3.57k
      }
485
117k
    }
486
1.73k
  }
487
5.08k
  return true;
488
5.08k
}
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
141k
                                 uint32_t &fl_v) {
499
141k
  if (reader->UsesLZ77()) {
500
8.59k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
8.59k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
8.59k
        tree_lut, image, fl_run, fl_v);
503
132k
  } else {
504
132k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
132k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
132k
        tree_lut, image, fl_run, fl_v);
507
132k
  }
508
141k
}
509
510
99.8k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
19.8k
                                 const ModularOptions &options) {
514
19.8k
  size_t nb_channels = image.channel.size();
515
39.6k
  for (bool is_dc : {true, false}) {
516
39.6k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
39.6k
    size_t c = image.nb_meta_channels;
518
326k
    for (; c < nb_channels; c++) {
519
288k
      const Channel &ch = image.channel[c];
520
288k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
288k
    }
522
58.2k
    for (; c < nb_channels; c++) {
523
18.5k
      const Channel &ch = image.channel[c];
524
18.5k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
18.5k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
18.5k
      if (is_dc_channel != is_dc) continue;
527
9.29k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
9.29k
      if (tile_dim == 0) {
529
0
        return JXL_FAILURE("Inconsistent transforms");
530
0
      }
531
9.29k
    }
532
39.6k
  }
533
19.8k
  return true;
534
19.8k
}
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
24.6k
                     const bool allow_truncated_group) {
541
24.6k
  if (image.channel.empty()) return true;
542
19.8k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
19.8k
  Status status = Bundle::Read(br, &header);
546
19.8k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
19.8k
  if (status.IsFatalError()) return status;
548
19.8k
  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
19.8k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
19.8k
              header.transforms.size());
560
19.8k
  image.transform = header.transforms;
561
19.8k
  for (Transform &transform : image.transform) {
562
9.83k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
9.83k
  }
564
19.8k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
19.8k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
19.8k
  size_t nb_channels = image.channel.size();
570
571
19.8k
  size_t num_chans = 0;
572
19.8k
  size_t distance_multiplier = 0;
573
164k
  for (size_t i = 0; i < nb_channels; i++) {
574
145k
    Channel &channel = image.channel[i];
575
145k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
143k
                                        channel.h > options->max_chan_size)) {
577
989
      break;
578
989
    }
579
144k
    if (!channel.w || !channel.h) {
580
1.36k
      continue;  // skip empty channels
581
1.36k
    }
582
143k
    if (channel.w > distance_multiplier) {
583
29.0k
      distance_multiplier = channel.w;
584
29.0k
    }
585
143k
    num_chans++;
586
143k
  }
587
19.8k
  if (num_chans == 0) return true;
588
589
19.7k
  size_t next_channel = 0;
590
19.7k
  auto scope_guard = MakeScopeGuard([&]() {
591
1.99k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
1.94k
      ZeroFillImage(&image.channel[c].plane);
593
1.94k
    }
594
49
  });
595
  // Do not do anything if truncated groups are not allowed.
596
19.7k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
19.7k
  Tree tree_storage;
600
19.7k
  std::vector<uint8_t> context_map_storage;
601
19.7k
  ANSCode code_storage;
602
19.7k
  const Tree *tree = &tree_storage;
603
19.7k
  const ANSCode *code = &code_storage;
604
19.7k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
19.7k
  if (!header.use_global_tree) {
606
2.80k
    uint64_t max_tree_size = 1024;
607
26.2k
    for (size_t i = 0; i < nb_channels; i++) {
608
23.3k
      Channel &channel = image.channel[i];
609
23.3k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
23.1k
                                          channel.h > options->max_chan_size)) {
611
0
        break;
612
0
      }
613
23.3k
      uint64_t pixels = channel.w * channel.h;
614
23.3k
      max_tree_size += pixels;
615
23.3k
    }
616
2.80k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
2.80k
    JXL_RETURN_IF_ERROR(
618
2.80k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
2.78k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
2.78k
                                         (tree_storage.size() + 1) / 2,
621
2.78k
                                         &code_storage, &context_map_storage));
622
16.9k
  } else {
623
16.9k
    if (!global_tree || !global_code || !global_ctx_map ||
624
16.9k
        global_tree->empty()) {
625
2
      return JXL_FAILURE("No global tree available but one was requested");
626
2
    }
627
16.9k
    tree = global_tree;
628
16.9k
    code = global_code;
629
16.9k
    context_map = global_ctx_map;
630
16.9k
  }
631
632
  // Read channels
633
39.4k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
39.4k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
39.4k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
39.4k
  uint32_t fl_run = 0;
637
39.4k
  uint32_t fl_v = 0;
638
162k
  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
142k
        (channel.w > options->max_chan_size ||
642
141k
         channel.h > options->max_chan_size)) {
643
891
      break;
644
891
    }
645
142k
    if (!channel.w || !channel.h) {
646
1.36k
      continue;  // skip empty channels
647
1.36k
    }
648
141k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
141k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
141k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
141k
    if (!br->AllReadsWithinBounds()) {
654
29
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
29
    }
657
141k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
19.6k
  scope_guard.Disarm();
661
662
19.6k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
19.6k
  return true;
666
19.6k
}
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
24.6k
                                bool allow_truncated_group) {
674
24.6k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
24.6k
  req_sizes.reserve(image.channel.size());
676
78.4k
  for (const auto &c : image.channel) {
677
78.4k
    req_sizes.emplace_back(c.w, c.h);
678
78.4k
  }
679
24.6k
  GroupHeader local_header;
680
24.6k
  if (header == nullptr) header = &local_header;
681
24.6k
  size_t bit_pos = br->TotalBitsConsumed();
682
24.6k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
24.6k
                                  code, ctx_map, allow_truncated_group);
684
24.6k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
24.5k
  if (dec_status.IsFatalError()) return dec_status;
686
24.5k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
24.5k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
24.5k
  JXL_DEBUG_V(4,
689
24.5k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
24.5k
              " image from %" PRIuS " bytes",
691
24.5k
              image.w, image.h, image.channel.size(),
692
24.5k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
24.5k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
24.5k
  (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
24.5k
  if (undo_transforms) {
699
15.4k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
76.8k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
61.3k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
61.3k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
61.3k
    }
704
15.4k
  }
705
24.5k
  return dec_status;
706
24.5k
}
707
708
}  // namespace jxl