Coverage Report

Created: 2026-02-14 07:11

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
374k
                    bool *gradient_only) {
46
374k
  *num_props = 0;
47
374k
  bool has_wp = false;
48
374k
  bool has_non_wp = false;
49
374k
  *gradient_only = true;
50
965k
  const auto mark_property = [&](int32_t p) {
51
965k
    if (p == kWPProp) {
52
89.5k
      has_wp = true;
53
876k
    } else if (p >= kNumStaticProperties) {
54
536k
      has_non_wp = true;
55
536k
    }
56
965k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
566k
      *gradient_only = false;
58
566k
    }
59
965k
  };
60
374k
  FlatTree output;
61
374k
  std::queue<size_t> nodes;
62
374k
  nodes.push(0);
63
  // Produces a trimmed and flattened tree by doing a BFS visit of the original
64
  // tree, ignoring branches that are known to be false and proceeding two
65
  // levels at a time to collapse nodes in a flatter tree; if an inner parent
66
  // node has a leaf as a child, the leaf is duplicated and an implicit fake
67
  // node is added. This allows to reduce the number of branches when traversing
68
  // the resulting flat tree.
69
2.03M
  while (!nodes.empty()) {
70
1.66M
    size_t cur = nodes.front();
71
1.66M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.71M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.38M
           global_tree[cur].property != -1) {
75
48.5k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
27.6k
        cur = global_tree[cur].lchild;
77
27.6k
      } else {
78
20.8k
        cur = global_tree[cur].rchild;
79
20.8k
      }
80
48.5k
    }
81
1.66M
    FlatDecisionNode flat;
82
1.66M
    if (global_tree[cur].property == -1) {
83
1.34M
      flat.property0 = -1;
84
1.34M
      flat.childID = global_tree[cur].lchild;
85
1.34M
      flat.predictor = global_tree[cur].predictor;
86
1.34M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.34M
      flat.multiplier = global_tree[cur].multiplier;
88
1.34M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.34M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.34M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.34M
      output.push_back(flat);
92
1.34M
      continue;
93
1.34M
    }
94
321k
    flat.childID = output.size() + nodes.size() + 1;
95
96
321k
    flat.property0 = global_tree[cur].property;
97
321k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
321k
    flat.splitval0 = global_tree[cur].splitval;
99
100
965k
    for (size_t i = 0; i < 2; i++) {
101
643k
      size_t cur_child =
102
643k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
655k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
351k
             global_tree[cur_child].property != -1) {
106
11.3k
        if (static_props[global_tree[cur_child].property] >
107
11.3k
            global_tree[cur_child].splitval) {
108
7.53k
          cur_child = global_tree[cur_child].lchild;
109
7.53k
        } else {
110
3.79k
          cur_child = global_tree[cur_child].rchild;
111
3.79k
        }
112
11.3k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
643k
      if (global_tree[cur_child].property == -1) {
116
340k
        flat.properties[i] = 0;
117
340k
        flat.splitvals[i] = 0;
118
340k
        nodes.push(cur_child);
119
340k
        nodes.push(cur_child);
120
340k
      } else {
121
303k
        flat.properties[i] = global_tree[cur_child].property;
122
303k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
303k
        nodes.push(global_tree[cur_child].lchild);
124
303k
        nodes.push(global_tree[cur_child].rchild);
125
303k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
303k
      }
127
643k
    }
128
129
643k
    for (int16_t property : flat.properties) mark_property(property);
130
321k
    mark_property(flat.property0);
131
321k
    output.push_back(flat);
132
321k
  }
133
374k
  if (*num_props > kNumNonrefProperties) {
134
1.62k
    *num_props =
135
1.62k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.62k
            kExtraPropsPerChannel +
137
1.62k
        kNumNonrefProperties;
138
373k
  } else {
139
373k
    *num_props = kNumNonrefProperties;
140
373k
  }
141
374k
  *use_wp = has_wp;
142
374k
  *wp_only = has_wp && !has_non_wp;
143
144
374k
  return output;
145
374k
}
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
352k
                                 uint32_t &fl_v) {
157
352k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
352k
  Channel &channel = image->channel[chan];
159
160
352k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
352k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
352k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
352k
  bool tree_has_wp_prop_or_pred = false;
168
352k
  bool is_wp_only = false;
169
352k
  bool is_gradient_only = false;
170
352k
  size_t num_props;
171
352k
  FlatTree tree =
172
352k
      FilterTree(global_tree, static_props, &num_props,
173
352k
                 &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
496k
  for (auto &node : tree) {
178
496k
    if (node.property0 == -1) {
179
460k
      node.childID = context_map[node.childID];
180
460k
    }
181
496k
  }
182
183
352k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
352k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
224M
                             pixel_type_w offset) -> pixel_type {
188
224M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
224M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
224M
    return val * multiplier + offset;
192
224M
  };
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
39.4M
                             pixel_type_w offset) -> pixel_type {
188
39.4M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
39.4M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
39.4M
    return val * multiplier + offset;
192
39.4M
  };
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
185M
                             pixel_type_w offset) -> pixel_type {
188
185M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
185M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
185M
    return val * multiplier + offset;
192
185M
  };
