Coverage Report

Created: 2026-09-13 07:02

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
439k
                    bool *gradient_only) {
46
439k
  *num_props = 0;
47
439k
  bool has_wp = false;
48
439k
  bool has_non_wp = false;
49
439k
  *gradient_only = true;
50
1.26M
  const auto mark_property = [&](int32_t p) {
51
1.26M
    if (p == kWPProp) {
52
128k
      has_wp = true;
53
1.13M
    } else if (p >= kNumStaticProperties) {
54
688k
      has_non_wp = true;
55
688k
    }
56
1.26M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
734k
      *gradient_only = false;
58
734k
    }
59
1.26M
  };
60
439k
  FlatTree output;
61
439k
  std::queue<size_t> nodes;
62
439k
  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.56M
  while (!nodes.empty()) {
70
2.12M
    size_t cur = nodes.front();
71
2.12M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
2.18M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.76M
           global_tree[cur].property != -1) {
75
63.6k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
33.0k
        cur = global_tree[cur].lchild;
77
33.0k
      } else {
78
30.6k
        cur = global_tree[cur].rchild;
79
30.6k
      }
80
63.6k
    }
81
2.12M
    FlatDecisionNode flat;
82
2.12M
    if (global_tree[cur].property == -1) {
83
1.70M
      flat.property0 = -1;
84
1.70M
      flat.childID = global_tree[cur].lchild;
85
1.70M
      flat.predictor = global_tree[cur].predictor;
86
1.70M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.70M
      flat.multiplier = global_tree[cur].multiplier;
88
1.70M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.70M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.70M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.70M
      output.push_back(flat);
92
1.70M
      continue;
93
1.70M
    }
94
420k
    flat.childID = output.size() + nodes.size() + 1;
95
96
420k
    flat.property0 = global_tree[cur].property;
97
420k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
420k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.26M
    for (size_t i = 0; i < 2; i++) {
101
841k
      size_t cur_child =
102
841k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
864k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
468k
             global_tree[cur_child].property != -1) {
106
22.8k
        if (static_props[global_tree[cur_child].property] >
107
22.8k
            global_tree[cur_child].splitval) {
108
11.1k
          cur_child = global_tree[cur_child].lchild;
109
11.6k
        } else {
110
11.6k
          cur_child = global_tree[cur_child].rchild;
111
11.6k
        }
112
22.8k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
841k
      if (global_tree[cur_child].property == -1) {
116
446k
        flat.properties[i] = 0;
117
446k
        flat.splitvals[i] = 0;
118
446k
        nodes.push(cur_child);
119
446k
        nodes.push(cur_child);
120
446k
      } else {
121
395k
        flat.properties[i] = global_tree[cur_child].property;
122
395k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
395k
        nodes.push(global_tree[cur_child].lchild);
124
395k
        nodes.push(global_tree[cur_child].rchild);
125
395k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
395k
      }
127
841k
    }
128
129
841k
    for (int16_t property : flat.properties) mark_property(property);
130
420k
    mark_property(flat.property0);
131
420k
    output.push_back(flat);
132
420k
  }
133
439k
  if (*num_props > kNumNonrefProperties) {
134
1.75k
    *num_props =
135
1.75k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.75k
            kExtraPropsPerChannel +
137
1.75k
        kNumNonrefProperties;
138
437k
  } else {
139
437k
    *num_props = kNumNonrefProperties;
140
437k
  }
141
439k
  *use_wp = has_wp;
142
439k
  *wp_only = has_wp && !has_non_wp;
143
144
439k
  return output;
145
439k
}
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
412k
                                 uint32_t &fl_v) {
157
412k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
412k
  Channel &channel = image->channel[chan];
159
160
412k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
412k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
412k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
412k
  bool tree_has_wp_prop_or_pred = false;
168
412k
  bool is_wp_only = false;
169
412k
  bool is_gradient_only = false;
170
412k
  size_t num_props;
171
412k
  FlatTree tree =
172
412k
      FilterTree(global_tree, static_props, &num_props,
173
412k
                 &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
585k
  for (auto &node : tree) {
178
585k
    if (node.property0 == -1) {
179
541k
      node.childID = context_map[node.childID];
180
541k
    }
181
585k
  }
182
183
412k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
412k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
268M
                             pixel_type_w offset) -> pixel_type {
188
268M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
268M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
268M
    return val * multiplier + offset;
192
268M
  };
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
57.6M
                             pixel_type_w offset) -> pixel_type {
188
57.6M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
57.6M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
57.6M
    return val * multiplier + offset;
192
57.6M
  };
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
211M
                             pixel_type_w offset) -> pixel_type {
188
211M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
211M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
211M
    return val * multiplier + offset;
192
211M
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
412k
  const bool global_tree_is_all_gradient_noop = [&] {
200
417k
    for (const auto& n : global_tree) {
201
417k
      if (n.property == -1) {
202
403k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
4.24k
            n.multiplier != 1)
204
399k
          return false;
205
403k
      } else if (n.property >= kNumStaticProperties) {
206
10.1k
        return false;
207
10.1k
      }
208
417k
    }
209
2.26k
    return true;
210
412k
  }();
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()#1}::operator()() const
Line
Count
Source
199
37.3k
  const bool global_tree_is_all_gradient_noop = [&] {
200
37.5k
    for (const auto& n : global_tree) {
201
37.5k
      if (n.property == -1) {
202
35.3k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
1.42k
            n.multiplier != 1)
204
34.1k
          return false;
205
35.3k
      } else if (n.property >= kNumStaticProperties) {
206
1.96k
        return false;
207
1.96k
      }
208
37.5k
    }
209
1.17k
    return true;
