Coverage Report

Created: 2026-11-12 07:35

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
430k
                    bool *gradient_only) {
46
430k
  *num_props = 0;
47
430k
  bool has_wp = false;
48
430k
  bool has_non_wp = false;
49
430k
  *gradient_only = true;
50
1.19M
  const auto mark_property = [&](int32_t p) {
51
1.19M
    if (p == kWPProp) {
52
114k
      has_wp = true;
53
1.07M
    } else if (p >= kNumStaticProperties) {
54
655k
      has_non_wp = true;
55
655k
    }
56
1.19M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
694k
      *gradient_only = false;
58
694k
    }
59
1.19M
  };
60
430k
  FlatTree output;
61
430k
  std::queue<size_t> nodes;
62
430k
  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.45M
  while (!nodes.empty()) {
70
2.02M
    size_t cur = nodes.front();
71
2.02M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
2.08M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.68M
           global_tree[cur].property != -1) {
75
61.8k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
32.3k
        cur = global_tree[cur].lchild;
77
32.3k
      } else {
78
29.4k
        cur = global_tree[cur].rchild;
79
29.4k
      }
80
61.8k
    }
81
2.02M
    FlatDecisionNode flat;
82
2.02M
    if (global_tree[cur].property == -1) {
83
1.62M
      flat.property0 = -1;
84
1.62M
      flat.childID = global_tree[cur].lchild;
85
1.62M
      flat.predictor = global_tree[cur].predictor;
86
1.62M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.62M
      flat.multiplier = global_tree[cur].multiplier;
88
1.62M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.62M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.62M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.62M
      output.push_back(flat);
92
1.62M
      continue;
93
1.62M
    }
94
397k
    flat.childID = output.size() + nodes.size() + 1;
95
96
397k
    flat.property0 = global_tree[cur].property;
97
397k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
397k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.19M
    for (size_t i = 0; i < 2; i++) {
101
795k
      size_t cur_child =
102
795k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
817k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
445k
             global_tree[cur_child].property != -1) {
106
21.6k
        if (static_props[global_tree[cur_child].property] >
107
21.6k
            global_tree[cur_child].splitval) {
108
10.4k
          cur_child = global_tree[cur_child].lchild;
109
11.2k
        } else {
110
11.2k
          cur_child = global_tree[cur_child].rchild;
111
11.2k
        }
112
21.6k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
795k
      if (global_tree[cur_child].property == -1) {
116
423k
        flat.properties[i] = 0;
117
423k
        flat.splitvals[i] = 0;
118
423k
        nodes.push(cur_child);
119
423k
        nodes.push(cur_child);
120
423k
      } else {
121
371k
        flat.properties[i] = global_tree[cur_child].property;
122
371k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
371k
        nodes.push(global_tree[cur_child].lchild);
124
371k
        nodes.push(global_tree[cur_child].rchild);
125
371k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
371k
      }
127
795k
    }
128
129
795k
    for (int16_t property : flat.properties) mark_property(property);
130
397k
    mark_property(flat.property0);
131
397k
    output.push_back(flat);
132
397k
  }
133
430k
  if (*num_props > kNumNonrefProperties) {
134
2.14k
    *num_props =
135
2.14k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
2.14k
            kExtraPropsPerChannel +
137
2.14k
        kNumNonrefProperties;
138
428k
  } else {
139
428k
    *num_props = kNumNonrefProperties;
140
428k
  }
141
430k
  *use_wp = has_wp;
142
430k
  *wp_only = has_wp && !has_non_wp;
143
144
430k
  return output;
145
430k
}
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
404k
                                 uint32_t &fl_v) {
157
404k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
404k
  Channel &channel = image->channel[chan];
159
160
404k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
404k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
404k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
404k
  bool tree_has_wp_prop_or_pred = false;
168
404k
  bool is_wp_only = false;
169
404k
  bool is_gradient_only = false;
170
404k
  size_t num_props;
171
404k
  FlatTree tree =
172
404k
      FilterTree(global_tree, static_props, &num_props,
173
404k
                 &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
587k
  for (auto &node : tree) {
178
587k
    if (node.property0 == -1) {
179
541k
      node.childID = context_map[node.childID];
180
541k
    }
181
587k
  }
182
183
404k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
404k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
275M
                             pixel_type_w offset) -> pixel_type {
188
275M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
275M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
275M
    return val * multiplier + offset;
192
275M
  };
jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda(unsigned long, int, long)#1}::operator()(unsigned long, int, long) const
Line
Count
Source
187
48.2M
                             pixel_type_w offset) -> pixel_type {
188
48.2M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
48.2M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
48.2M
    return val * multiplier + offset;
192
48.2M
  };
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
227M
                             pixel_type_w offset) -> pixel_type {
188
227M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
227M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
227M
    return val * multiplier + offset;
192
227M
  };
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
404k
  const bool global_tree_is_all_gradient_noop = [&] {
200
410k
    for (const auto& n : global_tree) {
201
410k
      if (n.property == -1) {
202
392k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
4.60k
            n.multiplier != 1)
204
388k
          return false;
205
392k
      } else if (n.property >= kNumStaticProperties) {
206
13.1k
        return false;
207
13.1k
      }
208
410k
    }
