Coverage Report

Created: 2026-09-28 06:47

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
465k
                    bool *gradient_only) {
46
465k
  *num_props = 0;
47
465k
  bool has_wp = false;
48
465k
  bool has_non_wp = false;
49
465k
  *gradient_only = true;
50
1.23M
  const auto mark_property = [&](int32_t p) {
51
1.23M
    if (p == kWPProp) {
52
124k
      has_wp = true;
53
1.10M
    } else if (p >= kNumStaticProperties) {
54
670k
      has_non_wp = true;
55
670k
    }
56
1.23M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
715k
      *gradient_only = false;
58
715k
    }
59
1.23M
  };
60
465k
  FlatTree output;
61
465k
  std::queue<size_t> nodes;
62
465k
  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.57M
  while (!nodes.empty()) {
70
2.10M
    size_t cur = nodes.front();
71
2.10M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
2.16M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.75M
           global_tree[cur].property != -1) {
75
63.8k
      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.7k
        cur = global_tree[cur].rchild;
79
30.7k
      }
80
63.8k
    }
81
2.10M
    FlatDecisionNode flat;
82
2.10M
    if (global_tree[cur].property == -1) {
83
1.69M
      flat.property0 = -1;
84
1.69M
      flat.childID = global_tree[cur].lchild;
85
1.69M
      flat.predictor = global_tree[cur].predictor;
86
1.69M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.69M
      flat.multiplier = global_tree[cur].multiplier;
88
1.69M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.69M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.69M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.69M
      output.push_back(flat);
92
1.69M
      continue;
93
1.69M
    }
94
410k
    flat.childID = output.size() + nodes.size() + 1;
95
96
410k
    flat.property0 = global_tree[cur].property;
97
410k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
410k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.23M
    for (size_t i = 0; i < 2; i++) {
101
820k
      size_t cur_child =
102
820k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
842k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
457k
             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.0k
          cur_child = global_tree[cur_child].lchild;
109
11.7k
        } else {
110
11.7k
          cur_child = global_tree[cur_child].rchild;
111
11.7k
        }
112
22.8k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
820k
      if (global_tree[cur_child].property == -1) {
116
435k
        flat.properties[i] = 0;
117
435k
        flat.splitvals[i] = 0;
118
435k
        nodes.push(cur_child);
119
435k
        nodes.push(cur_child);
120
435k
      } else {
121
384k
        flat.properties[i] = global_tree[cur_child].property;
122
384k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
384k
        nodes.push(global_tree[cur_child].lchild);
124
384k
        nodes.push(global_tree[cur_child].rchild);
125
384k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
384k
      }
127
820k
    }
128
129
820k
    for (int16_t property : flat.properties) mark_property(property);
130
410k
    mark_property(flat.property0);
131
410k
    output.push_back(flat);
132
410k
  }
133
465k
  if (*num_props > kNumNonrefProperties) {
134
1.98k
    *num_props =
135
1.98k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.98k
            kExtraPropsPerChannel +
137
1.98k
        kNumNonrefProperties;
138
463k
  } else {
139
463k
    *num_props = kNumNonrefProperties;
140
463k
  }
141
465k
  *use_wp = has_wp;
142
465k
  *wp_only = has_wp && !has_non_wp;
143
144
465k
  return output;
145
465k
}
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
439k
                                 uint32_t &fl_v) {
157
439k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
439k
  Channel &channel = image->channel[chan];
159
160
439k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
439k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
439k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
439k
  bool tree_has_wp_prop_or_pred = false;
168
439k
  bool is_wp_only = false;
169
439k
  bool is_gradient_only = false;
170
439k
  size_t num_props;
171
439k
  FlatTree tree =
172
439k
      FilterTree(global_tree, static_props, &num_props,
173
439k
                 &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
615k
  for (auto &node : tree) {
178
615k
    if (node.property0 == -1) {
179
571k
      node.childID = context_map[node.childID];
180
571k
    }
181
615k
  }
182
183
439k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
439k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
271M
                             pixel_type_w offset) -> pixel_type {
188
271M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
271M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
271M
    return val * multiplier + offset;
192
271M
  };
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
54.9M
                             pixel_type_w offset) -> pixel_type {
188
54.9M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
54.9M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
54.9M
    return val * multiplier + offset;
192
54.9M
  };
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
216M
                             pixel_type_w offset) -> pixel_type {
188
216M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
216M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
216M
    return val * multiplier + offset;
192
216M
  };
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
439k
  const bool global_tree_is_all_gradient_noop = [&] {
200
445k
    for (const auto& n : global_tree) {
201
445k
      if (n.property == -1) {
202
429k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
4.52k
            n.multiplier != 1)
204
425k
          return false;
205
429k
      } else if (n.property >= kNumStaticProperties) {
206
11.1k
        return false;
207
11.1k
      }
208
445k
    }
209
2.41k
    return true;