193
194
352k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
342k
    Predictor predictor = tree[0].predictor;
198
342k
    int64_t offset = tree[0].predictor_offset;
199
342k
    int32_t multiplier = tree[0].multiplier;
200
342k
    size_t ctx_id = tree[0].childID;
201
342k
    if (predictor == Predictor::Zero) {
202
323k
      uint32_t value;
203
323k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
323k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
130k
        JXL_DEBUG_V(8, "Fastest track.");
208
130k
        pixel_type v = make_pixel(value, multiplier, offset);
209
3.67M
        for (size_t y = 0; y < channel.h; y++) {
210
3.54M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
3.54M
          std::fill(r, r + channel.w, v);
212
3.54M
        }
213
192k
      } else {
214
192k
        JXL_DEBUG_V(8, "Fast track.");
215
192k
        if (multiplier == 1 && offset == 0) {
216
3.01M
          for (size_t y = 0; y < channel.h; y++) {
217
2.85M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
203M
            for (size_t x = 0; x < channel.w; x++) {
219
200M
              uint32_t v =
220
200M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
200M
              r[x] = UnpackSigned(v);
222
200M
            }
223
2.85M
          }
224
163k
        } else {
225
1.30M
          for (size_t y = 0; y < channel.h; y++) {
226
1.28M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
148M
            for (size_t x = 0; x < channel.w; x++) {
228
146M
              uint32_t v =
229
146M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
146M
                                                                         br);
231
146M
              r[x] = make_pixel(v, multiplier, offset);
232
146M
            }
233
1.28M
          }
234
29.1k
        }
235
192k
      }
236
323k
      return true;
237
323k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.37k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
395
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
395
      pixel_type_w sv = UnpackSigned(fl_v);
241
14.5k
      for (size_t y = 0; y < channel.h; y++) {
242
14.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
14.1k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
14.1k
        const pixel_type *JXL_RESTRICT rtopleft =
245
14.1k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
14.1k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
14.1k
        if (fl_run == 0) {
248
4.34k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
4.34k
                                                     &fl_run);
250
4.34k
          sv = UnpackSigned(fl_v);
251
9.83k
        } else {
252
9.83k
          fl_run--;
253
9.83k
        }
254
14.1k
        r[0] = sv + guess_0;
255
458k
        for (size_t x = 1; x < channel.w; x++) {
256
443k
          pixel_type left = r[x - 1];
257
443k
          pixel_type top = rtop[x];
258
443k
          pixel_type topleft = rtopleft[x];
259
443k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
443k
          if (!fl_run) {
261
122k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
122k
                                                       &fl_run);
263
122k
            sv = UnpackSigned(fl_v);
264
321k
          } else {
265
321k
            fl_run--;
266
321k
          }
267
443k
          r[x] = sv + guess;
268
443k
        }
269
14.1k
      }
270
395
      return true;
271
19.2k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
2.67k
               multiplier == 1) {
273
2.25k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
2.25k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
50.1k
      for (size_t y = 0; y < channel.h; y++) {
276
47.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.73M
        for (size_t x = 0; x < channel.w; x++) {
278
2.68M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.68M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.68M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.68M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.68M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.68M
              ctx_id, br);
284
2.68M
          r[x] = make_pixel(v, 1, guess);
285
2.68M
        }
286
47.8k
      }
287
2.25k
      return true;
288
2.25k
    }
289
342k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
26.2k
  if (is_wp_only) {
294
4.13k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.13k
  }
296
26.2k
  if (is_gradient_only) {
297
1.91k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.91k
  }
