Coverage Report

Created: 2026-10-28 07:26

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
1.13M
                    bool *gradient_only) {
46
1.13M
  *num_props = 0;
47
1.13M
  bool has_wp = false;
48
1.13M
  bool has_non_wp = false;
49
1.13M
  *gradient_only = true;
50
1.13M
  const auto mark_property = [&](int32_t p) {
51
1.09M
    if (p == kWPProp) {
52
172k
      has_wp = true;
53
925k
    } else if (p >= kNumStaticProperties) {
54
463k
      has_non_wp = true;
55
463k
    }
56
1.09M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
535k
      *gradient_only = false;
58
535k
    }
59
1.09M
  };
60
1.13M
  FlatTree output;
61
1.13M
  std::queue<size_t> nodes;
62
1.13M
  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
3.73M
  while (!nodes.empty()) {
70
2.60M
    size_t cur = nodes.front();
71
2.60M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
2.77M
    while (global_tree[cur].property < kNumStaticProperties &&
74
2.41M
           global_tree[cur].property != -1) {
75
175k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
99.7k
        cur = global_tree[cur].lchild;
77
99.7k
      } else {
78
75.9k
        cur = global_tree[cur].rchild;
79
75.9k
      }
80
175k
    }
81
2.60M
    FlatDecisionNode flat;
82
2.60M
    if (global_tree[cur].property == -1) {
83
2.23M
      flat.property0 = -1;
84
2.23M
      flat.childID = global_tree[cur].lchild;
85
2.23M
      flat.predictor = global_tree[cur].predictor;
86
2.23M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
2.23M
      flat.multiplier = global_tree[cur].multiplier;
88
2.23M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
2.23M
      has_wp |= flat.predictor == Predictor::Weighted;
90
2.23M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
2.23M
      output.push_back(flat);
92
2.23M
      continue;
93
2.23M
    }
94
365k
    flat.childID = output.size() + nodes.size() + 1;
95
96
365k
    flat.property0 = global_tree[cur].property;
97
365k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
365k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.09M
    for (size_t i = 0; i < 2; i++) {
101
731k
      size_t cur_child =
102
731k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
776k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
506k
             global_tree[cur_child].property != -1) {
106
44.9k
        if (static_props[global_tree[cur_child].property] >
107
44.9k
            global_tree[cur_child].splitval) {
108
23.3k
          cur_child = global_tree[cur_child].lchild;
109
23.3k
        } else {
110
21.5k
          cur_child = global_tree[cur_child].rchild;
111
21.5k
        }
112
44.9k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
731k
      if (global_tree[cur_child].property == -1) {
116
461k
        flat.properties[i] = 0;
117
461k
        flat.splitvals[i] = 0;
118
461k
        nodes.push(cur_child);
119
461k
        nodes.push(cur_child);
120
461k
      } else {
121
269k
        flat.properties[i] = global_tree[cur_child].property;
122
269k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
269k
        nodes.push(global_tree[cur_child].lchild);
124
269k
        nodes.push(global_tree[cur_child].rchild);
125
269k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
269k
      }
127
731k
    }
128
129
731k
    for (int16_t property : flat.properties) mark_property(property);
130
365k
    mark_property(flat.property0);
131
365k
    output.push_back(flat);
132
365k
  }
133
1.13M
  if (*num_props > kNumNonrefProperties) {
134
4.48k
    *num_props =
135
4.48k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
4.48k
            kExtraPropsPerChannel +
137
4.48k
        kNumNonrefProperties;
138
1.13M
  } else {
139
1.13M
    *num_props = kNumNonrefProperties;
140
1.13M
  }
141
1.13M
  *use_wp = has_wp;
142
1.13M
  *wp_only = has_wp && !has_non_wp;
143
144
1.13M
  return output;
145
1.13M
}
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
1.09M
                                 uint32_t &fl_v) {
157
1.09M
  JxlMemoryManager *memory_manager = image->memory_manager();
158
1.09M
  Channel &channel = image->channel[chan];
159
160
1.09M
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
1.09M
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
1.09M
  if (channel.w == 0 || channel.h == 0) return true;
166
167
1.09M
  bool tree_has_wp_prop_or_pred = false;
168
1.09M
  bool is_wp_only = false;
169
1.09M
  bool is_gradient_only = false;
170
1.09M
  size_t num_props;
171
1.09M
  FlatTree tree =
172
1.09M
      FilterTree(global_tree, static_props, &num_props,
173
1.09M
                 &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
2.05M
  for (auto &node : tree) {
178
2.05M
    if (node.property0 == -1) {
179
1.81M
      node.childID = context_map[node.childID];
180
1.81M
    }
181
2.05M
  }
182
183
1.09M
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
1.09M
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
694M
                             pixel_type_w offset) -> pixel_type {
188
694M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
694M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
694M
    return val * multiplier + offset;
192
694M
  };
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
269M
                             pixel_type_w offset) -> pixel_type {
188
269M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
269M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
269M
    return val * multiplier + offset;
192
269M
  };
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
424M
                             pixel_type_w offset) -> pixel_type {
188
424M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
424M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
424M
    return val * multiplier + offset;
192
424M
  };
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
1.09M
  const bool global_tree_is_all_gradient_noop = [&] {
200
1.16M
    for (const auto& n : global_tree) {
201
1.16M
      if (n.property == -1) {
202
1.00M
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
8.85k
            n.multiplier != 1)
204
1.00M
          return false;
205
1.00M
      } else if (n.property >= kNumStaticProperties) {
206
89.6k
        return false;
207
89.6k
      }
208
1.16M
    }
