Coverage Report

Created: 2026-05-16 07:22

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
417k
                    bool *gradient_only) {
46
417k
  *num_props = 0;
47
417k
  bool has_wp = false;
48
417k
  bool has_non_wp = false;
49
417k
  *gradient_only = true;
50
1.06M
  const auto mark_property = [&](int32_t p) {
51
1.06M
    if (p == kWPProp) {
52
99.8k
      has_wp = true;
53
967k
    } else if (p >= kNumStaticProperties) {
54
587k
      has_non_wp = true;
55
587k
    }
56
1.06M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
619k
      *gradient_only = false;
58
619k
    }
59
1.06M
  };
60
417k
  FlatTree output;
61
417k
  std::queue<size_t> nodes;
62
417k
  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.25M
  while (!nodes.empty()) {
70
1.84M
    size_t cur = nodes.front();
71
1.84M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.89M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.54M
           global_tree[cur].property != -1) {
75
57.3k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
29.8k
        cur = global_tree[cur].lchild;
77
29.8k
      } else {
78
27.5k
        cur = global_tree[cur].rchild;
79
27.5k
      }
80
57.3k
    }
81
1.84M
    FlatDecisionNode flat;
82
1.84M
    if (global_tree[cur].property == -1) {
83
1.48M
      flat.property0 = -1;
84
1.48M
      flat.childID = global_tree[cur].lchild;
85
1.48M
      flat.predictor = global_tree[cur].predictor;
86
1.48M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.48M
      flat.multiplier = global_tree[cur].multiplier;
88
1.48M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.48M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.48M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.48M
      output.push_back(flat);
92
1.48M
      continue;
93
1.48M
    }
94
355k
    flat.childID = output.size() + nodes.size() + 1;
95
96
355k
    flat.property0 = global_tree[cur].property;
97
355k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
355k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.06M
    for (size_t i = 0; i < 2; i++) {
101
711k
      size_t cur_child =
102
711k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
732k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
401k
             global_tree[cur_child].property != -1) {
106
20.9k
        if (static_props[global_tree[cur_child].property] >
107
20.9k
            global_tree[cur_child].splitval) {
108
10.5k
          cur_child = global_tree[cur_child].lchild;
109
10.5k
        } else {
110
10.3k
          cur_child = global_tree[cur_child].rchild;
111
10.3k
        }
112
20.9k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
711k
      if (global_tree[cur_child].property == -1) {
116
380k
        flat.properties[i] = 0;
117
380k
        flat.splitvals[i] = 0;
118
380k
        nodes.push(cur_child);
119
380k
        nodes.push(cur_child);
120
380k
      } else {
121
331k
        flat.properties[i] = global_tree[cur_child].property;
122
331k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
331k
        nodes.push(global_tree[cur_child].lchild);
124
331k
        nodes.push(global_tree[cur_child].rchild);
125
331k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
331k
      }
127
711k
    }
128
129
711k
    for (int16_t property : flat.properties) mark_property(property);
130
355k
    mark_property(flat.property0);
131
355k
    output.push_back(flat);
132
355k
  }
133
417k
  if (*num_props > kNumNonrefProperties) {
134
2.63k
    *num_props =
135
2.63k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
2.63k
            kExtraPropsPerChannel +
137
2.63k
        kNumNonrefProperties;
138
414k
  } else {
139
414k
    *num_props = kNumNonrefProperties;
140
414k
  }
141
417k
  *use_wp = has_wp;
142
417k
  *wp_only = has_wp && !has_non_wp;
143
144
417k
  return output;
145
417k
}
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
393k
                                 uint32_t &fl_v) {
157
393k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
393k
  Channel &channel = image->channel[chan];
159
160
393k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
393k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
393k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
393k
  bool tree_has_wp_prop_or_pred = false;
168
393k
  bool is_wp_only = false;
169
393k
  bool is_gradient_only = false;
170
393k
  size_t num_props;
171
393k
  FlatTree tree =
172
393k
      FilterTree(global_tree, static_props, &num_props,
173
393k
                 &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
561k
  for (auto &node : tree) {
178
561k
    if (node.property0 == -1) {
179
519k
      node.childID = context_map[node.childID];
180
519k
    }
181
561k
  }
182
183
393k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
393k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
234M
                             pixel_type_w offset) -> pixel_type {
188
234M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
234M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
234M
    return val * multiplier + offset;
192
234M
  };
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
48.7M
                             pixel_type_w offset) -> pixel_type {
188
48.7M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
48.7M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
48.7M
    return val * multiplier + offset;
192
48.7M
  };
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
393k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
380k
    Predictor predictor = tree[0].predictor;
198
380k
    int64_t offset = tree[0].predictor_offset;