299
300
26.2k
  if (is_gradient_only) {
301
615
    JXL_DEBUG_V(8, "Gradient fast track.");
302
615
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
14.1k
    for (size_t y = 0; y < channel.h; y++) {
304
13.5k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
472k
      for (size_t x = 0; x < channel.w; x++) {
306
459k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
459k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
459k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
459k
        int32_t guess = ClampedGradient(top, left, topleft);
310
459k
        uint32_t pos =
311
459k
            kPropRangeFast +
312
459k
            std::min<pixel_type_w>(
313
459k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
459k
                kPropRangeFast - 1);
315
459k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
459k
        uint64_t v =
317
459k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
459k
        r[x] = make_pixel(v, 1, guess);
319
459k
      }
320
13.5k
    }
321
25.5k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
758
    JXL_DEBUG_V(8, "WP fast track.");
323
758
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
758
    Properties properties(1);
325
18.1k
    for (size_t y = 0; y < channel.h; y++) {
326
17.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
17.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
17.3k
      const pixel_type *JXL_RESTRICT rtoptop =
329
17.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
17.3k
      const pixel_type *JXL_RESTRICT rtopleft =
331
17.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
17.3k
      const pixel_type *JXL_RESTRICT rtopright =
333
17.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
17.3k
      size_t x = 0;
335
17.3k
      {
336
17.3k
        size_t offset = 0;
337
17.3k
        pixel_type_w left = y ? rtop[x] : 0;
338
17.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
17.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
17.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
17.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
17.3k
            offset);
343
17.3k
        uint32_t pos =
344
17.3k
            kPropRangeFast +
345
17.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
17.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
17.3k
        uint64_t v =
348
17.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
17.3k
        r[x] = make_pixel(v, 1, guess);
350
17.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
17.3k
      }
352
1.90M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.88M
        size_t offset = 0;
354
1.88M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.88M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.88M
            rtoptop[x], &properties, offset);
357
1.88M
        uint32_t pos =
358
1.88M
            kPropRangeFast +
359
1.88M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.88M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.88M
        uint64_t v =
362
1.88M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.88M
        r[x] = make_pixel(v, 1, guess);
364
1.88M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.88M
      }
366
17.3k
      {
367
17.3k
        size_t offset = 0;
368
17.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
17.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
17.3k
            rtoptop[x], &properties, offset);
371
17.3k
        uint32_t pos =
372
17.3k
            kPropRangeFast +
373
17.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
17.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
17.3k
        uint64_t v =
376
17.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
17.3k
        r[x] = make_pixel(v, 1, guess);
378
17.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
17.3k
      }
380
17.3k
    }
381
24.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
17.1k
    JXL_DEBUG_V(8, "Slow track.");
385
17.1k
    MATreeLookup tree_lookup(tree);
386
17.1k
    Properties properties = Properties(num_props);
387
17.1k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
17.1k
    JXL_ASSIGN_OR_RETURN(
389
17.1k
        Channel references,
390
17.1k
        Channel::Create(memory_manager,
391
17.1k
                        properties.size() - kNumNonrefProperties, channel.w));
392
564k
    for (size_t y = 0; y < channel.h; y++) {
393
547k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
547k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
547k
      InitPropsRow(&properties, static_props, y);
396
547k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.40M
        for (size_t x = 0; x < 2; x++) {
398
939k
          PredictionResult res =
399
939k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
939k
                              tree_lookup, references);
401
939k
          uint64_t v =
402
939k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
939k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
939k
        }
405
52.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
52.2M
          PredictionResult res =
407
52.2M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
52.2M
                                 tree_lookup, references);
409
52.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
52.2M
              res.context, br);
411
52.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
52.2M
        }
413
1.40M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
939k
          PredictionResult res =
415
939k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
939k
                              tree_lookup, references);
417
939k
          uint64_t v =
418
939k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
939k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
939k
        }
421
469k
      } else {
422
2.37M
        for (size_t x = 0; x < channel.w; x++) {
423
2.29M
          PredictionResult res =
424
2.29M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
2.29M
                              tree_lookup, references);
426
2.29M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
2.29M
              res.context, br);
428
2.29M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
2.29M
        }
430
78.1k
      }
431
547k
    }
432
17.1k
  } else {
433
7.73k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.73k
    MATreeLookup tree_lookup(tree);
435
7.73k
    Properties properties = Properties(num_props);
436
7.73k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
7.73k
    JXL_ASSIGN_OR_RETURN(
438
7.73k
        Channel references,
439
7.73k
        Channel::Create(memory_manager,
440
7.73k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.73k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
223k
    for (size_t y = 0; y < channel.h; y++) {
443
215k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
215k
      InitPropsRow(&properties, static_props, y);
445
215k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
215k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
529k
        for (size_t x = 0; x < 2; x++) {
448
353k
          PredictionResult res =
449
353k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
353k
                            tree_lookup, references, &wp_state);
451
353k
          uint64_t v =
452
353k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
353k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
353k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
353k
        }
456
13.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
13.0M
          PredictionResult res =
458
13.0M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
13.0M
                               tree_lookup, references, &wp_state);
460
13.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
13.0M
              res.context, br);
462
13.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
13.0M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
13.0M
        }
465
529k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
353k
          PredictionResult res =
467
353k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
353k
                            tree_lookup, references, &wp_state);
469
353k
          uint64_t v =
470
353k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
353k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
353k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
353k
        }