210
37.3k
  }();
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()#1}::operator()() const
Line
Count
Source
199
374k
  const bool global_tree_is_all_gradient_noop = [&] {
200
380k
    for (const auto& n : global_tree) {
201
380k
      if (n.property == -1) {
202
368k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
2.82k
            n.multiplier != 1)
204
365k
          return false;
205
368k
      } else if (n.property >= kNumStaticProperties) {
206
8.15k
        return false;
207
8.15k
      }
208
380k
    }
209
1.08k
    return true;
210
374k
  }();
211
212
412k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
402k
    Predictor predictor = tree[0].predictor;
216
402k
    int64_t offset = tree[0].predictor_offset;
217
402k
    int32_t multiplier = tree[0].multiplier;
218
402k
    size_t ctx_id = tree[0].childID;
219
402k
    if (predictor == Predictor::Zero) {
220
380k
      uint32_t value;
221
380k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
380k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
175k
        JXL_DEBUG_V(8, "Fastest track.");
226
175k
        pixel_type v = make_pixel(value, multiplier, offset);
227
5.28M
        for (size_t y = 0; y < channel.h; y++) {
228
5.10M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
5.10M
          std::fill(r, r + channel.w, v);
230
5.10M
        }
231
205k
      } else {
232
205k
        JXL_DEBUG_V(8, "Fast track.");
233
205k
        if (multiplier == 1 && offset == 0) {
234
3.14M
          for (size_t y = 0; y < channel.h; y++) {
235
2.97M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
240M
            for (size_t x = 0; x < channel.w; x++) {
237
237M
              uint32_t v =
238
237M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
237M
              r[x] = UnpackSigned(v);
240
237M
            }
241
2.97M
          }
242
167k
        } else {
243
1.61M
          for (size_t y = 0; y < channel.h; y++) {
244
1.57M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
173M
            for (size_t x = 0; x < channel.w; x++) {
246
171M
              uint32_t v =
247
171M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
171M
                                                                         br);
249
171M
              r[x] = make_pixel(v, multiplier, offset);
250
171M
            }
251
1.57M
          }
252
37.8k
        }
253
205k
      }
254
380k
      return true;
255
380k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
745
               global_tree_is_all_gradient_noop) {
257
592
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
592
      pixel_type_w sv = UnpackSigned(fl_v);
259
19.8k
      for (size_t y = 0; y < channel.h; y++) {
260
19.2k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
19.2k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
19.2k
        const pixel_type *JXL_RESTRICT rtopleft =
263
19.2k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
19.2k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
19.2k
        if (fl_run == 0) {
266
5.04k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.04k
                                                     &fl_run);
268
5.04k
          sv = UnpackSigned(fl_v);
269
14.2k
        } else {
270
14.2k
          fl_run--;
271
14.2k
        }
272
19.2k
        r[0] = sv + guess_0;
273
515k
        for (size_t x = 1; x < channel.w; x++) {
274
495k
          pixel_type left = r[x - 1];
275
495k
          pixel_type top = rtop[x];
276
495k
          pixel_type topleft = rtopleft[x];
277
495k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
495k
          if (!fl_run) {
279
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
119k
                                                       &fl_run);
281
119k
            sv = UnpackSigned(fl_v);
282
375k
          } else {
283
375k
            fl_run--;
284
375k
          }
285
495k
          r[x] = sv + guess;
286
495k
        }
287
19.2k
      }
288
592
      return true;
289
21.3k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
2.43k
               multiplier == 1) {
291
2.06k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
2.06k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
50.6k
      for (size_t y = 0; y < channel.h; y++) {
294
48.5k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
2.81M
        for (size_t x = 0; x < channel.w; x++) {
296
2.76M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.76M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.76M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.76M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.76M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.76M
              ctx_id, br);
302
2.76M
          r[x] = make_pixel(v, 1, guess);
303
2.76M
        }
304
48.5k
      }
305
2.06k
      return true;
306
2.06k
    }
307
402k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
28.9k
  if (is_wp_only) {
312
4.07k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
4.07k
  }
314
28.9k
  if (is_gradient_only) {
315
1.46k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.46k
  }
317
318
28.9k
  if (is_gradient_only) {
319
671
    JXL_DEBUG_V(8, "Gradient fast track.");
320
671
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
17.1k
    for (size_t y = 0; y < channel.h; y++) {
322
16.4k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
1.03M
      for (size_t x = 0; x < channel.w; x++) {
324
1.02M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
1.02M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
1.02M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
1.02M
        int32_t guess = ClampedGradient(top, left, topleft);
328
1.02M
        uint32_t pos =
329
1.02M
            kPropRangeFast +
330
1.02M
            std::min<pixel_type_w>(
331
1.02M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
1.02M
                kPropRangeFast - 1);
333
1.02M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
1.02M
        uint64_t v =
335
1.02M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
1.02M
        r[x] = make_pixel(v, 1, guess);
337
1.02M
      }
338
16.4k
    }
339
28.3k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
807
    JXL_DEBUG_V(8, "WP fast track.");
341
807
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
807
    Properties properties(1);
343
22.6k
    for (size_t y = 0; y < channel.h; y++) {
344
21.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
21.8k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
21.8k
      const pixel_type *JXL_RESTRICT rtoptop =
347
21.8k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
21.8k
      const pixel_type *JXL_RESTRICT rtopleft =
349
21.8k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
21.8k
      const pixel_type *JXL_RESTRICT rtopright =
351
21.8k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
21.8k
      size_t x = 0;
353
21.8k
      {
354
21.8k
        size_t offset = 0;
355
21.8k
        pixel_type_w left = y ? rtop[x] : 0;
356
21.8k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
21.8k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
21.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
21.8k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
21.8k
            offset);
361
21.8k
        uint32_t pos =
362
21.8k
            kPropRangeFast +
363
21.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
21.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
21.8k
        uint64_t v =
366
21.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
21.8k
        r[x] = make_pixel(v, 1, guess);
368
21.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
21.8k
      }
370
2.84M
      for (x = 1; x + 1 < channel.w; x++) {
371
2.82M
        size_t offset = 0;
372
2.82M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
2.82M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
2.82M
            rtoptop[x], &properties, offset);
375
2.82M
        uint32_t pos =
376
2.82M
            kPropRangeFast +
377
2.82M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
2.82M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
2.82M
        uint64_t v =
380
2.82M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
2.82M
        r[x] = make_pixel(v, 1, guess);
382
2.82M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
2.82M
      }