199
380k
    int32_t multiplier = tree[0].multiplier;
200
380k
    size_t ctx_id = tree[0].childID;
201
380k
    if (predictor == Predictor::Zero) {
202
355k
      uint32_t value;
203
355k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
355k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
157k
        JXL_DEBUG_V(8, "Fastest track.");
208
157k
        pixel_type v = make_pixel(value, multiplier, offset);
209
4.83M
        for (size_t y = 0; y < channel.h; y++) {
210
4.67M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
4.67M
          std::fill(r, r + channel.w, v);
212
4.67M
        }
213
198k
      } else {
214
198k
        JXL_DEBUG_V(8, "Fast track.");
215
198k
        if (multiplier == 1 && offset == 0) {
216
2.94M
          for (size_t y = 0; y < channel.h; y++) {
217
2.77M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
215M
            for (size_t x = 0; x < channel.w; x++) {
219
213M
              uint32_t v =
220
213M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
213M
              r[x] = UnpackSigned(v);
222
213M
            }
223
2.77M
          }
224
164k
        } else {
225
1.42M
          for (size_t y = 0; y < channel.h; y++) {
226
1.38M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
152M
            for (size_t x = 0; x < channel.w; x++) {
228
151M
              uint32_t v =
229
151M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
151M
                                                                         br);
231
151M
              r[x] = make_pixel(v, multiplier, offset);
232
151M
            }
233
1.38M
          }
234
34.1k
        }
235
198k
      }
236
355k
      return true;
237
355k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.91k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
385
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
385
      pixel_type_w sv = UnpackSigned(fl_v);
241
14.3k
      for (size_t y = 0; y < channel.h; y++) {
242
13.9k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
13.9k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
13.9k
        const pixel_type *JXL_RESTRICT rtopleft =
245
13.9k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
13.9k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
13.9k
        if (fl_run == 0) {
248
3.88k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
3.88k
                                                     &fl_run);
250
3.88k
          sv = UnpackSigned(fl_v);
251
10.0k
        } else {
252
10.0k
          fl_run--;
253
10.0k
        }
254
13.9k
        r[0] = sv + guess_0;
255
419k
        for (size_t x = 1; x < channel.w; x++) {
256
405k
          pixel_type left = r[x - 1];
257
405k
          pixel_type top = rtop[x];
258
405k
          pixel_type topleft = rtopleft[x];
259
405k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
405k
          if (!fl_run) {
261
113k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
113k
                                                       &fl_run);
263
113k
            sv = UnpackSigned(fl_v);
264
291k
          } else {
265
291k
            fl_run--;
266
291k
          }
267
405k
          r[x] = sv + guess;
268
405k
        }
269
13.9k
      }
270
385
      return true;
271
24.5k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
3.25k
               multiplier == 1) {
273
2.90k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
2.90k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
69.3k
      for (size_t y = 0; y < channel.h; y++) {
276
66.4k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
3.70M
        for (size_t x = 0; x < channel.w; x++) {
278
3.63M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
3.63M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
3.63M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
3.63M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
3.63M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
3.63M
              ctx_id, br);
284
3.63M
          r[x] = make_pixel(v, 1, guess);
285
3.63M
        }
286
66.4k
      }
287
2.90k
      return true;
288
2.90k
    }
289
380k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
34.0k
  if (is_wp_only) {
294
4.45k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.45k
  }
296
34.0k
  if (is_gradient_only) {
297
1.66k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.66k
  }
299
300
34.0k
  if (is_gradient_only) {
301
740
    JXL_DEBUG_V(8, "Gradient fast track.");
302
740
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
16.0k
    for (size_t y = 0; y < channel.h; y++) {
304
15.2k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
623k
      for (size_t x = 0; x < channel.w; x++) {
306
607k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
607k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
607k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
607k
        int32_t guess = ClampedGradient(top, left, topleft);
310
607k
        uint32_t pos =
311
607k
            kPropRangeFast +
312
607k
            std::min<pixel_type_w>(
313
607k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
607k
                kPropRangeFast - 1);
315
607k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
607k
        uint64_t v =
317
607k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
607k
        r[x] = make_pixel(v, 1, guess);
319
607k
      }
320
15.2k
    }
321
33.3k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
947
    JXL_DEBUG_V(8, "WP fast track.");
323
947
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
947
    Properties properties(1);
325
22.3k
    for (size_t y = 0; y < channel.h; y++) {
326
21.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
21.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
21.3k
      const pixel_type *JXL_RESTRICT rtoptop =
329
21.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
21.3k
      const pixel_type *JXL_RESTRICT rtopleft =
331
21.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
21.3k
      const pixel_type *JXL_RESTRICT rtopright =
333
21.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
21.3k
      size_t x = 0;
335
21.3k
      {
336
21.3k
        size_t offset = 0;
337
21.3k
        pixel_type_w left = y ? rtop[x] : 0;
338
21.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
21.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
21.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
21.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
21.3k
            offset);
343
21.3k
        uint32_t pos =
344
21.3k
            kPropRangeFast +
345
21.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
21.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
21.3k
        uint64_t v =
348
21.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
21.3k
        r[x] = make_pixel(v, 1, guess);
350
21.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
21.3k
      }
352
1.86M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.84M
        size_t offset = 0;
354
1.84M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.84M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.84M
            rtoptop[x], &properties, offset);