474
176k
      } else {
475
2.44M
        for (size_t x = 0; x < channel.w; x++) {
476
2.40M
          PredictionResult res =
477
2.40M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
2.40M
                            tree_lookup, references, &wp_state);
479
2.40M
          uint64_t v =
480
2.40M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
2.40M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
2.40M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
2.40M
        }
484
38.9k
      }
485
215k
    }
486
7.73k
  }
487
26.2k
  return true;
488
26.2k
}
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
29.9k
                                 uint32_t &fl_v) {
157
29.9k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
29.9k
  Channel &channel = image->channel[chan];
159
160
29.9k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
29.9k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
29.9k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
29.9k
  bool tree_has_wp_prop_or_pred = false;
168
29.9k
  bool is_wp_only = false;
169
29.9k
  bool is_gradient_only = false;
170
29.9k
  size_t num_props;
171
29.9k
  FlatTree tree =
172
29.9k
      FilterTree(global_tree, static_props, &num_props,
173
29.9k
                 &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
38.4k
  for (auto &node : tree) {
178
38.4k
    if (node.property0 == -1) {
179
36.3k
      node.childID = context_map[node.childID];
180
36.3k
    }
181
38.4k
  }
182
183
29.9k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
29.9k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
29.9k
                             pixel_type_w offset) -> pixel_type {
188
29.9k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
29.9k
    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.9k
    return val * multiplier + offset;
192
29.9k
  };
193
194
29.9k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
28.0k
    Predictor predictor = tree[0].predictor;
198
28.0k
    int64_t offset = tree[0].predictor_offset;
199
28.0k
    int32_t multiplier = tree[0].multiplier;
200
28.0k
    size_t ctx_id = tree[0].childID;
201
28.0k
    if (predictor == Predictor::Zero) {
202
21.9k
      uint32_t value;
203
21.9k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
21.9k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
8.23k
        JXL_DEBUG_V(8, "Fastest track.");
208
8.23k
        pixel_type v = make_pixel(value, multiplier, offset);
209
319k
        for (size_t y = 0; y < channel.h; y++) {
210
311k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
311k
          std::fill(r, r + channel.w, v);
212
311k
        }
213
13.6k
      } else {
214
13.6k
        JXL_DEBUG_V(8, "Fast track.");
215
13.6k
        if (multiplier == 1 && offset == 0) {
216
294k
          for (size_t y = 0; y < channel.h; y++) {
217
290k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
45.9M
            for (size_t x = 0; x < channel.w; x++) {
219
45.6M
              uint32_t v =
220
45.6M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
45.6M
              r[x] = UnpackSigned(v);
222
45.6M
            }
223
290k
          }
224
9.23k
        } else {
225
294k
          for (size_t y = 0; y < channel.h; y++) {
226
285k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
19.6M
            for (size_t x = 0; x < channel.w; x++) {
228
19.3M
              uint32_t v =
229
19.3M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
19.3M
                                                                         br);
231
19.3M
              r[x] = make_pixel(v, multiplier, offset);
232
19.3M
            }
233
285k
          }
234
9.23k
        }
235
13.6k
      }
236
21.9k
      return true;
237
21.9k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.37k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
395
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
395
      pixel_type_w sv = UnpackSigned(fl_v);
241
14.5k
      for (size_t y = 0; y < channel.h; y++) {
242
14.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
14.1k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
14.1k
        const pixel_type *JXL_RESTRICT rtopleft =
245
14.1k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
14.1k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
14.1k
        if (fl_run == 0) {
248
4.34k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
4.34k
                                                     &fl_run);
250
4.34k
          sv = UnpackSigned(fl_v);
251
9.83k
        } else {
252
9.83k
          fl_run--;
253
9.83k
        }
254
14.1k
        r[0] = sv + guess_0;
255
458k
        for (size_t x = 1; x < channel.w; x++) {
256
443k
          pixel_type left = r[x - 1];
257
443k
          pixel_type top = rtop[x];
258
443k
          pixel_type topleft = rtopleft[x];
259
443k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
443k
          if (!fl_run) {
261
122k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
122k
                                                       &fl_run);
263
122k
            sv = UnpackSigned(fl_v);
264
321k
          } else {
265
321k
            fl_run--;
266
321k
          }
267
443k
          r[x] = sv + guess;
268
443k
        }
269
14.1k
      }
270
395
      return true;
271
5.70k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
982
               multiplier == 1) {
273
876
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
876
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
10.5k
      for (size_t y = 0; y < channel.h; y++) {
276
9.65k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
286k
        for (size_t x = 0; x < channel.w; x++) {
278
276k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
276k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
276k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
276k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
276k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
276k
              ctx_id, br);
284
276k
          r[x] = make_pixel(v, 1, guess);
285
276k
        }
286
9.65k
      }
287
876
      return true;
288
876
    }