209
3.88k
    return true;
210
1.09M
  }();
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
199k
  const bool global_tree_is_all_gradient_noop = [&] {
200
202k
    for (const auto& n : global_tree) {
201
202k
      if (n.property == -1) {
202
154k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
2.23k
            n.multiplier != 1)
204
152k
          return false;
205
154k
      } else if (n.property >= kNumStaticProperties) {
206
44.8k
        return false;
207
44.8k
      }
208
202k
    }
209
1.68k
    return true;
210
199k
  }();
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
894k
  const bool global_tree_is_all_gradient_noop = [&] {
200
963k
    for (const auto& n : global_tree) {
201
963k
      if (n.property == -1) {
202
853k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
6.61k
            n.multiplier != 1)
204
847k
          return false;
205
853k
      } else if (n.property >= kNumStaticProperties) {
206
44.7k
        return false;
207
44.7k
      }
208
963k
    }
209
2.20k
    return true;
210
894k
  }();
211
212
1.09M
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
1.01M
    Predictor predictor = tree[0].predictor;
216
1.01M
    int64_t offset = tree[0].predictor_offset;
217
1.01M
    int32_t multiplier = tree[0].multiplier;
218
1.01M
    size_t ctx_id = tree[0].childID;
219
1.01M
    if (predictor == Predictor::Zero) {
220
802k
      uint32_t value;
221
802k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
802k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
114k
        JXL_DEBUG_V(8, "Fastest track.");
226
114k
        pixel_type v = make_pixel(value, multiplier, offset);
227
2.33M
        for (size_t y = 0; y < channel.h; y++) {
228
2.22M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
2.22M
          std::fill(r, r + channel.w, v);
230
2.22M
        }
231
688k
      } else {
232
688k
        JXL_DEBUG_V(8, "Fast track.");
233
688k
        if (multiplier == 1 && offset == 0) {
234
7.72M
          for (size_t y = 0; y < channel.h; y++) {
235
7.09M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
305M
            for (size_t x = 0; x < channel.w; x++) {
237
298M
              uint32_t v =
238
298M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
298M
              r[x] = UnpackSigned(v);
240
298M
            }
241
7.09M
          }
242
621k
        } else {
243
675k
          for (size_t y = 0; y < channel.h; y++) {
244
607k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
28.6M
            for (size_t x = 0; x < channel.w; x++) {
246
28.0M
              uint32_t v =
247
28.0M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
28.0M
                                                                         br);
249
28.0M
              r[x] = make_pixel(v, multiplier, offset);
250
28.0M
            }
251
607k
          }
252
67.2k
        }
253
688k
      }
254
802k
      return true;
255
802k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
484
               global_tree_is_all_gradient_noop) {
257
477
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
477
      pixel_type_w sv = UnpackSigned(fl_v);
259
6.40k
      for (size_t y = 0; y < channel.h; y++) {
260
5.93k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
5.93k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
5.93k
        const pixel_type *JXL_RESTRICT rtopleft =
263
5.93k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
5.93k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
5.93k
        if (fl_run == 0) {
266
5.93k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.93k
                                                     &fl_run);
268
5.93k
          sv = UnpackSigned(fl_v);
269
5.93k
        } else {
270
0
          fl_run--;
271
0
        }
272
5.93k
        r[0] = sv + guess_0;
273
223k
        for (size_t x = 1; x < channel.w; x++) {
274
217k
          pixel_type left = r[x - 1];
275
217k
          pixel_type top = rtop[x];
276
217k
          pixel_type topleft = rtopleft[x];
277
217k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
217k
          if (!fl_run) {
279
217k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
217k
                                                       &fl_run);
281
217k
            sv = UnpackSigned(fl_v);
282
217k
          } else {
283
0
            fl_run--;
284
0
          }
285
217k
          r[x] = sv + guess;
286
217k
        }
287
5.93k
      }
288
477
      return true;
289
206k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
10.5k
               multiplier == 1) {
291
9.46k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
9.46k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
196k
      for (size_t y = 0; y < channel.h; y++) {
294
186k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
4.21M
        for (size_t x = 0; x < channel.w; x++) {
296
4.02M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
4.02M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
4.02M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
4.02M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
4.02M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
4.02M
              ctx_id, br);
302
4.02M
          r[x] = make_pixel(v, 1, guess);
303
4.02M
        }
304
186k
      }
305
9.46k
      return true;
306
9.46k
    }
307
1.01M
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
281k
  if (is_wp_only) {
312
18.5k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
18.5k
  }
314
281k
  if (is_gradient_only) {
315
7.63k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
7.63k
  }