357
1.84M
        uint32_t pos =
358
1.84M
            kPropRangeFast +
359
1.84M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.84M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.84M
        uint64_t v =
362
1.84M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.84M
        r[x] = make_pixel(v, 1, guess);
364
1.84M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.84M
      }
366
21.3k
      {
367
21.3k
        size_t offset = 0;
368
21.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
21.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
21.3k
            rtoptop[x], &properties, offset);
371
21.3k
        uint32_t pos =
372
21.3k
            kPropRangeFast +
373
21.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
21.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
21.3k
        uint64_t v =
376
21.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
21.3k
        r[x] = make_pixel(v, 1, guess);
378
21.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
21.3k
      }
380
21.3k
    }
381
32.3k
  } 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
22.4k
    JXL_DEBUG_V(8, "Slow track.");
385
22.4k
    MATreeLookup tree_lookup(tree);
386
22.4k
    Properties properties = Properties(num_props);
387
22.4k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
22.4k
    JXL_ASSIGN_OR_RETURN(
389
22.4k
        Channel references,
390
22.4k
        Channel::Create(memory_manager,
391
22.4k
                        properties.size() - kNumNonrefProperties, channel.w));
392
655k
    for (size_t y = 0; y < channel.h; y++) {
393
632k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
632k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
632k
      InitPropsRow(&properties, static_props, y);
396
632k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.56M
        for (size_t x = 0; x < 2; x++) {
398
1.04M
          PredictionResult res =
399
1.04M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
1.04M
                              tree_lookup, references);
401
1.04M
          uint64_t v =
402
1.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
1.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
1.04M
        }
405
55.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
54.6M
          PredictionResult res =
407
54.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
54.6M
                                 tree_lookup, references);
409
54.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
54.6M
              res.context, br);
411
54.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
54.6M
        }
413
1.56M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
1.04M
          PredictionResult res =
415
1.04M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
1.04M
                              tree_lookup, references);
417
1.04M
          uint64_t v =
418
1.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
1.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
1.04M
        }
421
520k
      } else {
422
2.27M
        for (size_t x = 0; x < channel.w; x++) {
423
2.16M
          PredictionResult res =
424
2.16M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
2.16M
                              tree_lookup, references);
426
2.16M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
2.16M
              res.context, br);
428
2.16M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
2.16M
        }
430
112k
      }
431
632k
    }
432
22.4k
  } else {
433
9.90k
    JXL_DEBUG_V(8, "Slowest track.");
434
9.90k
    MATreeLookup tree_lookup(tree);
435
9.90k
    Properties properties = Properties(num_props);
436
9.90k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
9.90k
    JXL_ASSIGN_OR_RETURN(
438
9.90k
        Channel references,
439
9.90k
        Channel::Create(memory_manager,
440
9.90k
                        properties.size() - kNumNonrefProperties, channel.w));
441
9.90k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
258k
    for (size_t y = 0; y < channel.h; y++) {
443
248k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
248k
      InitPropsRow(&properties, static_props, y);
445
248k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
248k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
592k
        for (size_t x = 0; x < 2; x++) {
448
394k
          PredictionResult res =
449
394k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
394k
                            tree_lookup, references, &wp_state);
451
394k
          uint64_t v =
452
394k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
394k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
394k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
394k
        }
456
15.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
15.0M
          PredictionResult res =
458
15.0M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
15.0M
                               tree_lookup, references, &wp_state);
460
15.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
15.0M
              res.context, br);
462
15.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
15.0M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
15.0M
        }
465
592k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
394k
          PredictionResult res =
467
394k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
394k
                            tree_lookup, references, &wp_state);
469
394k
          uint64_t v =
470
394k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
394k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
394k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
394k
        }
474
197k
      } else {
475
2.08M
        for (size_t x = 0; x < channel.w; x++) {
476
2.03M
          PredictionResult res =
477
2.03M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
2.03M
                            tree_lookup, references, &wp_state);
479
2.03M
          uint64_t v =
480
2.03M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
2.03M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
2.03M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
2.03M
        }