289
28.0k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
6.77k
  if (is_wp_only) {
294
313
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
313
  }
296
6.77k
  if (is_gradient_only) {
297
657
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
657
  }
299
300
6.77k
  if (is_gradient_only) {
301
102
    JXL_DEBUG_V(8, "Gradient fast track.");
302
102
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
2.64k
    for (size_t y = 0; y < channel.h; y++) {
304
2.54k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
103k
      for (size_t x = 0; x < channel.w; x++) {
306
100k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
100k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
100k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
100k
        int32_t guess = ClampedGradient(top, left, topleft);
310
100k
        uint32_t pos =
311
100k
            kPropRangeFast +
312
100k
            std::min<pixel_type_w>(
313
100k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
100k
                kPropRangeFast - 1);
315
100k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
100k
        uint64_t v =
317
100k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
100k
        r[x] = make_pixel(v, 1, guess);
319
100k
      }
320
2.54k
    }
321
6.67k
  } 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
6.67k
  } 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
6.12k
    JXL_DEBUG_V(8, "Slow track.");
385
6.12k
    MATreeLookup tree_lookup(tree);
386
6.12k
    Properties properties = Properties(num_props);
387
6.12k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
6.12k
    JXL_ASSIGN_OR_RETURN(
389
6.12k
        Channel references,
390
6.12k
        Channel::Create(memory_manager,
391
6.12k
                        properties.size() - kNumNonrefProperties, channel.w));
392
148k
    for (size_t y = 0; y < channel.h; y++) {
393
141k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
141k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
141k
      InitPropsRow(&properties, static_props, y);
396
141k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
359k
        for (size_t x = 0; x < 2; x++) {
398
239k
          PredictionResult res =
399
239k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
239k
                              tree_lookup, references);
401
239k
          uint64_t v =
402
239k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
239k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
239k
        }
405
17.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
17.5M
          PredictionResult res =
407
17.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
17.5M
                                 tree_lookup, references);
409
17.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
17.5M
              res.context, br);
411
17.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
17.5M
        }
413
359k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
239k
          PredictionResult res =
415
239k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
239k
                              tree_lookup, references);
417
239k
          uint64_t v =
418
239k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
239k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
239k
        }
421
119k
      } else {
422
721k
        for (size_t x = 0; x < channel.w; x++) {
423
698k
          PredictionResult res =
424
698k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
698k
                              tree_lookup, references);
426
698k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
698k
              res.context, br);
428
698k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
698k
        }
430
22.0k
      }
431
141k
    }
432
6.12k
  } else {
433
554
    JXL_DEBUG_V(8, "Slowest track.");
434
554
    MATreeLookup tree_lookup(tree);
435
554
    Properties properties = Properties(num_props);
436
554
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
554
    JXL_ASSIGN_OR_RETURN(
438
554
        Channel references,
439
554
        Channel::Create(memory_manager,
440
554
                        properties.size() - kNumNonrefProperties, channel.w));
441
554
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
10.7k
    for (size_t y = 0; y < channel.h; y++) {
443
10.1k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
10.1k
      InitPropsRow(&properties, static_props, y);
445
10.1k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
10.1k
      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
10.1k
      } else {
475
973k
        for (size_t x = 0; x < channel.w; x++) {
476
963k
          PredictionResult res =
477
963k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
963k
                            tree_lookup, references, &wp_state);
479
963k
          uint64_t v =
480
963k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
963k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
963k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
963k
        }
484
10.1k
      }
485
10.1k
    }
486
554
  }
487
6.77k
  return true;