317
318
281k
  if (is_gradient_only) {
319
4.73k
    JXL_DEBUG_V(8, "Gradient fast track.");
320
4.73k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
189k
    for (size_t y = 0; y < channel.h; y++) {
322
184k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
4.81M
      for (size_t x = 0; x < channel.w; x++) {
324
4.63M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
4.63M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
4.63M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
4.63M
        int32_t guess = ClampedGradient(top, left, topleft);
328
4.63M
        uint32_t pos =
329
4.63M
            kPropRangeFast +
330
4.63M
            std::min<pixel_type_w>(
331
4.63M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
4.63M
                kPropRangeFast - 1);
333
4.63M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
4.63M
        uint64_t v =
335
4.63M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
4.63M
        r[x] = make_pixel(v, 1, guess);
337
4.63M
      }
338
184k
    }
339
276k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
9.07k
    JXL_DEBUG_V(8, "WP fast track.");
341
9.07k
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
9.07k
    Properties properties(1);
343
361k
    for (size_t y = 0; y < channel.h; y++) {
344
352k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
352k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
352k
      const pixel_type *JXL_RESTRICT rtoptop =
347
352k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
352k
      const pixel_type *JXL_RESTRICT rtopleft =
349
352k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
352k
      const pixel_type *JXL_RESTRICT rtopright =
351
352k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
352k
      size_t x = 0;
353
352k
      {
354
352k
        size_t offset = 0;
355
352k
        pixel_type_w left = y ? rtop[x] : 0;
356
352k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
352k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
352k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
352k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
352k
            offset);
361
352k
        uint32_t pos =
362
352k
            kPropRangeFast +
363
352k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
352k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
352k
        uint64_t v =
366
352k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
352k
        r[x] = make_pixel(v, 1, guess);
368
352k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
352k
      }
370
14.2M
      for (x = 1; x + 1 < channel.w; x++) {
371
13.8M
        size_t offset = 0;
372
13.8M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
13.8M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
13.8M
            rtoptop[x], &properties, offset);
375
13.8M
        uint32_t pos =
376
13.8M
            kPropRangeFast +
377
13.8M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
13.8M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
13.8M
        uint64_t v =
380
13.8M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
13.8M
        r[x] = make_pixel(v, 1, guess);
382
13.8M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
13.8M
      }
384
352k
      {
385
352k
        size_t offset = 0;
386
352k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
352k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
352k
            rtoptop[x], &properties, offset);
389
352k
        uint32_t pos =
390
352k
            kPropRangeFast +
391
352k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
352k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
352k
        uint64_t v =
394
352k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
352k
        r[x] = make_pixel(v, 1, guess);
396
352k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
352k
      }
398
352k
    }
399
267k
  } 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
201k
    JXL_DEBUG_V(8, "Slow track.");
403
201k
    MATreeLookup tree_lookup(tree);
404
201k
    Properties properties = Properties(num_props);
405
201k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
201k
    JXL_ASSIGN_OR_RETURN(
407
201k
        Channel references,
408
201k
        Channel::Create(memory_manager,
409
201k
                        properties.size() - kNumNonrefProperties, channel.w));
410
12.8M
    for (size_t y = 0; y < channel.h; y++) {
411
12.6M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
12.6M
      PrecomputeReferences(channel, y, *image, chan, &references);
413
12.6M
      InitPropsRow(&properties, static_props, y);
414
12.6M
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
23.3M
        for (size_t x = 0; x < 2; x++) {
416
15.5M
          PredictionResult res =
417
15.5M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
15.5M
                              tree_lookup, references);
419
15.5M
          uint64_t v =
420
15.5M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
15.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
15.5M
        }
423
458M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
451M
          PredictionResult res =
425
451M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
451M
                                 tree_lookup, references);
427
451M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
451M
              res.context, br);
429
451M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
451M
        }
431
23.3M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
15.5M
          PredictionResult res =
433
15.5M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
15.5M
                              tree_lookup, references);
435
15.5M
          uint64_t v =
436
15.5M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
15.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
15.5M
        }
439
7.78M
      } else {
440
43.5M
        for (size_t x = 0; x < channel.w; x++) {
441
38.7M
          PredictionResult res =
442
38.7M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
38.7M
                              tree_lookup, references);
444
38.7M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
38.7M
              res.context, br);
446
38.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
38.7M
        }
448
4.81M
      }
449
12.6M
    }
450
201k
  } else {
451
65.4k
    JXL_DEBUG_V(8, "Slowest track.");
452
65.4k
    MATreeLookup tree_lookup(tree);
453
65.4k
    Properties properties = Properties(num_props);
454
65.4k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
65.4k
    JXL_ASSIGN_OR_RETURN(
456
65.4k
        Channel references,
457
65.4k
        Channel::Create(memory_manager,
458
65.4k
                        properties.size() - kNumNonrefProperties, channel.w));
459
65.4k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
1.59M
    for (size_t y = 0; y < channel.h; y++) {
461
1.53M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
1.53M
      InitPropsRow(&properties, static_props, y);
463
1.53M
      PrecomputeReferences(channel, y, *image, chan, &references);
464
1.53M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
1.51M
        for (size_t x = 0; x < 2; x++) {
466
1.00M
          PredictionResult res =
467
1.00M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
1.00M
                            tree_lookup, references, &wp_state);
469
1.00M
          uint64_t v =
470
1.00M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
1.00M
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
1.00M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
1.00M
        }
474
110M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
109M
          PredictionResult res =
476
109M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
109M
                               tree_lookup, references, &wp_state);