484
51.5k
      }
485
248k
    }
486
9.90k
  }
487
34.0k
  return true;
488
34.0k
}
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
39.6k
                                 uint32_t &fl_v) {
157
39.6k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
39.6k
  Channel &channel = image->channel[chan];
159
160
39.6k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
39.6k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
39.6k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
39.6k
  bool tree_has_wp_prop_or_pred = false;
168
39.6k
  bool is_wp_only = false;
169
39.6k
  bool is_gradient_only = false;
170
39.6k
  size_t num_props;
171
39.6k
  FlatTree tree =
172
39.6k
      FilterTree(global_tree, static_props, &num_props,
173
39.6k
                 &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
54.1k
  for (auto &node : tree) {
178
54.1k
    if (node.property0 == -1) {
179
50.5k
      node.childID = context_map[node.childID];
180
50.5k
    }
181
54.1k
  }
182
183
39.6k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
39.6k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
39.6k
                             pixel_type_w offset) -> pixel_type {
188
39.6k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
39.6k
    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.6k
    return val * multiplier + offset;
192
39.6k
  };
193
194
39.6k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
36.8k
    Predictor predictor = tree[0].predictor;
198
36.8k
    int64_t offset = tree[0].predictor_offset;
199
36.8k
    int32_t multiplier = tree[0].multiplier;
200
36.8k
    size_t ctx_id = tree[0].childID;
201
36.8k
    if (predictor == Predictor::Zero) {
202
28.9k
      uint32_t value;
203
28.9k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
28.9k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
9.60k
        JXL_DEBUG_V(8, "Fastest track.");
208
9.60k
        pixel_type v = make_pixel(value, multiplier, offset);
209
344k
        for (size_t y = 0; y < channel.h; y++) {
210
334k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
334k
          std::fill(r, r + channel.w, v);
212
334k
        }
213
19.3k
      } else {
214
19.3k
        JXL_DEBUG_V(8, "Fast track.");
215
19.3k
        if (multiplier == 1 && offset == 0) {
216
373k
          for (size_t y = 0; y < channel.h; y++) {
217
367k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
54.9M
            for (size_t x = 0; x < channel.w; x++) {
219
54.5M
              uint32_t v =
220
54.5M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
54.5M
              r[x] = UnpackSigned(v);
222
54.5M
            }
223
367k
          }
224
12.9k
        } else {
225
407k
          for (size_t y = 0; y < channel.h; y++) {
226
394k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
26.6M
            for (size_t x = 0; x < channel.w; x++) {
228
26.2M
              uint32_t v =
229
26.2M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
26.2M
                                                                         br);
231
26.2M
              r[x] = make_pixel(v, multiplier, offset);
232
26.2M
            }
233
394k
          }
234
12.9k
        }
235
19.3k
      }
236
28.9k
      return true;
237
28.9k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.91k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
385
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
385
      pixel_type_w sv = UnpackSigned(fl_v);
241
14.3k
      for (size_t y = 0; y < channel.h; y++) {
242
13.9k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
13.9k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
13.9k
        const pixel_type *JXL_RESTRICT rtopleft =
245
13.9k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
13.9k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
13.9k
        if (fl_run == 0) {
248
3.88k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
3.88k
                                                     &fl_run);
250
3.88k
          sv = UnpackSigned(fl_v);
251
10.0k
        } else {
252
10.0k
          fl_run--;
253
10.0k
        }
254
13.9k
        r[0] = sv + guess_0;
255
419k
        for (size_t x = 1; x < channel.w; x++) {
256
405k
          pixel_type left = r[x - 1];
257
405k
          pixel_type top = rtop[x];
258
405k
          pixel_type topleft = rtopleft[x];
259
405k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
405k
          if (!fl_run) {
261
113k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
113k
                                                       &fl_run);
263
113k
            sv = UnpackSigned(fl_v);
264
291k
          } else {
265
291k
            fl_run--;
266
291k
          }
267
405k
          r[x] = sv + guess;
268
405k
        }
269
13.9k
      }
270
385
      return true;
271
7.43k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.53k
               multiplier == 1) {
273
1.36k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.36k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
28.6k
      for (size_t y = 0; y < channel.h; y++) {
276
27.2k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
1.31M
        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
27.2k
      }
287
1.36k
      return true;
288
1.36k
    }
289
36.8k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
8.91k
  if (is_wp_only) {
294
359
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
359
  }
296
8.91k
  if (is_gradient_only) {
297
573
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
573
  }