209
2.66k
    return true;
210
404k
  }();
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
40.3k
  const bool global_tree_is_all_gradient_noop = [&] {
200
41.0k
    for (const auto& n : global_tree) {
201
41.0k
      if (n.property == -1) {
202
36.9k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
1.53k
            n.multiplier != 1)
204
35.6k
          return false;
205
36.9k
      } else if (n.property >= kNumStaticProperties) {
206
3.41k
        return false;
207
3.41k
      }
208
41.0k
    }
209
1.25k
    return true;
210
40.3k
  }();
jxl::detail::DecodeModularChannelMAANS<false>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda()#1}::operator()() const
Line
Count
Source
199
363k
  const bool global_tree_is_all_gradient_noop = [&] {
200
369k
    for (const auto& n : global_tree) {
201
369k
      if (n.property == -1) {
202
355k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
3.06k
            n.multiplier != 1)
204
352k
          return false;
205
355k
      } else if (n.property >= kNumStaticProperties) {
206
9.73k
        return false;
207
9.73k
      }
208
369k
    }
209
1.40k
    return true;
210
363k
  }();
211
212
404k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
391k
    Predictor predictor = tree[0].predictor;
216
391k
    int64_t offset = tree[0].predictor_offset;
217
391k
    int32_t multiplier = tree[0].multiplier;
218
391k
    size_t ctx_id = tree[0].childID;
219
391k
    if (predictor == Predictor::Zero) {
220
361k
      uint32_t value;
221
361k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
361k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
165k
        JXL_DEBUG_V(8, "Fastest track.");
226
165k
        pixel_type v = make_pixel(value, multiplier, offset);
227
4.90M
        for (size_t y = 0; y < channel.h; y++) {
228
4.73M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
4.73M
          std::fill(r, r + channel.w, v);
230
4.73M
        }
231
196k
      } else {
232
196k
        JXL_DEBUG_V(8, "Fast track.");
233
196k
        if (multiplier == 1 && offset == 0) {
234
2.98M
          for (size_t y = 0; y < channel.h; y++) {
235
2.82M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
213M
            for (size_t x = 0; x < channel.w; x++) {
237
210M
              uint32_t v =
238
210M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
210M
              r[x] = UnpackSigned(v);
240
210M
            }
241
2.82M
          }
242
159k
        } else {
243
1.52M
          for (size_t y = 0; y < channel.h; y++) {
244
1.48M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
159M
            for (size_t x = 0; x < channel.w; x++) {
246
157M
              uint32_t v =
247
157M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
157M
                                                                         br);
249
157M
              r[x] = make_pixel(v, multiplier, offset);
250
157M
            }
251
1.48M
          }
252
37.3k
        }
253
196k
      }
254
361k
      return true;
255
361k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
698
               global_tree_is_all_gradient_noop) {
257
542
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
542
      pixel_type_w sv = UnpackSigned(fl_v);
259
17.1k
      for (size_t y = 0; y < channel.h; y++) {
260
16.5k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
16.5k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
16.5k
        const pixel_type *JXL_RESTRICT rtopleft =
263
16.5k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
16.5k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
16.5k
        if (fl_run == 0) {
266
5.01k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.01k
                                                     &fl_run);
268
5.01k
          sv = UnpackSigned(fl_v);
269
11.5k
        } else {
270
11.5k
          fl_run--;
271
11.5k
        }
272
16.5k
        r[0] = sv + guess_0;
273
487k
        for (size_t x = 1; x < channel.w; x++) {
274
471k
          pixel_type left = r[x - 1];
275
471k
          pixel_type top = rtop[x];
276
471k
          pixel_type topleft = rtopleft[x];
277
471k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
471k
          if (!fl_run) {
279
116k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
116k
                                                       &fl_run);
281
116k
            sv = UnpackSigned(fl_v);
282
354k
          } else {
283
354k
            fl_run--;
284
354k
          }
285
471k
          r[x] = sv + guess;
286
471k
        }
287
16.5k
      }
288
542
      return true;
289
28.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
2.95k
               multiplier == 1) {
291
2.49k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
2.49k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
60.5k
      for (size_t y = 0; y < channel.h; y++) {
294
58.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
3.40M
        for (size_t x = 0; x < channel.w; x++) {
296
3.34M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
3.34M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
3.34M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
3.34M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
3.34M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
3.34M
              ctx_id, br);
302
3.34M
          r[x] = make_pixel(v, 1, guess);
303
3.34M
        }
304
58.0k
      }
305
2.49k
      return true;
306
2.49k
    }
307
391k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
39.0k
  if (is_wp_only) {
312
7.41k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
7.41k
  }
314
39.0k
  if (is_gradient_only) {
315
1.75k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.75k
  }