478
109M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
109M
              res.context, br);
480
109M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
109M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
109M
        }
483
1.51M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
1.00M
          PredictionResult res =
485
1.00M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
1.00M
                            tree_lookup, references, &wp_state);
487
1.00M
          uint64_t v =
488
1.00M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
1.00M
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
1.00M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
1.00M
        }
492
1.02M
      } else {
493
11.5M
        for (size_t x = 0; x < channel.w; x++) {
494
10.4M
          PredictionResult res =
495
10.4M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
10.4M
                            tree_lookup, references, &wp_state);
497
10.4M
          uint64_t v =
498
10.4M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
10.4M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
10.4M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
10.4M
        }
502
1.02M
      }
503
1.53M
    }
504
65.4k
  }
505
281k
  return true;
506
281k
}
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
199k
                                 uint32_t &fl_v) {
157
199k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
199k
  Channel &channel = image->channel[chan];
159
160
199k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
199k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
199k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
199k
  bool tree_has_wp_prop_or_pred = false;
168
199k
  bool is_wp_only = false;
169
199k
  bool is_gradient_only = false;
170
199k
  size_t num_props;
171
199k
  FlatTree tree =
172
199k
      FilterTree(global_tree, static_props, &num_props,
173
199k
                 &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
381k
  for (auto &node : tree) {
178
381k
    if (node.property0 == -1) {
179
336k
      node.childID = context_map[node.childID];
180
336k
    }
181
381k
  }
182
183
199k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
199k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
199k
                             pixel_type_w offset) -> pixel_type {
188
199k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
199k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
199k
    return val * multiplier + offset;
192
199k
  };
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
199k
  const bool global_tree_is_all_gradient_noop = [&] {
200
199k
    for (const auto& n : global_tree) {
201
199k
      if (n.property == -1) {
202
199k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
199k
            n.multiplier != 1)
204
199k
          return false;
205
199k
      } else if (n.property >= kNumStaticProperties) {
206
199k
        return false;
207
199k
      }
208
199k
    }
209
199k
    return true;
210
199k
  }();
211
212
199k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
154k
    Predictor predictor = tree[0].predictor;
216
154k
    int64_t offset = tree[0].predictor_offset;
217
154k
    int32_t multiplier = tree[0].multiplier;
218
154k
    size_t ctx_id = tree[0].childID;
219
154k
    if (predictor == Predictor::Zero) {
220
107k
      uint32_t value;
221
107k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
107k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
20.4k
        JXL_DEBUG_V(8, "Fastest track.");
226
20.4k
        pixel_type v = make_pixel(value, multiplier, offset);
227
640k
        for (size_t y = 0; y < channel.h; y++) {
228
619k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
619k
          std::fill(r, r + channel.w, v);
230
619k
        }
231
86.9k
      } else {
232
86.9k
        JXL_DEBUG_V(8, "Fast track.");
233
86.9k
        if (multiplier == 1 && offset == 0) {
234
1.26M
          for (size_t y = 0; y < channel.h; y++) {
235
1.19M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
36.8M
            for (size_t x = 0; x < channel.w; x++) {
237
35.6M
              uint32_t v =
238
35.6M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
35.6M
              r[x] = UnpackSigned(v);
240
35.6M
            }
241
1.19M
          }
242
70.7k
        } else {
243
201k
          for (size_t y = 0; y < channel.h; y++) {
244
185k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
8.35M
            for (size_t x = 0; x < channel.w; x++) {
246
8.16M
              uint32_t v =
247
8.16M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
8.16M
                                                                         br);
249
8.16M
              r[x] = make_pixel(v, multiplier, offset);
250
8.16M
            }
251
185k
          }
252
16.2k
        }
253
86.9k
      }
254
107k
      return true;
255
107k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
484
               global_tree_is_all_gradient_noop) {
257
477
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
477
      pixel_type_w sv = UnpackSigned(fl_v);
259
6.40k
      for (size_t y = 0; y < channel.h; y++) {
260
5.93k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
5.93k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
5.93k
        const pixel_type *JXL_RESTRICT rtopleft =
263
5.93k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
5.93k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
5.93k
        if (fl_run == 0) {
266
5.93k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.93k
                                                     &fl_run);
268
5.93k
          sv = UnpackSigned(fl_v);
269
5.93k
        } else {
270
0
          fl_run--;
271
0
        }
272
5.93k
        r[0] = sv + guess_0;
273
223k
        for (size_t x = 1; x < channel.w; x++) {
274
217k
          pixel_type left = r[x - 1];
275
217k
          pixel_type top = rtop[x];
276
217k
          pixel_type topleft = rtopleft[x];
277
217k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
217k
          if (!fl_run) {
279
217k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
217k
                                                       &fl_run);
281
217k
            sv = UnpackSigned(fl_v);
282
217k
          } else {
283
0
            fl_run--;
284
0
          }
285
217k
          r[x] = sv + guess;
286
217k
        }
