Coverage Report

Created: 2026-04-01 07:49

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
688k
                    bool *gradient_only) {
46
688k
  *num_props = 0;
47
688k
  bool has_wp = false;
48
688k
  bool has_non_wp = false;
49
688k
  *gradient_only = true;
50
858k
  const auto mark_property = [&](int32_t p) {
51
858k
    if (p == kWPProp) {
52
146k
      has_wp = true;
53
711k
    } else if (p >= kNumStaticProperties) {
54
374k
      has_non_wp = true;
55
374k
    }
56
858k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
432k
      *gradient_only = false;
58
432k
    }
59
858k
  };
60
688k
  FlatTree output;
61
688k
  std::queue<size_t> nodes;
62
688k
  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.52M
  while (!nodes.empty()) {
70
1.83M
    size_t cur = nodes.front();
71
1.83M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.96M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.68M
           global_tree[cur].property != -1) {
75
135k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
74.2k
        cur = global_tree[cur].lchild;
77
74.2k
      } else {
78
61.6k
        cur = global_tree[cur].rchild;
79
61.6k
      }
80
135k
    }
81
1.83M
    FlatDecisionNode flat;
82
1.83M
    if (global_tree[cur].property == -1) {
83
1.54M
      flat.property0 = -1;
84
1.54M
      flat.childID = global_tree[cur].lchild;
85
1.54M
      flat.predictor = global_tree[cur].predictor;
86
1.54M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.54M
      flat.multiplier = global_tree[cur].multiplier;
88
1.54M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.54M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.54M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.54M
      output.push_back(flat);
92
1.54M
      continue;
93
1.54M
    }
94
286k
    flat.childID = output.size() + nodes.size() + 1;
95
96
286k
    flat.property0 = global_tree[cur].property;
97
286k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
286k
    flat.splitval0 = global_tree[cur].splitval;
99
100
858k
    for (size_t i = 0; i < 2; i++) {
101
572k
      size_t cur_child =
102
572k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
611k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
376k
             global_tree[cur_child].property != -1) {
106
39.6k
        if (static_props[global_tree[cur_child].property] >
107
39.6k
            global_tree[cur_child].splitval) {
108
21.1k
          cur_child = global_tree[cur_child].lchild;
109
21.1k
        } else {
110
18.4k
          cur_child = global_tree[cur_child].rchild;
111
18.4k
        }
112
39.6k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
572k
      if (global_tree[cur_child].property == -1) {
116
336k
        flat.properties[i] = 0;
117
336k
        flat.splitvals[i] = 0;
118
336k
        nodes.push(cur_child);
119
336k
        nodes.push(cur_child);
120
336k
      } else {
121
235k
        flat.properties[i] = global_tree[cur_child].property;
122
235k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
235k
        nodes.push(global_tree[cur_child].lchild);
124
235k
        nodes.push(global_tree[cur_child].rchild);
125
235k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
235k
      }
127
572k
    }
128
129
572k
    for (int16_t property : flat.properties) mark_property(property);
130
286k
    mark_property(flat.property0);
131
286k
    output.push_back(flat);
132
286k
  }
133
688k
  if (*num_props > kNumNonrefProperties) {
134
3.98k
    *num_props =
135
3.98k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
3.98k
            kExtraPropsPerChannel +
137
3.98k
        kNumNonrefProperties;
138
684k
  } else {
139
684k
    *num_props = kNumNonrefProperties;
140
684k
  }
141
688k
  *use_wp = has_wp;
142
688k
  *wp_only = has_wp && !has_non_wp;
143
144
688k
  return output;
145
688k
}
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
651k
                                 uint32_t &fl_v) {
157
651k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
651k
  Channel &channel = image->channel[chan];
159
160
651k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
651k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
651k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
651k
  bool tree_has_wp_prop_or_pred = false;
168
651k
  bool is_wp_only = false;
169
651k
  bool is_gradient_only = false;
170
651k
  size_t num_props;
171
651k
  FlatTree tree =
172
651k
      FilterTree(global_tree, static_props, &num_props,
173
651k
                 &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
1.36M
  for (auto &node : tree) {
178
1.36M
    if (node.property0 == -1) {
179
1.18M
      node.childID = context_map[node.childID];
180
1.18M
    }
181
1.36M
  }
182
183
651k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
651k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
471M
                             pixel_type_w offset) -> pixel_type {
188
471M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
471M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
471M
    return val * multiplier + offset;
192
471M
  };
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
116M
                             pixel_type_w offset) -> pixel_type {
188
116M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
116M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
116M
    return val * multiplier + offset;
192
116M
  };
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
355M
                             pixel_type_w offset) -> pixel_type {
188
355M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
355M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
355M
    return val * multiplier + offset;
192
355M
  };
193
194
651k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
611k
    Predictor predictor = tree[0].predictor;