384
21.8k
      {
385
21.8k
        size_t offset = 0;
386
21.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
21.8k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
21.8k
            rtoptop[x], &properties, offset);
389
21.8k
        uint32_t pos =
390
21.8k
            kPropRangeFast +
391
21.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
21.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
21.8k
        uint64_t v =
394
21.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
21.8k
        r[x] = make_pixel(v, 1, guess);
396
21.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
21.8k
      }
398
21.8k
    }
399
27.5k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
19.6k
    JXL_DEBUG_V(8, "Slow track.");
403
19.6k
    MATreeLookup tree_lookup(tree);
404
19.6k
    Properties properties = Properties(num_props);
405
19.6k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
19.6k
    JXL_ASSIGN_OR_RETURN(
407
19.6k
        Channel references,
408
19.6k
        Channel::Create(memory_manager,
409
19.6k
                        properties.size() - kNumNonrefProperties, channel.w));
410
716k
    for (size_t y = 0; y < channel.h; y++) {
411
696k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
696k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
696k
      InitPropsRow(&properties, static_props, y);
414
696k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.84M
        for (size_t x = 0; x < 2; x++) {
416
1.22M
          PredictionResult res =
417
1.22M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
1.22M
                              tree_lookup, references);
419
1.22M
          uint64_t v =
420
1.22M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
1.22M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
1.22M
        }
423
67.8M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
67.2M
          PredictionResult res =
425
67.2M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
67.2M
                                 tree_lookup, references);
427
67.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
67.2M
              res.context, br);
429
67.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
67.2M
        }
431
1.84M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
1.22M
          PredictionResult res =
433
1.22M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
1.22M
                              tree_lookup, references);
435
1.22M
          uint64_t v =
436
1.22M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
1.22M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
1.22M
        }
439
614k
      } else {
440
2.27M
        for (size_t x = 0; x < channel.w; x++) {
441
2.18M
          PredictionResult res =
442
2.18M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
2.18M
                              tree_lookup, references);
444
2.18M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
2.18M
              res.context, br);
446
2.18M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
2.18M
        }
448
82.4k
      }
449
696k
    }
450
19.6k
  } else {
451
7.84k
    JXL_DEBUG_V(8, "Slowest track.");
452
7.84k
    MATreeLookup tree_lookup(tree);
453
7.84k
    Properties properties = Properties(num_props);
454
7.84k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
7.84k
    JXL_ASSIGN_OR_RETURN(
456
7.84k
        Channel references,
457
7.84k
        Channel::Create(memory_manager,
458
7.84k
                        properties.size() - kNumNonrefProperties, channel.w));
459
7.84k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
244k
    for (size_t y = 0; y < channel.h; y++) {
461
236k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
236k
      InitPropsRow(&properties, static_props, y);
463
236k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
236k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
596k
        for (size_t x = 0; x < 2; x++) {
466
397k
          PredictionResult res =
467
397k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
397k
                            tree_lookup, references, &wp_state);
469
397k
          uint64_t v =
470
397k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
397k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
397k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
397k
        }
474
15.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
15.5M
          PredictionResult res =
476
15.5M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
15.5M
                               tree_lookup, references, &wp_state);
478
15.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
15.5M
              res.context, br);
480
15.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
15.5M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
15.5M
        }
483
596k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
397k
          PredictionResult res =
485
397k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
397k
                            tree_lookup, references, &wp_state);
487
397k
          uint64_t v =
488
397k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
397k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
397k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
397k
        }
492
198k
      } else {
493
1.91M
        for (size_t x = 0; x < channel.w; x++) {
494
1.87M
          PredictionResult res =
495
1.87M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
1.87M
                            tree_lookup, references, &wp_state);
497
1.87M
          uint64_t v =
498
1.87M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
1.87M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
1.87M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
1.87M
        }
502
37.3k
      }
503
236k
    }
504
7.84k
  }
505
28.9k
  return true;