210
439k
  }();
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
38.6k
  const bool global_tree_is_all_gradient_noop = [&] {
200
39.2k
    for (const auto& n : global_tree) {
201
39.2k
      if (n.property == -1) {
202
36.3k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
1.53k
            n.multiplier != 1)
204
35.0k
          return false;
205
36.3k
      } else if (n.property >= kNumStaticProperties) {
206
2.38k
        return false;
207
2.38k
      }
208
39.2k
    }
209
1.21k
    return true;
210
38.6k
  }();
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
400k
  const bool global_tree_is_all_gradient_noop = [&] {
200
406k
    for (const auto& n : global_tree) {
201
406k
      if (n.property == -1) {
202
393k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
2.99k
            n.multiplier != 1)
204
390k
          return false;
205
393k
      } else if (n.property >= kNumStaticProperties) {
206
8.76k
        return false;
207
8.76k
      }
208
406k
    }
209
1.20k
    return true;
210
400k
  }();
211
212
439k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
428k
    Predictor predictor = tree[0].predictor;
216
428k
    int64_t offset = tree[0].predictor_offset;
217
428k
    int32_t multiplier = tree[0].multiplier;
218
428k
    size_t ctx_id = tree[0].childID;
219
428k
    if (predictor == Predictor::Zero) {
220
400k
      uint32_t value;
221
400k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
400k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
189k
        JXL_DEBUG_V(8, "Fastest track.");
226
189k
        pixel_type v = make_pixel(value, multiplier, offset);
227
5.91M
        for (size_t y = 0; y < channel.h; y++) {
228
5.72M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
5.72M
          std::fill(r, r + channel.w, v);
230
5.72M
        }
231
210k
      } else {
232
210k
        JXL_DEBUG_V(8, "Fast track.");
233
210k
        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
228M
            for (size_t x = 0; x < channel.w; x++) {
237
225M
              uint32_t v =
238
225M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
225M
              r[x] = UnpackSigned(v);
240
225M
            }
241
2.97M
          }
242
171k
        } else {
243
1.63M
          for (size_t y = 0; y < channel.h; y++) {
244
1.59M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
176M
            for (size_t x = 0; x < channel.w; x++) {
246
174M
              uint32_t v =
247
174M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
174M
                                                                         br);
249
174M
              r[x] = make_pixel(v, multiplier, offset);
250
174M
            }
251
1.59M
          }
252
38.8k
        }
253
210k
      }
254
400k
      return true;
255
400k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
746
               global_tree_is_all_gradient_noop) {
257
585
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
585
      pixel_type_w sv = UnpackSigned(fl_v);
259
19.3k
      for (size_t y = 0; y < channel.h; y++) {
260
18.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
18.7k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
18.7k
        const pixel_type *JXL_RESTRICT rtopleft =
263
18.7k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
18.7k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
18.7k
        if (fl_run == 0) {
266
4.99k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
4.99k
                                                     &fl_run);
268
4.99k
          sv = UnpackSigned(fl_v);
269
13.7k
        } else {
270
13.7k
          fl_run--;
271
13.7k
        }
272
18.7k
        r[0] = sv + guess_0;
273
516k
        for (size_t x = 1; x < channel.w; x++) {
274
497k
          pixel_type left = r[x - 1];
275
497k
          pixel_type top = rtop[x];
276
497k
          pixel_type topleft = rtopleft[x];
277
497k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
497k
          if (!fl_run) {
279
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
119k
                                                       &fl_run);
281
119k
            sv = UnpackSigned(fl_v);
282
378k
          } else {
283
378k
            fl_run--;
284
378k
          }
285
497k
          r[x] = sv + guess;
286
497k
        }
287
18.7k
      }
288
585
      return true;
289
27.2k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
2.73k
               multiplier == 1) {
291
2.23k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
2.23k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
52.4k
      for (size_t y = 0; y < channel.h; y++) {
294
50.2k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
2.84M
        for (size_t x = 0; x < channel.w; x++) {
296
2.79M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.79M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.79M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.79M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.79M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.79M
              ctx_id, br);
302
2.79M
          r[x] = make_pixel(v, 1, guess);
303
2.79M
        }
304
50.2k
      }
305
2.23k
      return true;
306
2.23k
    }
307
428k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
35.7k
  if (is_wp_only) {
312
6.83k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
6.83k
  }
314
35.7k
  if (is_gradient_only) {
315
1.77k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.77k
  }