198
611k
    int64_t offset = tree[0].predictor_offset;
199
611k
    int32_t multiplier = tree[0].multiplier;
200
611k
    size_t ctx_id = tree[0].childID;
201
611k
    if (predictor == Predictor::Zero) {
202
482k
      uint32_t value;
203
482k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
482k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
76.6k
        JXL_DEBUG_V(8, "Fastest track.");
208
76.6k
        pixel_type v = make_pixel(value, multiplier, offset);
209
1.67M
        for (size_t y = 0; y < channel.h; y++) {
210
1.59M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
1.59M
          std::fill(r, r + channel.w, v);
212
1.59M
        }
213
405k
      } else {
214
405k
        JXL_DEBUG_V(8, "Fast track.");
215
405k
        if (multiplier == 1 && offset == 0) {
216
5.88M
          for (size_t y = 0; y < channel.h; y++) {
217
5.50M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
276M
            for (size_t x = 0; x < channel.w; x++) {
219
270M
              uint32_t v =
220
270M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
270M
              r[x] = UnpackSigned(v);
222
270M
            }
223
5.50M
          }
224
380k
        } else {
225
516k
          for (size_t y = 0; y < channel.h; y++) {
226
490k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
26.5M
            for (size_t x = 0; x < channel.w; x++) {
228
26.1M
              uint32_t v =
229
26.1M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
26.1M
                                                                         br);
231
26.1M
              r[x] = make_pixel(v, multiplier, offset);
232
26.1M
            }
233
490k
          }
234
25.8k
        }
235
405k
      }
236
482k
      return true;
237
482k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
2.75k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
410
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
410
      pixel_type_w sv = UnpackSigned(fl_v);
241
5.94k
      for (size_t y = 0; y < channel.h; y++) {
242
5.53k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
5.53k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
5.53k
        const pixel_type *JXL_RESTRICT rtopleft =
245
5.53k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
5.53k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
5.53k
        if (fl_run == 0) {
248
5.53k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.53k
                                                     &fl_run);
250
5.53k
          sv = UnpackSigned(fl_v);
251
5.53k
        } else {
252
0
          fl_run--;
253
0
        }
254
5.53k
        r[0] = sv + guess_0;
255
215k
        for (size_t x = 1; x < channel.w; x++) {
256
209k
          pixel_type left = r[x - 1];
257
209k
          pixel_type top = rtop[x];
258
209k
          pixel_type topleft = rtopleft[x];
259
209k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
209k
          if (!fl_run) {
261
209k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
209k
                                                       &fl_run);
263
209k
            sv = UnpackSigned(fl_v);
264
209k
          } else {
265
0
            fl_run--;
266
0
          }
267
209k
          r[x] = sv + guess;
268
209k
        }
269
5.53k
      }
270
410
      return true;
271
128k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
9.03k
               multiplier == 1) {
273
7.87k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
7.87k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
175k
      for (size_t y = 0; y < channel.h; y++) {
276
167k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
5.50M
        for (size_t x = 0; x < channel.w; x++) {
278
5.33M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
5.33M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
5.33M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
5.33M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
5.33M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
5.33M
              ctx_id, br);
284
5.33M
          r[x] = make_pixel(v, 1, guess);
285
5.33M
        }
286
167k
      }
287
7.87k
      return true;
288
7.87k
    }
289
611k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
160k
  if (is_wp_only) {
294
17.5k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
17.5k
  }
296
160k
  if (is_gradient_only) {
297
7.19k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
7.19k
  }
299
300
160k
  if (is_gradient_only) {
301
4.20k
    JXL_DEBUG_V(8, "Gradient fast track.");
302
4.20k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
204k
    for (size_t y = 0; y < channel.h; y++) {
304
200k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
3.88M
      for (size_t x = 0; x < channel.w; x++) {
306
3.68M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
3.68M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
3.68M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
3.68M
        int32_t guess = ClampedGradient(top, left, topleft);
310
3.68M
        uint32_t pos =
311
3.68M
            kPropRangeFast +
312
3.68M
            std::min<pixel_type_w>(
313
3.68M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
3.68M
                kPropRangeFast - 1);
315
3.68M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
3.68M
        uint64_t v =
317
3.68M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
3.68M
        r[x] = make_pixel(v, 1, guess);
319
3.68M
      }
320
200k
    }
321
156k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
8.29k
    JXL_DEBUG_V(8, "WP fast track.");
323
8.29k
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
8.29k
    Properties properties(1);
325
286k
    for (size_t y = 0; y < channel.h; y++) {
326
278k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
278k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
278k
      const pixel_type *JXL_RESTRICT rtoptop =
329
278k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
278k
      const pixel_type *JXL_RESTRICT rtopleft =
331
278k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
278k
      const pixel_type *JXL_RESTRICT rtopright =
333
278k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
278k
      size_t x = 0;
335
278k
      {
336
278k
        size_t offset = 0;
337
278k
        pixel_type_w left = y ? rtop[x] : 0;
338
278k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
278k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
278k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
278k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
278k
            offset);
343
278k
        uint32_t pos =
344
278k
            kPropRangeFast +
345
278k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
278k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
278k
        uint64_t v =
348
278k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
278k
        r[x] = make_pixel(v, 1, guess);
350
278k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
278k
      }
352
13.7M
      for (x = 1; x + 1 < channel.w; x++) {
353
13.4M
        size_t offset = 0;
354
13.4M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
13.4M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
13.4M
            rtoptop[x], &properties, offset);
357
13.4M
        uint32_t pos =
358
13.4M
            kPropRangeFast +
359
13.4M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
13.4M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
13.4M
        uint64_t v =
362
13.4M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
13.4M
        r[x] = make_pixel(v, 1, guess);
364
13.4M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
13.4M
      }
