Coverage Report

Created: 2026-06-07 07:20

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
452k
                    bool *gradient_only) {
46
452k
  *num_props = 0;
47
452k
  bool has_wp = false;
48
452k
  bool has_non_wp = false;
49
452k
  *gradient_only = true;
50
1.11M
  const auto mark_property = [&](int32_t p) {
51
1.11M
    if (p == kWPProp) {
52
106k
      has_wp = true;
53
1.00M
    } else if (p >= kNumStaticProperties) {
54
610k
      has_non_wp = true;
55
610k
    }
56
1.11M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
646k
      *gradient_only = false;
58
646k
    }
59
1.11M
  };
60
452k
  FlatTree output;
61
452k
  std::queue<size_t> nodes;
62
452k
  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.39M
  while (!nodes.empty()) {
70
1.93M
    size_t cur = nodes.front();
71
1.93M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.99M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.62M
           global_tree[cur].property != -1) {
75
59.0k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
30.7k
        cur = global_tree[cur].lchild;
77
30.7k
      } else {
78
28.2k
        cur = global_tree[cur].rchild;
79
28.2k
      }
80
59.0k
    }
81
1.93M
    FlatDecisionNode flat;
82
1.93M
    if (global_tree[cur].property == -1) {
83
1.56M
      flat.property0 = -1;
84
1.56M
      flat.childID = global_tree[cur].lchild;
85
1.56M
      flat.predictor = global_tree[cur].predictor;
86
1.56M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.56M
      flat.multiplier = global_tree[cur].multiplier;
88
1.56M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.56M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.56M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.56M
      output.push_back(flat);
92
1.56M
      continue;
93
1.56M
    }
94
371k
    flat.childID = output.size() + nodes.size() + 1;
95
96
371k
    flat.property0 = global_tree[cur].property;
97
371k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
371k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.11M
    for (size_t i = 0; i < 2; i++) {
101
742k
      size_t cur_child =
102
742k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
763k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
418k
             global_tree[cur_child].property != -1) {
106
21.5k
        if (static_props[global_tree[cur_child].property] >
107
21.5k
            global_tree[cur_child].splitval) {
108
11.0k
          cur_child = global_tree[cur_child].lchild;
109
11.0k
        } else {
110
10.5k
          cur_child = global_tree[cur_child].rchild;
111
10.5k
        }
112
21.5k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
742k
      if (global_tree[cur_child].property == -1) {
116
396k
        flat.properties[i] = 0;
117
396k
        flat.splitvals[i] = 0;
118
396k
        nodes.push(cur_child);
119
396k
        nodes.push(cur_child);
120
396k
      } else {
121
345k
        flat.properties[i] = global_tree[cur_child].property;
122
345k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
345k
        nodes.push(global_tree[cur_child].lchild);
124
345k
        nodes.push(global_tree[cur_child].rchild);
125
345k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
345k
      }
127
742k
    }
128
129
742k
    for (int16_t property : flat.properties) mark_property(property);
130
371k
    mark_property(flat.property0);
131
371k
    output.push_back(flat);
132
371k
  }
133
452k
  if (*num_props > kNumNonrefProperties) {
134
2.46k
    *num_props =
135
2.46k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
2.46k
            kExtraPropsPerChannel +
137
2.46k
        kNumNonrefProperties;
138
450k
  } else {
139
450k
    *num_props = kNumNonrefProperties;
140
450k
  }
141
452k
  *use_wp = has_wp;
142
452k
  *wp_only = has_wp && !has_non_wp;
143
144
452k
  return output;
145
452k
}
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
427k
                                 uint32_t &fl_v) {
157
427k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
427k
  Channel &channel = image->channel[chan];
159
160
427k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
427k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
427k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
427k
  bool tree_has_wp_prop_or_pred = false;
168
427k
  bool is_wp_only = false;
169
427k
  bool is_gradient_only = false;
170
427k
  size_t num_props;
171
427k
  FlatTree tree =
172
427k
      FilterTree(global_tree, static_props, &num_props,
173
427k
                 &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
602k
  for (auto &node : tree) {
178
602k
    if (node.property0 == -1) {
179
558k
      node.childID = context_map[node.childID];
180
558k
    }
181
602k
  }
182
183
427k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
427k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
246M
                             pixel_type_w offset) -> pixel_type {
188
246M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
246M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
246M
    return val * multiplier + offset;
192
246M
  };
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
52.5M
                             pixel_type_w offset) -> pixel_type {
188
52.5M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
52.5M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
52.5M
    return val * multiplier + offset;
192
52.5M
  };
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
193M
                             pixel_type_w offset) -> pixel_type {
188
193M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
193M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
193M
    return val * multiplier + offset;
192
193M
  };
193
194
427k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
414k
    Predictor predictor = tree[0].predictor;