317
318
35.7k
  if (is_gradient_only) {
319
652
    JXL_DEBUG_V(8, "Gradient fast track.");
320
652
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
16.3k
    for (size_t y = 0; y < channel.h; y++) {
322
15.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
993k
      for (size_t x = 0; x < channel.w; x++) {
324
977k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
977k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
977k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
977k
        int32_t guess = ClampedGradient(top, left, topleft);
328
977k
        uint32_t pos =
329
977k
            kPropRangeFast +
330
977k
            std::min<pixel_type_w>(
331
977k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
977k
                kPropRangeFast - 1);
333
977k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
977k
        uint64_t v =
335
977k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
977k
        r[x] = make_pixel(v, 1, guess);
337
977k
      }
338
15.7k
    }
339
35.1k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
1.14k
    JXL_DEBUG_V(8, "WP fast track.");
341
1.14k
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
1.14k
    Properties properties(1);
343
26.0k
    for (size_t y = 0; y < channel.h; y++) {
344
24.9k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
24.9k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
24.9k
      const pixel_type *JXL_RESTRICT rtoptop =
347
24.9k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
24.9k
      const pixel_type *JXL_RESTRICT rtopleft =
349
24.9k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
24.9k
      const pixel_type *JXL_RESTRICT rtopright =
351
24.9k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
24.9k
      size_t x = 0;
353
24.9k
      {
354
24.9k
        size_t offset = 0;
355
24.9k
        pixel_type_w left = y ? rtop[x] : 0;
356
24.9k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
24.9k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
24.9k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
24.9k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
24.9k
            offset);
361
24.9k
        uint32_t pos =
362
24.9k
            kPropRangeFast +
363
24.9k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
24.9k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
24.9k
        uint64_t v =
366
24.9k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
24.9k
        r[x] = make_pixel(v, 1, guess);
368
24.9k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
24.9k
      }
370
2.75M
      for (x = 1; x + 1 < channel.w; x++) {
371
2.72M
        size_t offset = 0;
372
2.72M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
2.72M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
2.72M
            rtoptop[x], &properties, offset);
375
2.72M
        uint32_t pos =
376
2.72M
            kPropRangeFast +
377
2.72M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
2.72M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
2.72M
        uint64_t v =
380
2.72M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
2.72M
        r[x] = make_pixel(v, 1, guess);
382
2.72M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
2.72M
      }
384
24.9k
      {
385
24.9k
        size_t offset = 0;
386
24.9k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
24.9k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
24.9k
            rtoptop[x], &properties, offset);
389
24.9k
        uint32_t pos =
390
24.9k
            kPropRangeFast +
391
24.9k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
24.9k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
24.9k
        uint64_t v =
394
24.9k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
24.9k
        r[x] = make_pixel(v, 1, guess);
396
24.9k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
24.9k
      }
398
24.9k
    }
399
34.0k
  } 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
23.5k
    JXL_DEBUG_V(8, "Slow track.");
403
23.5k
    MATreeLookup tree_lookup(tree);
404
23.5k
    Properties properties = Properties(num_props);
405
23.5k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
23.5k
    JXL_ASSIGN_OR_RETURN(
407
23.5k
        Channel references,
408
23.5k
        Channel::Create(memory_manager,
409
23.5k
                        properties.size() - kNumNonrefProperties, channel.w));
410
759k
    for (size_t y = 0; y < channel.h; y++) {
411
735k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
735k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
735k
      InitPropsRow(&properties, static_props, y);
414
735k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.91M
        for (size_t x = 0; x < 2; x++) {
416
1.27M
          PredictionResult res =
417
1.27M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
1.27M
                              tree_lookup, references);
419
1.27M
          uint64_t v =
420
1.27M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
1.27M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
1.27M
        }
423
66.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
66.0M
          PredictionResult res =
425
66.0M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
66.0M
                                 tree_lookup, references);
427
66.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
66.0M
              res.context, br);
429
66.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
66.0M
        }
431
1.91M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
1.27M
          PredictionResult res =
433
1.27M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
1.27M
                              tree_lookup, references);
435
1.27M
          uint64_t v =
436
1.27M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
1.27M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
1.27M
        }
439
637k
      } else {
440
2.59M
        for (size_t x = 0; x < channel.w; x++) {
441
2.49M
          PredictionResult res =
442
2.49M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
2.49M
                              tree_lookup, references);
444
2.49M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
2.49M
              res.context, br);
446
2.49M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
2.49M
        }
448
97.9k
      }
449
735k
    }
450
23.5k
  } else {
451
10.4k
    JXL_DEBUG_V(8, "Slowest track.");
452
10.4k
    MATreeLookup tree_lookup(tree);
453
10.4k
    Properties properties = Properties(num_props);
454
10.4k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
10.4k
    JXL_ASSIGN_OR_RETURN(
456
10.4k
        Channel references,
457
10.4k
        Channel::Create(memory_manager,
458
10.4k
                        properties.size() - kNumNonrefProperties, channel.w));
459
10.4k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
283k
    for (size_t y = 0; y < channel.h; y++) {
461
273k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
273k
      InitPropsRow(&properties, static_props, y);
463
273k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
273k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
663k
        for (size_t x = 0; x < 2; x++) {
466
442k
          PredictionResult res =
467
442k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
442k
                            tree_lookup, references, &wp_state);
469
442k
          uint64_t v =
470
442k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
442k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
442k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
442k
        }
474
16.5M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
16.3M
          PredictionResult res =
476
16.3M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
16.3M
                               tree_lookup, references, &wp_state);
478
16.3M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
16.3M
              res.context, br);
480
16.3M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
16.3M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
16.3M
        }
483
663k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
442k
          PredictionResult res =
485
442k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
442k
                            tree_lookup, references, &wp_state);
