Coverage Report

Created: 2025-07-23 08:18

/src/libjxl/lib/jxl/modular/encoding/encoding.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/modular/encoding/encoding.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <array>
12
#include <cstddef>
13
#include <cstdint>
14
#include <cstdlib>
15
#include <queue>
16
#include <utility>
17
#include <vector>
18
19
#include "lib/jxl/base/common.h"
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/printf_macros.h"
22
#include "lib/jxl/base/scope_guard.h"
23
#include "lib/jxl/base/status.h"
24
#include "lib/jxl/dec_ans.h"
25
#include "lib/jxl/dec_bit_reader.h"
26
#include "lib/jxl/fields.h"
27
#include "lib/jxl/frame_dimensions.h"
28
#include "lib/jxl/image_ops.h"
29
#include "lib/jxl/modular/encoding/context_predict.h"
30
#include "lib/jxl/modular/encoding/dec_ma.h"
31
#include "lib/jxl/modular/modular_image.h"
32
#include "lib/jxl/modular/options.h"
33
#include "lib/jxl/modular/transform/transform.h"
34
#include "lib/jxl/pack_signed.h"
35
36
namespace jxl {
37
38
// Removes all nodes that use a static property (i.e. channel or group ID) from
39
// the tree and collapses each node on even levels with its two children to
40
// produce a flatter tree. Also computes whether the resulting tree requires
41
// using the weighted predictor.
42
FlatTree FilterTree(const Tree &global_tree,
43
                    std::array<pixel_type, kNumStaticProperties> &static_props,
44
                    size_t *num_props, bool *use_wp, bool *wp_only,
45
183k
                    bool *gradient_only) {
46
183k
  *num_props = 0;
47
183k
  bool has_wp = false;
48
183k
  bool has_non_wp = false;
49
183k
  *gradient_only = true;
50
393k
  const auto mark_property = [&](int32_t p) {
51
393k
    if (p == kWPProp) {
52
66.0k
      has_wp = true;
53
327k
    } else if (p >= kNumStaticProperties) {
54
176k
      has_non_wp = true;
55
176k
    }
56
393k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
203k
      *gradient_only = false;
58
203k
    }
59
393k
  };
60
183k
  FlatTree output;
61
183k
  std::queue<size_t> nodes;
62
183k
  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
892k
  while (!nodes.empty()) {
70
708k
    size_t cur = nodes.front();
71
708k
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
748k
    while (global_tree[cur].property < kNumStaticProperties &&
74
748k
           global_tree[cur].property != -1) {
75
39.5k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
21.8k
        cur = global_tree[cur].lchild;
77
21.8k
      } else {
78
17.6k
        cur = global_tree[cur].rchild;
79
17.6k
      }
80
39.5k
    }
81
708k
    FlatDecisionNode flat;
82
708k
    if (global_tree[cur].property == -1) {
83
577k
      flat.property0 = -1;
84
577k
      flat.childID = global_tree[cur].lchild;
85
577k
      flat.predictor = global_tree[cur].predictor;
86
577k
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
577k
      flat.multiplier = global_tree[cur].multiplier;
88
577k
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
577k
      has_wp |= flat.predictor == Predictor::Weighted;
90
577k
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
577k
      output.push_back(flat);
92
577k
      continue;
93
577k
    }
94
131k
    flat.childID = output.size() + nodes.size() + 1;
95
96
131k
    flat.property0 = global_tree[cur].property;
97
131k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
131k
    flat.splitval0 = global_tree[cur].splitval;
99
100
393k
    for (size_t i = 0; i < 2; i++) {
101
262k
      size_t cur_child =
102
262k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
280k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
280k
             global_tree[cur_child].property != -1) {
106
18.2k
        if (static_props[global_tree[cur_child].property] >
107
18.2k
            global_tree[cur_child].splitval) {
108
10.5k
          cur_child = global_tree[cur_child].lchild;
109
10.5k
        } else {
110
7.70k
          cur_child = global_tree[cur_child].rchild;
111
7.70k
        }
112
18.2k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
262k
      if (global_tree[cur_child].property == -1) {
116
151k
        flat.properties[i] = 0;
117
151k
        flat.splitvals[i] = 0;
118
151k
        nodes.push(cur_child);
119
151k
        nodes.push(cur_child);
120
151k
      } else {
121
111k
        flat.properties[i] = global_tree[cur_child].property;
122
111k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
111k
        nodes.push(global_tree[cur_child].lchild);
124
111k
        nodes.push(global_tree[cur_child].rchild);
125
111k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
111k
      }
127
262k
    }
128
129
262k
    for (int16_t property : flat.properties) mark_property(property);
130
131k
    mark_property(flat.property0);
131
131k
    output.push_back(flat);
132
131k
  }
133
183k
  if (*num_props > kNumNonrefProperties) {
134
1.55k
    *num_props =
135
1.55k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.55k
            kExtraPropsPerChannel +
137
1.55k
        kNumNonrefProperties;
138
182k
  } else {
139
182k
    *num_props = kNumNonrefProperties;
140
182k
  }
141
183k
  *use_wp = has_wp;
142
183k
  *wp_only = has_wp && !has_non_wp;
143
144
183k
  return output;