366
278k
      {
367
278k
        size_t offset = 0;
368
278k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
278k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
278k
            rtoptop[x], &properties, offset);
371
278k
        uint32_t pos =
372
278k
            kPropRangeFast +
373
278k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
278k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
278k
        uint64_t v =
376
278k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
278k
        r[x] = make_pixel(v, 1, guess);
378
278k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
278k
      }
380
278k
    }
381
148k
  } 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
123k
    JXL_DEBUG_V(8, "Slow track.");
385
123k
    MATreeLookup tree_lookup(tree);
386
123k
    Properties properties = Properties(num_props);
387
123k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
123k
    JXL_ASSIGN_OR_RETURN(
389
123k
        Channel references,
390
123k
        Channel::Create(memory_manager,
391
123k
                        properties.size() - kNumNonrefProperties, channel.w));
392
5.17M
    for (size_t y = 0; y < channel.h; y++) {
393
5.04M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
5.04M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
5.04M
      InitPropsRow(&properties, static_props, y);
396
5.04M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
13.2M
        for (size_t x = 0; x < 2; x++) {
398
8.83M
          PredictionResult res =
399
8.83M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
8.83M
                              tree_lookup, references);
401
8.83M
          uint64_t v =
402
8.83M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
8.83M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
8.83M
        }
405
306M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
301M
          PredictionResult res =
407
301M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
301M
                                 tree_lookup, references);
409
301M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
301M
              res.context, br);
411
301M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
301M
        }
413
13.2M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
8.83M
          PredictionResult res =
415
8.83M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
8.83M
                              tree_lookup, references);
417
8.83M
          uint64_t v =
418
8.83M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
8.83M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
8.83M
        }
421
4.41M
      } else {
422
18.7M
        for (size_t x = 0; x < channel.w; x++) {
423
18.1M
          PredictionResult res =
424
18.1M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
18.1M
                              tree_lookup, references);
426
18.1M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
18.1M
              res.context, br);
428
18.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
18.1M
        }
430
630k
      }
431
5.04M
    }
432
123k
  } else {
433
24.7k
    JXL_DEBUG_V(8, "Slowest track.");
434
24.7k
    MATreeLookup tree_lookup(tree);
435
24.7k
    Properties properties = Properties(num_props);
436
24.7k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
24.7k
    JXL_ASSIGN_OR_RETURN(
438
24.7k
        Channel references,
439
24.7k
        Channel::Create(memory_manager,
440
24.7k
                        properties.size() - kNumNonrefProperties, channel.w));
441
24.7k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
1.43M
    for (size_t y = 0; y < channel.h; y++) {
443
1.41M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
1.41M
      InitPropsRow(&properties, static_props, y);
445
1.41M
      PrecomputeReferences(channel, y, *image, chan, &references);
446
1.41M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
1.47M
        for (size_t x = 0; x < 2; x++) {
448
981k
          PredictionResult res =
449
981k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
981k
                            tree_lookup, references, &wp_state);
451
981k
          uint64_t v =
452
981k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
981k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
981k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
981k
        }
456
72.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
72.1M
          PredictionResult res =
458
72.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
72.1M
                               tree_lookup, references, &wp_state);
460
72.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
72.1M
              res.context, br);
462
72.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
72.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
72.1M
        }
465
1.47M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
981k
          PredictionResult res =
467
981k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
981k
                            tree_lookup, references, &wp_state);
469
981k
          uint64_t v =
470
981k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
981k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
981k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
981k
        }
474
920k
      } else {
475
11.8M
        for (size_t x = 0; x < channel.w; x++) {
476
10.9M
          PredictionResult res =
477
10.9M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
10.9M
                            tree_lookup, references, &wp_state);
479
10.9M
          uint64_t v =
480
10.9M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
10.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
10.9M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
10.9M
        }
484
920k
      }
485
1.41M
    }
486
24.7k
  }
487
160k
  return true;