198
414k
    int64_t offset = tree[0].predictor_offset;
199
414k
    int32_t multiplier = tree[0].multiplier;
200
414k
    size_t ctx_id = tree[0].childID;
201
414k
    if (predictor == Predictor::Zero) {
202
389k
      uint32_t value;
203
389k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
389k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
172k
        JXL_DEBUG_V(8, "Fastest track.");
208
172k
        pixel_type v = make_pixel(value, multiplier, offset);
209
5.28M
        for (size_t y = 0; y < channel.h; y++) {
210
5.10M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
5.10M
          std::fill(r, r + channel.w, v);
212
5.10M
        }
213
216k
      } else {
214
216k
        JXL_DEBUG_V(8, "Fast track.");
215
216k
        if (multiplier == 1 && offset == 0) {
216
3.20M
          for (size_t y = 0; y < channel.h; y++) {
217
3.02M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
234M
            for (size_t x = 0; x < channel.w; x++) {
219
231M
              uint32_t v =
220
231M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
231M
              r[x] = UnpackSigned(v);
222
231M
            }
223
3.02M
          }
224
180k
        } else {
225
1.51M
          for (size_t y = 0; y < channel.h; y++) {
226
1.48M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
161M
            for (size_t x = 0; x < channel.w; x++) {
228
159M
              uint32_t v =
229
159M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
159M
                                                                         br);
231
159M
              r[x] = make_pixel(v, multiplier, offset);
232
159M
            }
233
1.48M
          }
234
36.2k
        }
235
216k
      }
236
389k
      return true;
237
389k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.95k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
451
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
451
      pixel_type_w sv = UnpackSigned(fl_v);
241
17.4k
      for (size_t y = 0; y < channel.h; y++) {
242
17.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
17.0k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
17.0k
        const pixel_type *JXL_RESTRICT rtopleft =
245
17.0k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
17.0k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
17.0k
        if (fl_run == 0) {
248
5.19k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.19k
                                                     &fl_run);
250
5.19k
          sv = UnpackSigned(fl_v);
251
11.8k
        } else {
252
11.8k
          fl_run--;
253
11.8k
        }
254
17.0k
        r[0] = sv + guess_0;
255
457k
        for (size_t x = 1; x < channel.w; x++) {
256
440k
          pixel_type left = r[x - 1];
257
440k
          pixel_type top = rtop[x];
258
440k
          pixel_type topleft = rtopleft[x];
259
440k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
440k
          if (!fl_run) {
261
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
119k
                                                       &fl_run);
263
119k
            sv = UnpackSigned(fl_v);
264
321k
          } else {
265
321k
            fl_run--;
266
321k
          }
267
440k
          r[x] = sv + guess;
268
440k
        }
269
17.0k
      }
270
451
      return true;
271
24.9k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
3.20k
               multiplier == 1) {
273
2.89k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
2.89k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
69.8k
      for (size_t y = 0; y < channel.h; y++) {
276
66.9k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
3.75M
        for (size_t x = 0; x < channel.w; x++) {
278
3.68M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
3.68M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
3.68M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
3.68M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
3.68M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
3.68M
              ctx_id, br);
284
3.68M
          r[x] = make_pixel(v, 1, guess);
285
3.68M
        }
286
66.9k
      }
287
2.89k
      return true;
288
2.89k
    }
289
414k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
34.8k
  if (is_wp_only) {
294
4.37k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.37k
  }
296
34.8k
  if (is_gradient_only) {
297
1.63k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.63k
  }
299
300
34.8k
  if (is_gradient_only) {
301
759
    JXL_DEBUG_V(8, "Gradient fast track.");
302
759
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
16.3k
    for (size_t y = 0; y < channel.h; y++) {
304
15.6k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
639k
      for (size_t x = 0; x < channel.w; x++) {
306
624k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
624k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
624k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
624k
        int32_t guess = ClampedGradient(top, left, topleft);
310
624k
        uint32_t pos =
311
624k
            kPropRangeFast +
312
624k
            std::min<pixel_type_w>(
313
624k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
624k
                kPropRangeFast - 1);
315
624k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
624k
        uint64_t v =
317
624k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
624k
        r[x] = make_pixel(v, 1, guess);
319
624k
      }
320
15.6k
    }
321
34.0k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
935
    JXL_DEBUG_V(8, "WP fast track.");
323
935
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
935
    Properties properties(1);
325
23.8k
    for (size_t y = 0; y < channel.h; y++) {
326
22.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
22.8k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
22.8k
      const pixel_type *JXL_RESTRICT rtoptop =
329
22.8k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
22.8k
      const pixel_type *JXL_RESTRICT rtopleft =
331
22.8k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
22.8k
      const pixel_type *JXL_RESTRICT rtopright =
333
22.8k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
22.8k
      size_t x = 0;
335
22.8k
      {
336
22.8k
        size_t offset = 0;
337
22.8k
        pixel_type_w left = y ? rtop[x] : 0;
338
22.8k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
22.8k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
22.8k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
22.8k
            offset);
343
22.8k
        uint32_t pos =
344
22.8k
            kPropRangeFast +
345
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
22.8k
        uint64_t v =
348
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
22.8k
        r[x] = make_pixel(v, 1, guess);
350
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
22.8k
      }
352
2.12M
      for (x = 1; x + 1 < channel.w; x++) {
353
2.10M
        size_t offset = 0;
354
2.10M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
2.10M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
2.10M
            rtoptop[x], &properties, offset);
357
2.10M
        uint32_t pos =
358
2.10M
            kPropRangeFast +
359
2.10M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
2.10M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
2.10M
        uint64_t v =
362
2.10M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
2.10M
        r[x] = make_pixel(v, 1, guess);
364
2.10M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
2.10M
      }