487
442k
          uint64_t v =
488
442k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
442k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
442k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
442k
        }
492
221k
      } else {
493
2.20M
        for (size_t x = 0; x < channel.w; x++) {
494
2.15M
          PredictionResult res =
495
2.15M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.15M
                            tree_lookup, references, &wp_state);
497
2.15M
          uint64_t v =
498
2.15M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.15M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.15M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.15M
        }
502
52.2k
      }
503
273k
    }
504
10.4k
  }
505
35.7k
  return true;
506
35.7k
}
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
38.6k
                                 uint32_t &fl_v) {
157
38.6k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
38.6k
  Channel &channel = image->channel[chan];
159
160
38.6k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
38.6k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
38.6k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
38.6k
  bool tree_has_wp_prop_or_pred = false;
168
38.6k
  bool is_wp_only = false;
169
38.6k
  bool is_gradient_only = false;
170
38.6k
  size_t num_props;
171
38.6k
  FlatTree tree =
172
38.6k
      FilterTree(global_tree, static_props, &num_props,
173
38.6k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
49.4k
  for (auto &node : tree) {
178
49.4k
    if (node.property0 == -1) {
179
46.7k
      node.childID = context_map[node.childID];
180
46.7k
    }
181
49.4k
  }
182
183
38.6k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
38.6k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
38.6k
                             pixel_type_w offset) -> pixel_type {
188
38.6k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
38.6k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
38.6k
    return val * multiplier + offset;
192
38.6k
  };
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
38.6k
  const bool global_tree_is_all_gradient_noop = [&] {
200
38.6k
    for (const auto& n : global_tree) {
201
38.6k
      if (n.property == -1) {
202
38.6k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
38.6k
            n.multiplier != 1)
204
38.6k
          return false;
205
38.6k
      } else if (n.property >= kNumStaticProperties) {
206
38.6k
        return false;
207
38.6k
      }
208
38.6k
    }
209
38.6k
    return true;
210
38.6k
  }();
211
212
38.6k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
36.3k
    Predictor predictor = tree[0].predictor;
216
36.3k
    int64_t offset = tree[0].predictor_offset;
217
36.3k
    int32_t multiplier = tree[0].multiplier;
218
36.3k
    size_t ctx_id = tree[0].childID;
219
36.3k
    if (predictor == Predictor::Zero) {
220
28.0k
      uint32_t value;
221
28.0k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
28.0k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
5.93k
        JXL_DEBUG_V(8, "Fastest track.");
226
5.93k
        pixel_type v = make_pixel(value, multiplier, offset);
227
201k
        for (size_t y = 0; y < channel.h; y++) {
228
195k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
195k
          std::fill(r, r + channel.w, v);
230
195k
        }
231
22.0k
      } else {
232
22.0k
        JXL_DEBUG_V(8, "Fast track.");
233
22.0k
        if (multiplier == 1 && offset == 0) {
234
393k
          for (size_t y = 0; y < channel.h; y++) {
235
387k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
63.0M
            for (size_t x = 0; x < channel.w; x++) {
237
62.6M
              uint32_t v =
238
62.6M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
62.6M
              r[x] = UnpackSigned(v);
240
62.6M
            }
241
387k
          }
242
15.6k
        } else {
243
469k
          for (size_t y = 0; y < channel.h; y++) {
244
453k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
30.1M
            for (size_t x = 0; x < channel.w; x++) {
246
29.6M
              uint32_t v =
247
29.6M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
29.6M
                                                                         br);
249
29.6M
              r[x] = make_pixel(v, multiplier, offset);
250
29.6M
            }
251
453k
          }
252
15.6k
        }
253
22.0k
      }
254
28.0k
      return true;
255
28.0k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
746
               global_tree_is_all_gradient_noop) {
257
585
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
585
      pixel_type_w sv = UnpackSigned(fl_v);
259
19.3k
      for (size_t y = 0; y < channel.h; y++) {
260
18.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
18.7k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
18.7k
        const pixel_type *JXL_RESTRICT rtopleft =
263
18.7k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
18.7k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
18.7k
        if (fl_run == 0) {
266
4.99k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
4.99k
                                                     &fl_run);
268
4.99k
          sv = UnpackSigned(fl_v);
269
13.7k
        } else {
270
13.7k
          fl_run--;
271
13.7k
        }
272
18.7k
        r[0] = sv + guess_0;
273
516k
        for (size_t x = 1; x < channel.w; x++) {
274
497k
          pixel_type left = r[x - 1];
275
497k
          pixel_type top = rtop[x];
276
497k
          pixel_type topleft = rtopleft[x];
277
497k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
497k
          if (!fl_run) {
279
119k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
119k
                                                       &fl_run);
281
119k
            sv = UnpackSigned(fl_v);
282
378k
          } else {
283
378k
            fl_run--;
284
378k
          }
285
497k
          r[x] = sv + guess;
286
497k
        }
287
18.7k
      }
288
585
      return true;