145
183k
}
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
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
381k
  for (auto &node : tree) {
178
381k
    if (node.property0 == -1) {
179
327k
      node.childID = context_map[node.childID];
180
327k
    }
181
381k
  }
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
79.7M
                             pixel_type_w offset) -> pixel_type {
188
79.7M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
79.7M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
79.7M
    return val * multiplier + offset;
192
79.7M
  };
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
20.9M
                             pixel_type_w offset) -> pixel_type {
188
20.9M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
20.9M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
20.9M
    return val * multiplier + offset;
192
20.9M
  };
jxl::detail::DecodeModularChannelMAANS<false>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda(unsigned long, int, long)#1}::operator()(unsigned long, int, long) const
Line
Count
Source
187
58.7M
                             pixel_type_w offset) -> pixel_type {
188
58.7M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
58.7M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
58.7M
    return val * multiplier + offset;
192
58.7M
  };
193
194
165k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
153k
    Predictor predictor = tree[0].predictor;
198
153k
    int64_t offset = tree[0].predictor_offset;
199
153k
    int32_t multiplier = tree[0].multiplier;
200
153k
    size_t ctx_id = tree[0].childID;
201
153k
    if (predictor == Predictor::Zero) {
202
128k
      uint32_t value;
203
128k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
128k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
40.1k
        JXL_DEBUG_V(8, "Fastest track.");
208
40.1k
        pixel_type v = make_pixel(value, multiplier, offset);
209
863k
        for (size_t y = 0; y < channel.h; y++) {
210
822k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
822k
          std::fill(r, r + channel.w, v);
212
822k
        }
213
87.9k
      } else {
214
87.9k
        JXL_DEBUG_V(8, "Fast track.");
215
87.9k
        if (multiplier == 1 && offset == 0) {
216
2.31M
          for (size_t y = 0; y < channel.h; y++) {
217
2.24M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
120M
            for (size_t x = 0; x < channel.w; x++) {
219
118M
              uint32_t v =
220
118M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
118M
              r[x] = UnpackSigned(v);
222
118M
            }
223
2.24M
          }
224
69.3k
        } else {
225
421k
          for (size_t y = 0; y < channel.h; y++) {
226
403k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
16.5M
            for (size_t x = 0; x < channel.w; x++) {
228
16.1M
              uint32_t v =
229
16.1M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
16.1M
                                                                         br);
231
16.1M
              r[x] = make_pixel(v, multiplier, offset);
232
16.1M
            }
233
403k
          }
234
18.5k
        }
235
87.9k
      }
236
128k
      return true;
237
128k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
25.2k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
75
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
75
      pixel_type_w sv = UnpackSigned(fl_v);
241
969
      for (size_t y = 0; y < channel.h; y++) {
242
894
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
894
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
894
        const pixel_type *JXL_RESTRICT rtopleft =
245
894
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
894
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
894
        if (fl_run == 0) {
248
894
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
894
                                                     &fl_run);
250
894
          sv = UnpackSigned(fl_v);
251
894
        } else {
252
0
          fl_run--;
253
0
        }
254
894
        r[0] = sv + guess_0;
255
33.3k
        for (size_t x = 1; x < channel.w; x++) {
256
32.4k
          pixel_type left = r[x - 1];
257
32.4k
          pixel_type top = rtop[x];
258
32.4k
          pixel_type topleft = rtopleft[x];
259
32.4k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
32.4k
          if (!fl_run) {
261
32.4k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
32.4k
                                                       &fl_run);
263
32.4k
            sv = UnpackSigned(fl_v);
264
32.4k
          } else {
265
0
            fl_run--;
266
0
          }
267
32.4k
          r[x] = sv + guess;
268
32.4k
        }
269
894
      }
270
75
      return true;
271
25.2k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
25.2k
               multiplier == 1) {
273
778
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
778
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
15.4k
      for (size_t y = 0; y < channel.h; y++) {
276
14.6k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
596k
        for (size_t x = 0; x < channel.w; x++) {
278
581k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
581k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
581k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
581k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
581k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
581k
              ctx_id, br);
284
581k
          r[x] = make_pixel(v, 1, guess);
285
581k
        }
286
14.6k
      }
287
778
      return true;
288
778
    }
289
153k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
36.8k
  if (is_wp_only) {
294
2.32k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
2.32k
  }
296
36.8k
  if (is_gradient_only) {
297
1.61k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.61k
  }