287
5.93k
      }
288
477
      return true;
289
46.6k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
1.89k
               multiplier == 1) {
291
1.36k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
1.36k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
23.5k
      for (size_t y = 0; y < channel.h; y++) {
294
22.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
1.72M
        for (size_t x = 0; x < channel.w; x++) {
296
1.69M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
1.69M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
1.69M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
1.69M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
1.69M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
1.69M
              ctx_id, br);
302
1.69M
          r[x] = make_pixel(v, 1, guess);
303
1.69M
        }
304
22.1k
      }
305
1.36k
      return true;
306
1.36k
    }
307
154k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
90.0k
  if (is_wp_only) {
312
1.84k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
1.84k
  }
314
90.0k
  if (is_gradient_only) {
315
1.46k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.46k
  }
317
318
90.0k
  if (is_gradient_only) {
319
156
    JXL_DEBUG_V(8, "Gradient fast track.");
320
156
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
12.3k
    for (size_t y = 0; y < channel.h; y++) {
322
12.1k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
1.92M
      for (size_t x = 0; x < channel.w; x++) {
324
1.91M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
1.91M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
1.91M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
1.91M
        int32_t guess = ClampedGradient(top, left, topleft);
328
1.91M
        uint32_t pos =
329
1.91M
            kPropRangeFast +
330
1.91M
            std::min<pixel_type_w>(
331
1.91M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
1.91M
                kPropRangeFast - 1);
333
1.91M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
1.91M
        uint64_t v =
335
1.91M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
1.91M
        r[x] = make_pixel(v, 1, guess);
337
1.91M
      }
338
12.1k
    }
339
89.8k
  } 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
89.8k
  } 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
45.9k
    JXL_DEBUG_V(8, "Slow track.");
403
45.9k
    MATreeLookup tree_lookup(tree);
404
45.9k
    Properties properties = Properties(num_props);
405
45.9k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
45.9k
    JXL_ASSIGN_OR_RETURN(
407
45.9k
        Channel references,
408
45.9k
        Channel::Create(memory_manager,
409
45.9k
                        properties.size() - kNumNonrefProperties, channel.w));
410
7.39M
    for (size_t y = 0; y < channel.h; y++) {
411
7.35M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
7.35M
      PrecomputeReferences(channel, y, *image, chan, &references);
413
7.35M
      InitPropsRow(&properties, static_props, y);
414
7.35M
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
9.84M
        for (size_t x = 0; x < 2; x++) {
416
6.56M
          PredictionResult res =
417
6.56M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
6.56M
                              tree_lookup, references);
419
6.56M
          uint64_t v =
420
6.56M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
6.56M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
6.56M
        }
423
222M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
218M
          PredictionResult res =
425
218M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
218M
                                 tree_lookup, references);
427
218M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
218M
              res.context, br);
429
218M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
218M
        }
431
9.84M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
6.56M
          PredictionResult res =
433
6.56M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
6.56M
                              tree_lookup, references);
435
6.56M
          uint64_t v =
436
6.56M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
6.56M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
6.56M
        }
439
4.06M
      } else {
440
27.6M
        for (size_t x = 0; x < channel.w; x++) {
441
23.6M
          PredictionResult res =
442
23.6M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
23.6M
                              tree_lookup, references);
444
23.6M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
23.6M
              res.context, br);
446
23.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
23.6M
        }
448
4.06M
      }
449
7.35M
    }
450
45.9k
  } else {
451
43.9k
    JXL_DEBUG_V(8, "Slowest track.");
452
43.9k
    MATreeLookup tree_lookup(tree);
453
43.9k
    Properties properties = Properties(num_props);
454
43.9k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
43.9k
    JXL_ASSIGN_OR_RETURN(
456
43.9k
        Channel references,
457
43.9k
        Channel::Create(memory_manager,
458
43.9k
                        properties.size() - kNumNonrefProperties, channel.w));
459
43.9k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
135k
    for (size_t y = 0; y < channel.h; y++) {
461
91.3k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
91.3k
      InitPropsRow(&properties, static_props, y);
463
91.3k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
91.3k
      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
91.3k
      } else {
493
2.44M
        for (size_t x = 0; x < channel.w; x++) {
494
2.35M
          PredictionResult res =
495
2.35M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.35M
                            tree_lookup, references, &wp_state);
497
2.35M
          uint64_t v =
498
2.35M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.35M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.35M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.35M
        }
502
91.3k
      }
503
91.3k
    }
504
43.9k
  }
505
90.0k
  return true;
506
90.0k
}
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
894k
                                 uint32_t &fl_v) {
157
894k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
894k
  Channel &channel = image->channel[chan];
159
160
894k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
894k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
894k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
894k
  bool tree_has_wp_prop_or_pred = false;
168
894k
  bool is_wp_only = false;
169
894k
  bool is_gradient_only = false;
170
894k
  size_t num_props;
171
894k
  FlatTree tree =
172
894k
      FilterTree(global_tree, static_props, &num_props,
173
894k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
1.67M
  for (auto &node : tree) {
178
1.67M
    if (node.property0 == -1) {
179
1.48M
      node.childID = context_map[node.childID];
180
1.48M
    }
181
1.67M
  }
182
183
894k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
894k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
894k
                             pixel_type_w offset) -> pixel_type {
188
894k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
894k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
894k
    return val * multiplier + offset;
192
894k
  };
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
894k
  const bool global_tree_is_all_gradient_noop = [&] {
200
894k
    for (const auto& n : global_tree) {
201
894k
      if (n.property == -1) {
202
894k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
894k
            n.multiplier != 1)
204
894k
          return false;
205
894k
      } else if (n.property >= kNumStaticProperties) {
206
894k
        return false;
207
894k
      }
208
894k
    }
209
894k
    return true;
210
894k
  }();