506
28.9k
}
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
37.3k
                                 uint32_t &fl_v) {
157
37.3k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
37.3k
  Channel &channel = image->channel[chan];
159
160
37.3k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
37.3k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
37.3k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
37.3k
  bool tree_has_wp_prop_or_pred = false;
168
37.3k
  bool is_wp_only = false;
169
37.3k
  bool is_gradient_only = false;
170
37.3k
  size_t num_props;
171
37.3k
  FlatTree tree =
172
37.3k
      FilterTree(global_tree, static_props, &num_props,
173
37.3k
                 &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
45.9k
  for (auto &node : tree) {
178
45.9k
    if (node.property0 == -1) {
179
43.7k
      node.childID = context_map[node.childID];
180
43.7k
    }
181
45.9k
  }
182
183
37.3k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
37.3k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
37.3k
                             pixel_type_w offset) -> pixel_type {
188
37.3k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
37.3k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
37.3k
    return val * multiplier + offset;
192
37.3k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
37.3k
  const bool global_tree_is_all_gradient_noop = [&] {
200
37.3k
    for (const auto& n : global_tree) {
201
37.3k
      if (n.property == -1) {
202
37.3k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
37.3k
            n.multiplier != 1)
204
37.3k
          return false;
205
37.3k
      } else if (n.property >= kNumStaticProperties) {
206
37.3k
        return false;
207
37.3k
      }
208
37.3k
    }
209
37.3k
    return true;
210
37.3k
  }();
211
212
37.3k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
35.3k
    Predictor predictor = tree[0].predictor;
216
35.3k
    int64_t offset = tree[0].predictor_offset;
217
35.3k
    int32_t multiplier = tree[0].multiplier;
218
35.3k
    size_t ctx_id = tree[0].childID;
219
35.3k
    if (predictor == Predictor::Zero) {
220
27.7k
      uint32_t value;
221
27.7k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
27.7k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
5.62k
        JXL_DEBUG_V(8, "Fastest track.");
226
5.62k
        pixel_type v = make_pixel(value, multiplier, offset);
227
196k
        for (size_t y = 0; y < channel.h; y++) {
228
190k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
190k
          std::fill(r, r + channel.w, v);
230
190k
        }
231
22.1k
      } else {
232
22.1k
        JXL_DEBUG_V(8, "Fast track.");
233
22.1k
        if (multiplier == 1 && offset == 0) {
234
415k
          for (size_t y = 0; y < channel.h; y++) {
235
409k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
72.7M
            for (size_t x = 0; x < channel.w; x++) {
237
72.3M
              uint32_t v =
238
72.3M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
72.3M
              r[x] = UnpackSigned(v);
240
72.3M
            }
241
409k
          }
242
15.6k
        } else {
243
471k
          for (size_t y = 0; y < channel.h; y++) {
244
455k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
30.1M
            for (size_t x = 0; x < channel.w; x++) {
246
29.7M
              uint32_t v =
247
29.7M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
29.7M
                                                                         br);
249
29.7M
              r[x] = make_pixel(v, multiplier, offset);
250
29.7M
            }
251
455k
          }
252
15.6k
        }
253
22.1k
      }
254
27.7k
      return true;
255
27.7k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
745
               global_tree_is_all_gradient_noop) {
257
592
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
592
      pixel_type_w sv = UnpackSigned(fl_v);
259
19.8k
      for (size_t y = 0; y < channel.h; y++) {
260
19.2k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
19.2k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
19.2k
        const pixel_type *JXL_RESTRICT rtopleft =
263
19.2k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
19.2k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
19.2k
        if (fl_run == 0) {
266
5.04k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.04k
                                                     &fl_run);
268
5.04k
          sv = UnpackSigned(fl_v);
269
14.2k
        } else {
270
14.2k
          fl_run--;
271
14.2k
        }
272
19.2k
        r[0] = sv + guess_0;
273
515k
        for (size_t x = 1; x < channel.w; x++) {
274
495k
          pixel_type left = r[x - 1];
275
495k
          pixel_type top = rtop[x];
276
495k
          pixel_type topleft = rtopleft[x];
277
495k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
495k
          if (!fl_run) {
279
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
119k
                                                       &fl_run);
281
119k
            sv = UnpackSigned(fl_v);
282
375k
          } else {
283
375k
            fl_run--;
284
375k
          }
285
495k
          r[x] = sv + guess;
286
495k
        }
287
19.2k
      }
288
592
      return true;
289
6.96k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
826
               multiplier == 1) {
291
586
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
586
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
8.37k
      for (size_t y = 0; y < channel.h; y++) {
294
7.79k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
223k
        for (size_t x = 0; x < channel.w; x++) {
296
215k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
215k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
215k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
215k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
215k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
215k
              ctx_id, br);
302
215k
          r[x] = make_pixel(v, 1, guess);
303
215k
        }
304
7.79k
      }
305
586
      return true;
306
586
    }
307
35.3k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
8.34k
  if (is_wp_only) {
312
294
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
294
  }
314
8.34k
  if (is_gradient_only) {
315
526
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
526
  }
317
318
8.34k
  if (is_gradient_only) {
319
92
    JXL_DEBUG_V(8, "Gradient fast track.");
320
92
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
2.99k
    for (size_t y = 0; y < channel.h; y++) {
322
2.89k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
526k
      for (size_t x = 0; x < channel.w; x++) {
324
523k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
523k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
523k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
523k
        int32_t guess = ClampedGradient(top, left, topleft);
328
523k
        uint32_t pos =
329
523k
            kPropRangeFast +
330
523k
            std::min<pixel_type_w>(
331
523k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
523k
                kPropRangeFast - 1);
333
523k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
523k
        uint64_t v =
335
523k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
523k
        r[x] = make_pixel(v, 1, guess);
337
523k
      }
338
2.89k
    }
339
8.25k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
0
    JXL_DEBUG_V(8, "WP fast track.");
341
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
0
    Properties properties(1);
343
0
    for (size_t y = 0; y < channel.h; y++) {
344
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
0
      const pixel_type *JXL_RESTRICT rtoptop =
347
0
          (y > 1 ? channel.Row(y - 2) : rtop);
348
0
      const pixel_type *JXL_RESTRICT rtopleft =
349
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
0
      const pixel_type *JXL_RESTRICT rtopright =
351
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
0
      size_t x = 0;
353
0
      {
354
0
        size_t offset = 0;
355
0
        pixel_type_w left = y ? rtop[x] : 0;
356
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
0
            offset);
361
0
        uint32_t pos =
362
0
            kPropRangeFast +
363
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
0
        uint64_t v =
366
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
0
        r[x] = make_pixel(v, 1, guess);
368
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
0
      }
370
0
      for (x = 1; x + 1 < channel.w; x++) {
371
0
        size_t offset = 0;
372
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
0
            rtoptop[x], &properties, offset);
375
0
        uint32_t pos =
376
0
            kPropRangeFast +
377
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
0
        uint64_t v =
380
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
0
        r[x] = make_pixel(v, 1, guess);
382
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
0
      }