366
22.8k
      {
367
22.8k
        size_t offset = 0;
368
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
22.8k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
22.8k
            rtoptop[x], &properties, offset);
371
22.8k
        uint32_t pos =
372
22.8k
            kPropRangeFast +
373
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
22.8k
        uint64_t v =
376
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
22.8k
        r[x] = make_pixel(v, 1, guess);
378
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
22.8k
      }
380
22.8k
    }
381
33.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
23.0k
    JXL_DEBUG_V(8, "Slow track.");
385
23.0k
    MATreeLookup tree_lookup(tree);
386
23.0k
    Properties properties = Properties(num_props);
387
23.0k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
23.0k
    JXL_ASSIGN_OR_RETURN(
389
23.0k
        Channel references,
390
23.0k
        Channel::Create(memory_manager,
391
23.0k
                        properties.size() - kNumNonrefProperties, channel.w));
392
682k
    for (size_t y = 0; y < channel.h; y++) {
393
659k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
659k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
659k
      InitPropsRow(&properties, static_props, y);
396
659k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.63M
        for (size_t x = 0; x < 2; x++) {
398
1.09M
          PredictionResult res =
399
1.09M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
1.09M
                              tree_lookup, references);
401
1.09M
          uint64_t v =
402
1.09M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
1.09M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
1.09M
        }
405
57.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
56.7M
          PredictionResult res =
407
56.7M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
56.7M
                                 tree_lookup, references);
409
56.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
56.7M
              res.context, br);
411
56.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
56.7M
        }
413
1.63M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
1.09M
          PredictionResult res =
415
1.09M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
1.09M
                              tree_lookup, references);
417
1.09M
          uint64_t v =
418
1.09M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
1.09M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
1.09M
        }
421
546k
      } else {
422
2.49M
        for (size_t x = 0; x < channel.w; x++) {
423
2.37M
          PredictionResult res =
424
2.37M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
2.37M
                              tree_lookup, references);
426
2.37M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
2.37M
              res.context, br);
428
2.37M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
2.37M
        }
430
113k
      }
431
659k
    }
432
23.0k
  } else {
433
10.0k
    JXL_DEBUG_V(8, "Slowest track.");
434
10.0k
    MATreeLookup tree_lookup(tree);
435
10.0k
    Properties properties = Properties(num_props);
436
10.0k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
10.0k
    JXL_ASSIGN_OR_RETURN(
438
10.0k
        Channel references,
439
10.0k
        Channel::Create(memory_manager,
440
10.0k
                        properties.size() - kNumNonrefProperties, channel.w));
441
10.0k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
268k
    for (size_t y = 0; y < channel.h; y++) {
443
258k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
258k
      InitPropsRow(&properties, static_props, y);
445
258k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
258k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
620k
        for (size_t x = 0; x < 2; x++) {
448
413k
          PredictionResult res =
449
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
413k
                            tree_lookup, references, &wp_state);
451
413k
          uint64_t v =
452
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
413k
        }
456
16.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
15.8M
          PredictionResult res =
458
15.8M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
15.8M
                               tree_lookup, references, &wp_state);
460
15.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
15.8M
              res.context, br);
462
15.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
15.8M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
15.8M
        }
465
620k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
413k
          PredictionResult res =
467
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
413k
                            tree_lookup, references, &wp_state);
469
413k
          uint64_t v =
470
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
413k
        }
474
206k
      } else {
475
2.09M
        for (size_t x = 0; x < channel.w; x++) {
476
2.04M
          PredictionResult res =
477
2.04M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
2.04M
                            tree_lookup, references, &wp_state);
479
2.04M
          uint64_t v =
480
2.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
2.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
2.04M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
2.04M
        }
484
51.2k
      }