317
318
39.0k
  if (is_gradient_only) {
319
630
    JXL_DEBUG_V(8, "Gradient fast track.");
320
630
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
14.7k
    for (size_t y = 0; y < channel.h; y++) {
322
14.1k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
905k
      for (size_t x = 0; x < channel.w; x++) {
324
891k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
891k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
891k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
891k
        int32_t guess = ClampedGradient(top, left, topleft);
328
891k
        uint32_t pos =
329
891k
            kPropRangeFast +
330
891k
            std::min<pixel_type_w>(
331
891k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
891k
                kPropRangeFast - 1);
333
891k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
891k
        uint64_t v =
335
891k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
891k
        r[x] = make_pixel(v, 1, guess);
337
891k
      }
338
14.1k
    }
339
38.4k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
1.02k
    JXL_DEBUG_V(8, "WP fast track.");
341
1.02k
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
1.02k
    Properties properties(1);
343
33.4k
    for (size_t y = 0; y < channel.h; y++) {
344
32.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
32.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
32.3k
      const pixel_type *JXL_RESTRICT rtoptop =
347
32.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
32.3k
      const pixel_type *JXL_RESTRICT rtopleft =
349
32.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
32.3k
      const pixel_type *JXL_RESTRICT rtopright =
351
32.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
32.3k
      size_t x = 0;
353
32.3k
      {
354
32.3k
        size_t offset = 0;
355
32.3k
        pixel_type_w left = y ? rtop[x] : 0;
356
32.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
32.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
32.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
32.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
32.3k
            offset);
361
32.3k
        uint32_t pos =
362
32.3k
            kPropRangeFast +
363
32.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
32.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
32.3k
        uint64_t v =
366
32.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
32.3k
        r[x] = make_pixel(v, 1, guess);
368
32.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
32.3k
      }
370
3.55M
      for (x = 1; x + 1 < channel.w; x++) {
371
3.52M
        size_t offset = 0;
372
3.52M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
3.52M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
3.52M
            rtoptop[x], &properties, offset);
375
3.52M
        uint32_t pos =
376
3.52M
            kPropRangeFast +
377
3.52M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
3.52M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
3.52M
        uint64_t v =
380
3.52M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
3.52M
        r[x] = make_pixel(v, 1, guess);
382
3.52M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
3.52M
      }
384
32.3k
      {
385
32.3k
        size_t offset = 0;
386
32.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
32.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
32.3k
            rtoptop[x], &properties, offset);
389
32.3k
        uint32_t pos =
390
32.3k
            kPropRangeFast +
391
32.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
32.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
32.3k
        uint64_t v =
394
32.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
32.3k
        r[x] = make_pixel(v, 1, guess);
396
32.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
32.3k
      }
398
32.3k
    }
399
37.4k
  } 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
25.9k
    JXL_DEBUG_V(8, "Slow track.");
403
25.9k
    MATreeLookup tree_lookup(tree);
404
25.9k
    Properties properties = Properties(num_props);
405
25.9k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
25.9k
    JXL_ASSIGN_OR_RETURN(
407
25.9k
        Channel references,
408
25.9k
        Channel::Create(memory_manager,
409
25.9k
                        properties.size() - kNumNonrefProperties, channel.w));
410
771k
    for (size_t y = 0; y < channel.h; y++) {
411
745k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
745k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
745k
      InitPropsRow(&properties, static_props, y);
414
745k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.92M
        for (size_t x = 0; x < 2; x++) {
416
1.28M
          PredictionResult res =
417
1.28M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
1.28M
                              tree_lookup, references);
419
1.28M
          uint64_t v =
420
1.28M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
1.28M
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
1.28M
        }
423
68.5M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
67.8M
          PredictionResult res =
425
67.8M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
67.8M
                                 tree_lookup, references);
427
67.8M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
67.8M
              res.context, br);
429
67.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
67.8M
        }
431
1.92M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
1.28M
          PredictionResult res =
433
1.28M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
1.28M
                              tree_lookup, references);
435
1.28M
          uint64_t v =
436
1.28M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
1.28M
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
1.28M
        }
439
642k
      } else {
440
3.50M
        for (size_t x = 0; x < channel.w; x++) {
441
3.39M
          PredictionResult res =
442
3.39M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
3.39M
                              tree_lookup, references);
444
3.39M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
3.39M
              res.context, br);
446
3.39M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
3.39M
        }
448
103k
      }
449
745k
    }
450
25.9k
  } else {
451
11.4k
    JXL_DEBUG_V(8, "Slowest track.");
452
11.4k
    MATreeLookup tree_lookup(tree);
453
11.4k
    Properties properties = Properties(num_props);
454
11.4k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
11.4k
    JXL_ASSIGN_OR_RETURN(
456
11.4k
        Channel references,
457
11.4k
        Channel::Create(memory_manager,
458
11.4k
                        properties.size() - kNumNonrefProperties, channel.w));
459
11.4k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
389k
    for (size_t y = 0; y < channel.h; y++) {
461
378k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
378k
      InitPropsRow(&properties, static_props, y);
463
378k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
378k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
969k
        for (size_t x = 0; x < 2; x++) {
466
646k
          PredictionResult res =
467
646k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
646k
                            tree_lookup, references, &wp_state);
469
646k
          uint64_t v =
470
646k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
646k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
646k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
646k
        }
474
32.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
32.1M
          PredictionResult res =
476
32.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
32.1M
                               tree_lookup, references, &wp_state);