488
160k
}
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
89.5k
                                 uint32_t &fl_v) {
157
89.5k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
89.5k
  Channel &channel = image->channel[chan];
159
160
89.5k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
89.5k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
89.5k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
89.5k
  bool tree_has_wp_prop_or_pred = false;
168
89.5k
  bool is_wp_only = false;
169
89.5k
  bool is_gradient_only = false;
170
89.5k
  size_t num_props;
171
89.5k
  FlatTree tree =
172
89.5k
      FilterTree(global_tree, static_props, &num_props,
173
89.5k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
107k
  for (auto &node : tree) {
178
107k
    if (node.property0 == -1) {
179
102k
      node.childID = context_map[node.childID];
180
102k
    }
181
107k
  }
182
183
89.5k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
89.5k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
89.5k
                             pixel_type_w offset) -> pixel_type {
188
89.5k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
89.5k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
89.5k
    return val * multiplier + offset;
192
89.5k
  };
193
194
89.5k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
85.7k
    Predictor predictor = tree[0].predictor;
198
85.7k
    int64_t offset = tree[0].predictor_offset;
199
85.7k
    int32_t multiplier = tree[0].multiplier;
200
85.7k
    size_t ctx_id = tree[0].childID;
201
85.7k
    if (predictor == Predictor::Zero) {
202
66.6k
      uint32_t value;
203
66.6k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
66.6k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
20.3k
        JXL_DEBUG_V(8, "Fastest track.");
208
20.3k
        pixel_type v = make_pixel(value, multiplier, offset);
209
603k
        for (size_t y = 0; y < channel.h; y++) {
210
583k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
583k
          std::fill(r, r + channel.w, v);
212
583k
        }
213
46.2k
      } else {
214
46.2k
        JXL_DEBUG_V(8, "Fast track.");
215
46.2k
        if (multiplier == 1 && offset == 0) {
216
969k
          for (size_t y = 0; y < channel.h; y++) {
217
932k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
30.8M
            for (size_t x = 0; x < channel.w; x++) {
219
29.8M
              uint32_t v =
220
29.8M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
29.8M
              r[x] = UnpackSigned(v);
222
29.8M
            }
223
932k
          }
224
37.4k
        } else {
225
191k
          for (size_t y = 0; y < channel.h; y++) {
226
182k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
9.49M
            for (size_t x = 0; x < channel.w; x++) {
228
9.31M
              uint32_t v =
229
9.31M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
9.31M
                                                                         br);
231
9.31M
              r[x] = make_pixel(v, multiplier, offset);
232
9.31M
            }
233
182k
          }
234
8.82k
        }
235
46.2k
      }
236
66.6k
      return true;
237
66.6k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
2.75k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
410
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
410
      pixel_type_w sv = UnpackSigned(fl_v);
241
5.94k
      for (size_t y = 0; y < channel.h; y++) {
242
5.53k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
5.53k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
5.53k
        const pixel_type *JXL_RESTRICT rtopleft =
245
5.53k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
5.53k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
5.53k
        if (fl_run == 0) {
248
5.53k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.53k
                                                     &fl_run);
250
5.53k
          sv = UnpackSigned(fl_v);
251
5.53k
        } else {
252
0
          fl_run--;
253
0
        }
254
5.53k
        r[0] = sv + guess_0;
255
215k
        for (size_t x = 1; x < channel.w; x++) {
256
209k
          pixel_type left = r[x - 1];
257
209k
          pixel_type top = rtop[x];
258
209k
          pixel_type topleft = rtopleft[x];
259
209k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
209k
          if (!fl_run) {
261
209k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
209k
                                                       &fl_run);
263
209k
            sv = UnpackSigned(fl_v);
264
209k
          } else {
265
0
            fl_run--;
266
0
          }
267
209k
          r[x] = sv + guess;
268
209k
        }
269
5.53k
      }
270
410
      return true;
271
18.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
2.34k
               multiplier == 1) {
273
1.92k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.92k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
37.0k
      for (size_t y = 0; y < channel.h; y++) {
276
35.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.56M
        for (size_t x = 0; x < channel.w; x++) {
278
2.53M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.53M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.53M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.53M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.53M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.53M
              ctx_id, br);
284
2.53M
          r[x] = make_pixel(v, 1, guess);
285
2.53M
        }
286
35.1k
      }
287
1.92k
      return true;
288
1.92k
    }
289
85.7k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
20.5k
  if (is_wp_only) {
294
1.48k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
1.48k
  }
296
20.5k
  if (is_gradient_only) {
297
1.52k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.52k
  }