485
258k
    }
486
10.0k
  }
487
34.8k
  return true;
488
34.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
43.4k
                                 uint32_t &fl_v) {
157
43.4k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
43.4k
  Channel &channel = image->channel[chan];
159
160
43.4k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
43.4k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
43.4k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
43.4k
  bool tree_has_wp_prop_or_pred = false;
168
43.4k
  bool is_wp_only = false;
169
43.4k
  bool is_gradient_only = false;
170
43.4k
  size_t num_props;
171
43.4k
  FlatTree tree =
172
43.4k
      FilterTree(global_tree, static_props, &num_props,
173
43.4k
                 &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
57.4k
  for (auto &node : tree) {
178
57.4k
    if (node.property0 == -1) {
179
53.9k
      node.childID = context_map[node.childID];
180
53.9k
    }
181
57.4k
  }
182
183
43.4k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
43.4k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
43.4k
                             pixel_type_w offset) -> pixel_type {
188
43.4k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
43.4k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
43.4k
    return val * multiplier + offset;
192
43.4k
  };
193
194
43.4k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
40.6k
    Predictor predictor = tree[0].predictor;
198
40.6k
    int64_t offset = tree[0].predictor_offset;
199
40.6k
    int32_t multiplier = tree[0].multiplier;
200
40.6k
    size_t ctx_id = tree[0].childID;
201
40.6k
    if (predictor == Predictor::Zero) {
202
32.5k
      uint32_t value;
203
32.5k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
32.5k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
10.9k
        JXL_DEBUG_V(8, "Fastest track.");
208
10.9k
        pixel_type v = make_pixel(value, multiplier, offset);
209
362k
        for (size_t y = 0; y < channel.h; y++) {
210
351k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
351k
          std::fill(r, r + channel.w, v);
212
351k
        }
213
21.5k
      } else {
214
21.5k
        JXL_DEBUG_V(8, "Fast track.");
215
21.5k
        if (multiplier == 1 && offset == 0) {
216
429k
          for (size_t y = 0; y < channel.h; y++) {
217
422k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
67.9M
            for (size_t x = 0; x < channel.w; x++) {
219
67.5M
              uint32_t v =
220
67.5M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
67.5M
              r[x] = UnpackSigned(v);
222
67.5M
            }
223
422k
          }
224
14.6k
        } else {
225
459k
          for (size_t y = 0; y < channel.h; y++) {
226
445k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
29.8M
            for (size_t x = 0; x < channel.w; x++) {
228
29.3M
              uint32_t v =
229
29.3M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
29.3M
                                                                         br);
231
29.3M
              r[x] = make_pixel(v, multiplier, offset);
232
29.3M
            }
233
445k
          }
234
14.6k
        }
235
21.5k
      }
236
32.5k
      return true;
237
32.5k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.95k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
451
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
451
      pixel_type_w sv = UnpackSigned(fl_v);
241
17.4k
      for (size_t y = 0; y < channel.h; y++) {
242
17.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
17.0k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
17.0k
        const pixel_type *JXL_RESTRICT rtopleft =
245
17.0k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
17.0k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
17.0k
        if (fl_run == 0) {
248
5.19k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.19k
                                                     &fl_run);
250
5.19k
          sv = UnpackSigned(fl_v);
251
11.8k
        } else {
252
11.8k
          fl_run--;
253
11.8k
        }
254
17.0k
        r[0] = sv + guess_0;
255
457k
        for (size_t x = 1; x < channel.w; x++) {
256
440k
          pixel_type left = r[x - 1];
257
440k
          pixel_type top = rtop[x];
258
440k
          pixel_type topleft = rtopleft[x];
259
440k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
440k
          if (!fl_run) {
261
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
119k
                                                       &fl_run);
263
119k
            sv = UnpackSigned(fl_v);
264
321k
          } else {
265
321k
            fl_run--;
266
321k
          }
267
440k
          r[x] = sv + guess;
268
440k
        }
269
17.0k
      }
270
451
      return true;
271
7.64k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.50k
               multiplier == 1) {
273
1.33k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.33k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
28.0k
      for (size_t y = 0; y < channel.h; y++) {
276
26.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
1.30M
        for (size_t x = 0; x < channel.w; x++) {
278
1.28M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
1.28M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
1.28M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
1.28M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
1.28M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
1.28M
              ctx_id, br);
284
1.28M
          r[x] = make_pixel(v, 1, guess);
285
1.28M
        }
286
26.7k
      }
287
1.33k
      return true;
288
1.33k
    }
289
40.6k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
9.05k
  if (is_wp_only) {
294
357
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
357
  }
296
9.05k
  if (is_gradient_only) {
297
557
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
557
  }