299
300
36.8k
  if (is_gradient_only) {
301
436
    JXL_DEBUG_V(8, "Gradient fast track.");
302
436
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
11.1k
    for (size_t y = 0; y < channel.h; y++) {
304
10.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
360k
      for (size_t x = 0; x < channel.w; x++) {
306
349k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
349k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
349k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
349k
        int32_t guess = ClampedGradient(top, left, topleft);
310
349k
        uint32_t pos =
311
349k
            kPropRangeFast +
312
349k
            std::min<pixel_type_w>(
313
349k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
349k
                kPropRangeFast - 1);
315
349k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
349k
        uint64_t v =
317
349k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
349k
        r[x] = make_pixel(v, 1, guess);
319
349k
      }
320
10.7k
    }
321
36.4k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
571
    JXL_DEBUG_V(8, "WP fast track.");
323
571
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
571
    Properties properties(1);
325
15.9k
    for (size_t y = 0; y < channel.h; y++) {
326
15.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
15.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
15.3k
      const pixel_type *JXL_RESTRICT rtoptop =
329
15.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
15.3k
      const pixel_type *JXL_RESTRICT rtopleft =
331
15.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
15.3k
      const pixel_type *JXL_RESTRICT rtopright =
333
15.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
15.3k
      size_t x = 0;
335
15.3k
      {
336
15.3k
        size_t offset = 0;
337
15.3k
        pixel_type_w left = y ? rtop[x] : 0;
338
15.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
15.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
15.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
15.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
15.3k
            offset);
343
15.3k
        uint32_t pos =
344
15.3k
            kPropRangeFast +
345
15.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
15.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
15.3k
        uint64_t v =
348
15.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
15.3k
        r[x] = make_pixel(v, 1, guess);
350
15.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
15.3k
      }
352
513k
      for (x = 1; x + 1 < channel.w; x++) {
353
498k
        size_t offset = 0;
354
498k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
498k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
498k
            rtoptop[x], &properties, offset);
357
498k
        uint32_t pos =
358
498k
            kPropRangeFast +
359
498k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
498k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
498k
        uint64_t v =
362
498k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
498k
        r[x] = make_pixel(v, 1, guess);
364
498k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
498k
      }
366
15.3k
      {
367
15.3k
        size_t offset = 0;
368
15.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
15.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
15.3k
            rtoptop[x], &properties, offset);
371
15.3k
        uint32_t pos =
372
15.3k
            kPropRangeFast +
373
15.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
15.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
15.3k
        uint64_t v =
376
15.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
15.3k
        r[x] = make_pixel(v, 1, guess);
378
15.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
15.3k
      }
380
15.3k
    }
381
35.8k
  } 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
28.4k
    JXL_DEBUG_V(8, "Slow track.");
385
28.4k
    MATreeLookup tree_lookup(tree);
386
28.4k
    Properties properties = Properties(num_props);
387
28.4k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
28.4k
    JXL_ASSIGN_OR_RETURN(
389
28.4k
        Channel references,
390
28.4k
        Channel::Create(memory_manager,
391
28.4k
                        properties.size() - kNumNonrefProperties, channel.w));
392
580k
    for (size_t y = 0; y < channel.h; y++) {
393
552k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
552k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
552k
      InitPropsRow(&properties, static_props, y);
396
552k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.28M
        for (size_t x = 0; x < 2; x++) {
398
856k
          PredictionResult res =
399
856k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
856k
                              tree_lookup, references);
401
856k
          uint64_t v =
402
856k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
856k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
856k
        }
405
28.8M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
28.4M
          PredictionResult res =
407
28.4M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
28.4M
                                 tree_lookup, references);
409
28.4M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
28.4M
              res.context, br);
411
28.4M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
28.4M
        }
413
1.28M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
856k
          PredictionResult res =
415
856k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
856k
                              tree_lookup, references);
417
856k
          uint64_t v =
418
856k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
856k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
856k
        }
421
428k
      } else {
422
3.34M
        for (size_t x = 0; x < channel.w; x++) {
423
3.22M
          PredictionResult res =
424
3.22M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
3.22M
                              tree_lookup, references);
426
3.22M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
3.22M
              res.context, br);
428
3.22M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
3.22M
        }
430
123k
      }
431
552k
    }
432
28.4k
  } else {
433
7.42k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.42k
    MATreeLookup tree_lookup(tree);
435
7.42k
    Properties properties = Properties(num_props);
436
7.42k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
7.42k
    JXL_ASSIGN_OR_RETURN(
438
7.42k
        Channel references,
439
7.42k
        Channel::Create(memory_manager,
440
7.42k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.42k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
318k
    for (size_t y = 0; y < channel.h; y++) {
443
311k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
311k
      InitPropsRow(&properties, static_props, y);
445
311k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
311k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
757k
        for (size_t x = 0; x < 2; x++) {
448
504k
          PredictionResult res =
449
504k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
504k
                            tree_lookup, references, &wp_state);
451
504k
          uint64_t v =
452
504k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
504k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
504k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
504k
        }
456
26.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
25.9M
          PredictionResult res =
458
25.9M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
25.9M
                               tree_lookup, references, &wp_state);
460
25.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
25.9M
              res.context, br);
462
25.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
25.9M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
25.9M
        }
465
757k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
504k
          PredictionResult res =
467
504k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
504k
                            tree_lookup, references, &wp_state);
469
504k
          uint64_t v =
470
504k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
504k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
504k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
504k
        }
474
252k
      } else {
475
1.77M
        for (size_t x = 0; x < channel.w; x++) {
476
1.71M
          PredictionResult res =
477
1.71M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.71M
                            tree_lookup, references, &wp_state);
479
1.71M
          uint64_t v =
480
1.71M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.71M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.71M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.71M
        }
484
58.7k
      }
485
311k
    }
486
7.42k
  }
487
36.8k
  return true;