289
7.70k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
951
               multiplier == 1) {
291
632
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
632
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
8.66k
      for (size_t y = 0; y < channel.h; y++) {
294
8.02k
        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
8.02k
      }
305
632
      return true;
306
632
    }
307
36.3k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
9.45k
  if (is_wp_only) {
312
486
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
486
  }
314
9.45k
  if (is_gradient_only) {
315
653
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
653
  }
317
318
9.45k
  if (is_gradient_only) {
319
86
    JXL_DEBUG_V(8, "Gradient fast track.");
320
86
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
2.78k
    for (size_t y = 0; y < channel.h; y++) {
322
2.69k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
504k
      for (size_t x = 0; x < channel.w; x++) {
324
501k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
501k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
501k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
501k
        int32_t guess = ClampedGradient(top, left, topleft);
328
501k
        uint32_t pos =
329
501k
            kPropRangeFast +
330
501k
            std::min<pixel_type_w>(
331
501k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
501k
                kPropRangeFast - 1);
333
501k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
501k
        uint64_t v =
335
501k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
501k
        r[x] = make_pixel(v, 1, guess);
337
501k
      }
338
2.69k
    }
339
9.36k
  } 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
9.36k
  } 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
8.71k
    JXL_DEBUG_V(8, "Slow track.");
403
8.71k
    MATreeLookup tree_lookup(tree);
404
8.71k
    Properties properties = Properties(num_props);
405
8.71k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
8.71k
    JXL_ASSIGN_OR_RETURN(
407
8.71k
        Channel references,
408
8.71k
        Channel::Create(memory_manager,
409
8.71k
                        properties.size() - kNumNonrefProperties, channel.w));
410
221k
    for (size_t y = 0; y < channel.h; y++) {
411
212k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
212k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
212k
      InitPropsRow(&properties, static_props, y);
414
212k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
548k
        for (size_t x = 0; x < 2; x++) {
416
365k
          PredictionResult res =
417
365k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
365k
                              tree_lookup, references);
419
365k
          uint64_t v =
420
365k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
365k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
365k
        }
423
23.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
22.8M
          PredictionResult res =
425
22.8M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
22.8M
                                 tree_lookup, references);
427
22.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
22.8M
              res.context, br);
429
22.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
22.8M
        }
431
548k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
365k
          PredictionResult res =
433
365k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
365k
                              tree_lookup, references);
435
365k
          uint64_t v =
436
365k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
365k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
365k
        }
439
182k
      } else {
440
590k
        for (size_t x = 0; x < channel.w; x++) {
441
560k
          PredictionResult res =
442
560k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
560k
                              tree_lookup, references);
444
560k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
560k
              res.context, br);
446
560k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
560k
        }
448
30.0k
      }
449
212k
    }
450
8.71k
  } else {
451
649
    JXL_DEBUG_V(8, "Slowest track.");
452
649
    MATreeLookup tree_lookup(tree);
453
649
    Properties properties = Properties(num_props);
454
649
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
649
    JXL_ASSIGN_OR_RETURN(
456
649
        Channel references,
457
649
        Channel::Create(memory_manager,
458
649
                        properties.size() - kNumNonrefProperties, channel.w));
459
649
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
13.4k
    for (size_t y = 0; y < channel.h; y++) {
461
12.8k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
12.8k
      InitPropsRow(&properties, static_props, y);
463
12.8k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
12.8k
      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
12.8k
      } else {
493
418k
        for (size_t x = 0; x < channel.w; x++) {
494
405k
          PredictionResult res =
495
405k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
405k
                            tree_lookup, references, &wp_state);
497
405k
          uint64_t v =
498
405k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
405k
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
405k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
405k
        }
502
12.8k
      }
503
12.8k
    }
504
649
  }
505
9.45k
  return true;
506
9.45k
}
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
400k
                                 uint32_t &fl_v) {
157
400k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
400k
  Channel &channel = image->channel[chan];
159
160
400k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
400k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
400k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
400k
  bool tree_has_wp_prop_or_pred = false;
168
400k
  bool is_wp_only = false;
169
400k
  bool is_gradient_only = false;
170
400k
  size_t num_props;
171
400k
  FlatTree tree =
172
400k
      FilterTree(global_tree, static_props, &num_props,
173
400k
                 &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
565k
  for (auto &node : tree) {
178
565k
    if (node.property0 == -1) {
179
524k
      node.childID = context_map[node.childID];
180
524k
    }
181
565k
  }
182
183
400k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
400k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
400k
                             pixel_type_w offset) -> pixel_type {
188
400k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
400k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
400k
    return val * multiplier + offset;
192
400k
  };
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
400k
  const bool global_tree_is_all_gradient_noop = [&] {
200
400k
    for (const auto& n : global_tree) {
201
400k
      if (n.property == -1) {
202
400k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
400k
            n.multiplier != 1)
204
400k
          return false;
205
400k
      } else if (n.property >= kNumStaticProperties) {
206
400k
        return false;
207
400k
      }
208
400k
    }
209
400k
    return true;
210
400k
  }();