478
32.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
32.1M
              res.context, br);
480
32.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
32.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
32.1M
        }
483
969k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
646k
          PredictionResult res =
485
646k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
646k
                            tree_lookup, references, &wp_state);
487
646k
          uint64_t v =
488
646k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
646k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
646k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
646k
        }
492
323k
      } else {
493
2.54M
        for (size_t x = 0; x < channel.w; x++) {
494
2.49M
          PredictionResult res =
495
2.49M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.49M
                            tree_lookup, references, &wp_state);
497
2.49M
          uint64_t v =
498
2.49M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.49M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.49M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.49M
        }
502
55.0k
      }
503
378k
    }
504
11.4k
  }
505
39.0k
  return true;
506
39.0k
}
jxl::Status jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)
Line
Count
Source
156
40.3k
                                 uint32_t &fl_v) {
157
40.3k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
40.3k
  Channel &channel = image->channel[chan];
159
160
40.3k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
40.3k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
40.3k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
40.3k
  bool tree_has_wp_prop_or_pred = false;
168
40.3k
  bool is_wp_only = false;
169
40.3k
  bool is_gradient_only = false;
170
40.3k
  size_t num_props;
171
40.3k
  FlatTree tree =
172
40.3k
      FilterTree(global_tree, static_props, &num_props,
173
40.3k
                 &tree_has_wp_prop_or_pred, &is_wp_only, &is_gradient_only);
174
175
  // From here on, tree lookup returns a *clustered* context ID.
176
  // This avoids an extra memory lookup after tree traversal.
177
61.0k
  for (auto &node : tree) {
178
61.0k
    if (node.property0 == -1) {
179
55.8k
      node.childID = context_map[node.childID];
180
55.8k
    }
181
61.0k
  }
182
183
40.3k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
40.3k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
40.3k
                             pixel_type_w offset) -> pixel_type {
188
40.3k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
40.3k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
40.3k
    return val * multiplier + offset;
192
40.3k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
40.3k
  const bool global_tree_is_all_gradient_noop = [&] {
200
40.3k
    for (const auto& n : global_tree) {
201
40.3k
      if (n.property == -1) {
202
40.3k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
40.3k
            n.multiplier != 1)
204
40.3k
          return false;
205
40.3k
      } else if (n.property >= kNumStaticProperties) {
206
40.3k
        return false;
207
40.3k
      }
208
40.3k
    }
209
40.3k
    return true;
210
40.3k
  }();
211
212
40.3k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
36.9k
    Predictor predictor = tree[0].predictor;
216
36.9k
    int64_t offset = tree[0].predictor_offset;
217
36.9k
    int32_t multiplier = tree[0].multiplier;
218
36.9k
    size_t ctx_id = tree[0].childID;
219
36.9k
    if (predictor == Predictor::Zero) {
220
29.0k
      uint32_t value;
221
29.0k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
29.0k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
6.27k
        JXL_DEBUG_V(8, "Fastest track.");
226
6.27k
        pixel_type v = make_pixel(value, multiplier, offset);
227
200k
        for (size_t y = 0; y < channel.h; y++) {
228
194k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
194k
          std::fill(r, r + channel.w, v);
230
194k
        }
231
22.7k
      } else {
232
22.7k
        JXL_DEBUG_V(8, "Fast track.");
233
22.7k
        if (multiplier == 1 && offset == 0) {
234
401k
          for (size_t y = 0; y < channel.h; y++) {
235
393k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
67.3M
            for (size_t x = 0; x < channel.w; x++) {
237
66.9M
              uint32_t v =
238
66.9M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
66.9M
              r[x] = UnpackSigned(v);
240
66.9M
            }
241
393k
          }
242
14.7k
        } else {
243
433k
          for (size_t y = 0; y < channel.h; y++) {
244
419k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
26.4M
            for (size_t x = 0; x < channel.w; x++) {
246
26.0M
              uint32_t v =
247
26.0M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
26.0M
                                                                         br);
249
26.0M
              r[x] = make_pixel(v, multiplier, offset);
250
26.0M
            }
251
419k
          }
252
14.7k
        }
253
22.7k
      }
254
29.0k
      return true;
255
29.0k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
698
               global_tree_is_all_gradient_noop) {
257
542
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
542
      pixel_type_w sv = UnpackSigned(fl_v);
259
17.1k
      for (size_t y = 0; y < channel.h; y++) {
260
16.5k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
16.5k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
16.5k
        const pixel_type *JXL_RESTRICT rtopleft =
263
16.5k
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
16.5k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
16.5k
        if (fl_run == 0) {
266
5.01k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
5.01k
                                                     &fl_run);
268
5.01k
          sv = UnpackSigned(fl_v);
269
11.5k
        } else {
270
11.5k
          fl_run--;
271
11.5k
        }
272
16.5k
        r[0] = sv + guess_0;
273
487k
        for (size_t x = 1; x < channel.w; x++) {
274
471k
          pixel_type left = r[x - 1];
275
471k
          pixel_type top = rtop[x];
276
471k
          pixel_type topleft = rtopleft[x];
277
471k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
471k
          if (!fl_run) {
279
116k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
116k
                                                       &fl_run);
281
116k
            sv = UnpackSigned(fl_v);
282
354k
          } else {
283
354k
            fl_run--;
284
354k
          }
285
471k
          r[x] = sv + guess;
286
471k
        }