488
6.77k
}
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
322k
                                 uint32_t &fl_v) {
157
322k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
322k
  Channel &channel = image->channel[chan];
159
160
322k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
322k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
322k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
322k
  bool tree_has_wp_prop_or_pred = false;
168
322k
  bool is_wp_only = false;
169
322k
  bool is_gradient_only = false;
170
322k
  size_t num_props;
171
322k
  FlatTree tree =
172
322k
      FilterTree(global_tree, static_props, &num_props,
173
322k
                 &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
458k
  for (auto &node : tree) {
178
458k
    if (node.property0 == -1) {
179
424k
      node.childID = context_map[node.childID];
180
424k
    }
181
458k
  }
182
183
322k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
322k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
322k
                             pixel_type_w offset) -> pixel_type {
188
322k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
322k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
322k
    return val * multiplier + offset;
192
322k
  };
193
194
322k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
314k
    Predictor predictor = tree[0].predictor;
198
314k
    int64_t offset = tree[0].predictor_offset;
199
314k
    int32_t multiplier = tree[0].multiplier;
200
314k
    size_t ctx_id = tree[0].childID;
201
314k
    if (predictor == Predictor::Zero) {
202
301k
      uint32_t value;
203
301k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
301k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
122k
        JXL_DEBUG_V(8, "Fastest track.");
208
122k
        pixel_type v = make_pixel(value, multiplier, offset);
209
3.35M
        for (size_t y = 0; y < channel.h; y++) {
210
3.23M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
3.23M
          std::fill(r, r + channel.w, v);
212
3.23M
        }
213
179k
      } else {
214
179k
        JXL_DEBUG_V(8, "Fast track.");
215
179k
        if (multiplier == 1 && offset == 0) {
216
2.71M
          for (size_t y = 0; y < channel.h; y++) {
217
2.55M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
157M
            for (size_t x = 0; x < channel.w; x++) {
219
154M
              uint32_t v =
220
154M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
154M
              r[x] = UnpackSigned(v);
222
154M
            }
223
2.55M
          }
224
159k
        } else {
225
1.01M
          for (size_t y = 0; y < channel.h; y++) {
226
994k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
128M
            for (size_t x = 0; x < channel.w; x++) {
228
127M
              uint32_t v =
229
127M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
127M
                                                                         br);
231
127M
              r[x] = make_pixel(v, multiplier, offset);
232
127M
            }
233
994k
          }
234
19.9k
        }
235
179k
      }
236
301k
      return true;
237
301k
    } 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
13.5k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.68k
               multiplier == 1) {
273
1.38k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.38k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
39.5k
      for (size_t y = 0; y < channel.h; y++) {
276
38.2k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.44M
        for (size_t x = 0; x < channel.w; x++) {
278
2.40M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.40M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.40M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.40M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.40M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.40M
              ctx_id, br);
284
2.40M
          r[x] = make_pixel(v, 1, guess);
285
2.40M
        }
286
38.2k
      }
287
1.38k
      return true;
288
1.38k
    }
289
314k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
19.4k
  if (is_wp_only) {
294
3.82k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
3.82k
  }
296
19.4k
  if (is_gradient_only) {
297
1.26k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.26k
  }
299
300
19.4k
  if (is_gradient_only) {
301
513
    JXL_DEBUG_V(8, "Gradient fast track.");
302
513
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
11.5k
    for (size_t y = 0; y < channel.h; y++) {
304
11.0k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
369k
      for (size_t x = 0; x < channel.w; x++) {
306
358k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
358k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
358k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
358k
        int32_t guess = ClampedGradient(top, left, topleft);
310
358k
        uint32_t pos =
311
358k
            kPropRangeFast +
312
358k
            std::min<pixel_type_w>(
313
358k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
358k
                kPropRangeFast - 1);
315
358k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
358k
        uint64_t v =
317
358k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
358k
        r[x] = make_pixel(v, 1, guess);
319
358k
      }
320
11.0k
    }
321
18.9k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
758
    JXL_DEBUG_V(8, "WP fast track.");
323
758
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
758
    Properties properties(1);
325
18.1k
    for (size_t y = 0; y < channel.h; y++) {
326
17.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
17.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
17.3k
      const pixel_type *JXL_RESTRICT rtoptop =
329
17.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
17.3k
      const pixel_type *JXL_RESTRICT rtopleft =
331
17.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
17.3k
      const pixel_type *JXL_RESTRICT rtopright =
333
17.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
17.3k
      size_t x = 0;
335
17.3k
      {
336
17.3k
        size_t offset = 0;
337
17.3k
        pixel_type_w left = y ? rtop[x] : 0;
338
17.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
17.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
17.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
17.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
17.3k
            offset);
343
17.3k
        uint32_t pos =
344
17.3k
            kPropRangeFast +
345
17.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
17.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
17.3k
        uint64_t v =
348
17.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
17.3k
        r[x] = make_pixel(v, 1, guess);
350
17.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
17.3k
      }
352
1.90M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.88M
        size_t offset = 0;
354
1.88M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.88M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.88M
            rtoptop[x], &properties, offset);
357
1.88M
        uint32_t pos =
358
1.88M
            kPropRangeFast +
359
1.88M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.88M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.88M
        uint64_t v =
362
1.88M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.88M
        r[x] = make_pixel(v, 1, guess);
364
1.88M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.88M
      }
366
17.3k
      {
367
17.3k
        size_t offset = 0;
368
17.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
17.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
17.3k
            rtoptop[x], &properties, offset);
371
17.3k
        uint32_t pos =
372
17.3k
            kPropRangeFast +
373
17.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
17.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
17.3k
        uint64_t v =
376
17.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
17.3k
        r[x] = make_pixel(v, 1, guess);
378
17.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
17.3k
      }
380
17.3k
    }
381
18.1k
  } 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.9k
    JXL_DEBUG_V(8, "Slow track.");
385
10.9k
    MATreeLookup tree_lookup(tree);