211
212
400k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
392k
    Predictor predictor = tree[0].predictor;
216
392k
    int64_t offset = tree[0].predictor_offset;
217
392k
    int32_t multiplier = tree[0].multiplier;
218
392k
    size_t ctx_id = tree[0].childID;
219
392k
    if (predictor == Predictor::Zero) {
220
372k
      uint32_t value;
221
372k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
372k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
183k
        JXL_DEBUG_V(8, "Fastest track.");
226
183k
        pixel_type v = make_pixel(value, multiplier, offset);
227
5.71M
        for (size_t y = 0; y < channel.h; y++) {
228
5.53M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
5.53M
          std::fill(r, r + channel.w, v);
230
5.53M
        }
231
188k
      } else {
232
188k
        JXL_DEBUG_V(8, "Fast track.");
233
188k
        if (multiplier == 1 && offset == 0) {
234
2.74M
          for (size_t y = 0; y < channel.h; y++) {
235
2.58M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
165M
            for (size_t x = 0; x < channel.w; x++) {
237
162M
              uint32_t v =
238
162M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
162M
              r[x] = UnpackSigned(v);
240
162M
            }
241
2.58M
          }
242
165k
        } else {
243
1.16M
          for (size_t y = 0; y < channel.h; y++) {
244
1.14M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
145M
            for (size_t x = 0; x < channel.w; x++) {
246
144M
              uint32_t v =
247
144M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
144M
                                                                         br);
249
144M
              r[x] = make_pixel(v, multiplier, offset);
250
144M
            }
251
1.14M
          }
252
23.2k
        }
253
188k
      }
254
372k
      return true;
255
372k
    } 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
19.5k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
1.78k
               multiplier == 1) {
291
1.59k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
1.59k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
43.7k
      for (size_t y = 0; y < channel.h; y++) {
294
42.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
2.61M
        for (size_t x = 0; x < channel.w; x++) {
296
2.57M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.57M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.57M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.57M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.57M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.57M
              ctx_id, br);
302
2.57M
          r[x] = make_pixel(v, 1, guess);
303
2.57M
        }
304
42.1k
      }
305
1.59k
      return true;
306
1.59k
    }
307
392k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
26.3k
  if (is_wp_only) {
312
6.34k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
6.34k
  }
314
26.3k
  if (is_gradient_only) {
315
1.12k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.12k
  }
317
318
26.3k
  if (is_gradient_only) {
319
566
    JXL_DEBUG_V(8, "Gradient fast track.");
320
566
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
13.5k
    for (size_t y = 0; y < channel.h; y++) {
322
13.0k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
488k
      for (size_t x = 0; x < channel.w; x++) {
324
475k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
475k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
475k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
475k
        int32_t guess = ClampedGradient(top, left, topleft);
328
475k
        uint32_t pos =
329
475k
            kPropRangeFast +
330
475k
            std::min<pixel_type_w>(
331
475k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
475k
                kPropRangeFast - 1);
333
475k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
475k
        uint64_t v =
335
475k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
475k
        r[x] = make_pixel(v, 1, guess);
337
475k
      }
338
13.0k
    }
339
25.7k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
1.14k
    JXL_DEBUG_V(8, "WP fast track.");
341
1.14k
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
1.14k
    Properties properties(1);
343
26.0k
    for (size_t y = 0; y < channel.h; y++) {
344
24.9k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
24.9k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
24.9k
      const pixel_type *JXL_RESTRICT rtoptop =
347
24.9k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
24.9k
      const pixel_type *JXL_RESTRICT rtopleft =
349
24.9k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
24.9k
      const pixel_type *JXL_RESTRICT rtopright =
351
24.9k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
24.9k
      size_t x = 0;
353
24.9k
      {
354
24.9k
        size_t offset = 0;
355
24.9k
        pixel_type_w left = y ? rtop[x] : 0;
356
24.9k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
24.9k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
24.9k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
24.9k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
24.9k
            offset);
361
24.9k
        uint32_t pos =
362
24.9k
            kPropRangeFast +
363
24.9k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
24.9k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
24.9k
        uint64_t v =
366
24.9k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
24.9k
        r[x] = make_pixel(v, 1, guess);
368
24.9k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
24.9k
      }
370
2.75M
      for (x = 1; x + 1 < channel.w; x++) {
371
2.72M
        size_t offset = 0;
372
2.72M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
2.72M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
2.72M
            rtoptop[x], &properties, offset);
375
2.72M
        uint32_t pos =
376
2.72M
            kPropRangeFast +
377
2.72M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
2.72M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
2.72M
        uint64_t v =
380
2.72M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
2.72M
        r[x] = make_pixel(v, 1, guess);
382
2.72M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
2.72M
      }
384
24.9k
      {
385
24.9k
        size_t offset = 0;
386
24.9k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
24.9k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
24.9k
            rtoptop[x], &properties, offset);
389
24.9k
        uint32_t pos =
390
24.9k
            kPropRangeFast +
391
24.9k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
24.9k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
24.9k
        uint64_t v =