287
16.5k
      }
288
542
      return true;
289
7.38k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
994
               multiplier == 1) {
291
718
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
718
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
10.8k
      for (size_t y = 0; y < channel.h; y++) {
294
10.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
400k
        for (size_t x = 0; x < channel.w; x++) {
296
390k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
390k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
390k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
390k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
390k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
390k
              ctx_id, br);
302
390k
          r[x] = make_pixel(v, 1, guess);
303
390k
        }
304
10.1k
      }
305
718
      return true;
306
718
    }
307
36.9k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
10.0k
  if (is_wp_only) {
312
481
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
481
  }
314
10.0k
  if (is_gradient_only) {
315
680
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
680
  }
317
318
10.0k
  if (is_gradient_only) {
319
119
    JXL_DEBUG_V(8, "Gradient fast track.");
320
119
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
3.12k
    for (size_t y = 0; y < channel.h; y++) {
322
3.00k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
510k
      for (size_t x = 0; x < channel.w; x++) {
324
507k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
507k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
507k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
507k
        int32_t guess = ClampedGradient(top, left, topleft);
328
507k
        uint32_t pos =
329
507k
            kPropRangeFast +
330
507k
            std::min<pixel_type_w>(
331
507k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
507k
                kPropRangeFast - 1);
333
507k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
507k
        uint64_t v =
335
507k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
507k
        r[x] = make_pixel(v, 1, guess);
337
507k
      }
338
3.00k
    }
339
9.95k
  } 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.95k
  } 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
9.15k
    JXL_DEBUG_V(8, "Slow track.");
403
9.15k
    MATreeLookup tree_lookup(tree);
404
9.15k
    Properties properties = Properties(num_props);
405
9.15k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
9.15k
    JXL_ASSIGN_OR_RETURN(
407
9.15k
        Channel references,
408
9.15k
        Channel::Create(memory_manager,
409
9.15k
                        properties.size() - kNumNonrefProperties, channel.w));
410
214k
    for (size_t y = 0; y < channel.h; y++) {
411
205k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
205k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
205k
      InitPropsRow(&properties, static_props, y);
414
205k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
523k
        for (size_t x = 0; x < 2; x++) {
416
348k
          PredictionResult res =
417
348k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
348k
                              tree_lookup, references);
419
348k
          uint64_t v =
420
348k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
348k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
348k
        }
423
19.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
19.2M
          PredictionResult res =
425
19.2M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
19.2M
                                 tree_lookup, references);
427
19.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
19.2M
              res.context, br);
429
19.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
19.2M
        }
431
523k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
348k
          PredictionResult res =
433
348k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
348k
                              tree_lookup, references);
435
348k
          uint64_t v =
436
348k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
348k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
348k
        }
439
174k
      } else {
440
854k
        for (size_t x = 0; x < channel.w; x++) {
441
823k
          PredictionResult res =
442
823k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
823k
                              tree_lookup, references);
444
823k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
823k
              res.context, br);
446
823k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
823k
        }
448
30.6k
      }
449
205k
    }
450
9.15k
  } else {
451
799
    JXL_DEBUG_V(8, "Slowest track.");
452
799
    MATreeLookup tree_lookup(tree);
453
799
    Properties properties = Properties(num_props);
454
799
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
799
    JXL_ASSIGN_OR_RETURN(
456
799
        Channel references,
457
799
        Channel::Create(memory_manager,
458
799
                        properties.size() - kNumNonrefProperties, channel.w));
459
799
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
15.7k
    for (size_t y = 0; y < channel.h; y++) {
461
14.9k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
14.9k
      InitPropsRow(&properties, static_props, y);
463
14.9k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
14.9k
      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
14.9k
      } else {
493
539k
        for (size_t x = 0; x < channel.w; x++) {
494
524k
          PredictionResult res =
495
524k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
524k
                            tree_lookup, references, &wp_state);
497
524k
          uint64_t v =
498
524k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
524k
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
524k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
524k
        }
502
14.9k
      }
503
14.9k
    }
504
799
  }
505
10.0k
  return true;
506
10.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
363k
                                 uint32_t &fl_v) {
157
363k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
363k
  Channel &channel = image->channel[chan];
159
160
363k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
363k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
363k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
363k
  bool tree_has_wp_prop_or_pred = false;
168
363k
  bool is_wp_only = false;
169
363k
  bool is_gradient_only = false;
170
363k
  size_t num_props;
171
363k
  FlatTree tree =
172
363k
      FilterTree(global_tree, static_props, &num_props,
173
363k
                 &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
526k
  for (auto &node : tree) {
178
526k
    if (node.property0 == -1) {
179
485k
      node.childID = context_map[node.childID];
180
485k
    }
181
526k
  }
182
183
363k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
363k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
363k
                             pixel_type_w offset) -> pixel_type {
188
363k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
363k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
363k
    return val * multiplier + offset;
192
363k
  };
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
363k
  const bool global_tree_is_all_gradient_noop = [&] {
200
363k
    for (const auto& n : global_tree) {
201
363k
      if (n.property == -1) {
202
363k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
363k
            n.multiplier != 1)
204
363k
          return false;
205
363k
      } else if (n.property >= kNumStaticProperties) {
206
363k
        return false;
207
363k
      }
208
363k
    }
209
363k
    return true;
210
363k
  }();