488
36.8k
}
jxl::Status jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)
Line
Count
Source
156
45.5k
                                 uint32_t &fl_v) {
157
45.5k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
45.5k
  Channel &channel = image->channel[chan];
159
160
45.5k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
45.5k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
45.5k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
45.5k
  bool tree_has_wp_prop_or_pred = false;
168
45.5k
  bool is_wp_only = false;
169
45.5k
  bool is_gradient_only = false;
170
45.5k
  size_t num_props;
171
45.5k
  FlatTree tree =
172
45.5k
      FilterTree(global_tree, static_props, &num_props,
173
45.5k
                 &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
55.3k
  for (auto &node : tree) {
178
55.3k
    if (node.property0 == -1) {
179
52.8k
      node.childID = context_map[node.childID];
180
52.8k
    }
181
55.3k
  }
182
183
45.5k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
45.5k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
45.5k
                             pixel_type_w offset) -> pixel_type {
188
45.5k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
45.5k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
45.5k
    return val * multiplier + offset;
192
45.5k
  };
193
194
45.5k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
43.5k
    Predictor predictor = tree[0].predictor;
198
43.5k
    int64_t offset = tree[0].predictor_offset;
199
43.5k
    int32_t multiplier = tree[0].multiplier;
200
43.5k
    size_t ctx_id = tree[0].childID;
201
43.5k
    if (predictor == Predictor::Zero) {
202
34.0k
      uint32_t value;
203
34.0k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
34.0k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
22.5k
        JXL_DEBUG_V(8, "Fastest track.");
208
22.5k
        pixel_type v = make_pixel(value, multiplier, offset);
209
462k
        for (size_t y = 0; y < channel.h; y++) {
210
439k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
439k
          std::fill(r, r + channel.w, v);
212
439k
        }
213
22.5k
      } else {
214
11.4k
        JXL_DEBUG_V(8, "Fast track.");
215
11.4k
        if (multiplier == 1 && offset == 0) {
216
58.2k
          for (size_t y = 0; y < channel.h; y++) {
217
54.2k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
3.11M
            for (size_t x = 0; x < channel.w; x++) {
219
3.06M
              uint32_t v =
220
3.06M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
3.06M
              r[x] = UnpackSigned(v);
222
3.06M
            }
223
54.2k
          }
224
7.46k
        } else {
225
183k
          for (size_t y = 0; y < channel.h; y++) {
226
176k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
7.99M
            for (size_t x = 0; x < channel.w; x++) {
228
7.82M
              uint32_t v =
229
7.82M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
7.82M
                                                                         br);
231
7.82M
              r[x] = make_pixel(v, multiplier, offset);
232
7.82M
            }
233
176k
          }
234
7.46k
        }
235
11.4k
      }
236
34.0k
      return true;
237
34.0k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
9.51k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
75
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
75
      pixel_type_w sv = UnpackSigned(fl_v);
241
969
      for (size_t y = 0; y < channel.h; y++) {
242
894
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
894
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
894
        const pixel_type *JXL_RESTRICT rtopleft =
245
894
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
894
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
894
        if (fl_run == 0) {
248
894
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
894
                                                     &fl_run);
250
894
          sv = UnpackSigned(fl_v);
251
894
        } else {
252
0
          fl_run--;
253
0
        }
254
894
        r[0] = sv + guess_0;
255
33.3k
        for (size_t x = 1; x < channel.w; x++) {
256
32.4k
          pixel_type left = r[x - 1];
257
32.4k
          pixel_type top = rtop[x];
258
32.4k
          pixel_type topleft = rtopleft[x];
259
32.4k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
32.4k
          if (!fl_run) {
261
32.4k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
32.4k
                                                       &fl_run);
263
32.4k
            sv = UnpackSigned(fl_v);
264
32.4k
          } else {
265
0
            fl_run--;
266
0
          }
267
32.4k
          r[x] = sv + guess;
268
32.4k
        }
269
894
      }
270
75
      return true;
271
9.43k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
9.43k
               multiplier == 1) {
273
227
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
227
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
5.10k
      for (size_t y = 0; y < channel.h; y++) {
276
4.87k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
110k
        for (size_t x = 0; x < channel.w; x++) {
278
106k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
106k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
106k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
106k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
106k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
106k
              ctx_id, br);
284
106k
          r[x] = make_pixel(v, 1, guess);
285
106k
        }
286
4.87k
      }
287
227
      return true;
288
227
    }
289
43.5k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
11.2k
  if (is_wp_only) {
294
858
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
858
  }
296
11.2k
  if (is_gradient_only) {
297
595
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
595
  }
299
300
11.2k
  if (is_gradient_only) {
301
0
    JXL_DEBUG_V(8, "Gradient fast track.");
302
0
    const intptr_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
11.2k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
0
    JXL_DEBUG_V(8, "WP fast track.");
323
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
0
    Properties properties(1);
325
0
    for (size_t y = 0; y < channel.h; y++) {
326
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
0
      const pixel_type *JXL_RESTRICT rtoptop =
329
0
          (y > 1 ? channel.Row(y - 2) : rtop);
330
0
      const pixel_type *JXL_RESTRICT rtopleft =
331
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
0
      const pixel_type *JXL_RESTRICT rtopright =
333
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
0
      size_t x = 0;
335
0
      {
336
0
        size_t offset = 0;
337
0
        pixel_type_w left = y ? rtop[x] : 0;
338
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
0
            offset);
343
0
        uint32_t pos =
344
0
            kPropRangeFast +
345
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
0
        uint64_t v =
348
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
0
        r[x] = make_pixel(v, 1, guess);
350
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
0
      }
352
0
      for (x = 1; x + 1 < channel.w; x++) {
353
0
        size_t offset = 0;
354
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
0
            rtoptop[x], &properties, offset);
357
0
        uint32_t pos =
358
0
            kPropRangeFast +
359
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
0
        uint64_t v =
362
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
0
        r[x] = make_pixel(v, 1, guess);
364
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
0
      }