386
10.9k
    Properties properties = Properties(num_props);
387
10.9k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
10.9k
    JXL_ASSIGN_OR_RETURN(
389
10.9k
        Channel references,
390
10.9k
        Channel::Create(memory_manager,
391
10.9k
                        properties.size() - kNumNonrefProperties, channel.w));
392
416k
    for (size_t y = 0; y < channel.h; y++) {
393
405k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
405k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
405k
      InitPropsRow(&properties, static_props, y);
396
405k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.04M
        for (size_t x = 0; x < 2; x++) {
398
699k
          PredictionResult res =
399
699k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
699k
                              tree_lookup, references);
401
699k
          uint64_t v =
402
699k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
699k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
699k
        }
405
35.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
34.6M
          PredictionResult res =
407
34.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
34.6M
                                 tree_lookup, references);
409
34.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
34.6M
              res.context, br);
411
34.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
34.6M
        }
413
1.04M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
699k
          PredictionResult res =
415
699k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
699k
                              tree_lookup, references);
417
699k
          uint64_t v =
418
699k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
699k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
699k
        }
421
349k
      } else {
422
1.65M
        for (size_t x = 0; x < channel.w; x++) {
423
1.59M
          PredictionResult res =
424
1.59M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.59M
                              tree_lookup, references);
426
1.59M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.59M
              res.context, br);
428
1.59M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.59M
        }
430
56.0k
      }
431
405k
    }
432
10.9k
  } else {
433
7.17k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.17k
    MATreeLookup tree_lookup(tree);
435
7.17k
    Properties properties = Properties(num_props);
436
7.17k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
7.17k
    JXL_ASSIGN_OR_RETURN(
438
7.17k
        Channel references,
439
7.17k
        Channel::Create(memory_manager,
440
7.17k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.17k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
212k
    for (size_t y = 0; y < channel.h; y++) {
443
205k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
205k
      InitPropsRow(&properties, static_props, y);
445
205k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
205k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
529k
        for (size_t x = 0; x < 2; x++) {
448
353k
          PredictionResult res =
449
353k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
353k
                            tree_lookup, references, &wp_state);
451
353k
          uint64_t v =
452
353k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
353k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
353k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
353k
        }
456
13.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
13.0M
          PredictionResult res =
458
13.0M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
13.0M
                               tree_lookup, references, &wp_state);
460
13.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
13.0M
              res.context, br);
462
13.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
13.0M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
13.0M
        }
465
529k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
353k
          PredictionResult res =
467
353k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
353k
                            tree_lookup, references, &wp_state);
469
353k
          uint64_t v =
470
353k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
353k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
353k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
353k
        }
474
176k
      } else {
475
1.47M
        for (size_t x = 0; x < channel.w; x++) {
476
1.44M
          PredictionResult res =
477
1.44M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.44M
                            tree_lookup, references, &wp_state);
479
1.44M
          uint64_t v =
480
1.44M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.44M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.44M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.44M
        }
484
28.7k
      }
485
205k
    }
486
7.17k
  }
487
19.4k
  return true;
488
19.4k
}
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
352k
                                 uint32_t &fl_v) {
499
352k
  if (reader->UsesLZ77()) {
500
29.9k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
29.9k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
29.9k
        tree_lut, image, fl_run, fl_v);
503
322k
  } else {
504
322k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
322k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
322k
        tree_lut, image, fl_run, fl_v);
507
322k
  }
508
352k
}
509
510
171k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
40.9k
                                 const ModularOptions &options) {
514
40.9k
  size_t nb_channels = image.channel.size();
515
81.9k
  for (bool is_dc : {true, false}) {
516
81.9k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
81.9k
    size_t c = image.nb_meta_channels;
518
812k
    for (; c < nb_channels; c++) {
519
733k
      const Channel &ch = image.channel[c];
520
733k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
733k
    }
522
108k
    for (; c < nb_channels; c++) {
523
26.6k
      const Channel &ch = image.channel[c];
524
26.6k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
26.0k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
26.0k
      if (is_dc_channel != is_dc) continue;
527
13.0k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
13.0k
      if (tile_dim == 0) {
529
2
        return JXL_FAILURE("Inconsistent transforms");
530
2
      }
531
13.0k
    }
532
81.9k
  }
533
40.9k
  return true;
534
40.9k
}
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
45.0k
                     const bool allow_truncated_group) {
541
45.0k
  if (image.channel.empty()) return true;
542
39.9k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
39.9k
  Status status = Bundle::Read(br, &header);
546
39.9k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
39.4k
  if (status.IsFatalError()) return status;
548
39.4k
  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
39.4k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
39.4k
              header.transforms.size());
560
39.4k
  image.transform = header.transforms;