211
212
363k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
354k
    Predictor predictor = tree[0].predictor;
216
354k
    int64_t offset = tree[0].predictor_offset;
217
354k
    int32_t multiplier = tree[0].multiplier;
218
354k
    size_t ctx_id = tree[0].childID;
219
354k
    if (predictor == Predictor::Zero) {
220
332k
      uint32_t value;
221
332k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
332k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
159k
        JXL_DEBUG_V(8, "Fastest track.");
226
159k
        pixel_type v = make_pixel(value, multiplier, offset);
227
4.69M
        for (size_t y = 0; y < channel.h; y++) {
228
4.54M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
4.54M
          std::fill(r, r + channel.w, v);
230
4.54M
        }
231
173k
      } else {
232
173k
        JXL_DEBUG_V(8, "Fast track.");
233
173k
        if (multiplier == 1 && offset == 0) {
234
2.58M
          for (size_t y = 0; y < channel.h; y++) {
235
2.43M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
145M
            for (size_t x = 0; x < channel.w; x++) {
237
143M
              uint32_t v =
238
143M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
143M
              r[x] = UnpackSigned(v);
240
143M
            }
241
2.43M
          }
242
151k
        } else {
243
1.08M
          for (size_t y = 0; y < channel.h; y++) {
244
1.06M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
132M
            for (size_t x = 0; x < channel.w; x++) {
246
131M
              uint32_t v =
247
131M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
131M
                                                                         br);
249
131M
              r[x] = make_pixel(v, multiplier, offset);
250
131M
            }
251
1.06M
          }
252
22.6k
        }
253
173k
      }
254
332k
      return true;
255
332k
    } 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
21.3k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
1.95k
               multiplier == 1) {
291
1.77k
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
1.77k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
49.6k
      for (size_t y = 0; y < channel.h; y++) {
294
47.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
3.00M
        for (size_t x = 0; x < channel.w; x++) {
296
2.95M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
2.95M
          pixel_type top = (y ? *(r + x - onerow) : left);
298
2.95M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
2.95M
          pixel_type guess = ClampedGradient(top, left, topleft);
300
2.95M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
2.95M
              ctx_id, br);
302
2.95M
          r[x] = make_pixel(v, 1, guess);
303
2.95M
        }
304
47.8k
      }
305
1.77k
      return true;
306
1.77k
    }
307
354k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
29.0k
  if (is_wp_only) {
312
6.93k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
6.93k
  }
314
29.0k
  if (is_gradient_only) {
315
1.07k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.07k
  }
317
318
29.0k
  if (is_gradient_only) {
319
511
    JXL_DEBUG_V(8, "Gradient fast track.");
320
511
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
11.6k
    for (size_t y = 0; y < channel.h; y++) {
322
11.1k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
394k
      for (size_t x = 0; x < channel.w; x++) {
324
383k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
383k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
383k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
383k
        int32_t guess = ClampedGradient(top, left, topleft);
328
383k
        uint32_t pos =
329
383k
            kPropRangeFast +
330
383k
            std::min<pixel_type_w>(
331
383k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
383k
                kPropRangeFast - 1);
333
383k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
383k
        uint64_t v =
335
383k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
383k
        r[x] = make_pixel(v, 1, guess);
337
383k
      }
338
11.1k
    }
339
28.4k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
1.02k
    JXL_DEBUG_V(8, "WP fast track.");
341
1.02k
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
1.02k
    Properties properties(1);
343
33.4k
    for (size_t y = 0; y < channel.h; y++) {
344
32.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
32.3k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
32.3k
      const pixel_type *JXL_RESTRICT rtoptop =
347
32.3k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
32.3k
      const pixel_type *JXL_RESTRICT rtopleft =
349
32.3k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
32.3k
      const pixel_type *JXL_RESTRICT rtopright =
351
32.3k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
32.3k
      size_t x = 0;
353
32.3k
      {
354
32.3k
        size_t offset = 0;
355
32.3k
        pixel_type_w left = y ? rtop[x] : 0;
356
32.3k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
32.3k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
32.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
32.3k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
32.3k
            offset);
361
32.3k
        uint32_t pos =
362
32.3k
            kPropRangeFast +
363
32.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
32.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
32.3k
        uint64_t v =
366
32.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
32.3k
        r[x] = make_pixel(v, 1, guess);
368
32.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
32.3k
      }
370
3.55M
      for (x = 1; x + 1 < channel.w; x++) {
371
3.52M
        size_t offset = 0;
372
3.52M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
3.52M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
3.52M
            rtoptop[x], &properties, offset);
375
3.52M
        uint32_t pos =
376
3.52M
            kPropRangeFast +
377
3.52M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
3.52M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
3.52M
        uint64_t v =
380
3.52M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
3.52M
        r[x] = make_pixel(v, 1, guess);
382
3.52M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
3.52M
      }