299
300
8.91k
  if (is_gradient_only) {
301
108
    JXL_DEBUG_V(8, "Gradient fast track.");
302
108
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
2.30k
    for (size_t y = 0; y < channel.h; y++) {
304
2.19k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
171k
      for (size_t x = 0; x < channel.w; x++) {
306
169k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
169k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
169k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
169k
        int32_t guess = ClampedGradient(top, left, topleft);
310
169k
        uint32_t pos =
311
169k
            kPropRangeFast +
312
169k
            std::min<pixel_type_w>(
313
169k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
169k
                kPropRangeFast - 1);
315
169k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
169k
        uint64_t v =
317
169k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
169k
        r[x] = make_pixel(v, 1, guess);
319
169k
      }
320
2.19k
    }
321
8.80k
  } 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.80k
  } 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.84k
    JXL_DEBUG_V(8, "Slow track.");
385
7.84k
    MATreeLookup tree_lookup(tree);
386
7.84k
    Properties properties = Properties(num_props);
387
7.84k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
7.84k
    JXL_ASSIGN_OR_RETURN(
389
7.84k
        Channel references,
390
7.84k
        Channel::Create(memory_manager,
391
7.84k
                        properties.size() - kNumNonrefProperties, channel.w));
392
189k
    for (size_t y = 0; y < channel.h; y++) {
393
181k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
181k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
181k
      InitPropsRow(&properties, static_props, y);
396
181k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
459k
        for (size_t x = 0; x < 2; x++) {
398
306k
          PredictionResult res =
399
306k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
306k
                              tree_lookup, references);
401
306k
          uint64_t v =
402
306k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
306k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
306k
        }
405
19.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
19.4M
          PredictionResult res =
407
19.4M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
19.4M
                                 tree_lookup, references);
409
19.4M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
19.4M
              res.context, br);
411
19.4M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
19.4M
        }
413
459k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
306k
          PredictionResult res =
415
306k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
306k
                              tree_lookup, references);
417
306k
          uint64_t v =
418
306k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
306k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
306k
        }
421
153k
      } else {
422
500k
        for (size_t x = 0; x < channel.w; x++) {
423
471k
          PredictionResult res =
424
471k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
471k
                              tree_lookup, references);
426
471k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
471k
              res.context, br);
428
471k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
471k
        }
430
28.8k
      }
431
181k
    }
432
7.84k
  } else {
433
959
    JXL_DEBUG_V(8, "Slowest track.");
434
959
    MATreeLookup tree_lookup(tree);
435
959
    Properties properties = Properties(num_props);
436
959
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
959
    JXL_ASSIGN_OR_RETURN(
438
959
        Channel references,
439
959
        Channel::Create(memory_manager,
440
959
                        properties.size() - kNumNonrefProperties, channel.w));
441
959
    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
503k
        for (size_t x = 0; x < channel.w; x++) {
476
491k
          PredictionResult res =
477
491k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
491k
                            tree_lookup, references, &wp_state);
479
491k
          uint64_t v =
480
491k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
491k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
491k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
491k
        }
484
12.3k
      }
485
12.3k
    }
486
959
  }
487
8.91k
  return true;
488
8.91k
}
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
353k
                                 uint32_t &fl_v) {
157
353k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
353k
  Channel &channel = image->channel[chan];
159
160
353k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
353k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
353k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
353k
  bool tree_has_wp_prop_or_pred = false;
168
353k
  bool is_wp_only = false;
169
353k
  bool is_gradient_only = false;
170
353k
  size_t num_props;
171
353k
  FlatTree tree =
172
353k
      FilterTree(global_tree, static_props, &num_props,
173
353k
                 &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
506k
  for (auto &node : tree) {
178
506k
    if (node.property0 == -1) {
179
468k
      node.childID = context_map[node.childID];
180
468k
    }
181
506k
  }
182
183
353k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
353k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
353k
                             pixel_type_w offset) -> pixel_type {
188
353k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
353k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
353k
    return val * multiplier + offset;
192
353k
  };
193
194
353k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
343k
    Predictor predictor = tree[0].predictor;
198
343k
    int64_t offset = tree[0].predictor_offset;
199
343k
    int32_t multiplier = tree[0].multiplier;
200
343k
    size_t ctx_id = tree[0].childID;
201
343k
    if (predictor == Predictor::Zero) {
202
326k
      uint32_t value;
203
326k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
326k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
147k
        JXL_DEBUG_V(8, "Fastest track.");
208
147k
        pixel_type v = make_pixel(value, multiplier, offset);
209
4.48M
        for (size_t y = 0; y < channel.h; y++) {
210
4.34M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
4.34M
          std::fill(r, r + channel.w, v);
212
4.34M
        }
213
179k
      } else {
214
179k
        JXL_DEBUG_V(8, "Fast track.");
215
179k
        if (multiplier == 1 && offset == 0) {
216
2.56M
          for (size_t y = 0; y < channel.h; y++) {
217
2.40M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
160M
            for (size_t x = 0; x < channel.w; x++) {
219
158M
              uint32_t v =
220
158M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
158M
              r[x] = UnpackSigned(v);
222
158M
            }
223
2.40M
          }
224
158k
        } else {
225
1.01M
          for (size_t y = 0; y < channel.h; y++) {
226
993k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
125M
            for (size_t x = 0; x < channel.w; x++) {
228
124M
              uint32_t v =
229
124M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
124M
                                                                         br);
231
124M
              r[x] = make_pixel(v, multiplier, offset);
232
124M
            }
233
993k
          }
234
21.2k
        }
235
179k
      }