394
24.9k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
24.9k
        r[x] = make_pixel(v, 1, guess);
396
24.9k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
24.9k
      }
398
24.9k
    }
399
24.6k
  } 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
14.8k
    JXL_DEBUG_V(8, "Slow track.");
403
14.8k
    MATreeLookup tree_lookup(tree);
404
14.8k
    Properties properties = Properties(num_props);
405
14.8k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
14.8k
    JXL_ASSIGN_OR_RETURN(
407
14.8k
        Channel references,
408
14.8k
        Channel::Create(memory_manager,
409
14.8k
                        properties.size() - kNumNonrefProperties, channel.w));
410
537k
    for (size_t y = 0; y < channel.h; y++) {
411
522k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
522k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
522k
      InitPropsRow(&properties, static_props, y);
414
522k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.36M
        for (size_t x = 0; x < 2; x++) {
416
909k
          PredictionResult res =
417
909k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
909k
                              tree_lookup, references);
419
909k
          uint64_t v =
420
909k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
909k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
909k
        }
423
43.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
43.1M
          PredictionResult res =
425
43.1M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
43.1M
                                 tree_lookup, references);
427
43.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
43.1M
              res.context, br);
429
43.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
43.1M
        }
431
1.36M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
909k
          PredictionResult res =
433
909k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
909k
                              tree_lookup, references);
435
909k
          uint64_t v =
436
909k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
909k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
909k
        }
439
454k
      } else {
440
2.00M
        for (size_t x = 0; x < channel.w; x++) {
441
1.93M
          PredictionResult res =
442
1.93M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
1.93M
                              tree_lookup, references);
444
1.93M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
1.93M
              res.context, br);
446
1.93M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
1.93M
        }
448
67.9k
      }
449
522k
    }
450
14.8k
  } else {
451
9.84k
    JXL_DEBUG_V(8, "Slowest track.");
452
9.84k
    MATreeLookup tree_lookup(tree);
453
9.84k
    Properties properties = Properties(num_props);
454
9.84k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
9.84k
    JXL_ASSIGN_OR_RETURN(
456
9.84k
        Channel references,
457
9.84k
        Channel::Create(memory_manager,
458
9.84k
                        properties.size() - kNumNonrefProperties, channel.w));
459
9.84k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
270k
    for (size_t y = 0; y < channel.h; y++) {
461
260k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
260k
      InitPropsRow(&properties, static_props, y);
463
260k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
260k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
663k
        for (size_t x = 0; x < 2; x++) {
466
442k
          PredictionResult res =
467
442k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
442k
                            tree_lookup, references, &wp_state);
469
442k
          uint64_t v =
470
442k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
442k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
442k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
442k
        }
474
16.5M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
16.3M
          PredictionResult res =
476
16.3M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
16.3M
                               tree_lookup, references, &wp_state);
478
16.3M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
16.3M
              res.context, br);
480
16.3M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
16.3M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
16.3M
        }
483
663k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
442k
          PredictionResult res =
485
442k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
442k
                            tree_lookup, references, &wp_state);
487
442k
          uint64_t v =
488
442k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
442k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
442k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
442k
        }
492
221k
      } else {
493
1.78M
        for (size_t x = 0; x < channel.w; x++) {
494
1.74M
          PredictionResult res =
495
1.74M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
1.74M
                            tree_lookup, references, &wp_state);
497
1.74M
          uint64_t v =
498
1.74M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
1.74M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
1.74M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
1.74M
        }
502
39.4k
      }
503
260k
    }
504
9.84k
  }
505
26.3k
  return true;
506
26.3k
}
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
439k
                                 uint32_t &fl_v) {
517
439k
  if (reader->UsesLZ77()) {
518
38.6k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
38.6k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
38.6k
        tree_lut, image, fl_run, fl_v);
521
400k
  } else {
522
400k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
400k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
400k
        tree_lut, image, fl_run, fl_v);
525
400k
  }
526
439k
}
527
528
195k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
50.6k
                                 const ModularOptions &options) {
532
50.6k
  size_t nb_channels = image.channel.size();
533
101k
  for (bool is_dc : {true, false}) {
534
101k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
101k
    size_t c = image.nb_meta_channels;
536
1.01M
    for (; c < nb_channels; c++) {
537
913k
      const Channel &ch = image.channel[c];
538
913k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
913k
    }
540
128k
    for (; c < nb_channels; c++) {
541
27.5k
      const Channel &ch = image.channel[c];
542
27.5k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
26.9k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
26.9k
      if (is_dc_channel != is_dc) continue;
545
13.4k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
13.4k
      if (tile_dim == 0) {
547
3
        return JXL_FAILURE("Inconsistent transforms");
548
3
      }
549
13.4k
    }
550
101k
  }
551
50.6k
  return true;
552
50.6k
}
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
57.4k
                     const bool allow_truncated_group) {
559
57.4k
  if (image.channel.empty()) return true;
560
49.7k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
49.7k
  Status status = Bundle::Read(br, &header);
564
49.7k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
48.9k
  if (status.IsFatalError()) return status;
566
48.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
48.9k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
48.9k
              header.transforms.size());