384
32.3k
      {
385
32.3k
        size_t offset = 0;
386
32.3k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
32.3k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
32.3k
            rtoptop[x], &properties, offset);
389
32.3k
        uint32_t pos =
390
32.3k
            kPropRangeFast +
391
32.3k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
32.3k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
32.3k
        uint64_t v =
394
32.3k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
32.3k
        r[x] = make_pixel(v, 1, guess);
396
32.3k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
32.3k
      }
398
32.3k
    }
399
27.4k
  } 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
16.8k
    JXL_DEBUG_V(8, "Slow track.");
403
16.8k
    MATreeLookup tree_lookup(tree);
404
16.8k
    Properties properties = Properties(num_props);
405
16.8k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
16.8k
    JXL_ASSIGN_OR_RETURN(
407
16.8k
        Channel references,
408
16.8k
        Channel::Create(memory_manager,
409
16.8k
                        properties.size() - kNumNonrefProperties, channel.w));
410
557k
    for (size_t y = 0; y < channel.h; y++) {
411
540k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
540k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
540k
      InitPropsRow(&properties, static_props, y);
414
540k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
1.40M
        for (size_t x = 0; x < 2; x++) {
416
935k
          PredictionResult res =
417
935k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
935k
                              tree_lookup, references);
419
935k
          uint64_t v =
420
935k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
935k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
935k
        }
423
49.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
48.6M
          PredictionResult res =
425
48.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
48.6M
                                 tree_lookup, references);
427
48.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
48.6M
              res.context, br);
429
48.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
48.6M
        }
431
1.40M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
935k
          PredictionResult res =
433
935k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
935k
                              tree_lookup, references);
435
935k
          uint64_t v =
436
935k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
935k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
935k
        }
439
467k
      } else {
440
2.64M
        for (size_t x = 0; x < channel.w; x++) {
441
2.57M
          PredictionResult res =
442
2.57M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
2.57M
                              tree_lookup, references);
444
2.57M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
2.57M
              res.context, br);
446
2.57M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
2.57M
        }
448
72.7k
      }
449
540k
    }
450
16.8k
  } else {
451
10.6k
    JXL_DEBUG_V(8, "Slowest track.");
452
10.6k
    MATreeLookup tree_lookup(tree);
453
10.6k
    Properties properties = Properties(num_props);
454
10.6k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
10.6k
    JXL_ASSIGN_OR_RETURN(
456
10.6k
        Channel references,
457
10.6k
        Channel::Create(memory_manager,
458
10.6k
                        properties.size() - kNumNonrefProperties, channel.w));
459
10.6k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
373k
    for (size_t y = 0; y < channel.h; y++) {
461
363k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
363k
      InitPropsRow(&properties, static_props, y);
463
363k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
363k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
969k
        for (size_t x = 0; x < 2; x++) {
466
646k
          PredictionResult res =
467
646k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
646k
                            tree_lookup, references, &wp_state);
469
646k
          uint64_t v =
470
646k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
646k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
646k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
646k
        }
474
32.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
32.1M
          PredictionResult res =
476
32.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
32.1M
                               tree_lookup, references, &wp_state);
478
32.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
32.1M
              res.context, br);
480
32.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
32.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
32.1M
        }
483
969k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
646k
          PredictionResult res =
485
646k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
646k
                            tree_lookup, references, &wp_state);
487
646k
          uint64_t v =
488
646k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
646k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
646k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
646k
        }
492
323k
      } else {
493
2.00M
        for (size_t x = 0; x < channel.w; x++) {
494
1.96M
          PredictionResult res =
495
1.96M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
1.96M
                            tree_lookup, references, &wp_state);
497
1.96M
          uint64_t v =
498
1.96M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
1.96M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
1.96M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
1.96M
        }
502
40.0k
      }
503
363k
    }
504
10.6k
  }
505
29.0k
  return true;
506
29.0k
}
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
404k
                                 uint32_t &fl_v) {
517
404k
  if (reader->UsesLZ77()) {
518
40.3k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
40.3k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
40.3k
        tree_lut, image, fl_run, fl_v);
521
363k
  } else {
522
363k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
363k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
363k
        tree_lut, image, fl_run, fl_v);
525
363k
  }
526
404k
}
527
528
201k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
51.2k
                                 const ModularOptions &options) {
532
51.2k
  size_t nb_channels = image.channel.size();
533
102k
  for (bool is_dc : {true, false}) {
534
102k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
102k
    size_t c = image.nb_meta_channels;
536
954k
    for (; c < nb_channels; c++) {
537
855k
      const Channel &ch = image.channel[c];
538
855k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
855k
    }
540
129k
    for (; c < nb_channels; c++) {
541
27.3k
      const Channel &ch = image.channel[c];
542
27.3k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
26.8k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
26.8k
      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
4
        return JXL_FAILURE("Inconsistent transforms");
548
4
      }
549
13.4k
    }
550
102k
  }
551
51.2k
  return true;