236
326k
      return true;
237
326k
    } 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.0k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.72k
               multiplier == 1) {
273
1.54k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.54k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
40.7k
      for (size_t y = 0; y < channel.h; y++) {
276
39.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.38M
        for (size_t x = 0; x < channel.w; x++) {
278
2.34M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.34M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.34M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.34M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.34M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.34M
              ctx_id, br);
284
2.34M
          r[x] = make_pixel(v, 1, guess);
285
2.34M
        }
286
39.1k
      }
287
1.54k
      return true;
288
1.54k
    }
289
343k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
25.1k
  if (is_wp_only) {
294
4.09k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.09k
  }
296
25.1k
  if (is_gradient_only) {
297
1.09k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.09k
  }
299
300
25.1k
  if (is_gradient_only) {
301
632
    JXL_DEBUG_V(8, "Gradient fast track.");
302
632
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
13.6k
    for (size_t y = 0; y < channel.h; y++) {
304
13.0k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
451k
      for (size_t x = 0; x < channel.w; x++) {
306
438k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
438k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
438k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
438k
        int32_t guess = ClampedGradient(top, left, topleft);
310
438k
        uint32_t pos =
311
438k
            kPropRangeFast +
312
438k
            std::min<pixel_type_w>(
313
438k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
438k
                kPropRangeFast - 1);
315
438k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
438k
        uint64_t v =
317
438k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
438k
        r[x] = make_pixel(v, 1, guess);
319
438k
      }
320
13.0k
    }
321
24.5k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
947
    JXL_DEBUG_V(8, "WP fast track.");
323
947
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
947
    Properties properties(1);
325
22.3k
    for (size_t y = 0; y < channel.h; y++) {
326
21.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
21.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
21.3k
      const pixel_type *JXL_RESTRICT rtoptop =
329
21.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
21.3k
      const pixel_type *JXL_RESTRICT rtopleft =
331
21.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
21.3k
      const pixel_type *JXL_RESTRICT rtopright =
333
21.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
21.3k
      size_t x = 0;
335
21.3k
      {
336
21.3k
        size_t offset = 0;
337
21.3k
        pixel_type_w left = y ? rtop[x] : 0;
338
21.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
21.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
21.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
21.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
21.3k
            offset);
343
21.3k
        uint32_t pos =
344
21.3k
            kPropRangeFast +
345
21.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
21.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
21.3k
        uint64_t v =
348
21.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
21.3k
        r[x] = make_pixel(v, 1, guess);
350
21.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
21.3k
      }
352
1.86M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.84M
        size_t offset = 0;
354
1.84M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.84M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.84M
            rtoptop[x], &properties, offset);
357
1.84M
        uint32_t pos =
358
1.84M
            kPropRangeFast +
359
1.84M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.84M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.84M
        uint64_t v =
362
1.84M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.84M
        r[x] = make_pixel(v, 1, guess);
364
1.84M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.84M
      }
366
21.3k
      {
367
21.3k
        size_t offset = 0;
368
21.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
21.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
21.3k
            rtoptop[x], &properties, offset);
371
21.3k
        uint32_t pos =
372
21.3k
            kPropRangeFast +
373
21.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
21.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
21.3k
        uint64_t v =
376
21.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
21.3k
        r[x] = make_pixel(v, 1, guess);
378
21.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
21.3k
      }
380
21.3k
    }
381
23.5k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
14.6k
    JXL_DEBUG_V(8, "Slow track.");
385
14.6k
    MATreeLookup tree_lookup(tree);
386
14.6k
    Properties properties = Properties(num_props);
387
14.6k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
14.6k
    JXL_ASSIGN_OR_RETURN(
389
14.6k
        Channel references,
390
14.6k
        Channel::Create(memory_manager,
391
14.6k
                        properties.size() - kNumNonrefProperties, channel.w));