211
212
894k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
855k
    Predictor predictor = tree[0].predictor;
216
855k
    int64_t offset = tree[0].predictor_offset;
217
855k
    int32_t multiplier = tree[0].multiplier;
218
855k
    size_t ctx_id = tree[0].childID;
219
855k
    if (predictor == Predictor::Zero) {
220
695k
      uint32_t value;
221
695k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
695k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
93.7k
        JXL_DEBUG_V(8, "Fastest track.");
226
93.7k
        pixel_type v = make_pixel(value, multiplier, offset);
227
1.69M
        for (size_t y = 0; y < channel.h; y++) {
228
1.60M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
1.60M
          std::fill(r, r + channel.w, v);
230
1.60M
        }
231
601k
      } else {
232
601k
        JXL_DEBUG_V(8, "Fast track.");
233
601k
        if (multiplier == 1 && offset == 0) {
234
6.45M
          for (size_t y = 0; y < channel.h; y++) {
235
5.90M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
268M
            for (size_t x = 0; x < channel.w; x++) {
237
262M
              uint32_t v =
238
262M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
262M
              r[x] = UnpackSigned(v);
240
262M
            }
241
5.90M
          }
242
550k
        } else {
243
473k
          for (size_t y = 0; y < channel.h; y++) {
244
422k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
20.3M
            for (size_t x = 0; x < channel.w; x++) {
246
19.9M
              uint32_t v =
247
19.9M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
19.9M
                                                                         br);
249
19.9M
              r[x] = make_pixel(v, multiplier, offset);
250
19.9M
            }
251
422k
          }
252
50.9k
        }
253
601k
      }
254
695k
      return true;
255
695k
    } 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
160k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
8.65k
               multiplier == 1) {
291
8.10k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
8.10k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
172k
      for (size_t y = 0; y < channel.h; y++) {
294
164k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
2.48M
        for (size_t x = 0; x < channel.w; x++) {
296
2.32M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.32M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.32M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.32M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.32M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.32M
              ctx_id, br);
302
2.32M
          r[x] = make_pixel(v, 1, guess);
303
2.32M
        }
304
164k
      }
305
8.10k
      return true;
306
8.10k
    }
307
855k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
191k
  if (is_wp_only) {
312
16.7k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
16.7k
  }
314
191k
  if (is_gradient_only) {
315
6.16k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
6.16k
  }
317
318
191k
  if (is_gradient_only) {
319
4.58k
    JXL_DEBUG_V(8, "Gradient fast track.");
320
4.58k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
176k
    for (size_t y = 0; y < channel.h; y++) {
322
172k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
2.88M
      for (size_t x = 0; x < channel.w; x++) {
324
2.71M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
2.71M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
2.71M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
2.71M
        int32_t guess = ClampedGradient(top, left, topleft);
328
2.71M
        uint32_t pos =
329
2.71M
            kPropRangeFast +
330
2.71M
            std::min<pixel_type_w>(
331
2.71M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
2.71M
                kPropRangeFast - 1);
333
2.71M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
2.71M
        uint64_t v =
335
2.71M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
2.71M
        r[x] = make_pixel(v, 1, guess);
337
2.71M
      }
338
172k
    }
339
186k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
9.07k
    JXL_DEBUG_V(8, "WP fast track.");
341
9.07k
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
9.07k
    Properties properties(1);
343
361k
    for (size_t y = 0; y < channel.h; y++) {
344
352k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
352k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
352k
      const pixel_type *JXL_RESTRICT rtoptop =
347
352k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
352k
      const pixel_type *JXL_RESTRICT rtopleft =
349
352k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
352k
      const pixel_type *JXL_RESTRICT rtopright =
351
352k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
352k
      size_t x = 0;
353
352k
      {
354
352k
        size_t offset = 0;
355
352k
        pixel_type_w left = y ? rtop[x] : 0;
356
352k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
352k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
352k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
352k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
352k
            offset);
361
352k
        uint32_t pos =
362
352k
            kPropRangeFast +
363
352k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
352k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
352k
        uint64_t v =
366
352k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
352k
        r[x] = make_pixel(v, 1, guess);
368
352k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
352k
      }
370
14.2M
      for (x = 1; x + 1 < channel.w; x++) {
371
13.8M
        size_t offset = 0;
372
13.8M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
13.8M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
13.8M
            rtoptop[x], &properties, offset);
375
13.8M
        uint32_t pos =
376
13.8M
            kPropRangeFast +
377
13.8M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
13.8M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
13.8M
        uint64_t v =
380
13.8M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
13.8M
        r[x] = make_pixel(v, 1, guess);
382
13.8M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
13.8M
      }