366
0
      {
367
0
        size_t offset = 0;
368
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
0
            rtoptop[x], &properties, offset);
371
0
        uint32_t pos =
372
0
            kPropRangeFast +
373
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
0
        uint64_t v =
376
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
0
        r[x] = make_pixel(v, 1, guess);
378
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
0
      }
380
0
    }
381
11.2k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
10.0k
    JXL_DEBUG_V(8, "Slow track.");
385
10.0k
    MATreeLookup tree_lookup(tree);
386
10.0k
    Properties properties = Properties(num_props);
387
10.0k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
10.0k
    JXL_ASSIGN_OR_RETURN(
389
10.0k
        Channel references,
390
10.0k
        Channel::Create(memory_manager,
391
10.0k
                        properties.size() - kNumNonrefProperties, channel.w));
392
212k
    for (size_t y = 0; y < channel.h; y++) {
393
201k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
201k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
201k
      InitPropsRow(&properties, static_props, y);
396
201k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
508k
        for (size_t x = 0; x < 2; x++) {
398
339k
          PredictionResult res =
399
339k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
339k
                              tree_lookup, references);
401
339k
          uint64_t v =
402
339k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
339k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
339k
        }
405
10.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
10.4M
          PredictionResult res =
407
10.4M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
10.4M
                                 tree_lookup, references);
409
10.4M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
10.4M
              res.context, br);
411
10.4M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
10.4M
        }
413
508k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
339k
          PredictionResult res =
415
339k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
339k
                              tree_lookup, references);
417
339k
          uint64_t v =
418
339k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
339k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
339k
        }
421
169k
      } else {
422
1.30M
        for (size_t x = 0; x < channel.w; x++) {
423
1.27M
          PredictionResult res =
424
1.27M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.27M
                              tree_lookup, references);
426
1.27M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.27M
              res.context, br);
428
1.27M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.27M
        }
430
32.3k
      }
431
201k
    }
432
10.0k
  } else {
433
1.15k
    JXL_DEBUG_V(8, "Slowest track.");
434
1.15k
    MATreeLookup tree_lookup(tree);
435
1.15k
    Properties properties = Properties(num_props);
436
1.15k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
1.15k
    JXL_ASSIGN_OR_RETURN(
438
1.15k
        Channel references,
439
1.15k
        Channel::Create(memory_manager,
440
1.15k
                        properties.size() - kNumNonrefProperties, channel.w));
441
1.15k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
27.3k
    for (size_t y = 0; y < channel.h; y++) {
443
26.2k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
26.2k
      InitPropsRow(&properties, static_props, y);
445
26.2k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
26.2k
      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
26.2k
      } else {
475
668k
        for (size_t x = 0; x < channel.w; x++) {
476
642k
          PredictionResult res =
477
642k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
642k
                            tree_lookup, references, &wp_state);
479
642k
          uint64_t v =
480
642k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
642k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
642k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
642k
        }
484
26.2k
      }
485
26.2k
    }
486
1.15k
  }
487
11.2k
  return true;
488
11.2k
}
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
120k
                                 uint32_t &fl_v) {
157
120k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
120k
  Channel &channel = image->channel[chan];
159
160
120k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
120k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
120k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
120k
  bool tree_has_wp_prop_or_pred = false;
168
120k
  bool is_wp_only = false;
169
120k
  bool is_gradient_only = false;
170
120k
  size_t num_props;
171
120k
  FlatTree tree =
172
120k
      FilterTree(global_tree, static_props, &num_props,
173
120k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
326k
  for (auto &node : tree) {
178
326k
    if (node.property0 == -1) {
179
274k
      node.childID = context_map[node.childID];
180
274k
    }
181
326k
  }
182
183
120k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
120k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
120k
                             pixel_type_w offset) -> pixel_type {
188
120k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
120k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
120k
    return val * multiplier + offset;
192
120k
  };
193
194
120k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
109k
    Predictor predictor = tree[0].predictor;
198
109k
    int64_t offset = tree[0].predictor_offset;
199
109k
    int32_t multiplier = tree[0].multiplier;
200
109k
    size_t ctx_id = tree[0].childID;
201
109k
    if (predictor == Predictor::Zero) {
202
94.0k
      uint32_t value;
203
94.0k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
94.0k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
17.5k
        JXL_DEBUG_V(8, "Fastest track.");
208
17.5k
        pixel_type v = make_pixel(value, multiplier, offset);
209
400k
        for (size_t y = 0; y < channel.h; y++) {
210
383k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
383k
          std::fill(r, r + channel.w, v);
212
383k
        }
213
76.5k
      } else {
214
76.5k
        JXL_DEBUG_V(8, "Fast track.");
215
76.5k
        if (multiplier == 1 && offset == 0) {
216
2.26M
          for (size_t y = 0; y < channel.h; y++) {
217
2.19M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
117M
            for (size_t x = 0; x < channel.w; x++) {
219
115M
              uint32_t v =
220
115M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
115M
              r[x] = UnpackSigned(v);
222
115M
            }
223
2.19M
          }
224
65.4k
        } else {
225
238k
          for (size_t y = 0; y < channel.h; y++) {
226
227k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
8.58M
            for (size_t x = 0; x < channel.w; x++) {
228
8.35M
              uint32_t v =
229
8.35M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
8.35M
                                                                         br);
231
8.35M
              r[x] = make_pixel(v, multiplier, offset);
232
8.35M
            }
233
227k
          }
234
11.1k
        }
235
76.5k
      }