392
465k
    for (size_t y = 0; y < channel.h; y++) {
393
450k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
450k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
450k
      InitPropsRow(&properties, static_props, y);
396
450k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.10M
        for (size_t x = 0; x < 2; x++) {
398
735k
          PredictionResult res =
399
735k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
735k
                              tree_lookup, references);
401
735k
          uint64_t v =
402
735k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
735k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
735k
        }
405
35.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
35.1M
          PredictionResult res =
407
35.1M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
35.1M
                                 tree_lookup, references);
409
35.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
35.1M
              res.context, br);
411
35.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
35.1M
        }
413
1.10M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
735k
          PredictionResult res =
415
735k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
735k
                              tree_lookup, references);
417
735k
          uint64_t v =
418
735k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
735k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
735k
        }
421
367k
      } else {
422
1.77M
        for (size_t x = 0; x < channel.w; x++) {
423
1.69M
          PredictionResult res =
424
1.69M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.69M
                              tree_lookup, references);
426
1.69M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.69M
              res.context, br);
428
1.69M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.69M
        }
430
83.4k
      }
431
450k
    }
432
14.6k
  } else {
433
8.94k
    JXL_DEBUG_V(8, "Slowest track.");
434
8.94k
    MATreeLookup tree_lookup(tree);
435
8.94k
    Properties properties = Properties(num_props);
436
8.94k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
8.94k
    JXL_ASSIGN_OR_RETURN(
438
8.94k
        Channel references,
439
8.94k
        Channel::Create(memory_manager,
440
8.94k
                        properties.size() - kNumNonrefProperties, channel.w));
441
8.94k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
245k
    for (size_t y = 0; y < channel.h; y++) {
443
236k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
236k
      InitPropsRow(&properties, static_props, y);
445
236k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
236k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
592k
        for (size_t x = 0; x < 2; x++) {
448
394k
          PredictionResult res =
449
394k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
394k
                            tree_lookup, references, &wp_state);
451
394k
          uint64_t v =
452
394k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
394k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
394k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
394k
        }
456
15.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
15.0M
          PredictionResult res =
458
15.0M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
15.0M
                               tree_lookup, references, &wp_state);
460
15.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
15.0M
              res.context, br);
462
15.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
15.0M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
15.0M
        }
465
592k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
394k
          PredictionResult res =
467
394k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
394k
                            tree_lookup, references, &wp_state);
469
394k
          uint64_t v =
470
394k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
394k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
394k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
394k
        }
474
197k
      } else {
475
1.57M
        for (size_t x = 0; x < channel.w; x++) {
476
1.53M
          PredictionResult res =
477
1.53M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.53M
                            tree_lookup, references, &wp_state);
479
1.53M
          uint64_t v =
480
1.53M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.53M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.53M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.53M
        }
484
39.1k
      }
485
236k
    }
486
8.94k
  }
487
25.1k
  return true;
488
25.1k
}
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
393k
                                 uint32_t &fl_v) {
499
393k
  if (reader->UsesLZ77()) {
500
39.6k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
39.6k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
39.6k
        tree_lut, image, fl_run, fl_v);
503
353k
  } else {
504
353k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
353k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
353k
        tree_lut, image, fl_run, fl_v);
507
353k
  }
508
393k
}
509
510
182k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
45.8k
                                 const ModularOptions &options) {
514
45.8k
  size_t nb_channels = image.channel.size();
515
91.6k
  for (bool is_dc : {true, false}) {
516
91.6k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
91.6k
    size_t c = image.nb_meta_channels;
518
910k
    for (; c < nb_channels; c++) {
519
822k
      const Channel &ch = image.channel[c];
520
822k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
822k
    }
522
112k
    for (; c < nb_channels; c++) {
523
20.9k
      const Channel &ch = image.channel[c];
524
20.9k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
20.3k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
20.3k
      if (is_dc_channel != is_dc) continue;
527
10.1k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
10.1k
      if (tile_dim == 0) {
529
2
        return JXL_FAILURE("Inconsistent transforms");
530
2
      }
531
10.1k
    }
532
91.6k
  }
533
45.8k
  return true;
534
45.8k
}
535
536
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
537
                     size_t group_id, ModularOptions *options,
538
                     const Tree *global_tree, const ANSCode *global_code,
539
                     const std::vector<uint8_t> *global_ctx_map,
540
52.4k
                     const bool allow_truncated_group) {
541
52.4k
  if (image.channel.empty()) return true;
542
45.4k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
45.4k
  Status status = Bundle::Read(br, &header);
546
45.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
44.3k
  if (status.IsFatalError()) return status;
548
44.3k
  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
44.3k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
44.3k
              header.transforms.size());
560
44.3k
  image.transform = header.transforms;
561
44.3k
  for (Transform &transform : image.transform) {
562
27.3k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
27.3k
  }