384
0
      {
385
0
        size_t offset = 0;
386
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
0
            rtoptop[x], &properties, offset);
389
0
        uint32_t pos =
390
0
            kPropRangeFast +
391
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
0
        uint64_t v =
394
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
0
        r[x] = make_pixel(v, 1, guess);
396
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
0
      }
398
0
    }
399
8.25k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
7.83k
    JXL_DEBUG_V(8, "Slow track.");
403
7.83k
    MATreeLookup tree_lookup(tree);
404
7.83k
    Properties properties = Properties(num_props);
405
7.83k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
7.83k
    JXL_ASSIGN_OR_RETURN(
407
7.83k
        Channel references,
408
7.83k
        Channel::Create(memory_manager,
409
7.83k
                        properties.size() - kNumNonrefProperties, channel.w));
410
224k
    for (size_t y = 0; y < channel.h; y++) {
411
216k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
216k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
216k
      InitPropsRow(&properties, static_props, y);
414
216k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
570k
        for (size_t x = 0; x < 2; x++) {
416
380k
          PredictionResult res =
417
380k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
380k
                              tree_lookup, references);
419
380k
          uint64_t v =
420
380k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
380k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
380k
        }
423
25.8M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
25.6M
          PredictionResult res =
425
25.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
25.6M
                                 tree_lookup, references);
427
25.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
25.6M
              res.context, br);
429
25.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
25.6M
        }
431
570k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
380k
          PredictionResult res =
433
380k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
380k
                              tree_lookup, references);
435
380k
          uint64_t v =
436
380k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
380k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
380k
        }
439
190k
      } else {
440
580k
        for (size_t x = 0; x < channel.w; x++) {
441
554k
          PredictionResult res =
442
554k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
554k
                              tree_lookup, references);
444
554k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
554k
              res.context, br);
446
554k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
554k
        }
448
26.4k
      }
449
216k
    }
450
7.83k
  } else {
451
414
    JXL_DEBUG_V(8, "Slowest track.");
452
414
    MATreeLookup tree_lookup(tree);
453
414
    Properties properties = Properties(num_props);
454
414
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
414
    JXL_ASSIGN_OR_RETURN(
456
414
        Channel references,
457
414
        Channel::Create(memory_manager,
458
414
                        properties.size() - kNumNonrefProperties, channel.w));
459
414
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
9.24k
    for (size_t y = 0; y < channel.h; y++) {
461
8.83k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
8.83k
      InitPropsRow(&properties, static_props, y);
463
8.83k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
8.83k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
0
        for (size_t x = 0; x < 2; 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
0
        for (size_t x = 2; x < channel.w - 2; x++) {
475
0
          PredictionResult res =
476
0
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
0
                               tree_lookup, references, &wp_state);
478
0
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
0
              res.context, br);
480
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
0
        }
483
0
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
0
          PredictionResult res =
485
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
0
                            tree_lookup, references, &wp_state);
487
0
          uint64_t v =
488
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
0
        }
492
8.83k
      } else {
493
255k
        for (size_t x = 0; x < channel.w; x++) {
494
247k
          PredictionResult res =
495
247k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
247k
                            tree_lookup, references, &wp_state);
497
247k
          uint64_t v =
498
247k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
247k
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
247k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
247k
        }
502
8.83k
      }
503
8.83k
    }
504
414
  }
505
8.34k
  return true;
506
8.34k
}
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
374k
                                 uint32_t &fl_v) {
157
374k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
374k
  Channel &channel = image->channel[chan];
159
160
374k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
374k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
374k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
374k
  bool tree_has_wp_prop_or_pred = false;
168
374k
  bool is_wp_only = false;
169
374k
  bool is_gradient_only = false;
170
374k
  size_t num_props;
171
374k
  FlatTree tree =
172
374k
      FilterTree(global_tree, static_props, &num_props,
173
374k
                 &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
539k
  for (auto &node : tree) {
178
539k
    if (node.property0 == -1) {
179
498k
      node.childID = context_map[node.childID];
180
498k
    }
181
539k
  }
182
183
374k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
374k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
374k
                             pixel_type_w offset) -> pixel_type {
188
374k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
374k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
374k
    return val * multiplier + offset;
192
374k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
374k
  const bool global_tree_is_all_gradient_noop = [&] {
200
374k
    for (const auto& n : global_tree) {
201
374k
      if (n.property == -1) {
202
374k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
374k
            n.multiplier != 1)
204
374k
          return false;
205
374k
      } else if (n.property >= kNumStaticProperties) {
206
374k
        return false;
207
374k
      }
208
374k
    }
209
374k
    return true;
210
374k
  }();
211
212
374k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
367k
    Predictor predictor = tree[0].predictor;
216
367k
    int64_t offset = tree[0].predictor_offset;
217
367k
    int32_t multiplier = tree[0].multiplier;
218
367k
    size_t ctx_id = tree[0].childID;
219
367k
    if (predictor == Predictor::Zero) {
220
352k
      uint32_t value;
221
352k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
352k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
169k
        JXL_DEBUG_V(8, "Fastest track.");
226
169k
        pixel_type v = make_pixel(value, multiplier, offset);
227
5.08M
        for (size_t y = 0; y < channel.h; y++) {
228
4.91M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
4.91M
          std::fill(r, r + channel.w, v);
230
4.91M
        }
231
182k
      } else {
232
182k
        JXL_DEBUG_V(8, "Fast track.");
233
182k
        if (multiplier == 1 && offset == 0) {
234
2.72M
          for (size_t y = 0; y < channel.h; y++) {
235
2.56M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
167M
            for (size_t x = 0; x < channel.w; x++) {
237
165M
              uint32_t v =
238
165M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
165M
              r[x] = UnpackSigned(v);
240
165M
            }
241
2.56M
          }
242
160k
        } else {
243
1.14M
          for (size_t y = 0; y < channel.h; y++) {
244
1.12M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
143M
            for (size_t x = 0; x < channel.w; x++) {
246
142M
              uint32_t v =
247
142M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
142M
                                                                         br);
249
142M
              r[x] = make_pixel(v, multiplier, offset);
250
142M
            }
251
1.12M
          }
252
22.1k
        }
253
182k
      }