299
300
9.05k
  if (is_gradient_only) {
301
140
    JXL_DEBUG_V(8, "Gradient fast track.");
302
140
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
2.49k
    for (size_t y = 0; y < channel.h; y++) {
304
2.35k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
167k
      for (size_t x = 0; x < channel.w; x++) {
306
165k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
165k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
165k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
165k
        int32_t guess = ClampedGradient(top, left, topleft);
310
165k
        uint32_t pos =
311
165k
            kPropRangeFast +
312
165k
            std::min<pixel_type_w>(
313
165k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
165k
                kPropRangeFast - 1);
315
165k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
165k
        uint64_t v =
317
165k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
165k
        r[x] = make_pixel(v, 1, guess);
319
165k
      }
320
2.35k
    }
321
8.91k
  } 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
8.91k
  } 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
7.92k
    JXL_DEBUG_V(8, "Slow track.");
385
7.92k
    MATreeLookup tree_lookup(tree);
386
7.92k
    Properties properties = Properties(num_props);
387
7.92k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
7.92k
    JXL_ASSIGN_OR_RETURN(
389
7.92k
        Channel references,
390
7.92k
        Channel::Create(memory_manager,
391
7.92k
                        properties.size() - kNumNonrefProperties, channel.w));
392
194k
    for (size_t y = 0; y < channel.h; y++) {
393
186k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
186k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
186k
      InitPropsRow(&properties, static_props, y);
396
186k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
472k
        for (size_t x = 0; x < 2; x++) {
398
314k
          PredictionResult res =
399
314k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
314k
                              tree_lookup, references);
401
314k
          uint64_t v =
402
314k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
314k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
314k
        }
405
20.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
20.1M
          PredictionResult res =
407
20.1M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
20.1M
                                 tree_lookup, references);
409
20.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
20.1M
              res.context, br);
411
20.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
20.1M
        }
413
472k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
314k
          PredictionResult res =
415
314k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
314k
                              tree_lookup, references);
417
314k
          uint64_t v =
418
314k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
314k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
314k
        }
421
157k
      } else {
422
515k
        for (size_t x = 0; x < channel.w; x++) {
423
486k
          PredictionResult res =
424
486k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
486k
                              tree_lookup, references);
426
486k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
486k
              res.context, br);
428
486k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
486k
        }
430
28.9k
      }
431
186k
    }
432
7.92k
  } else {
433
984
    JXL_DEBUG_V(8, "Slowest track.");
434
984
    MATreeLookup tree_lookup(tree);
435
984
    Properties properties = Properties(num_props);
436
984
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
984
    JXL_ASSIGN_OR_RETURN(
438
984
        Channel references,
439
984
        Channel::Create(memory_manager,
440
984
                        properties.size() - kNumNonrefProperties, channel.w));
441
984
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
13.3k
    for (size_t y = 0; y < channel.h; y++) {
443
12.3k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
12.3k
      InitPropsRow(&properties, static_props, y);
445
12.3k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
12.3k
      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
12.3k
      } else {
475
501k
        for (size_t x = 0; x < channel.w; x++) {
476
488k
          PredictionResult res =
477
488k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
488k
                            tree_lookup, references, &wp_state);
479
488k
          uint64_t v =
480
488k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
488k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
488k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
488k
        }
484
12.3k
      }
485
12.3k
    }
486
984
  }
487
9.05k
  return true;
488
9.05k
}
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
384k
                                 uint32_t &fl_v) {
157
384k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
384k
  Channel &channel = image->channel[chan];
159
160
384k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
384k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
384k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
384k
  bool tree_has_wp_prop_or_pred = false;
168
384k
  bool is_wp_only = false;
169
384k
  bool is_gradient_only = false;
170
384k
  size_t num_props;
171
384k
  FlatTree tree =
172
384k
      FilterTree(global_tree, static_props, &num_props,
173
384k
                 &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
544k
  for (auto &node : tree) {
178
544k
    if (node.property0 == -1) {
179
504k
      node.childID = context_map[node.childID];
180
504k
    }
181
544k
  }
182
183
384k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
384k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
384k
                             pixel_type_w offset) -> pixel_type {
188
384k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
384k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
384k
    return val * multiplier + offset;
192
384k
  };
193
194
384k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
374k
    Predictor predictor = tree[0].predictor;
198
374k
    int64_t offset = tree[0].predictor_offset;
199
374k
    int32_t multiplier = tree[0].multiplier;
200
374k
    size_t ctx_id = tree[0].childID;
201
374k
    if (predictor == Predictor::Zero) {
202
356k
      uint32_t value;
203
356k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
356k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
161k
        JXL_DEBUG_V(8, "Fastest track.");
208
161k
        pixel_type v = make_pixel(value, multiplier, offset);
209
4.91M
        for (size_t y = 0; y < channel.h; y++) {
210
4.75M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
4.75M
          std::fill(r, r + channel.w, v);
212
4.75M
        }
213
195k
      } else {
214
195k
        JXL_DEBUG_V(8, "Fast track.");
215
195k
        if (multiplier == 1 && offset == 0) {
216
2.77M
          for (size_t y = 0; y < channel.h; y++) {
217
2.59M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
166M
            for (size_t x = 0; x < channel.w; x++) {
219
164M
              uint32_t v =
220
164M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
164M
              r[x] = UnpackSigned(v);
222
164M
            }
223
2.59M
          }
224
173k
        } else {
225
1.05M
          for (size_t y = 0; y < channel.h; y++) {
226
1.03M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
131M
            for (size_t x = 0; x < channel.w; x++) {
228
130M
              uint32_t v =
229
130M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
130M
                                                                         br);
231
130M
              r[x] = make_pixel(v, multiplier, offset);
232
130M
            }
233
1.03M
          }
234
21.6k
        }
235
195k
      }