384
352k
      {
385
352k
        size_t offset = 0;
386
352k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
352k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
352k
            rtoptop[x], &properties, offset);
389
352k
        uint32_t pos =
390
352k
            kPropRangeFast +
391
352k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
352k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
352k
        uint64_t v =
394
352k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
352k
        r[x] = make_pixel(v, 1, guess);
396
352k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
352k
      }
398
352k
    }
399
177k
  } 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
155k
    JXL_DEBUG_V(8, "Slow track.");
403
155k
    MATreeLookup tree_lookup(tree);
404
155k
    Properties properties = Properties(num_props);
405
155k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
155k
    JXL_ASSIGN_OR_RETURN(
407
155k
        Channel references,
408
155k
        Channel::Create(memory_manager,
409
155k
                        properties.size() - kNumNonrefProperties, channel.w));
410
5.40M
    for (size_t y = 0; y < channel.h; y++) {
411
5.25M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
5.25M
      PrecomputeReferences(channel, y, *image, chan, &references);
413
5.25M
      InitPropsRow(&properties, static_props, y);
414
5.25M
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
13.5M
        for (size_t x = 0; x < 2; x++) {
416
9.01M
          PredictionResult res =
417
9.01M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
9.01M
                              tree_lookup, references);
419
9.01M
          uint64_t v =
420
9.01M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
9.01M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
9.01M
        }
423
236M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
232M
          PredictionResult res =
425
232M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
232M
                                 tree_lookup, references);
427
232M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
232M
              res.context, br);
429
232M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
232M
        }
431
13.5M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
9.01M
          PredictionResult res =
433
9.01M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
9.01M
                              tree_lookup, references);
435
9.01M
          uint64_t v =
436
9.01M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
9.01M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
9.01M
        }
439
4.50M
      } else {
440
15.8M
        for (size_t x = 0; x < channel.w; x++) {
441
15.1M
          PredictionResult res =
442
15.1M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
15.1M
                              tree_lookup, references);
444
15.1M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
15.1M
              res.context, br);
446
15.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
15.1M
        }
448
745k
      }
449
5.25M
    }
450
155k
  } else {
451
21.5k
    JXL_DEBUG_V(8, "Slowest track.");
452
21.5k
    MATreeLookup tree_lookup(tree);
453
21.5k
    Properties properties = Properties(num_props);
454
21.5k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
21.5k
    JXL_ASSIGN_OR_RETURN(
456
21.5k
        Channel references,
457
21.5k
        Channel::Create(memory_manager,
458
21.5k
                        properties.size() - kNumNonrefProperties, channel.w));
459
21.5k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
1.46M
    for (size_t y = 0; y < channel.h; y++) {
461
1.44M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
1.44M
      InitPropsRow(&properties, static_props, y);
463
1.44M
      PrecomputeReferences(channel, y, *image, chan, &references);
464
1.44M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
1.51M
        for (size_t x = 0; x < 2; x++) {
466
1.00M
          PredictionResult res =
467
1.00M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
1.00M
                            tree_lookup, references, &wp_state);
469
1.00M
          uint64_t v =
470
1.00M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
1.00M
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
1.00M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
1.00M
        }
474
110M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
109M
          PredictionResult res =
476
109M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
109M
                               tree_lookup, references, &wp_state);
478
109M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
109M
              res.context, br);
480
109M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
109M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
109M
        }
483
1.51M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
1.00M
          PredictionResult res =
485
1.00M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
1.00M
                            tree_lookup, references, &wp_state);
487
1.00M
          uint64_t v =
488
1.00M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
1.00M
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
1.00M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
1.00M
        }
492
938k
      } else {
493
9.08M
        for (size_t x = 0; x < channel.w; x++) {
494
8.14M
          PredictionResult res =
495
8.14M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
8.14M
                            tree_lookup, references, &wp_state);
497
8.14M
          uint64_t v =
498
8.14M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
8.14M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
8.14M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
8.14M
        }
502
938k
      }
503
1.44M
    }
504
21.5k
  }
505
191k
  return true;
506
191k
}
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
1.09M
                                 uint32_t &fl_v) {
517
1.09M
  if (reader->UsesLZ77()) {
518
199k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
199k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
199k
        tree_lut, image, fl_run, fl_v);
521
894k
  } else {
522
894k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
894k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
894k
        tree_lut, image, fl_run, fl_v);
525
894k
  }
526
1.09M
}
527
528
965k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
258k
                                 const ModularOptions &options) {
532
258k
  size_t nb_channels = image.channel.size();
533
517k
  for (bool is_dc : {true, false}) {
534
517k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
517k
    size_t c = image.nb_meta_channels;
536
3.04M
    for (; c < nb_channels; c++) {
537
2.54M
      const Channel &ch = image.channel[c];
538
2.54M
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
2.54M
    }
540
577k
    for (; c < nb_channels; c++) {
541
59.8k
      const Channel &ch = image.channel[c];
542
59.8k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
58.8k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
58.8k
      if (is_dc_channel != is_dc) continue;
545
29.4k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
29.4k
      if (tile_dim == 0) {
547
8
        return JXL_FAILURE("Inconsistent transforms");
548
8
      }
549
29.4k
    }
550
517k
  }
551
258k
  return true;
552
258k
}
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
412k
                     const bool allow_truncated_group) {
559
412k
  if (image.channel.empty()) return true;
560
294k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
294k
  Status status = Bundle::Read(br, &header);
564
294k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
266k
  if (status.IsFatalError()) return status;
566
266k
  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
266k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
266k
              header.transforms.size());