254
352k
      return true;
255
352k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
0
               global_tree_is_all_gradient_noop) {
257
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
0
      pixel_type_w sv = UnpackSigned(fl_v);
259
0
      for (size_t y = 0; y < channel.h; y++) {
260
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
0
        const pixel_type *JXL_RESTRICT rtopleft =
263
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
0
        if (fl_run == 0) {
266
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
0
                                                     &fl_run);
268
0
          sv = UnpackSigned(fl_v);
269
0
        } else {
270
0
          fl_run--;
271
0
        }
272
0
        r[0] = sv + guess_0;
273
0
        for (size_t x = 1; x < channel.w; x++) {
274
0
          pixel_type left = r[x - 1];
275
0
          pixel_type top = rtop[x];
276
0
          pixel_type topleft = rtopleft[x];
277
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
0
          if (!fl_run) {
279
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
0
                                                       &fl_run);
281
0
            sv = UnpackSigned(fl_v);
282
0
          } else {
283
0
            fl_run--;
284
0
          }
285
0
          r[x] = sv + guess;
286
0
        }
287
0
      }
288
0
      return true;
289
14.3k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
1.61k
               multiplier == 1) {
291
1.47k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
1.47k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
42.2k
      for (size_t y = 0; y < channel.h; y++) {
294
40.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
2.59M
        for (size_t x = 0; x < channel.w; x++) {
296
2.55M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.55M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.55M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.55M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.55M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.55M
              ctx_id, br);
302
2.55M
          r[x] = make_pixel(v, 1, guess);
303
2.55M
        }
304
40.8k
      }
305
1.47k
      return true;
306
1.47k
    }
307
367k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
20.6k
  if (is_wp_only) {
312
3.77k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
3.77k
  }
314
20.6k
  if (is_gradient_only) {
315
938
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
938
  }
317
318
20.6k
  if (is_gradient_only) {
319
579
    JXL_DEBUG_V(8, "Gradient fast track.");
320
579
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
14.1k
    for (size_t y = 0; y < channel.h; y++) {
322
13.5k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
511k
      for (size_t x = 0; x < channel.w; x++) {
324
497k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
497k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
497k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
497k
        int32_t guess = ClampedGradient(top, left, topleft);
328
497k
        uint32_t pos =
329
497k
            kPropRangeFast +
330
497k
            std::min<pixel_type_w>(
331
497k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
497k
                kPropRangeFast - 1);
333
497k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
497k
        uint64_t v =
335
497k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
497k
        r[x] = make_pixel(v, 1, guess);
337
497k
      }
338
13.5k
    }
339
20.0k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
807
    JXL_DEBUG_V(8, "WP fast track.");
341
807
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
807
    Properties properties(1);
343
22.6k
    for (size_t y = 0; y < channel.h; y++) {
344
21.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
21.8k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
21.8k
      const pixel_type *JXL_RESTRICT rtoptop =
347
21.8k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
21.8k
      const pixel_type *JXL_RESTRICT rtopleft =
349
21.8k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
21.8k
      const pixel_type *JXL_RESTRICT rtopright =
351
21.8k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
21.8k
      size_t x = 0;
353
21.8k
      {
354
21.8k
        size_t offset = 0;
355
21.8k
        pixel_type_w left = y ? rtop[x] : 0;
356
21.8k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
21.8k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
21.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
21.8k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
21.8k
            offset);
361
21.8k
        uint32_t pos =
362
21.8k
            kPropRangeFast +
363
21.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
21.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
21.8k
        uint64_t v =
366
21.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
21.8k
        r[x] = make_pixel(v, 1, guess);
368
21.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
21.8k
      }
370
2.84M
      for (x = 1; x + 1 < channel.w; x++) {
371
2.82M
        size_t offset = 0;
372
2.82M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
2.82M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
2.82M
            rtoptop[x], &properties, offset);
375
2.82M
        uint32_t pos =
376
2.82M
            kPropRangeFast +
377
2.82M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
2.82M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
2.82M
        uint64_t v =
380
2.82M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
2.82M
        r[x] = make_pixel(v, 1, guess);
382
2.82M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
2.82M
      }
384
21.8k
      {
385
21.8k
        size_t offset = 0;
386
21.8k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
21.8k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
21.8k
            rtoptop[x], &properties, offset);
389
21.8k
        uint32_t pos =
390
21.8k
            kPropRangeFast +
391
21.8k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
21.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
21.8k
        uint64_t v =
394
21.8k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
21.8k
        r[x] = make_pixel(v, 1, guess);
396
21.8k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
21.8k
      }