236
94.0k
      return true;
237
94.0k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
15.7k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
0
      pixel_type_w sv = UnpackSigned(fl_v);
241
0
      for (size_t y = 0; y < channel.h; y++) {
242
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
0
        const pixel_type *JXL_RESTRICT rtopleft =
245
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
0
        if (fl_run == 0) {
248
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
0
                                                     &fl_run);
250
0
          sv = UnpackSigned(fl_v);
251
0
        } else {
252
0
          fl_run--;
253
0
        }
254
0
        r[0] = sv + guess_0;
255
0
        for (size_t x = 1; x < channel.w; x++) {
256
0
          pixel_type left = r[x - 1];
257
0
          pixel_type top = rtop[x];
258
0
          pixel_type topleft = rtopleft[x];
259
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
0
          if (!fl_run) {
261
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
0
                                                       &fl_run);
263
0
            sv = UnpackSigned(fl_v);
264
0
          } else {
265
0
            fl_run--;
266
0
          }
267
0
          r[x] = sv + guess;
268
0
        }
269
0
      }
270
0
      return true;
271
15.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
15.7k
               multiplier == 1) {
273
551
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
551
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
10.3k
      for (size_t y = 0; y < channel.h; y++) {
276
9.81k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
485k
        for (size_t x = 0; x < channel.w; x++) {
278
475k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
475k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
475k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
475k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
475k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
475k
              ctx_id, br);
284
475k
          r[x] = make_pixel(v, 1, guess);
285
475k
        }
286
9.81k
      }
287
551
      return true;
288
551
    }
289
109k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
25.6k
  if (is_wp_only) {
294
1.46k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
1.46k
  }
296
25.6k
  if (is_gradient_only) {
297
1.02k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.02k
  }
299
300
25.6k
  if (is_gradient_only) {
301
436
    JXL_DEBUG_V(8, "Gradient fast track.");
302
436
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
11.1k
    for (size_t y = 0; y < channel.h; y++) {
304
10.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
360k
      for (size_t x = 0; x < channel.w; x++) {
306
349k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
349k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
349k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
349k
        int32_t guess = ClampedGradient(top, left, topleft);
310
349k
        uint32_t pos =
311
349k
            kPropRangeFast +
312
349k
            std::min<pixel_type_w>(
313
349k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
349k
                kPropRangeFast - 1);
315
349k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
349k
        uint64_t v =
317
349k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
349k
        r[x] = make_pixel(v, 1, guess);
319
349k
      }
320
10.7k
    }
321
25.1k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
571
    JXL_DEBUG_V(8, "WP fast track.");
323
571
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
571
    Properties properties(1);
325
15.9k
    for (size_t y = 0; y < channel.h; y++) {
326
15.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
15.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
15.3k
      const pixel_type *JXL_RESTRICT rtoptop =
329
15.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
15.3k
      const pixel_type *JXL_RESTRICT rtopleft =
331
15.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
15.3k
      const pixel_type *JXL_RESTRICT rtopright =
333
15.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
15.3k
      size_t x = 0;
335
15.3k
      {
336
15.3k
        size_t offset = 0;
337
15.3k
        pixel_type_w left = y ? rtop[x] : 0;
338
15.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
15.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
15.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
15.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
15.3k
            offset);
343
15.3k
        uint32_t pos =
344
15.3k
            kPropRangeFast +
345
15.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
15.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
15.3k
        uint64_t v =
348
15.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
15.3k
        r[x] = make_pixel(v, 1, guess);
350
15.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
15.3k
      }
352
513k
      for (x = 1; x + 1 < channel.w; x++) {
353
498k
        size_t offset = 0;
354
498k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
498k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
498k
            rtoptop[x], &properties, offset);
357
498k
        uint32_t pos =
358
498k
            kPropRangeFast +
359
498k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
498k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
498k
        uint64_t v =
362
498k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
498k
        r[x] = make_pixel(v, 1, guess);
364
498k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
498k
      }
366
15.3k
      {
367
15.3k
        size_t offset = 0;
368
15.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
15.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
15.3k
            rtoptop[x], &properties, offset);
371
15.3k
        uint32_t pos =
372
15.3k
            kPropRangeFast +