299
300
20.5k
  if (is_gradient_only) {
301
134
    JXL_DEBUG_V(8, "Gradient fast track.");
302
134
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
5.11k
    for (size_t y = 0; y < channel.h; y++) {
304
4.98k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
520k
      for (size_t x = 0; x < channel.w; x++) {
306
515k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
515k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
515k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
515k
        int32_t guess = ClampedGradient(top, left, topleft);
310
515k
        uint32_t pos =
311
515k
            kPropRangeFast +
312
515k
            std::min<pixel_type_w>(
313
515k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
515k
                kPropRangeFast - 1);
315
515k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
515k
        uint64_t v =
317
515k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
515k
        r[x] = make_pixel(v, 1, guess);
319
515k
      }
320
4.98k
    }
321
20.4k
  } 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
20.4k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
17.4k
    JXL_DEBUG_V(8, "Slow track.");
385
17.4k
    MATreeLookup tree_lookup(tree);
386
17.4k
    Properties properties = Properties(num_props);
387
17.4k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
17.4k
    JXL_ASSIGN_OR_RETURN(
389
17.4k
        Channel references,
390
17.4k
        Channel::Create(memory_manager,
391
17.4k
                        properties.size() - kNumNonrefProperties, channel.w));
392
1.38M
    for (size_t y = 0; y < channel.h; y++) {
393
1.36M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
1.36M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
1.36M
      InitPropsRow(&properties, static_props, y);
396
1.36M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
3.90M
        for (size_t x = 0; x < 2; x++) {
398
2.60M
          PredictionResult res =
399
2.60M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
2.60M
                              tree_lookup, references);
401
2.60M
          uint64_t v =
402
2.60M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
2.60M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
2.60M
        }
405
91.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
90.0M
          PredictionResult res =
407
90.0M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
90.0M
                                 tree_lookup, references);
409
90.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
90.0M
              res.context, br);
411
90.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
90.0M
        }
413
3.90M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
2.60M
          PredictionResult res =
415
2.60M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
2.60M
                              tree_lookup, references);
417
2.60M
          uint64_t v =
418
2.60M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
2.60M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
2.60M
        }
421
1.30M
      } else {
422
4.75M
        for (size_t x = 0; x < channel.w; x++) {
423
4.69M
          PredictionResult res =
424
4.69M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
4.69M
                              tree_lookup, references);
426
4.69M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
4.69M
              res.context, br);
428
4.69M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
4.69M
        }
430
63.6k
      }
431
1.36M
    }
432
17.4k
  } else {
433
2.99k
    JXL_DEBUG_V(8, "Slowest track.");
434
2.99k
    MATreeLookup tree_lookup(tree);
435
2.99k
    Properties properties = Properties(num_props);
436
2.99k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
2.99k
    JXL_ASSIGN_OR_RETURN(
438
2.99k
        Channel references,
439
2.99k
        Channel::Create(memory_manager,
440
2.99k
                        properties.size() - kNumNonrefProperties, channel.w));
441
2.99k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
64.1k
    for (size_t y = 0; y < channel.h; y++) {
443
61.1k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
61.1k
      InitPropsRow(&properties, static_props, y);
445
61.1k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
61.1k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
0
        for (size_t x = 0; x < 2; x++) {
448
0
          PredictionResult res =
449
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
0
                            tree_lookup, references, &wp_state);
451
0
          uint64_t v =
452
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
0
        }
456
0
        for (size_t x = 2; x < channel.w - 2; x++) {
457
0
          PredictionResult res =
458
0
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
0
                               tree_lookup, references, &wp_state);
460
0
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
0
              res.context, br);
462
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
0
        }
465
0
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
0
          PredictionResult res =
467
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
0
                            tree_lookup, references, &wp_state);
469
0
          uint64_t v =
470
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
0
        }
474
61.1k
      } else {
475
3.85M
        for (size_t x = 0; x < channel.w; x++) {
476
3.79M
          PredictionResult res =
477
3.79M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
3.79M
                            tree_lookup, references, &wp_state);
479
3.79M
          uint64_t v =
480
3.79M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
3.79M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
3.79M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
3.79M
        }
484
61.1k
      }
485
61.1k
    }
486
2.99k
  }
487
20.5k
  return true;