236
356k
      return true;
237
356k
    } 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
17.3k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.70k
               multiplier == 1) {
273
1.55k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.55k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
41.7k
      for (size_t y = 0; y < channel.h; y++) {
276
40.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
40.2k
      }
287
1.55k
      return true;
288
1.55k
    }
289
374k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
25.7k
  if (is_wp_only) {
294
4.01k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.01k
  }
296
25.7k
  if (is_gradient_only) {
297
1.07k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.07k
  }
299
300
25.7k
  if (is_gradient_only) {
301
619
    JXL_DEBUG_V(8, "Gradient fast track.");
302
619
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
13.8k
    for (size_t y = 0; y < channel.h; y++) {
304
13.2k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
471k
      for (size_t x = 0; x < channel.w; x++) {
306
458k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
458k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
458k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
458k
        int32_t guess = ClampedGradient(top, left, topleft);
310
458k
        uint32_t pos =
311
458k
            kPropRangeFast +
312
458k
            std::min<pixel_type_w>(
313
458k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
458k
                kPropRangeFast - 1);
315
458k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
458k
        uint64_t v =
317
458k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
458k
        r[x] = make_pixel(v, 1, guess);
319
458k
      }
320
13.2k
    }
321
25.1k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
935
    JXL_DEBUG_V(8, "WP fast track.");
323
935
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
935
    Properties properties(1);
325
23.8k
    for (size_t y = 0; y < channel.h; y++) {
326
22.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
22.8k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
22.8k
      const pixel_type *JXL_RESTRICT rtoptop =
329
22.8k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
22.8k
      const pixel_type *JXL_RESTRICT rtopleft =
331
22.8k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
22.8k
      const pixel_type *JXL_RESTRICT rtopright =
333
22.8k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
22.8k
      size_t x = 0;
335
22.8k
      {
336
22.8k
        size_t offset = 0;
337
22.8k
        pixel_type_w left = y ? rtop[x] : 0;
338
22.8k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
22.8k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
22.8k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
22.8k
            offset);
343
22.8k
        uint32_t pos =
344
22.8k
            kPropRangeFast +
345
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
22.8k
        uint64_t v =
348
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
22.8k
        r[x] = make_pixel(v, 1, guess);
350
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
22.8k
      }
352
2.12M
      for (x = 1; x + 1 < channel.w; x++) {
353
2.10M
        size_t offset = 0;
354
2.10M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
2.10M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
2.10M
            rtoptop[x], &properties, offset);
357
2.10M
        uint32_t pos =
358
2.10M
            kPropRangeFast +
359
2.10M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
2.10M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
2.10M
        uint64_t v =
362
2.10M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
2.10M
        r[x] = make_pixel(v, 1, guess);
364
2.10M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
2.10M
      }
366
22.8k
      {
367
22.8k
        size_t offset = 0;
368
22.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
22.8k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
22.8k
            rtoptop[x], &properties, offset);
371
22.8k
        uint32_t pos =
372
22.8k
            kPropRangeFast +
373
22.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
22.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
22.8k
        uint64_t v =
376
22.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
22.8k
        r[x] = make_pixel(v, 1, guess);
378
22.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
22.8k
      }
380
22.8k
    }
381
24.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
15.0k
    JXL_DEBUG_V(8, "Slow track.");
385
15.0k
    MATreeLookup tree_lookup(tree);
386
15.0k
    Properties properties = Properties(num_props);
387
15.0k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
15.0k
    JXL_ASSIGN_OR_RETURN(
389
15.0k
        Channel references,
390
15.0k
        Channel::Create(memory_manager,
391
15.0k
                        properties.size() - kNumNonrefProperties, channel.w));