578
266k
  image.transform = header.transforms;
579
266k
  for (Transform &transform : image.transform) {
580
63.4k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
63.4k
  }
582
255k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
255k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
255k
  size_t nb_channels = image.channel.size();
588
589
255k
  size_t num_chans = 0;
590
255k
  size_t distance_multiplier = 0;
591
1.52M
  for (size_t i = 0; i < nb_channels; i++) {
592
1.27M
    Channel &channel = image.channel[i];
593
1.27M
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
1.25M
                                        channel.h > options->max_chan_size)) {
595
5.21k
      break;
596
5.21k
    }
597
1.26M
    if (!channel.w || !channel.h) {
598
51.0k
      continue;  // skip empty channels
599
51.0k
    }
600
1.21M
    if (channel.w > distance_multiplier) {
601
304k
      distance_multiplier = channel.w;
602
304k
    }
603
1.21M
    num_chans++;
604
1.21M
  }
605
255k
  if (num_chans == 0) return true;
606
607
252k
  size_t next_channel = 0;
608
252k
  auto scope_guard = MakeScopeGuard([&]() {
609
171k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
133k
      ZeroFillImage(&image.channel[c].plane);
611
133k
    }
612
38.4k
  });
613
  // Do not do anything if truncated groups are not allowed.
614
252k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
252k
  Tree tree_storage;
618
252k
  std::vector<uint8_t> context_map_storage;
619
252k
  ANSCode code_storage;
620
252k
  const Tree *tree = &tree_storage;
621
252k
  const ANSCode *code = &code_storage;
622
252k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
252k
  if (!header.use_global_tree) {
624
191k
    uint64_t max_tree_size = 1024;
625
1.03M
    for (size_t i = 0; i < nb_channels; i++) {
626
841k
      Channel &channel = image.channel[i];
627
841k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
837k
                                          channel.h > options->max_chan_size)) {
629
89
        break;
630
89
      }
631
840k
      uint64_t pixels = channel.w * channel.h;
632
840k
      max_tree_size += pixels;
633
840k
    }
634
191k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
191k
    JXL_RETURN_IF_ERROR(
636
191k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
168k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
168k
                                         (tree_storage.size() + 1) / 2,
639
168k
                                         &code_storage, &context_map_storage));
640
168k
  } else {
641
61.2k
    if (!global_tree || !global_code || !global_ctx_map ||
642
61.2k
        global_tree->empty()) {
643
1.07k
      return JXL_FAILURE("No global tree available but one was requested");
644
1.07k
    }
645
60.1k
    tree = global_tree;
646
60.1k
    code = global_code;
647
60.1k
    context_map = global_ctx_map;
648
60.1k
  }
649
650
  // Read channels
651
446k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
446k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
446k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
446k
  uint32_t fl_run = 0;
655
446k
  uint32_t fl_v = 0;
656
1.35M
  for (; next_channel < nb_channels; next_channel++) {
657
1.14M
    Channel &channel = image.channel[next_channel];
658
1.14M
    if (next_channel >= image.nb_meta_channels &&
659
1.13M
        (channel.w > options->max_chan_size ||
660
1.13M
         channel.h > options->max_chan_size)) {
661
1.89k
      break;
662
1.89k
    }
663
1.14M
    if (!channel.w || !channel.h) {
664
48.0k
      continue;  // skip empty channels
665
48.0k
    }
666
1.09M
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
1.09M
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
1.09M
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
1.09M
    if (!br->AllReadsWithinBounds()) {
672
9.12k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
9.12k
    }
675
1.09M
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
214k
  scope_guard.Disarm();
679
680
214k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
214k
  return true;
684
214k
}
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
412k
                                bool allow_truncated_group) {
692
412k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
412k
  req_sizes.reserve(image.channel.size());
694
987k
  for (const auto &c : image.channel) {
695
987k
    req_sizes.emplace_back(c.w, c.h);
696
987k
  }
697
412k
  GroupHeader local_header;
698
412k
  if (header == nullptr) header = &local_header;
699
412k
  size_t bit_pos = br->TotalBitsConsumed();
700
412k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
412k
                                  code, ctx_map, allow_truncated_group);
702
412k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
335k
  if (dec_status.IsFatalError()) return dec_status;
704
335k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
335k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
335k
  JXL_DEBUG_V(4,
707
335k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
335k
              " image from %" PRIuS " bytes",
709
335k
              image.w, image.h, image.channel.size(),
710
335k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
335k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
335k
  (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
335k
  if (undo_transforms) {
717
138k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
622k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
483k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
483k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
483k
    }
722
138k
  }
723
335k
  return dec_status;
724
335k
}
725
726
}  // namespace jxl