488
20.5k
}
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
562k
                                 uint32_t &fl_v) {
157
562k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
562k
  Channel &channel = image->channel[chan];
159
160
562k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
562k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
562k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
562k
  bool tree_has_wp_prop_or_pred = false;
168
562k
  bool is_wp_only = false;
169
562k
  bool is_gradient_only = false;
170
562k
  size_t num_props;
171
562k
  FlatTree tree =
172
562k
      FilterTree(global_tree, static_props, &num_props,
173
562k
                 &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
1.25M
  for (auto &node : tree) {
178
1.25M
    if (node.property0 == -1) {
179
1.08M
      node.childID = context_map[node.childID];
180
1.08M
    }
181
1.25M
  }
182
183
562k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
562k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
562k
                             pixel_type_w offset) -> pixel_type {
188
562k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
562k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
562k
    return val * multiplier + offset;
192
562k
  };
193
194
562k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
525k
    Predictor predictor = tree[0].predictor;
198
525k
    int64_t offset = tree[0].predictor_offset;
199
525k
    int32_t multiplier = tree[0].multiplier;
200
525k
    size_t ctx_id = tree[0].childID;
201
525k
    if (predictor == Predictor::Zero) {
202
415k
      uint32_t value;
203
415k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
415k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
56.3k
        JXL_DEBUG_V(8, "Fastest track.");
208
56.3k
        pixel_type v = make_pixel(value, multiplier, offset);
209
1.07M
        for (size_t y = 0; y < channel.h; y++) {
210
1.01M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
1.01M
          std::fill(r, r + channel.w, v);
212
1.01M
        }
213
359k
      } else {
214
359k
        JXL_DEBUG_V(8, "Fast track.");
215
359k
        if (multiplier == 1 && offset == 0) {
216
4.91M
          for (size_t y = 0; y < channel.h; y++) {
217
4.57M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
245M
            for (size_t x = 0; x < channel.w; x++) {
219
240M
              uint32_t v =
220
240M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
240M
              r[x] = UnpackSigned(v);
222
240M
            }
223
4.57M
          }
224
342k
        } else {
225
324k
          for (size_t y = 0; y < channel.h; y++) {
226
307k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
17.0M
            for (size_t x = 0; x < channel.w; x++) {
228
16.7M
              uint32_t v =
229
16.7M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
16.7M
                                                                         br);
231
16.7M
              r[x] = make_pixel(v, multiplier, offset);
232
16.7M
            }
233
307k
          }
234
17.0k
        }
235
359k
      }
236
415k
      return true;
237
415k
    } 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
109k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
6.68k
               multiplier == 1) {
273
5.94k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
5.94k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
138k
      for (size_t y = 0; y < channel.h; y++) {
276
132k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.93M
        for (size_t x = 0; x < channel.w; x++) {
278
2.80M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.80M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.80M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.80M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.80M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.80M
              ctx_id, br);
284
2.80M
          r[x] = make_pixel(v, 1, guess);
285
2.80M
        }
286
132k
      }
287
5.94k
      return true;
288
5.94k
    }
289
525k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
140k
  if (is_wp_only) {
294
16.1k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
16.1k
  }
296
140k
  if (is_gradient_only) {
297
5.67k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
5.67k
  }
299
300
140k
  if (is_gradient_only) {
301
4.07k
    JXL_DEBUG_V(8, "Gradient fast track.");
302
4.07k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
199k
    for (size_t y = 0; y < channel.h; y++) {
304
195k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
3.36M
      for (size_t x = 0; x < channel.w; x++) {
306
3.16M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
3.16M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
3.16M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
3.16M
        int32_t guess = ClampedGradient(top, left, topleft);
310
3.16M
        uint32_t pos =
311
3.16M
            kPropRangeFast +
312
3.16M
            std::min<pixel_type_w>(
313
3.16M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
3.16M
                kPropRangeFast - 1);
315
3.16M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
3.16M
        uint64_t v =
317
3.16M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
3.16M
        r[x] = make_pixel(v, 1, guess);
319
3.16M
      }
320
195k
    }
321
136k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
8.29k
    JXL_DEBUG_V(8, "WP fast track.");
323
8.29k
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
8.29k
    Properties properties(1);
325
286k
    for (size_t y = 0; y < channel.h; y++) {
326
278k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
278k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
278k
      const pixel_type *JXL_RESTRICT rtoptop =
329
278k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
278k
      const pixel_type *JXL_RESTRICT rtopleft =
331
278k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
278k
      const pixel_type *JXL_RESTRICT rtopright =
333
278k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
278k
      size_t x = 0;
335
278k
      {
336
278k
        size_t offset = 0;
337
278k
        pixel_type_w left = y ? rtop[x] : 0;
338
278k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
278k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
278k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
278k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
278k
            offset);
343
278k
        uint32_t pos =
344
278k
            kPropRangeFast +
345
278k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
278k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
278k
        uint64_t v =
348
278k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
278k
        r[x] = make_pixel(v, 1, guess);
350
278k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
278k
      }
352
13.7M
      for (x = 1; x + 1 < channel.w; x++) {
353
13.4M
        size_t offset = 0;
354
13.4M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
13.4M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
13.4M
            rtoptop[x], &properties, offset);
357
13.4M
        uint32_t pos =
358
13.4M
            kPropRangeFast +
359
13.4M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
13.4M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
13.4M
        uint64_t v =
362
13.4M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
13.4M
        r[x] = make_pixel(v, 1, guess);
364
13.4M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
13.4M
      }
366
278k
      {
367
278k
        size_t offset = 0;
368
278k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
278k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
278k
            rtoptop[x], &properties, offset);
371
278k
        uint32_t pos =
372
278k
            kPropRangeFast +
373
278k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
278k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
278k
        uint64_t v =