392
488k
    for (size_t y = 0; y < channel.h; y++) {
393
473k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
473k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
473k
      InitPropsRow(&properties, static_props, y);
396
473k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.16M
        for (size_t x = 0; x < 2; x++) {
398
777k
          PredictionResult res =
399
777k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
777k
                              tree_lookup, references);
401
777k
          uint64_t v =
402
777k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
777k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
777k
        }
405
37.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
36.6M
          PredictionResult res =
407
36.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
36.6M
                                 tree_lookup, references);
409
36.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
36.6M
              res.context, br);
411
36.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
36.6M
        }
413
1.16M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
777k
          PredictionResult res =
415
777k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
777k
                              tree_lookup, references);
417
777k
          uint64_t v =
418
777k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
777k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
777k
        }
421
388k
      } else {
422
1.97M
        for (size_t x = 0; x < channel.w; x++) {
423
1.89M
          PredictionResult res =
424
1.89M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.89M
                              tree_lookup, references);
426
1.89M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.89M
              res.context, br);
428
1.89M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.89M
        }
430
84.3k
      }
431
473k
    }
432
15.0k
  } else {
433
9.09k
    JXL_DEBUG_V(8, "Slowest track.");
434
9.09k
    MATreeLookup tree_lookup(tree);
435
9.09k
    Properties properties = Properties(num_props);
436
9.09k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
9.09k
    JXL_ASSIGN_OR_RETURN(
438
9.09k
        Channel references,
439
9.09k
        Channel::Create(memory_manager,
440
9.09k
                        properties.size() - kNumNonrefProperties, channel.w));
441
9.09k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
254k
    for (size_t y = 0; y < channel.h; y++) {
443
245k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
245k
      InitPropsRow(&properties, static_props, y);
445
245k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
245k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
620k
        for (size_t x = 0; x < 2; x++) {
448
413k
          PredictionResult res =
449
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
413k
                            tree_lookup, references, &wp_state);
451
413k
          uint64_t v =
452
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
413k
        }
456
16.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
15.8M
          PredictionResult res =
458
15.8M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
15.8M
                               tree_lookup, references, &wp_state);
460
15.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
15.8M
              res.context, br);
462
15.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
15.8M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
15.8M
        }
465
620k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
413k
          PredictionResult res =
467
413k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
413k
                            tree_lookup, references, &wp_state);
469
413k
          uint64_t v =
470
413k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
413k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
413k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
413k
        }
474
206k
      } else {
475
1.59M
        for (size_t x = 0; x < channel.w; x++) {
476
1.55M
          PredictionResult res =
477
1.55M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.55M
                            tree_lookup, references, &wp_state);
479
1.55M
          uint64_t v =
480
1.55M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.55M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.55M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.55M
        }
484
38.9k
      }
485
245k
    }
486
9.09k
  }
487
25.7k
  return true;
488
25.7k
}
489
}  // namespace detail
490
491
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
492
                                 const std::vector<uint8_t> &context_map,
493
                                 const Tree &global_tree,
494
                                 const weighted::Header &wp_header,
495
                                 pixel_type chan, size_t group_id,
496
                                 TreeLut<uint8_t, false, false> &tree_lut,
497
                                 Image *image, uint32_t &fl_run,
498
427k
                                 uint32_t &fl_v) {
499
427k
  if (reader->UsesLZ77()) {
500
43.4k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
43.4k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
43.4k
        tree_lut, image, fl_run, fl_v);
503
384k
  } else {
504
384k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
384k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
384k
        tree_lut, image, fl_run, fl_v);
507
384k
  }
508
427k
}
509
510
194k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
49.5k
                                 const ModularOptions &options) {
514
49.5k
  size_t nb_channels = image.channel.size();
515
99.1k
  for (bool is_dc : {true, false}) {
516
99.1k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
99.1k
    size_t c = image.nb_meta_channels;
518
988k
    for (; c < nb_channels; c++) {
519
892k
      const Channel &ch = image.channel[c];
520
892k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
892k
    }
522
124k
    for (; c < nb_channels; c++) {
523
25.0k
      const Channel &ch = image.channel[c];
524
25.0k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
24.3k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
24.3k
      if (is_dc_channel != is_dc) continue;
527
12.1k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
12.1k
      if (tile_dim == 0) {
529
3
        return JXL_FAILURE("Inconsistent transforms");
530
3
      }
531
12.1k
    }
532
99.1k
  }
533
49.5k
  return true;
534
49.5k
}
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
56.4k
                     const bool allow_truncated_group) {
541
56.4k
  if (image.channel.empty()) return true;
542
49.1k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
49.1k
  Status status = Bundle::Read(br, &header);
546
49.1k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
48.0k
  if (status.IsFatalError()) return status;
548
48.0k
  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
48.0k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
48.0k
              header.transforms.size());
560
48.0k
  image.transform = header.transforms;