552
51.2k
}
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
59.8k
                     const bool allow_truncated_group) {
559
59.8k
  if (image.channel.empty()) return true;
560
51.1k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
51.1k
  Status status = Bundle::Read(br, &header);
564
51.1k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
49.8k
  if (status.IsFatalError()) return status;
566
49.8k
  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
49.8k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
49.8k
              header.transforms.size());
578
49.8k
  image.transform = header.transforms;
579
49.8k
  for (Transform &transform : image.transform) {
580
30.4k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
30.4k
  }
582
49.5k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
49.5k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
49.5k
  size_t nb_channels = image.channel.size();
588
589
49.5k
  size_t num_chans = 0;
590
49.5k
  size_t distance_multiplier = 0;
591
478k
  for (size_t i = 0; i < nb_channels; i++) {
592
430k
    Channel &channel = image.channel[i];
593
430k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
423k
                                        channel.h > options->max_chan_size)) {
595
1.75k
      break;
596
1.75k
    }
597
428k
    if (!channel.w || !channel.h) {
598
6.41k
      continue;  // skip empty channels
599
6.41k
    }
600
422k
    if (channel.w > distance_multiplier) {
601
78.2k
      distance_multiplier = channel.w;
602
78.2k
    }
603
422k
    num_chans++;
604
422k
  }
605
49.5k
  if (num_chans == 0) return true;
606
607
48.6k
  size_t next_channel = 0;
608
48.6k
  auto scope_guard = MakeScopeGuard([&]() {
609
26.7k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
22.5k
      ZeroFillImage(&image.channel[c].plane);
611
22.5k
    }
612
4.22k
  });
613
  // Do not do anything if truncated groups are not allowed.
614
48.6k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
48.6k
  Tree tree_storage;
618
48.6k
  std::vector<uint8_t> context_map_storage;
619
48.6k
  ANSCode code_storage;
620
48.6k
  const Tree *tree = &tree_storage;
621
48.6k
  const ANSCode *code = &code_storage;
622
48.6k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
48.6k
  if (!header.use_global_tree) {
624
29.1k
    uint64_t max_tree_size = 1024;
625
327k
    for (size_t i = 0; i < nb_channels; i++) {
626
298k
      Channel &channel = image.channel[i];
627
298k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
295k
                                          channel.h > options->max_chan_size)) {
629
62
        break;
630
62
      }
631
298k
      uint64_t pixels = channel.w * channel.h;
632
298k
      max_tree_size += pixels;
633
298k
    }
634
29.1k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
29.1k
    JXL_RETURN_IF_ERROR(
636
29.1k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
28.6k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
28.6k
                                         (tree_storage.size() + 1) / 2,
639
28.6k
                                         &code_storage, &context_map_storage));
640
28.6k
  } else {
641
19.5k
    if (!global_tree || !global_code || !global_ctx_map ||
642
19.5k
        global_tree->empty()) {
643
127
      return JXL_FAILURE("No global tree available but one was requested");
644
127
    }
645
19.4k
    tree = global_tree;
646
19.4k
    code = global_code;
647
19.4k
    context_map = global_ctx_map;
648
19.4k
  }
649
650
  // Read channels
651
95.7k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
95.7k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
95.7k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
95.7k
  uint32_t fl_run = 0;
655
95.7k
  uint32_t fl_v = 0;
656
454k
  for (; next_channel < nb_channels; next_channel++) {
657
410k
    Channel &channel = image.channel[next_channel];
658
410k
    if (next_channel >= image.nb_meta_channels &&
659
404k
        (channel.w > options->max_chan_size ||
660
404k
         channel.h > options->max_chan_size)) {
661
863
      break;
662
863
    }
663
409k
    if (!channel.w || !channel.h) {
664
5.87k
      continue;  // skip empty channels
665
5.87k
    }
666
404k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
404k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
404k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
404k
    if (!br->AllReadsWithinBounds()) {
672
3.42k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
3.42k
    }
675
404k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
44.4k
  scope_guard.Disarm();
679
680
44.4k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
44.4k
  return true;
684
44.4k
}
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
59.8k
                                bool allow_truncated_group) {
692
59.8k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
59.8k
  req_sizes.reserve(image.channel.size());
694
184k
  for (const auto &c : image.channel) {
695
184k
    req_sizes.emplace_back(c.w, c.h);
696
184k
  }
697
59.8k
  GroupHeader local_header;
698
59.8k
  if (header == nullptr) header = &local_header;
699
59.8k
  size_t bit_pos = br->TotalBitsConsumed();
700
59.8k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
59.8k
                                  code, ctx_map, allow_truncated_group);
702
59.8k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
54.0k
  if (dec_status.IsFatalError()) return dec_status;
704
54.0k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
54.0k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
54.0k
  JXL_DEBUG_V(4,
707
54.0k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
54.0k
              " image from %" PRIuS " bytes",
709
54.0k
              image.w, image.h, image.channel.size(),
710
54.0k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
54.0k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
54.0k
  (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
54.0k
  if (undo_transforms) {
717
16.6k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
81.2k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
64.6k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
64.6k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
64.6k
    }
722
16.6k
  }
723
54.0k
  return dec_status;
724
54.0k
}
725
726
}  // namespace jxl