376
278k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
278k
        r[x] = make_pixel(v, 1, guess);
378
278k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
278k
      }
380
278k
    }
381
127k
  } 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
106k
    JXL_DEBUG_V(8, "Slow track.");
385
106k
    MATreeLookup tree_lookup(tree);
386
106k
    Properties properties = Properties(num_props);
387
106k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
106k
    JXL_ASSIGN_OR_RETURN(
389
106k
        Channel references,
390
106k
        Channel::Create(memory_manager,
391
106k
                        properties.size() - kNumNonrefProperties, channel.w));
392
3.78M
    for (size_t y = 0; y < channel.h; y++) {
393
3.68M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
3.68M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
3.68M
      InitPropsRow(&properties, static_props, y);
396
3.68M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
9.34M
        for (size_t x = 0; x < 2; x++) {
398
6.22M
          PredictionResult res =
399
6.22M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
6.22M
                              tree_lookup, references);
401
6.22M
          uint64_t v =
402
6.22M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
6.22M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
6.22M
        }
405
214M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
211M
          PredictionResult res =
407
211M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
211M
                                 tree_lookup, references);
409
211M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
211M
              res.context, br);
411
211M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
211M
        }
413
9.34M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
6.22M
          PredictionResult res =
415
6.22M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
6.22M
                              tree_lookup, references);
417
6.22M
          uint64_t v =
418
6.22M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
6.22M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
6.22M
        }
421
3.11M
      } else {
422
14.0M
        for (size_t x = 0; x < channel.w; x++) {
423
13.4M
          PredictionResult res =
424
13.4M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
13.4M
                              tree_lookup, references);
426
13.4M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
13.4M
              res.context, br);
428
13.4M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
13.4M
        }
430
566k
      }
431
3.68M
    }
432
106k
  } else {
433
21.7k
    JXL_DEBUG_V(8, "Slowest track.");
434
21.7k
    MATreeLookup tree_lookup(tree);
435
21.7k
    Properties properties = Properties(num_props);
436
21.7k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
21.7k
    JXL_ASSIGN_OR_RETURN(
438
21.7k
        Channel references,
439
21.7k
        Channel::Create(memory_manager,
440
21.7k
                        properties.size() - kNumNonrefProperties, channel.w));
441
21.7k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
1.37M
    for (size_t y = 0; y < channel.h; y++) {
443
1.35M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
1.35M
      InitPropsRow(&properties, static_props, y);
445
1.35M
      PrecomputeReferences(channel, y, *image, chan, &references);
446
1.35M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
1.47M
        for (size_t x = 0; x < 2; x++) {
448
981k
          PredictionResult res =
449
981k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
981k
                            tree_lookup, references, &wp_state);
451
981k
          uint64_t v =
452
981k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
981k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
981k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
981k
        }
456
72.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
72.1M
          PredictionResult res =
458
72.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
72.1M
                               tree_lookup, references, &wp_state);
460
72.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
72.1M
              res.context, br);
462
72.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
72.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
72.1M
        }
465
1.47M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
981k
          PredictionResult res =
467
981k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
981k
                            tree_lookup, references, &wp_state);
469
981k
          uint64_t v =
470
981k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
981k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
981k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
981k
        }
474
859k
      } else {
475
7.96M
        for (size_t x = 0; x < channel.w; x++) {
476
7.10M
          PredictionResult res =
477
7.10M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
7.10M
                            tree_lookup, references, &wp_state);
479
7.10M
          uint64_t v =
480
7.10M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
7.10M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
7.10M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
7.10M
        }
484
859k
      }
485
1.35M
    }
486
21.7k
  }
487
140k
  return true;
488
140k
}
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
651k
                                 uint32_t &fl_v) {
499
651k
  if (reader->UsesLZ77()) {
500
89.5k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
89.5k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
89.5k
        tree_lut, image, fl_run, fl_v);
503
562k
  } else {
504
562k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
562k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
562k
        tree_lut, image, fl_run, fl_v);
507
562k
  }
508
651k
}
509
510
621k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
134k
                                 const ModularOptions &options) {
514
134k
  size_t nb_channels = image.channel.size();
515
269k
  for (bool is_dc : {true, false}) {
516
269k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
269k
    size_t c = image.nb_meta_channels;
518
1.81M
    for (; c < nb_channels; c++) {
519
1.55M
      const Channel &ch = image.channel[c];
520
1.55M
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
1.55M
    }
522
317k
    for (; c < nb_channels; c++) {
523
48.0k
      const Channel &ch = image.channel[c];
524
48.0k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
47.1k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
47.1k
      if (is_dc_channel != is_dc) continue;
527
23.5k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
23.5k
      if (tile_dim == 0) {
529
7
        return JXL_FAILURE("Inconsistent transforms");
530
7
      }
531
23.5k
    }
532
269k
  }
533
134k
  return true;
534
134k
}
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
218k
                     const bool allow_truncated_group) {
541
218k
  if (image.channel.empty()) return true;
542
153k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
153k
  Status status = Bundle::Read(br, &header);
546
153k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
134k
  if (status.IsFatalError()) return status;
548
134k
  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
134k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
134k
              header.transforms.size());