561
39.4k
  for (Transform &transform : image.transform) {
562
23.4k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
23.4k
  }
564
39.3k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
39.3k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
39.3k
  size_t nb_channels = image.channel.size();
570
571
39.3k
  size_t num_chans = 0;
572
39.3k
  size_t distance_multiplier = 0;
573
405k
  for (size_t i = 0; i < nb_channels; i++) {
574
367k
    Channel &channel = image.channel[i];
575
367k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
362k
                                        channel.h > options->max_chan_size)) {
577
1.34k
      break;
578
1.34k
    }
579
365k
    if (!channel.w || !channel.h) {
580
4.76k
      continue;  // skip empty channels
581
4.76k
    }
582
360k
    if (channel.w > distance_multiplier) {
583
60.8k
      distance_multiplier = channel.w;
584
60.8k
    }
585
360k
    num_chans++;
586
360k
  }
587
39.3k
  if (num_chans == 0) return true;
588
589
38.9k
  size_t next_channel = 0;
590
38.9k
  auto scope_guard = MakeScopeGuard([&]() {
591
12.9k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
11.2k
      ZeroFillImage(&image.channel[c].plane);
593
11.2k
    }
594
1.66k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
38.9k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
38.9k
  Tree tree_storage;
600
38.9k
  std::vector<uint8_t> context_map_storage;
601
38.9k
  ANSCode code_storage;
602
38.9k
  const Tree *tree = &tree_storage;
603
38.9k
  const ANSCode *code = &code_storage;
604
38.9k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
38.9k
  if (!header.use_global_tree) {
606
21.9k
    uint64_t max_tree_size = 1024;
607
268k
    for (size_t i = 0; i < nb_channels; i++) {
608
246k
      Channel &channel = image.channel[i];
609
246k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
245k
                                          channel.h > options->max_chan_size)) {
611
41
        break;
612
41
      }
613
246k
      uint64_t pixels = channel.w * channel.h;
614
246k
      max_tree_size += pixels;
615
246k
    }
616
21.9k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
21.9k
    JXL_RETURN_IF_ERROR(
618
21.9k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
21.8k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
21.8k
                                         (tree_storage.size() + 1) / 2,
621
21.8k
                                         &code_storage, &context_map_storage));
622
21.8k
  } else {
623
16.9k
    if (!global_tree || !global_code || !global_ctx_map ||
624
16.9k
        global_tree->empty()) {
625
37
      return JXL_FAILURE("No global tree available but one was requested");
626
37
    }
627
16.9k
    tree = global_tree;
628
16.9k
    code = global_code;
629
16.9k
    context_map = global_ctx_map;
630
16.9k
  }
631
632
  // Read channels
633
77.3k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
77.3k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
77.3k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
77.3k
  uint32_t fl_run = 0;
637
77.3k
  uint32_t fl_v = 0;
638
393k
  for (; next_channel < nb_channels; next_channel++) {
639
357k
    Channel &channel = image.channel[next_channel];
640
357k
    if (next_channel >= image.nb_meta_channels &&
641
353k
        (channel.w > options->max_chan_size ||
642
353k
         channel.h > options->max_chan_size)) {
643
905
      break;
644
905
    }
645
356k
    if (!channel.w || !channel.h) {
646
4.57k
      continue;  // skip empty channels
647
4.57k
    }
648
352k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
352k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
352k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
352k
    if (!br->AllReadsWithinBounds()) {
654
1.43k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
1.43k
    }
657
352k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
37.2k
  scope_guard.Disarm();
661
662
37.2k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
37.2k
  return true;
666
37.2k
}
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
45.0k
                                bool allow_truncated_group) {
674
45.0k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
45.0k
  req_sizes.reserve(image.channel.size());
676
146k
  for (const auto &c : image.channel) {
677
146k
    req_sizes.emplace_back(c.w, c.h);
678
146k
  }
679
45.0k
  GroupHeader local_header;
680
45.0k
  if (header == nullptr) header = &local_header;
681
45.0k
  size_t bit_pos = br->TotalBitsConsumed();
682
45.0k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
45.0k
                                  code, ctx_map, allow_truncated_group);
684
45.0k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
42.7k
  if (dec_status.IsFatalError()) return dec_status;
686
42.7k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
42.7k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
42.7k
  JXL_DEBUG_V(4,
689
42.7k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
42.7k
              " image from %" PRIuS " bytes",
691
42.7k
              image.w, image.h, image.channel.size(),
692
42.7k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
42.7k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
42.7k
  (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
42.7k
  if (undo_transforms) {
699
12.7k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
65.6k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
52.9k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
52.9k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
52.9k
    }
704
12.7k
  }
705
42.7k
  return dec_status;
706
42.7k
}
707
708
}  // namespace jxl