373
15.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
15.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
15.3k
        uint64_t v =
376
15.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
15.3k
        r[x] = make_pixel(v, 1, guess);
378
15.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
15.3k
      }
380
15.3k
    }
381
24.5k
  } 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
18.3k
    JXL_DEBUG_V(8, "Slow track.");
385
18.3k
    MATreeLookup tree_lookup(tree);
386
18.3k
    Properties properties = Properties(num_props);
387
18.3k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
18.3k
    JXL_ASSIGN_OR_RETURN(
389
18.3k
        Channel references,
390
18.3k
        Channel::Create(memory_manager,
391
18.3k
                        properties.size() - kNumNonrefProperties, channel.w));
392
368k
    for (size_t y = 0; y < channel.h; y++) {
393
350k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
350k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
350k
      InitPropsRow(&properties, static_props, y);
396
350k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
776k
        for (size_t x = 0; x < 2; x++) {
398
517k
          PredictionResult res =
399
517k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
517k
                              tree_lookup, references);
401
517k
          uint64_t v =
402
517k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
517k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
517k
        }
405
18.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
17.9M
          PredictionResult res =
407
17.9M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
17.9M
                                 tree_lookup, references);
409
17.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
17.9M
              res.context, br);
411
17.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
17.9M
        }
413
776k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
517k
          PredictionResult res =
415
517k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
517k
                              tree_lookup, references);
417
517k
          uint64_t v =
418
517k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
517k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
517k
        }
421
258k
      } else {
422
2.03M
        for (size_t x = 0; x < channel.w; x++) {
423
1.94M
          PredictionResult res =
424
1.94M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.94M
                              tree_lookup, references);
426
1.94M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.94M
              res.context, br);
428
1.94M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.94M
        }
430
91.3k
      }
431
350k
    }
432
18.3k
  } else {
433
6.27k
    JXL_DEBUG_V(8, "Slowest track.");
434
6.27k
    MATreeLookup tree_lookup(tree);
435
6.27k
    Properties properties = Properties(num_props);
436
6.27k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
6.27k
    JXL_ASSIGN_OR_RETURN(
438
6.27k
        Channel references,
439
6.27k
        Channel::Create(memory_manager,
440
6.27k
                        properties.size() - kNumNonrefProperties, channel.w));
441
6.27k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
291k
    for (size_t y = 0; y < channel.h; y++) {
443
284k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
284k
      InitPropsRow(&properties, static_props, y);
445
284k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
284k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
757k
        for (size_t x = 0; x < 2; x++) {
448
504k
          PredictionResult res =
449
504k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
504k
                            tree_lookup, references, &wp_state);
451
504k
          uint64_t v =
452
504k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
504k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
504k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
504k
        }
456
26.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
25.9M
          PredictionResult res =
458
25.9M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
25.9M
                               tree_lookup, references, &wp_state);
460
25.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
25.9M
              res.context, br);
462
25.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
25.9M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
25.9M
        }
465
757k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
504k
          PredictionResult res =
467
504k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
504k
                            tree_lookup, references, &wp_state);
469
504k
          uint64_t v =
470
504k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
504k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
504k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
504k
        }
474
252k
      } else {
475
1.10M
        for (size_t x = 0; x < channel.w; x++) {
476
1.06M
          PredictionResult res =
477
1.06M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.06M
                            tree_lookup, references, &wp_state);
479
1.06M
          uint64_t v =
480
1.06M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.06M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.06M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.06M
        }
484
32.5k
      }
485
284k
    }
486
6.27k
  }
487
25.6k
  return true;
488
25.6k
}
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
165k
                                 uint32_t &fl_v) {
499
165k
  if (reader->UsesLZ77()) {
500
45.5k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
45.5k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
45.5k
        tree_lut, image, fl_run, fl_v);
503
120k
  } else {
504
120k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
120k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
120k
        tree_lut, image, fl_run, fl_v);
507
120k
  }
508
165k
}
509
510
202k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
45.4k
                                 const ModularOptions &options) {
514
45.4k
  size_t nb_channels = image.channel.size();
515
90.8k
  for (bool is_dc : {true, false}) {
516
90.8k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
90.8k
    size_t c = image.nb_meta_channels;
518
509k
    for (; c < nb_channels; c++) {
519
419k
      const Channel &ch = image.channel[c];
520
419k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
419k
    }
522
96.8k
    for (; c < nb_channels; c++) {
523
5.95k
      const Channel &ch = image.channel[c];
524
5.95k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
5.48k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
5.48k
      if (is_dc_channel != is_dc) continue;
527
2.75k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
2.75k
      if (tile_dim == 0) {
529
6
        return JXL_FAILURE("Inconsistent transforms");
530
6
      }
531
2.75k
    }
532
90.8k
  }
533
45.4k
  return true;
534
45.4k
}
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
57.4k
                     const bool allow_truncated_group) {
541
57.4k
  if (image.channel.empty()) return true;
542
49.2k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
49.2k
  Status status = Bundle::Read(br, &header);
546
49.2k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
45.2k
  if (status.IsFatalError()) return status;
548
45.2k
  if (!br->AllReadsWithinBounds()) {
549
    // Don't do/undo transforms if header is incomplete.
550
0
    header.transforms.clear();
551
0
    image.transform = header.transforms;
552
0
    for (auto &ch : image.channel) {
553
0
      ZeroFillImage(&ch.plane);
554
0
    }
555
0
    return JXL_NOT_ENOUGH_BYTES("Read overrun before ModularDecode");
556
0
  }
557
558
45.2k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
45.2k
              header.transforms.size());