398
21.8k
    }
399
19.2k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
11.8k
    JXL_DEBUG_V(8, "Slow track.");
403
11.8k
    MATreeLookup tree_lookup(tree);
404
11.8k
    Properties properties = Properties(num_props);
405
11.8k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
11.8k
    JXL_ASSIGN_OR_RETURN(
407
11.8k
        Channel references,
408
11.8k
        Channel::Create(memory_manager,
409
11.8k
                        properties.size() - kNumNonrefProperties, channel.w));
410
492k
    for (size_t y = 0; y < channel.h; y++) {
411
480k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
480k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
480k
      InitPropsRow(&properties, static_props, y);
414
480k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.27M
        for (size_t x = 0; x < 2; x++) {
416
848k
          PredictionResult res =
417
848k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
848k
                              tree_lookup, references);
419
848k
          uint64_t v =
420
848k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
848k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
848k
        }
423
42.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
41.5M
          PredictionResult res =
425
41.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
41.5M
                                 tree_lookup, references);
427
41.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
41.5M
              res.context, br);
429
41.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
41.5M
        }
431
1.27M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
848k
          PredictionResult res =
433
848k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
848k
                              tree_lookup, references);
435
848k
          uint64_t v =
436
848k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
848k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
848k
        }
439
424k
      } else {
440
1.68M
        for (size_t x = 0; x < channel.w; x++) {
441
1.63M
          PredictionResult res =
442
1.63M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
1.63M
                              tree_lookup, references);
444
1.63M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
1.63M
              res.context, br);
446
1.63M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
1.63M
        }
448
56.0k
      }
449
480k
    }
450
11.8k
  } else {
451
7.43k
    JXL_DEBUG_V(8, "Slowest track.");
452
7.43k
    MATreeLookup tree_lookup(tree);
453
7.43k
    Properties properties = Properties(num_props);
454
7.43k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
7.43k
    JXL_ASSIGN_OR_RETURN(
456
7.43k
        Channel references,
457
7.43k
        Channel::Create(memory_manager,
458
7.43k
                        properties.size() - kNumNonrefProperties, channel.w));
459
7.43k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
234k
    for (size_t y = 0; y < channel.h; y++) {
461
227k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
227k
      InitPropsRow(&properties, static_props, y);
463
227k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
227k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
596k
        for (size_t x = 0; x < 2; x++) {
466
397k
          PredictionResult res =
467
397k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
397k
                            tree_lookup, references, &wp_state);
469
397k
          uint64_t v =
470
397k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
397k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
397k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
397k
        }
474
15.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
15.5M
          PredictionResult res =
476
15.5M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
15.5M
                               tree_lookup, references, &wp_state);
478
15.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
15.5M
              res.context, br);
480
15.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
15.5M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
15.5M
        }
483
596k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
397k
          PredictionResult res =
485
397k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
397k
                            tree_lookup, references, &wp_state);
487
397k
          uint64_t v =
488
397k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
397k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
397k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
397k
        }
492
198k
      } else {
493
1.65M
        for (size_t x = 0; x < channel.w; x++) {
494
1.62M
          PredictionResult res =
495
1.62M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
1.62M
                            tree_lookup, references, &wp_state);
497
1.62M
          uint64_t v =
498
1.62M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
1.62M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
1.62M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
1.62M
        }
502
28.5k
      }
503
227k
    }
504
7.43k
  }
505
20.6k
  return true;
506
20.6k
}
507
}  // namespace detail
508
509
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
510
                                 const std::vector<uint8_t> &context_map,
511
                                 const Tree &global_tree,
512
                                 const weighted::Header &wp_header,
513
                                 pixel_type chan, size_t group_id,
514
                                 TreeLut<uint8_t, false, false> &tree_lut,
515
                                 Image *image, uint32_t &fl_run,
516
412k
                                 uint32_t &fl_v) {
517
412k
  if (reader->UsesLZ77()) {
518
37.3k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
37.3k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
37.3k
        tree_lut, image, fl_run, fl_v);
521
374k
  } else {
522
374k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
374k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
374k
        tree_lut, image, fl_run, fl_v);
525
374k
  }
526
412k
}
527
528
189k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
46.7k
                                 const ModularOptions &options) {
532
46.7k
  size_t nb_channels = image.channel.size();
533
93.4k
  for (bool is_dc : {true, false}) {
534
93.4k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
93.4k
    size_t c = image.nb_meta_channels;
536
942k
    for (; c < nb_channels; c++) {
537
853k
      const Channel &ch = image.channel[c];
538
853k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
853k
    }
540
120k
    for (; c < nb_channels; c++) {
541
26.8k
      const Channel &ch = image.channel[c];
542
26.8k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
26.3k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
26.3k
      if (is_dc_channel != is_dc) continue;
545
13.1k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
13.1k
      if (tile_dim == 0) {
547
3
        return JXL_FAILURE("Inconsistent transforms");
548
3
      }
549
13.1k
    }
550
93.4k
  }
551
46.7k
  return true;
552
46.7k
}
553
554
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
555
                     size_t group_id, ModularOptions *options,
556
                     const Tree *global_tree, const ANSCode *global_code,
557
                     const std::vector<uint8_t> *global_ctx_map,
558
51.1k
                     const bool allow_truncated_group) {
559
51.1k
  if (image.channel.empty()) return true;
560
45.4k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
45.4k
  Status status = Bundle::Read(br, &header);
564
45.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
44.9k
  if (status.IsFatalError()) return status;
566
44.9k
  if (!br->AllReadsWithinBounds()) {
567
    // Don't do/undo transforms if header is incomplete.
568
0
    header.transforms.clear();
569
0
    image.transform = header.transforms;
570
0
    for (auto &ch : image.channel) {
571
0
      ZeroFillImage(&ch.plane);
572
0
    }
573
0
    return JXL_NOT_ENOUGH_BYTES("Read overrun before ModularDecode");
574
0
  }
575
576
44.9k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
44.9k
              header.transforms.size());
