Coverage Report

Created: 2026-04-01 07:24

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