560
45.2k
  image.transform = header.transforms;
561
45.2k
  for (Transform &transform : image.transform) {
562
12.2k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
12.2k
  }
564
44.4k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
44.4k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
44.4k
  size_t nb_channels = image.channel.size();
570
571
44.4k
  size_t num_chans = 0;
572
44.4k
  size_t distance_multiplier = 0;
573
251k
  for (size_t i = 0; i < nb_channels; i++) {
574
207k
    Channel &channel = image.channel[i];
575
207k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
206k
                                        channel.h > options->max_chan_size)) {
577
629
      break;
578
629
    }
579
206k
    if (!channel.w || !channel.h) {
580
1.07k
      continue;  // skip empty channels
581
1.07k
    }
582
205k
    if (channel.w > distance_multiplier) {
583
53.7k
      distance_multiplier = channel.w;
584
53.7k
    }
585
205k
    num_chans++;
586
205k
  }
587
44.4k
  if (num_chans == 0) return true;
588
589
43.8k
  size_t next_channel = 0;
590
43.8k
  auto scope_guard = MakeScopeGuard([&]() {
591
54.6k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
43.8k
      ZeroFillImage(&image.channel[c].plane);
593
43.8k
    }
594
10.8k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
43.8k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
43.8k
  Tree tree_storage;
600
43.8k
  std::vector<uint8_t> context_map_storage;
601
43.8k
  ANSCode code_storage;
602
43.8k
  const Tree *tree = &tree_storage;
603
43.8k
  const ANSCode *code = &code_storage;
604
43.8k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
43.8k
  if (!header.use_global_tree) {
606
38.9k
    uint64_t max_tree_size = 1024;
607
219k
    for (size_t i = 0; i < nb_channels; i++) {
608
180k
      Channel &channel = image.channel[i];
609
180k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
179k
                                          channel.h > options->max_chan_size)) {
611
37
        break;
612
37
      }
613
180k
      uint64_t pixels = channel.w * channel.h;
614
180k
      max_tree_size += pixels;
615
180k
    }
616
38.9k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
38.9k
    JXL_RETURN_IF_ERROR(
618
38.9k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
33.7k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
33.7k
                                         (tree_storage.size() + 1) / 2,
621
33.7k
                                         &code_storage, &context_map_storage));
622
33.7k
  } else {
623
4.92k
    if (!global_tree || !global_code || !global_ctx_map ||
624
4.92k
        global_tree->empty()) {
625
545
      return JXL_FAILURE("No global tree available but one was requested");
626
545
    }
627
4.38k
    tree = global_tree;
628
4.38k
    code = global_code;
629
4.38k
    context_map = global_ctx_map;
630
4.38k
  }
631
632
  // Read channels
633
72.6k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
72.6k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
72.6k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
72.6k
  uint32_t fl_run = 0;
637
72.6k
  uint32_t fl_v = 0;
638
199k
  for (; next_channel < nb_channels; next_channel++) {
639
166k
    Channel &channel = image.channel[next_channel];
640
166k
    if (next_channel >= image.nb_meta_channels &&
641
166k
        (channel.w > options->max_chan_size ||
642
165k
         channel.h > options->max_chan_size)) {
643
63
      break;
644
63
    }
645
166k
    if (!channel.w || !channel.h) {
646
821
      continue;  // skip empty channels
647
821
    }
648
165k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
165k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
165k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
165k
    if (!br->AllReadsWithinBounds()) {
654
3.33k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
3.33k
    }
657
165k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
32.9k
  scope_guard.Disarm();
661
662
32.9k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
32.9k
  return true;
666
32.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
57.4k
                                bool allow_truncated_group) {
674
57.4k
  std::vector<std::pair<uint32_t, uint32_t>> req_sizes;
675
57.4k
  req_sizes.reserve(image.channel.size());
676
153k
  for (const auto &c : image.channel) {
677
153k
    req_sizes.emplace_back(c.w, c.h);
678
153k
  }
679
57.4k
  GroupHeader local_header;
680
57.4k
  if (header == nullptr) header = &local_header;
681
57.4k
  size_t bit_pos = br->TotalBitsConsumed();
682
57.4k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
57.4k
                                  code, ctx_map, allow_truncated_group);
684
57.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
41.6k
  if (dec_status.IsFatalError()) return dec_status;
686
41.6k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
41.6k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
41.6k
  JXL_DEBUG_V(4,
689
41.6k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
41.6k
              " image from %" PRIuS " bytes",
691
41.6k
              image.w, image.h, image.channel.size(),
692
41.6k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
41.6k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
41.6k
  (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
41.6k
  if (undo_transforms) {
699
5.75k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
25.6k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
19.8k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
19.8k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
19.8k
    }
704
5.75k
  }
705
41.6k
  return dec_status;
706
41.6k
}
707
708
}  // namespace jxl