560
134k
  image.transform = header.transforms;
561
134k
  for (Transform &transform : image.transform) {
562
39.2k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
39.2k
  }
564
132k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
132k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
132k
  size_t nb_channels = image.channel.size();
570
571
132k
  size_t num_chans = 0;
572
132k
  size_t distance_multiplier = 0;
573
906k
  for (size_t i = 0; i < nb_channels; i++) {
574
777k
    Channel &channel = image.channel[i];
575
777k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
769k
                                        channel.h > options->max_chan_size)) {
577
2.99k
      break;
578
2.99k
    }
579
774k
    if (!channel.w || !channel.h) {
580
28.7k
      continue;  // skip empty channels
581
28.7k
    }
582
745k
    if (channel.w > distance_multiplier) {
583
172k
      distance_multiplier = channel.w;
584
172k
    }
585
745k
    num_chans++;
586
745k
  }
587
132k
  if (num_chans == 0) return true;
588
589
131k
  size_t next_channel = 0;
590
131k
  auto scope_guard = MakeScopeGuard([&]() {
591
130k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
103k
      ZeroFillImage(&image.channel[c].plane);
593
103k
    }
594
26.9k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
131k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
131k
  Tree tree_storage;
600
131k
  std::vector<uint8_t> context_map_storage;
601
131k
  ANSCode code_storage;
602
131k
  const Tree *tree = &tree_storage;
603
131k
  const ANSCode *code = &code_storage;
604
131k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
131k
  if (!header.use_global_tree) {
606
86.9k
    uint64_t max_tree_size = 1024;
607
518k
    for (size_t i = 0; i < nb_channels; i++) {
608
431k
      Channel &channel = image.channel[i];
609
431k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
428k
                                          channel.h > options->max_chan_size)) {
611
107
        break;
612
107
      }
613
431k
      uint64_t pixels = channel.w * channel.h;
614
431k
      max_tree_size += pixels;
615
431k
    }
616
86.9k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
86.9k
    JXL_RETURN_IF_ERROR(
618
86.9k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
69.1k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
69.1k
                                         (tree_storage.size() + 1) / 2,
621
69.1k
                                         &code_storage, &context_map_storage));
622
69.1k
  } else {
623
44.3k
    if (!global_tree || !global_code || !global_ctx_map ||
624
44.3k
        global_tree->empty()) {
625
1.46k
      return JXL_FAILURE("No global tree available but one was requested");
626
1.46k
    }
627
42.9k
    tree = global_tree;
628
42.9k
    code = global_code;
629
42.9k
    context_map = global_ctx_map;
630
42.9k
  }
631
632
  // Read channels
633
222k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
222k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
222k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
222k
  uint32_t fl_run = 0;
637
222k
  uint32_t fl_v = 0;
638
783k
  for (; next_channel < nb_channels; next_channel++) {
639
680k
    Channel &channel = image.channel[next_channel];
640
680k
    if (next_channel >= image.nb_meta_channels &&
641
674k
        (channel.w > options->max_chan_size ||
642
673k
         channel.h > options->max_chan_size)) {
643
1.94k
      break;
644
1.94k
    }
645
678k
    if (!channel.w || !channel.h) {
646
27.1k
      continue;  // skip empty channels
647
27.1k
    }
648
651k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
651k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
651k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
651k
    if (!br->AllReadsWithinBounds()) {
654
6.58k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
6.58k
    }
657
651k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
104k
  scope_guard.Disarm();
661
662
104k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
104k
  return true;
666
104k
}
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
218k
                                bool allow_truncated_group) {
674
218k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
218k
  req_sizes.reserve(image.channel.size());
676
522k
  for (const auto &c : image.channel) {
677
522k
    req_sizes.emplace_back(c.w, c.h);
678
522k
  }
679
218k
  GroupHeader local_header;
680
218k
  if (header == nullptr) header = &local_header;
681
218k
  size_t bit_pos = br->TotalBitsConsumed();
682
218k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
218k
                                  code, ctx_map, allow_truncated_group);
684
218k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
169k
  if (dec_status.IsFatalError()) return dec_status;
686
169k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
169k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
169k
  JXL_DEBUG_V(4,
689
169k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
169k
              " image from %" PRIuS " bytes",
691
169k
              image.w, image.h, image.channel.size(),
692
169k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
169k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
169k
  (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
169k
  if (undo_transforms) {
699
65.6k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
299k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
233k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
233k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
233k
    }
704
65.6k
  }
705
169k
  return dec_status;
706
169k
}
707
708
}  // namespace jxl