564
44.1k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
44.1k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
44.1k
  size_t nb_channels = image.channel.size();
570
571
44.1k
  size_t num_chans = 0;
572
44.1k
  size_t distance_multiplier = 0;
573
454k
  for (size_t i = 0; i < nb_channels; i++) {
574
411k
    Channel &channel = image.channel[i];
575
411k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
406k
                                        channel.h > options->max_chan_size)) {
577
1.17k
      break;
578
1.17k
    }
579
410k
    if (!channel.w || !channel.h) {
580
5.33k
      continue;  // skip empty channels
581
5.33k
    }
582
405k
    if (channel.w > distance_multiplier) {
583
71.2k
      distance_multiplier = channel.w;
584
71.2k
    }
585
405k
    num_chans++;
586
405k
  }
587
44.1k
  if (num_chans == 0) return true;
588
589
43.7k
  size_t next_channel = 0;
590
43.7k
  auto scope_guard = MakeScopeGuard([&]() {
591
18.3k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
15.4k
      ZeroFillImage(&image.channel[c].plane);
593
15.4k
    }
594
2.87k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
43.7k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
43.7k
  Tree tree_storage;
600
43.7k
  std::vector<uint8_t> context_map_storage;
601
43.7k
  ANSCode code_storage;
602
43.7k
  const Tree *tree = &tree_storage;
603
43.7k
  const ANSCode *code = &code_storage;
604
43.7k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
43.7k
  if (!header.use_global_tree) {
606
26.3k
    uint64_t max_tree_size = 1024;
607
327k
    for (size_t i = 0; i < nb_channels; i++) {
608
301k
      Channel &channel = image.channel[i];
609
301k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
299k
                                          channel.h > options->max_chan_size)) {
611
44
        break;
612
44
      }
613
301k
      uint64_t pixels = channel.w * channel.h;
614
301k
      max_tree_size += pixels;
615
301k
    }
616
26.3k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
26.3k
    JXL_RETURN_IF_ERROR(
618
26.3k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
25.9k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
25.9k
                                         (tree_storage.size() + 1) / 2,
621
25.9k
                                         &code_storage, &context_map_storage));
622
25.9k
  } else {
623
17.3k
    if (!global_tree || !global_code || !global_ctx_map ||
624
17.3k
        global_tree->empty()) {
625
72
      return JXL_FAILURE("No global tree available but one was requested");
626
72
    }
627
17.3k
    tree = global_tree;
628
17.3k
    code = global_code;
629
17.3k
    context_map = global_ctx_map;
630
17.3k
  }
631
632
  // Read channels
633
86.5k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
86.5k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
86.5k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
86.5k
  uint32_t fl_run = 0;
637
86.5k
  uint32_t fl_v = 0;
638
438k
  for (; next_channel < nb_channels; next_channel++) {
639
398k
    Channel &channel = image.channel[next_channel];
640
398k
    if (next_channel >= image.nb_meta_channels &&
641
394k
        (channel.w > options->max_chan_size ||
642
393k
         channel.h > options->max_chan_size)) {
643
710
      break;
644
710
    }
645
397k
    if (!channel.w || !channel.h) {
646
4.93k
      continue;  // skip empty channels
647
4.93k
    }
648
393k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
393k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
393k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
393k
    if (!br->AllReadsWithinBounds()) {
654
2.40k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
2.40k
    }
657
393k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
40.8k
  scope_guard.Disarm();
661
662
40.8k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
40.8k
  return true;
666
40.8k
}
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
52.4k
                                bool allow_truncated_group) {
674
52.4k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
52.4k
  req_sizes.reserve(image.channel.size());
676
164k
  for (const auto &c : image.channel) {
677
164k
    req_sizes.emplace_back(c.w, c.h);
678
164k
  }
679
52.4k
  GroupHeader local_header;
680
52.4k
  if (header == nullptr) header = &local_header;
681
52.4k
  size_t bit_pos = br->TotalBitsConsumed();
682
52.4k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
52.4k
                                  code, ctx_map, allow_truncated_group);
684
52.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
48.2k
  if (dec_status.IsFatalError()) return dec_status;
686
48.2k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
48.2k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
48.2k
  JXL_DEBUG_V(4,
689
48.2k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
48.2k
              " image from %" PRIuS " bytes",
691
48.2k
              image.w, image.h, image.channel.size(),
692
48.2k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
48.2k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
48.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
48.2k
  if (undo_transforms) {
699
13.2k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
65.0k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
51.8k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
51.8k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
51.8k
    }
704
13.2k
  }
705
48.2k
  return dec_status;
706
48.2k
}
707
708
}  // namespace jxl