578
44.9k
  image.transform = header.transforms;
579
44.9k
  for (Transform &transform : image.transform) {
580
28.5k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
28.5k
  }
582
44.8k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
44.8k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
44.8k
  size_t nb_channels = image.channel.size();
588
589
44.8k
  size_t num_chans = 0;
590
44.8k
  size_t distance_multiplier = 0;
591
471k
  for (size_t i = 0; i < nb_channels; i++) {
592
427k
    Channel &channel = image.channel[i];
593
427k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
421k
                                        channel.h > options->max_chan_size)) {
595
1.45k
      break;
596
1.45k
    }
597
426k
    if (!channel.w || !channel.h) {
598
5.90k
      continue;  // skip empty channels
599
5.90k
    }
600
420k
    if (channel.w > distance_multiplier) {
601
74.5k
      distance_multiplier = channel.w;
602
74.5k
    }
603
420k
    num_chans++;
604
420k
  }
605
44.8k
  if (num_chans == 0) return true;
606
607
44.4k
  size_t next_channel = 0;
608
44.4k
  auto scope_guard = MakeScopeGuard([&]() {
609
11.8k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
10.1k
      ZeroFillImage(&image.channel[c].plane);
611
10.1k
    }
612
1.69k
  });
613
  // Do not do anything if truncated groups are not allowed.
614
44.4k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
44.4k
  Tree tree_storage;
618
44.4k
  std::vector<uint8_t> context_map_storage;
619
44.4k
  ANSCode code_storage;
620
44.4k
  const Tree *tree = &tree_storage;
621
44.4k
  const ANSCode *code = &code_storage;
622
44.4k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
44.4k
  if (!header.use_global_tree) {
624
24.3k
    uint64_t max_tree_size = 1024;
625
317k
    for (size_t i = 0; i < nb_channels; i++) {
626
293k
      Channel &channel = image.channel[i];
627
293k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
291k
                                          channel.h > options->max_chan_size)) {
629
35
        break;
630
35
      }
631
293k
      uint64_t pixels = channel.w * channel.h;
632
293k
      max_tree_size += pixels;
633
293k
    }
634
24.3k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
24.3k
    JXL_RETURN_IF_ERROR(
636
24.3k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
24.2k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
24.2k
                                         (tree_storage.size() + 1) / 2,
639
24.2k
                                         &code_storage, &context_map_storage));
640
24.2k
  } else {
641
20.0k
    if (!global_tree || !global_code || !global_ctx_map ||
642
20.0k
        global_tree->empty()) {
643
30
      return JXL_FAILURE("No global tree available but one was requested");
644
30
    }
645
20.0k
    tree = global_tree;
646
20.0k
    code = global_code;
647
20.0k
    context_map = global_ctx_map;
648
20.0k
  }
649
650
  // Read channels
651
88.3k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
88.3k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
88.3k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
88.3k
  uint32_t fl_run = 0;
655
88.3k
  uint32_t fl_v = 0;
656
460k
  for (; next_channel < nb_channels; next_channel++) {
657
418k
    Channel &channel = image.channel[next_channel];
658
418k
    if (next_channel >= image.nb_meta_channels &&
659
413k
        (channel.w > options->max_chan_size ||
660
413k
         channel.h > options->max_chan_size)) {
661
983
      break;
662
983
    }
663
417k
    if (!channel.w || !channel.h) {
664
5.71k
      continue;  // skip empty channels
665
5.71k
    }
666
412k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
412k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
412k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
412k
    if (!br->AllReadsWithinBounds()) {
672
1.45k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
1.45k
    }
675
412k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
42.7k
  scope_guard.Disarm();
679
680
42.7k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
42.7k
  return true;
684
42.7k
}
685
686
Status ModularGenericDecompress(BitReader *br, Image &image,
687
                                GroupHeader *header, size_t group_id,
688
                                ModularOptions *options, bool undo_transforms,
689
                                const Tree *tree, const ANSCode *code,
690
                                const std::vector<uint8_t> *ctx_map,
691
51.1k
                                bool allow_truncated_group) {
692
51.1k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
51.1k
  req_sizes.reserve(image.channel.size());
694
168k
  for (const auto &c : image.channel) {
695
168k
    req_sizes.emplace_back(c.w, c.h);
696
168k
  }
697
51.1k
  GroupHeader local_header;
698
51.1k
  if (header == nullptr) header = &local_header;
699
51.1k
  size_t bit_pos = br->TotalBitsConsumed();
700
51.1k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
51.1k
                                  code, ctx_map, allow_truncated_group);
702
51.1k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
48.9k
  if (dec_status.IsFatalError()) return dec_status;
704
48.9k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
48.9k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
48.9k
  JXL_DEBUG_V(4,
707
48.9k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
48.9k
              " image from %" PRIuS " bytes",
709
48.9k
              image.w, image.h, image.channel.size(),
710
48.9k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
48.9k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
48.9k
  (void)bit_pos;
713
  // Check that after applying all transforms we are back to the requested
714
  // image sizes, otherwise there's a programming error with the
715
  // transformations.
716
48.9k
  if (undo_transforms) {
717
14.3k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
72.8k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
58.4k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
58.4k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
58.4k
    }
722
14.3k
  }
723
48.9k
  return dec_status;
724
48.9k
}
725
726
}  // namespace jxl