578
48.9k
  image.transform = header.transforms;
579
48.9k
  for (Transform &transform : image.transform) {
580
29.9k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
29.9k
  }
582
48.8k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
48.8k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
48.8k
  size_t nb_channels = image.channel.size();
588
589
48.8k
  size_t num_chans = 0;
590
48.8k
  size_t distance_multiplier = 0;
591
505k
  for (size_t i = 0; i < nb_channels; i++) {
592
458k
    Channel &channel = image.channel[i];
593
458k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
452k
                                        channel.h > options->max_chan_size)) {
595
1.53k
      break;
596
1.53k
    }
597
456k
    if (!channel.w || !channel.h) {
598
6.28k
      continue;  // skip empty channels
599
6.28k
    }
600
450k
    if (channel.w > distance_multiplier) {
601
81.1k
      distance_multiplier = channel.w;
602
81.1k
    }
603
450k
    num_chans++;
604
450k
  }
605
48.8k
  if (num_chans == 0) return true;
606
607
48.2k
  size_t next_channel = 0;
608
48.2k
  auto scope_guard = MakeScopeGuard([&]() {
609
17.3k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
14.4k
      ZeroFillImage(&image.channel[c].plane);
611
14.4k
    }
612
2.95k
  });
613
  // Do not do anything if truncated groups are not allowed.
614
48.2k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
48.2k
  Tree tree_storage;
618
48.2k
  std::vector<uint8_t> context_map_storage;
619
48.2k
  ANSCode code_storage;
620
48.2k
  const Tree *tree = &tree_storage;
621
48.2k
  const ANSCode *code = &code_storage;
622
48.2k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
48.2k
  if (!header.use_global_tree) {
624
27.8k
    uint64_t max_tree_size = 1024;
625
348k
    for (size_t i = 0; i < nb_channels; i++) {
626
320k
      Channel &channel = image.channel[i];
627
320k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
319k
                                          channel.h > options->max_chan_size)) {
629
39
        break;
630
39
      }
631
320k
      uint64_t pixels = channel.w * channel.h;
632
320k
      max_tree_size += pixels;
633
320k
    }
634
27.8k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
27.8k
    JXL_RETURN_IF_ERROR(
636
27.8k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
27.5k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
27.5k
                                         (tree_storage.size() + 1) / 2,
639
27.5k
                                         &code_storage, &context_map_storage));
640
27.5k
  } else {
641
20.4k
    if (!global_tree || !global_code || !global_ctx_map ||
642
20.4k
        global_tree->empty()) {
643
66
      return JXL_FAILURE("No global tree available but one was requested");
644
66
    }
645
20.3k
    tree = global_tree;
646
20.3k
    code = global_code;
647
20.3k
    context_map = global_ctx_map;
648
20.3k
  }
649
650
  // Read channels
651
95.6k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
95.6k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
95.6k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
95.6k
  uint32_t fl_run = 0;
655
95.6k
  uint32_t fl_v = 0;
656
490k
  for (; next_channel < nb_channels; next_channel++) {
657
446k
    Channel &channel = image.channel[next_channel];
658
446k
    if (next_channel >= image.nb_meta_channels &&
659
440k
        (channel.w > options->max_chan_size ||
660
440k
         channel.h > options->max_chan_size)) {
661
994
      break;
662
994
    }
663
445k
    if (!channel.w || !channel.h) {
664
6.00k
      continue;  // skip empty channels
665
6.00k
    }
666
439k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
439k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
439k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
439k
    if (!br->AllReadsWithinBounds()) {
672
2.51k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
2.51k
    }
675
439k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
45.3k
  scope_guard.Disarm();
679
680
45.3k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
45.3k
  return true;
684
45.3k
}
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
57.4k
                                bool allow_truncated_group) {
692
57.4k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
57.4k
  req_sizes.reserve(image.channel.size());
694
182k
  for (const auto &c : image.channel) {
695
182k
    req_sizes.emplace_back(c.w, c.h);
696
182k
  }
697
57.4k
  GroupHeader local_header;
698
57.4k
  if (header == nullptr) header = &local_header;
699
57.4k
  size_t bit_pos = br->TotalBitsConsumed();
700
57.4k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
57.4k
                                  code, ctx_map, allow_truncated_group);
702
57.4k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
53.5k
  if (dec_status.IsFatalError()) return dec_status;
704
53.5k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
53.5k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
53.5k
  JXL_DEBUG_V(4,
707
53.5k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
53.5k
              " image from %" PRIuS " bytes",
709
53.5k
              image.w, image.h, image.channel.size(),
710
53.5k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
53.5k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
53.5k
  (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
53.5k
  if (undo_transforms) {
717
15.7k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
78.9k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
63.2k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
63.2k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
63.2k
    }
722
15.7k
  }
723
53.5k
  return dec_status;
724
53.5k
}
725
726
}  // namespace jxl