561
48.0k
  for (Transform &transform : image.transform) {
562
29.9k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
29.9k
  }
564
47.8k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
47.8k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
47.8k
  size_t nb_channels = image.channel.size();
570
571
47.8k
  size_t num_chans = 0;
572
47.8k
  size_t distance_multiplier = 0;
573
493k
  for (size_t i = 0; i < nb_channels; i++) {
574
447k
    Channel &channel = image.channel[i];
575
447k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
441k
                                        channel.h > options->max_chan_size)) {
577
1.36k
      break;
578
1.36k
    }
579
445k
    if (!channel.w || !channel.h) {
580
5.61k
      continue;  // skip empty channels
581
5.61k
    }
582
440k
    if (channel.w > distance_multiplier) {
583
77.4k
      distance_multiplier = channel.w;
584
77.4k
    }
585
440k
    num_chans++;
586
440k
  }
587
47.8k
  if (num_chans == 0) return true;
588
589
47.4k
  size_t next_channel = 0;
590
47.4k
  auto scope_guard = MakeScopeGuard([&]() {
591
18.8k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
15.9k
      ZeroFillImage(&image.channel[c].plane);
593
15.9k
    }
594
2.95k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
47.4k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
47.4k
  Tree tree_storage;
600
47.4k
  std::vector<uint8_t> context_map_storage;
601
47.4k
  ANSCode code_storage;
602
47.4k
  const Tree *tree = &tree_storage;
603
47.4k
  const ANSCode *code = &code_storage;
604
47.4k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
47.4k
  if (!header.use_global_tree) {
606
28.2k
    uint64_t max_tree_size = 1024;
607
348k
    for (size_t i = 0; i < nb_channels; i++) {
608
320k
      Channel &channel = image.channel[i];
609
320k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
318k
                                          channel.h > options->max_chan_size)) {
611
48
        break;
612
48
      }
613
320k
      uint64_t pixels = channel.w * channel.h;
614
320k
      max_tree_size += pixels;
615
320k
    }
616
28.2k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
28.2k
    JXL_RETURN_IF_ERROR(
618
28.2k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
27.8k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
27.8k
                                         (tree_storage.size() + 1) / 2,
621
27.8k
                                         &code_storage, &context_map_storage));
622
27.8k
  } else {
623
19.1k
    if (!global_tree || !global_code || !global_ctx_map ||
624
19.1k
        global_tree->empty()) {
625
72
      return JXL_FAILURE("No global tree available but one was requested");
626
72
    }
627
19.0k
    tree = global_tree;
628
19.0k
    code = global_code;
629
19.0k
    context_map = global_ctx_map;
630
19.0k
  }
631
632
  // Read channels
633
93.8k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
93.8k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
93.8k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
93.8k
  uint32_t fl_run = 0;
637
93.8k
  uint32_t fl_v = 0;
638
477k
  for (; next_channel < nb_channels; next_channel++) {
639
433k
    Channel &channel = image.channel[next_channel];
640
433k
    if (next_channel >= image.nb_meta_channels &&
641
428k
        (channel.w > options->max_chan_size ||
642
428k
         channel.h > options->max_chan_size)) {
643
893
      break;
644
893
    }
645
432k
    if (!channel.w || !channel.h) {
646
5.25k
      continue;  // skip empty channels
647
5.25k
    }
648
427k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
427k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
427k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
427k
    if (!br->AllReadsWithinBounds()) {
654
2.46k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
2.46k
    }
657
427k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
44.4k
  scope_guard.Disarm();
661
662
44.4k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
44.4k
  return true;
666
44.4k
}
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
56.4k
                                bool allow_truncated_group) {
674
56.4k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
56.4k
  req_sizes.reserve(image.channel.size());
676
178k
  for (const auto &c : image.channel) {
677
178k
    req_sizes.emplace_back(c.w, c.h);
678
178k
  }
679
56.4k
  GroupHeader local_header;
680
56.4k
  if (header == nullptr) header = &local_header;
681
56.4k
  size_t bit_pos = br->TotalBitsConsumed();
682
56.4k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
56.4k
                                  code, ctx_map, allow_truncated_group);
684
56.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
52.2k
  if (dec_status.IsFatalError()) return dec_status;
686
52.2k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
52.2k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
52.2k
  JXL_DEBUG_V(4,
689
52.2k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
52.2k
              " image from %" PRIuS " bytes",
691
52.2k
              image.w, image.h, image.channel.size(),
692
52.2k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
52.2k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
52.2k
  (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
52.2k
  if (undo_transforms) {
699
14.5k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
72.5k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
57.9k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
57.9k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
57.9k
    }
704
14.5k
  }
705
52.2k
  return dec_status;
706
52.2k
}
707
708
}  // namespace jxl