Coverage Report

Created: 2026-09-14 07:15

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
271k
                    bool *gradient_only) {
46
271k
  *num_props = 0;
47
271k
  bool has_wp = false;
48
271k
  bool has_non_wp = false;
49
271k
  *gradient_only = true;
50
271k
  const auto mark_property = [&](int32_t p) {
51
241k
    if (p == kWPProp) {
52
23.4k
      has_wp = true;
53
217k
    } else if (p >= kNumStaticProperties) {
54
133k
      has_non_wp = true;
55
133k
    }
56
241k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
131k
      *gradient_only = false;
58
131k
    }
59
241k
  };
60
271k
  FlatTree output;
61
271k
  std::queue<size_t> nodes;
62
271k
  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
865k
  while (!nodes.empty()) {
70
593k
    size_t cur = nodes.front();
71
593k
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
627k
    while (global_tree[cur].property < kNumStaticProperties &&
74
548k
           global_tree[cur].property != -1) {
75
33.4k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
18.7k
        cur = global_tree[cur].lchild;
77
18.7k
      } else {
78
14.7k
        cur = global_tree[cur].rchild;
79
14.7k
      }
80
33.4k
    }
81
593k
    FlatDecisionNode flat;
82
593k
    if (global_tree[cur].property == -1) {
83
517k
      flat.property0 = -1;
84
517k
      flat.childID = global_tree[cur].lchild;
85
517k
      flat.predictor = global_tree[cur].predictor;
86
517k
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
517k
      flat.multiplier = global_tree[cur].multiplier;
88
517k
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
517k
      has_wp |= flat.predictor == Predictor::Weighted;
90
517k
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
517k
      output.push_back(flat);
92
517k
      continue;
93
517k
    }
94
75.8k
    flat.childID = output.size() + nodes.size() + 1;
95
96
75.8k
    flat.property0 = global_tree[cur].property;
97
75.8k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
75.8k
    flat.splitval0 = global_tree[cur].splitval;
99
100
241k
    for (size_t i = 0; i < 2; i++) {
101
165k
      size_t cur_child =
102
165k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
184k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
108k
             global_tree[cur_child].property != -1) {
106
19.1k
        if (static_props[global_tree[cur_child].property] >
107
19.1k
            global_tree[cur_child].splitval) {
108
11.5k
          cur_child = global_tree[cur_child].lchild;
109
11.5k
        } else {
110
7.60k
          cur_child = global_tree[cur_child].rchild;
111
7.60k
        }
112
19.1k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
165k
      if (global_tree[cur_child].property == -1) {
116
90.8k
        flat.properties[i] = 0;
117
90.8k
        flat.splitvals[i] = 0;
118
90.8k
        nodes.push(cur_child);
119
90.8k
        nodes.push(cur_child);
120
90.8k
      } else {
121
74.7k
        flat.properties[i] = global_tree[cur_child].property;
122
74.7k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
74.7k
        nodes.push(global_tree[cur_child].lchild);
124
74.7k
        nodes.push(global_tree[cur_child].rchild);
125
74.7k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
74.7k
      }
127
165k
    }
128
129
162k
    for (int16_t property : flat.properties) mark_property(property);
130
75.8k
    mark_property(flat.property0);
131
75.8k
    output.push_back(flat);
132
75.8k
  }
133
271k
  if (*num_props > kNumNonrefProperties) {
134
1.69k
    *num_props =
135
1.69k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.69k
            kExtraPropsPerChannel +
137
1.69k
        kNumNonrefProperties;
138
269k
  } else {
139
269k
    *num_props = kNumNonrefProperties;
140
269k
  }
141
271k
  *use_wp = has_wp;
142
271k
  *wp_only = has_wp && !has_non_wp;
143
144
271k
  return output;
145
271k
}
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
271k
                                 uint32_t &fl_v) {
157
271k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
271k
  Channel &channel = image->channel[chan];
159
160
271k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
271k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
271k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
271k
  bool tree_has_wp_prop_or_pred = false;
168
271k
  bool is_wp_only = false;
169
271k
  bool is_gradient_only = false;
170
271k
  size_t num_props;
171
271k
  FlatTree tree =
172
271k
      FilterTree(global_tree, static_props, &num_props,
173
271k
                 &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
614k
  for (auto &node : tree) {
178
614k
    if (node.property0 == -1) {
179
529k
      node.childID = context_map[node.childID];
180
529k
    }
181
614k
  }
182
183
271k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
271k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
51.2M
                             pixel_type_w offset) -> pixel_type {
188
51.2M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
51.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
51.2M
    return val * multiplier + offset;
192
51.2M
  };
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
9.73M
                             pixel_type_w offset) -> pixel_type {
188
9.73M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
9.73M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
9.73M
    return val * multiplier + offset;
192
9.73M
  };
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
41.4M
                             pixel_type_w offset) -> pixel_type {
188
41.4M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
41.4M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
41.4M
    return val * multiplier + offset;
192
41.4M
  };
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
271k
  const bool global_tree_is_all_gradient_noop = [&] {
200
286k
    for (const auto& n : global_tree) {
201
286k
      if (n.property == -1) {
202
254k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
620
            n.multiplier != 1)
204
254k
          return false;
205
254k
      } else if (n.property >= kNumStaticProperties) {
206
16.4k
        return false;
207
16.4k
      }
208
286k
    }
209
634
    return true;
210
271k
  }();
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
9.68k
  const bool global_tree_is_all_gradient_noop = [&] {
200
9.99k
    for (const auto& n : global_tree) {
201
9.99k
      if (n.property == -1) {
202
8.74k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
4
            n.multiplier != 1)
204
8.74k
          return false;
205
8.74k
      } else if (n.property >= kNumStaticProperties) {
206
930
        return false;
207
930
      }
208
9.99k
    }
209
11
    return true;
210
9.68k
  }();
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
261k
  const bool global_tree_is_all_gradient_noop = [&] {
200
276k
    for (const auto& n : global_tree) {
201
276k
      if (n.property == -1) {
202
246k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
616
            n.multiplier != 1)
204
245k
          return false;
205
246k
      } else if (n.property >= kNumStaticProperties) {
206
15.5k
        return false;
207
15.5k
      }
208
276k
    }
209
623
    return true;
210
261k
  }();
211
212
271k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
256k
    Predictor predictor = tree[0].predictor;
216
256k
    int64_t offset = tree[0].predictor_offset;
217
256k
    int32_t multiplier = tree[0].multiplier;
218
256k
    size_t ctx_id = tree[0].childID;
219
256k
    if (predictor == Predictor::Zero) {
220
251k
      uint32_t value;
221
251k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
251k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
49.1k
        JXL_DEBUG_V(8, "Fastest track.");
226
49.1k
        pixel_type v = make_pixel(value, multiplier, offset);
227
2.62M
        for (size_t y = 0; y < channel.h; y++) {
228
2.57M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
2.57M
          std::fill(r, r + channel.w, v);
230
2.57M
        }
231
202k
      } else {
232
202k
        JXL_DEBUG_V(8, "Fast track.");
233
202k
        if (multiplier == 1 && offset == 0) {
234
4.14M
          for (size_t y = 0; y < channel.h; y++) {
235
3.94M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
210M
            for (size_t x = 0; x < channel.w; x++) {
237
206M
              uint32_t v =
238
206M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
206M
              r[x] = UnpackSigned(v);
240
206M
            }
241
3.94M
          }
242
201k
        } else {
243
32.3k
          for (size_t y = 0; y < channel.h; y++) {
244
31.2k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
5.49M
            for (size_t x = 0; x < channel.w; x++) {
246
5.46M
              uint32_t v =
247
5.46M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
5.46M
                                                                         br);
249
5.46M
              r[x] = make_pixel(v, multiplier, offset);
250
5.46M
            }
251
31.2k
          }
252
1.11k
        }
253
202k
      }
254
251k
      return true;
255
251k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
4
               global_tree_is_all_gradient_noop) {
257
4
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
4
      pixel_type_w sv = UnpackSigned(fl_v);
259
8
      for (size_t y = 0; y < channel.h; y++) {
260
4
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
4
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
4
        const pixel_type *JXL_RESTRICT rtopleft =
263
4
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
4
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
4
        if (fl_run == 0) {
266
4
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
4
                                                     &fl_run);
268
4
          sv = UnpackSigned(fl_v);
269
4
        } else {
270
0
          fl_run--;
271
0
        }
272
4
        r[0] = sv + guess_0;
273
8
        for (size_t x = 1; x < channel.w; x++) {
274
4
          pixel_type left = r[x - 1];
275
4
          pixel_type top = rtop[x];
276
4
          pixel_type topleft = rtopleft[x];
277
4
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
4
          if (!fl_run) {
279
4
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
4
                                                       &fl_run);
281
4
            sv = UnpackSigned(fl_v);
282
4
          } else {
283
0
            fl_run--;
284
0
          }
285
4
          r[x] = sv + guess;
286
4
        }
287
4
      }
288
4
      return true;
289
4.17k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
677
               multiplier == 1) {
291
676
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
676
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
53.1k
      for (size_t y = 0; y < channel.h; y++) {
294
52.4k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
150k
        for (size_t x = 0; x < channel.w; x++) {
296
98.4k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
98.4k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
98.4k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
98.4k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
98.4k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
98.4k
              ctx_id, br);
302
98.4k
          r[x] = make_pixel(v, 1, guess);
303
98.4k
        }
304
52.4k
      }
305
676
      return true;
306
676
    }
307
256k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
18.6k
  if (is_wp_only) {
312
2.07k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
2.07k
  }
314
18.6k
  if (is_gradient_only) {
315
1.02k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.02k
  }
317
318
18.6k
  if (is_gradient_only) {
319
955
    JXL_DEBUG_V(8, "Gradient fast track.");
320
955
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
63.9k
    for (size_t y = 0; y < channel.h; y++) {
322
63.0k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
275k
      for (size_t x = 0; x < channel.w; x++) {
324
212k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
212k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
212k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
212k
        int32_t guess = ClampedGradient(top, left, topleft);
328
212k
        uint32_t pos =
329
212k
            kPropRangeFast +
330
212k
            std::min<pixel_type_w>(
331
212k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
212k
                kPropRangeFast - 1);
333
212k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
212k
        uint64_t v =
335
212k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
212k
        r[x] = make_pixel(v, 1, guess);
337
212k
      }
338
63.0k
    }
339
17.7k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
670
    JXL_DEBUG_V(8, "WP fast track.");
341
670
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
670
    Properties properties(1);
343
6.51k
    for (size_t y = 0; y < channel.h; y++) {
344
5.84k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
5.84k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
5.84k
      const pixel_type *JXL_RESTRICT rtoptop =
347
5.84k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
5.84k
      const pixel_type *JXL_RESTRICT rtopleft =
349
5.84k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
5.84k
      const pixel_type *JXL_RESTRICT rtopright =
351
5.84k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
5.84k
      size_t x = 0;
353
5.84k
      {
354
5.84k
        size_t offset = 0;
355
5.84k
        pixel_type_w left = y ? rtop[x] : 0;
356
5.84k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
5.84k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
5.84k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
5.84k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
5.84k
            offset);
361
5.84k
        uint32_t pos =
362
5.84k
            kPropRangeFast +
363
5.84k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
5.84k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
5.84k
        uint64_t v =
366
5.84k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
5.84k
        r[x] = make_pixel(v, 1, guess);
368
5.84k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
5.84k
      }
370
291k
      for (x = 1; x + 1 < channel.w; x++) {
371
285k
        size_t offset = 0;
372
285k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
285k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
285k
            rtoptop[x], &properties, offset);
375
285k
        uint32_t pos =
376
285k
            kPropRangeFast +
377
285k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
285k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
285k
        uint64_t v =
380
285k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
285k
        r[x] = make_pixel(v, 1, guess);
382
285k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
285k
      }
384
5.84k
      {
385
5.84k
        size_t offset = 0;
386
5.84k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
5.84k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
5.84k
            rtoptop[x], &properties, offset);
389
5.84k
        uint32_t pos =
390
5.84k
            kPropRangeFast +
391
5.84k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
5.84k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
5.84k
        uint64_t v =
394
5.84k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
5.84k
        r[x] = make_pixel(v, 1, guess);
396
5.84k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
5.84k
      }
398
5.84k
    }
399
17.0k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
7.41k
    JXL_DEBUG_V(8, "Slow track.");
403
7.41k
    MATreeLookup tree_lookup(tree);
404
7.41k
    Properties properties = Properties(num_props);
405
7.41k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
7.41k
    JXL_ASSIGN_OR_RETURN(
407
7.41k
        Channel references,
408
7.41k
        Channel::Create(memory_manager,
409
7.41k
                        properties.size() - kNumNonrefProperties, channel.w));
410
231k
    for (size_t y = 0; y < channel.h; y++) {
411
224k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
224k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
224k
      InitPropsRow(&properties, static_props, y);
414
224k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
421k
        for (size_t x = 0; x < 2; x++) {
416
280k
          PredictionResult res =
417
280k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
280k
                              tree_lookup, references);
419
280k
          uint64_t v =
420
280k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
280k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
280k
        }
423
18.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
18.7M
          PredictionResult res =
425
18.7M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
18.7M
                                 tree_lookup, references);
427
18.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
18.7M
              res.context, br);
429
18.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
18.7M
        }
431
421k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
280k
          PredictionResult res =
433
280k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
280k
                              tree_lookup, references);
435
280k
          uint64_t v =
436
280k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
280k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
280k
        }
439
140k
      } else {
440
4.58M
        for (size_t x = 0; x < channel.w; x++) {
441
4.49M
          PredictionResult res =
442
4.49M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
4.49M
                              tree_lookup, references);
444
4.49M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
4.49M
              res.context, br);
446
4.49M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
4.49M
        }
448
83.8k
      }
449
224k
    }
450
9.63k
  } else {
451
9.63k
    JXL_DEBUG_V(8, "Slowest track.");
452
9.63k
    MATreeLookup tree_lookup(tree);
453
9.63k
    Properties properties = Properties(num_props);
454
9.63k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
9.63k
    JXL_ASSIGN_OR_RETURN(
456
9.63k
        Channel references,
457
9.63k
        Channel::Create(memory_manager,
458
9.63k
                        properties.size() - kNumNonrefProperties, channel.w));
459
9.63k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
527k
    for (size_t y = 0; y < channel.h; y++) {
461
517k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
517k
      InitPropsRow(&properties, static_props, y);
463
517k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
517k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
689k
        for (size_t x = 0; x < 2; x++) {
466
459k
          PredictionResult res =
467
459k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
459k
                            tree_lookup, references, &wp_state);
469
459k
          uint64_t v =
470
459k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
459k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
459k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
459k
        }
474
16.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
16.1M
          PredictionResult res =
476
16.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
16.1M
                               tree_lookup, references, &wp_state);
478
16.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
16.1M
              res.context, br);
480
16.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
16.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
16.1M
        }
483
689k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
459k
          PredictionResult res =
485
459k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
459k
                            tree_lookup, references, &wp_state);
487
459k
          uint64_t v =
488
459k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
459k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
459k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
459k
        }
492
287k
      } else {
493
7.20M
        for (size_t x = 0; x < channel.w; x++) {
494
6.91M
          PredictionResult res =
495
6.91M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
6.91M
                            tree_lookup, references, &wp_state);
497
6.91M
          uint64_t v =
498
6.91M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
6.91M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
6.91M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
6.91M
        }
502
287k
      }
503
517k
    }
504
9.63k
  }
505
18.6k
  return true;
506
18.6k
}
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
9.66k
                                 uint32_t &fl_v) {
157
9.66k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
9.66k
  Channel &channel = image->channel[chan];
159
160
9.66k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
9.66k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
9.67k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
9.66k
  bool tree_has_wp_prop_or_pred = false;
168
9.66k
  bool is_wp_only = false;
169
9.66k
  bool is_gradient_only = false;
170
9.66k
  size_t num_props;
171
9.66k
  FlatTree tree =
172
9.66k
      FilterTree(global_tree, static_props, &num_props,
173
9.66k
                 &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
13.9k
  for (auto &node : tree) {
178
13.9k
    if (node.property0 == -1) {
179
12.9k
      node.childID = context_map[node.childID];
180
12.9k
    }
181
13.9k
  }
182
183
9.66k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
9.66k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
9.66k
                             pixel_type_w offset) -> pixel_type {
188
9.66k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
9.66k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
9.66k
    return val * multiplier + offset;
192
9.66k
  };
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
9.66k
  const bool global_tree_is_all_gradient_noop = [&] {
200
9.66k
    for (const auto& n : global_tree) {
201
9.66k
      if (n.property == -1) {
202
9.66k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
9.66k
            n.multiplier != 1)
204
9.66k
          return false;
205
9.66k
      } else if (n.property >= kNumStaticProperties) {
206
9.66k
        return false;
207
9.66k
      }
208
9.66k
    }
209
9.66k
    return true;
210
9.66k
  }();
211
212
9.66k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
8.74k
    Predictor predictor = tree[0].predictor;
216
8.74k
    int64_t offset = tree[0].predictor_offset;
217
8.74k
    int32_t multiplier = tree[0].multiplier;
218
8.74k
    size_t ctx_id = tree[0].childID;
219
8.74k
    if (predictor == Predictor::Zero) {
220
8.29k
      uint32_t value;
221
8.29k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
8.29k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
170
        JXL_DEBUG_V(8, "Fastest track.");
226
170
        pixel_type v = make_pixel(value, multiplier, offset);
227
2.83k
        for (size_t y = 0; y < channel.h; y++) {
228
2.66k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
2.66k
          std::fill(r, r + channel.w, v);
230
2.66k
        }
231
8.12k
      } else {
232
8.12k
        JXL_DEBUG_V(8, "Fast track.");
233
8.12k
        if (multiplier == 1 && offset == 0) {
234
831k
          for (size_t y = 0; y < channel.h; y++) {
235
823k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
52.2M
            for (size_t x = 0; x < channel.w; x++) {
237
51.4M
              uint32_t v =
238
51.4M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
51.4M
              r[x] = UnpackSigned(v);
240
51.4M
            }
241
823k
          }
242
8.00k
        } else {
243
13.8k
          for (size_t y = 0; y < channel.h; y++) {
244
13.7k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
3.26M
            for (size_t x = 0; x < channel.w; x++) {
246
3.25M
              uint32_t v =
247
3.25M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
3.25M
                                                                         br);
249
3.25M
              r[x] = make_pixel(v, multiplier, offset);
250
3.25M
            }
251
13.7k
          }
252
123
        }
253
8.12k
      }
254
8.29k
      return true;
255
8.29k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
4
               global_tree_is_all_gradient_noop) {
257
4
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
4
      pixel_type_w sv = UnpackSigned(fl_v);
259
8
      for (size_t y = 0; y < channel.h; y++) {
260
4
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
4
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
4
        const pixel_type *JXL_RESTRICT rtopleft =
263
4
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
4
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
4
        if (fl_run == 0) {
266
4
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
4
                                                     &fl_run);
268
4
          sv = UnpackSigned(fl_v);
269
4
        } else {
270
0
          fl_run--;
271
0
        }
272
4
        r[0] = sv + guess_0;
273
8
        for (size_t x = 1; x < channel.w; x++) {
274
4
          pixel_type left = r[x - 1];
275
4
          pixel_type top = rtop[x];
276
4
          pixel_type topleft = rtopleft[x];
277
4
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
4
          if (!fl_run) {
279
4
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
4
                                                       &fl_run);
281
4
            sv = UnpackSigned(fl_v);
282
4
          } else {
283
0
            fl_run--;
284
0
          }
285
4
          r[x] = sv + guess;
286
4
        }
287
4
      }
288
4
      return true;
289
442
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
0
               multiplier == 1) {
291
0
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
0
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
0
      for (size_t y = 0; y < channel.h; y++) {
294
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
0
        for (size_t x = 0; x < channel.w; x++) {
296
0
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
0
          pixel_type top = (y ? *(r + x - onerow) : left);
298
0
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
0
          pixel_type guess = ClampedGradient(top, left, topleft);
300
0
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
0
              ctx_id, br);
302
0
          r[x] = make_pixel(v, 1, guess);
303
0
        }
304
0
      }
305
0
      return true;
306
0
    }
307
8.74k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
1.36k
  if (is_wp_only) {
312
314
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
314
  }
314
1.36k
  if (is_gradient_only) {
315
0
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
0
  }
317
318
1.36k
  if (is_gradient_only) {
319
0
    JXL_DEBUG_V(8, "Gradient fast track.");
320
0
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
0
    for (size_t y = 0; y < channel.h; y++) {
322
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
0
      for (size_t x = 0; x < channel.w; x++) {
324
0
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
0
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
0
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
0
        int32_t guess = ClampedGradient(top, left, topleft);
328
0
        uint32_t pos =
329
0
            kPropRangeFast +
330
0
            std::min<pixel_type_w>(
331
0
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
0
                kPropRangeFast - 1);
333
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
0
        uint64_t v =
335
0
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
0
        r[x] = make_pixel(v, 1, guess);
337
0
      }
338
0
    }
339
1.36k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
0
    JXL_DEBUG_V(8, "WP fast track.");
341
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
0
    Properties properties(1);
343
0
    for (size_t y = 0; y < channel.h; y++) {
344
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
0
      const pixel_type *JXL_RESTRICT rtoptop =
347
0
          (y > 1 ? channel.Row(y - 2) : rtop);
348
0
      const pixel_type *JXL_RESTRICT rtopleft =
349
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
0
      const pixel_type *JXL_RESTRICT rtopright =
351
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
0
      size_t x = 0;
353
0
      {
354
0
        size_t offset = 0;
355
0
        pixel_type_w left = y ? rtop[x] : 0;
356
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
0
            offset);
361
0
        uint32_t pos =
362
0
            kPropRangeFast +
363
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
0
        uint64_t v =
366
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
0
        r[x] = make_pixel(v, 1, guess);
368
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
0
      }
370
0
      for (x = 1; x + 1 < channel.w; x++) {
371
0
        size_t offset = 0;
372
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
0
            rtoptop[x], &properties, offset);
375
0
        uint32_t pos =
376
0
            kPropRangeFast +
377
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
0
        uint64_t v =
380
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
0
        r[x] = make_pixel(v, 1, guess);
382
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
0
      }
384
0
      {
385
0
        size_t offset = 0;
386
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
0
            rtoptop[x], &properties, offset);
389
0
        uint32_t pos =
390
0
            kPropRangeFast +
391
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
0
        uint64_t v =
394
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
0
        r[x] = make_pixel(v, 1, guess);
396
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
0
      }
398
0
    }
399
1.36k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
131
    JXL_DEBUG_V(8, "Slow track.");
403
131
    MATreeLookup tree_lookup(tree);
404
131
    Properties properties = Properties(num_props);
405
131
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
131
    JXL_ASSIGN_OR_RETURN(
407
131
        Channel references,
408
131
        Channel::Create(memory_manager,
409
131
                        properties.size() - kNumNonrefProperties, channel.w));
410
8.44k
    for (size_t y = 0; y < channel.h; y++) {
411
8.31k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
8.31k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
8.31k
      InitPropsRow(&properties, static_props, y);
414
8.31k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
23.9k
        for (size_t x = 0; x < 2; x++) {
416
15.9k
          PredictionResult res =
417
15.9k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
15.9k
                              tree_lookup, references);
419
15.9k
          uint64_t v =
420
15.9k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
15.9k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
15.9k
        }
423
2.18M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
2.17M
          PredictionResult res =
425
2.17M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
2.17M
                                 tree_lookup, references);
427
2.17M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
2.17M
              res.context, br);
429
2.17M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
2.17M
        }
431
23.9k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
15.9k
          PredictionResult res =
433
15.9k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
15.9k
                              tree_lookup, references);
435
15.9k
          uint64_t v =
436
15.9k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
15.9k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
15.9k
        }
439
7.99k
      } else {
440
23.0k
        for (size_t x = 0; x < channel.w; x++) {
441
22.7k
          PredictionResult res =
442
22.7k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
22.7k
                              tree_lookup, references);
444
22.7k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
22.7k
              res.context, br);
446
22.7k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
22.7k
        }
448
316
      }
449
8.31k
    }
450
1.23k
  } else {
451
1.23k
    JXL_DEBUG_V(8, "Slowest track.");
452
1.23k
    MATreeLookup tree_lookup(tree);
453
1.23k
    Properties properties = Properties(num_props);
454
1.23k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
1.23k
    JXL_ASSIGN_OR_RETURN(
456
1.23k
        Channel references,
457
1.23k
        Channel::Create(memory_manager,
458
1.23k
                        properties.size() - kNumNonrefProperties, channel.w));
459
1.23k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
27.5k
    for (size_t y = 0; y < channel.h; y++) {
461
26.3k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
26.3k
      InitPropsRow(&properties, static_props, y);
463
26.3k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
26.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
26.3k
      } else {
493
4.41M
        for (size_t x = 0; x < channel.w; x++) {
494
4.39M
          PredictionResult res =
495
4.39M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
4.39M
                            tree_lookup, references, &wp_state);
497
4.39M
          uint64_t v =
498
4.39M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
4.39M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
4.39M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
4.39M
        }
502
26.3k
      }
503
26.3k
    }
504
1.23k
  }
505
1.36k
  return true;
506
1.36k
}
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
261k
                                 uint32_t &fl_v) {
157
261k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
261k
  Channel &channel = image->channel[chan];
159
160
261k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
261k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
261k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
261k
  bool tree_has_wp_prop_or_pred = false;
168
261k
  bool is_wp_only = false;
169
261k
  bool is_gradient_only = false;
170
261k
  size_t num_props;
171
261k
  FlatTree tree =
172
261k
      FilterTree(global_tree, static_props, &num_props,
173
261k
                 &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
600k
  for (auto &node : tree) {
178
600k
    if (node.property0 == -1) {
179
516k
      node.childID = context_map[node.childID];
180
516k
    }
181
600k
  }
182
183
261k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
261k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
261k
                             pixel_type_w offset) -> pixel_type {
188
261k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
261k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
261k
    return val * multiplier + offset;
192
261k
  };
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
261k
  const bool global_tree_is_all_gradient_noop = [&] {
200
261k
    for (const auto& n : global_tree) {
201
261k
      if (n.property == -1) {
202
261k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
261k
            n.multiplier != 1)
204
261k
          return false;
205
261k
      } else if (n.property >= kNumStaticProperties) {
206
261k
        return false;
207
261k
      }
208
261k
    }
209
261k
    return true;
210
261k
  }();
211
212
261k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
247k
    Predictor predictor = tree[0].predictor;
216
247k
    int64_t offset = tree[0].predictor_offset;
217
247k
    int32_t multiplier = tree[0].multiplier;
218
247k
    size_t ctx_id = tree[0].childID;
219
247k
    if (predictor == Predictor::Zero) {
220
243k
      uint32_t value;
221
243k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
243k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
48.9k
        JXL_DEBUG_V(8, "Fastest track.");
226
48.9k
        pixel_type v = make_pixel(value, multiplier, offset);
227
2.62M
        for (size_t y = 0; y < channel.h; y++) {
228
2.57M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
2.57M
          std::fill(r, r + channel.w, v);
230
2.57M
        }
231
194k
      } else {
232
194k
        JXL_DEBUG_V(8, "Fast track.");
233
194k
        if (multiplier == 1 && offset == 0) {
234
3.31M
          for (size_t y = 0; y < channel.h; y++) {
235
3.12M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
158M
            for (size_t x = 0; x < channel.w; x++) {
237
155M
              uint32_t v =
238
155M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
155M
              r[x] = UnpackSigned(v);
240
155M
            }
241
3.12M
          }
242
193k
        } else {
243
18.4k
          for (size_t y = 0; y < channel.h; y++) {
244
17.4k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
2.23M
            for (size_t x = 0; x < channel.w; x++) {
246
2.21M
              uint32_t v =
247
2.21M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
2.21M
                                                                         br);
249
2.21M
              r[x] = make_pixel(v, multiplier, offset);
250
2.21M
            }
251
17.4k
          }
252
994
        }
253
194k
      }
254
243k
      return true;
255
243k
    } 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
3.73k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
677
               multiplier == 1) {
291
676
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
676
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
53.1k
      for (size_t y = 0; y < channel.h; y++) {
294
52.4k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
150k
        for (size_t x = 0; x < channel.w; x++) {
296
98.4k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
98.4k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
98.4k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
98.4k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
98.4k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
98.4k
              ctx_id, br);
302
98.4k
          r[x] = make_pixel(v, 1, guess);
303
98.4k
        }
304
52.4k
      }
305
676
      return true;
306
676
    }
307
247k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
17.3k
  if (is_wp_only) {
312
1.75k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
1.75k
  }
314
17.3k
  if (is_gradient_only) {
315
1.02k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
1.02k
  }
317
318
17.3k
  if (is_gradient_only) {
319
955
    JXL_DEBUG_V(8, "Gradient fast track.");
320
955
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
63.9k
    for (size_t y = 0; y < channel.h; y++) {
322
63.0k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
275k
      for (size_t x = 0; x < channel.w; x++) {
324
212k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
212k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
212k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
212k
        int32_t guess = ClampedGradient(top, left, topleft);
328
212k
        uint32_t pos =
329
212k
            kPropRangeFast +
330
212k
            std::min<pixel_type_w>(
331
212k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
212k
                kPropRangeFast - 1);
333
212k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
212k
        uint64_t v =
335
212k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
212k
        r[x] = make_pixel(v, 1, guess);
337
212k
      }
338
63.0k
    }
339
16.4k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
670
    JXL_DEBUG_V(8, "WP fast track.");
341
670
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
670
    Properties properties(1);
343
6.51k
    for (size_t y = 0; y < channel.h; y++) {
344
5.84k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
5.84k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
5.84k
      const pixel_type *JXL_RESTRICT rtoptop =
347
5.84k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
5.84k
      const pixel_type *JXL_RESTRICT rtopleft =
349
5.84k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
5.84k
      const pixel_type *JXL_RESTRICT rtopright =
351
5.84k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
5.84k
      size_t x = 0;
353
5.84k
      {
354
5.84k
        size_t offset = 0;
355
5.84k
        pixel_type_w left = y ? rtop[x] : 0;
356
5.84k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
5.84k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
5.84k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
5.84k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
5.84k
            offset);
361
5.84k
        uint32_t pos =
362
5.84k
            kPropRangeFast +
363
5.84k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
5.84k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
5.84k
        uint64_t v =
366
5.84k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
5.84k
        r[x] = make_pixel(v, 1, guess);
368
5.84k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
5.84k
      }
370
291k
      for (x = 1; x + 1 < channel.w; x++) {
371
285k
        size_t offset = 0;
372
285k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
285k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
285k
            rtoptop[x], &properties, offset);
375
285k
        uint32_t pos =
376
285k
            kPropRangeFast +
377
285k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
285k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
285k
        uint64_t v =
380
285k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
285k
        r[x] = make_pixel(v, 1, guess);
382
285k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
285k
      }
384
5.84k
      {
385
5.84k
        size_t offset = 0;
386
5.84k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
5.84k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
5.84k
            rtoptop[x], &properties, offset);
389
5.84k
        uint32_t pos =
390
5.84k
            kPropRangeFast +
391
5.84k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
5.84k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
5.84k
        uint64_t v =
394
5.84k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
5.84k
        r[x] = make_pixel(v, 1, guess);
396
5.84k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
5.84k
      }
398
5.84k
    }
399
15.6k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
7.28k
    JXL_DEBUG_V(8, "Slow track.");
403
7.28k
    MATreeLookup tree_lookup(tree);
404
7.28k
    Properties properties = Properties(num_props);
405
7.28k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
7.28k
    JXL_ASSIGN_OR_RETURN(
407
7.28k
        Channel references,
408
7.28k
        Channel::Create(memory_manager,
409
7.28k
                        properties.size() - kNumNonrefProperties, channel.w));
410
223k
    for (size_t y = 0; y < channel.h; y++) {
411
215k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
215k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
215k
      InitPropsRow(&properties, static_props, y);
414
215k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
397k
        for (size_t x = 0; x < 2; x++) {
416
264k
          PredictionResult res =
417
264k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
264k
                              tree_lookup, references);
419
264k
          uint64_t v =
420
264k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
264k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
264k
        }
423
16.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
16.5M
          PredictionResult res =
425
16.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
16.5M
                                 tree_lookup, references);
427
16.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
16.5M
              res.context, br);
429
16.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
16.5M
        }
431
397k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
264k
          PredictionResult res =
433
264k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
264k
                              tree_lookup, references);
435
264k
          uint64_t v =
436
264k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
264k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
264k
        }
439
132k
      } else {
440
4.56M
        for (size_t x = 0; x < channel.w; x++) {
441
4.47M
          PredictionResult res =
442
4.47M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
4.47M
                              tree_lookup, references);
444
4.47M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
4.47M
              res.context, br);
446
4.47M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
4.47M
        }
448
83.5k
      }
449
215k
    }
450
8.39k
  } else {
451
8.39k
    JXL_DEBUG_V(8, "Slowest track.");
452
8.39k
    MATreeLookup tree_lookup(tree);
453
8.39k
    Properties properties = Properties(num_props);
454
8.39k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
8.39k
    JXL_ASSIGN_OR_RETURN(
456
8.39k
        Channel references,
457
8.39k
        Channel::Create(memory_manager,
458
8.39k
                        properties.size() - kNumNonrefProperties, channel.w));
459
8.39k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
500k
    for (size_t y = 0; y < channel.h; y++) {
461
491k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
491k
      InitPropsRow(&properties, static_props, y);
463
491k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
504k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
689k
        for (size_t x = 0; x < 2; x++) {
466
459k
          PredictionResult res =
467
459k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
459k
                            tree_lookup, references, &wp_state);
469
459k
          uint64_t v =
470
459k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
459k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
459k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
459k
        }
474
16.3M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
16.1M
          PredictionResult res =
476
16.1M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
16.1M
                               tree_lookup, references, &wp_state);
478
16.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
16.1M
              res.context, br);
480
16.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
16.1M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
16.1M
        }
483
689k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
459k
          PredictionResult res =
485
459k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
459k
                            tree_lookup, references, &wp_state);
487
459k
          uint64_t v =
488
459k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
459k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
459k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
459k
        }
492
261k
      } else {
493
2.78M
        for (size_t x = 0; x < channel.w; x++) {
494
2.52M
          PredictionResult res =
495
2.52M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.52M
                            tree_lookup, references, &wp_state);
497
2.52M
          uint64_t v =
498
2.52M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.52M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.52M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.52M
        }
502
261k
      }
503
491k
    }
504
8.39k
  }
505
17.3k
  return true;
506
17.3k
}
507
}  // namespace detail
508
509
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
510
                                 const std::vector<uint8_t> &context_map,
511
                                 const Tree &global_tree,
512
                                 const weighted::Header &wp_header,
513
                                 pixel_type chan, size_t group_id,
514
                                 TreeLut<uint8_t, false, false> &tree_lut,
515
                                 Image *image, uint32_t &fl_run,
516
271k
                                 uint32_t &fl_v) {
517
271k
  if (reader->UsesLZ77()) {
518
9.66k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
9.66k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
9.66k
        tree_lut, image, fl_run, fl_v);
521
261k
  } else {
522
261k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
261k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
261k
        tree_lut, image, fl_run, fl_v);
525
261k
  }
526
271k
}
527
528
297k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
41.8k
                                 const ModularOptions &options) {
532
41.8k
  size_t nb_channels = image.channel.size();
533
83.5k
  for (bool is_dc : {true, false}) {
534
83.5k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
83.5k
    size_t c = image.nb_meta_channels;
536
635k
    for (; c < nb_channels; c++) {
537
555k
      const Channel &ch = image.channel[c];
538
555k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
555k
    }
540
116k
    for (; c < nb_channels; c++) {
541
32.7k
      const Channel &ch = image.channel[c];
542
32.7k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
32.5k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
32.5k
      if (is_dc_channel != is_dc) continue;
545
16.2k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
16.2k
      if (tile_dim == 0) {
547
0
        return JXL_FAILURE("Inconsistent transforms");
548
0
      }
549
16.2k
    }
550
83.5k
  }
551
41.8k
  return true;
552
41.8k
}
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
49.1k
                     const bool allow_truncated_group) {
559
49.1k
  if (image.channel.empty()) return true;
560
41.9k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
41.9k
  Status status = Bundle::Read(br, &header);
564
41.9k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
41.8k
  if (status.IsFatalError()) return status;
566
41.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
41.8k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
41.8k
              header.transforms.size());
578
41.8k
  image.transform = header.transforms;
579
41.8k
  for (Transform &transform : image.transform) {
580
21.5k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
21.5k
  }
582
41.8k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
41.8k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
41.8k
  size_t nb_channels = image.channel.size();
588
589
41.8k
  size_t num_chans = 0;
590
41.8k
  size_t distance_multiplier = 0;
591
323k
  for (size_t i = 0; i < nb_channels; i++) {
592
283k
    Channel &channel = image.channel[i];
593
283k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
277k
                                        channel.h > options->max_chan_size)) {
595
1.71k
      break;
596
1.71k
    }
597
282k
    if (!channel.w || !channel.h) {
598
8.61k
      continue;  // skip empty channels
599
8.61k
    }
600
273k
    if (channel.w > distance_multiplier) {
601
59.2k
      distance_multiplier = channel.w;
602
59.2k
    }
603
273k
    num_chans++;
604
273k
  }
605
41.8k
  if (num_chans == 0) return true;
606
607
41.4k
  size_t next_channel = 0;
608
41.4k
  auto scope_guard = MakeScopeGuard([&]() {
609
2.59k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
2.46k
      ZeroFillImage(&image.channel[c].plane);
611
2.46k
    }
612
129
  });
613
  // Do not do anything if truncated groups are not allowed.
614
41.4k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
41.4k
  Tree tree_storage;
618
41.4k
  std::vector<uint8_t> context_map_storage;
619
41.4k
  ANSCode code_storage;
620
41.4k
  const Tree *tree = &tree_storage;
621
41.4k
  const ANSCode *code = &code_storage;
622
41.4k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
41.4k
  if (!header.use_global_tree) {
624
12.4k
    uint64_t max_tree_size = 1024;
625
89.7k
    for (size_t i = 0; i < nb_channels; i++) {
626
77.3k
      Channel &channel = image.channel[i];
627
77.3k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
76.0k
                                          channel.h > options->max_chan_size)) {
629
16
        break;
630
16
      }
631
77.3k
      uint64_t pixels = channel.w * channel.h;
632
77.3k
      max_tree_size += pixels;
633
77.3k
    }
634
12.4k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
12.4k
    JXL_RETURN_IF_ERROR(
636
12.4k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
12.3k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
12.3k
                                         (tree_storage.size() + 1) / 2,
639
12.3k
                                         &code_storage, &context_map_storage));
640
29.0k
  } else {
641
29.0k
    if (!global_tree || !global_code || !global_ctx_map ||
642
29.0k
        global_tree->empty()) {
643
14
      return JXL_FAILURE("No global tree available but one was requested");
644
14
    }
645
29.0k
    tree = global_tree;
646
29.0k
    code = global_code;
647
29.0k
    context_map = global_ctx_map;
648
29.0k
  }
649
650
  // Read channels
651
82.8k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
82.8k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
82.8k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
82.8k
  uint32_t fl_run = 0;
655
82.8k
  uint32_t fl_v = 0;
656
321k
  for (; next_channel < nb_channels; next_channel++) {
657
281k
    Channel &channel = image.channel[next_channel];
658
281k
    if (next_channel >= image.nb_meta_channels &&
659
275k
        (channel.w > options->max_chan_size ||
660
274k
         channel.h > options->max_chan_size)) {
661
1.37k
      break;
662
1.37k
    }
663
279k
    if (!channel.w || !channel.h) {
664
8.61k
      continue;  // skip empty channels
665
8.61k
    }
666
271k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
271k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
271k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
271k
    if (!br->AllReadsWithinBounds()) {
672
62
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
62
    }
675
271k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
41.3k
  scope_guard.Disarm();
679
680
41.3k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
41.3k
  return true;
684
41.3k
}
685
686
Status ModularGenericDecompress(BitReader *br, Image &image,
687
                                GroupHeader *header, size_t group_id,
688
                                ModularOptions *options, bool undo_transforms,
689
                                const Tree *tree, const ANSCode *code,
690
                                const std::vector<uint8_t> *ctx_map,
691
49.2k
                                bool allow_truncated_group) {
692
49.2k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
49.2k
  req_sizes.reserve(image.channel.size());
694
165k
  for (const auto &c : image.channel) {
695
165k
    req_sizes.emplace_back(c.w, c.h);
696
165k
  }
697
49.2k
  GroupHeader local_header;
698
49.2k
  if (header == nullptr) header = &local_header;
699
49.2k
  size_t bit_pos = br->TotalBitsConsumed();
700
49.2k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
49.2k
                                  code, ctx_map, allow_truncated_group);
702
49.2k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
49.0k
  if (dec_status.IsFatalError()) return dec_status;
704
49.0k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
49.0k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
49.0k
  JXL_DEBUG_V(4,
707
49.0k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
49.0k
              " image from %" PRIuS " bytes",
709
49.0k
              image.w, image.h, image.channel.size(),
710
49.0k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
49.0k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
49.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
49.0k
  if (undo_transforms) {
717
24.4k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
128k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
104k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
104k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
104k
    }
722
24.4k
  }
723
49.0k
  return dec_status;
724
49.0k
}
725
726
}  // namespace jxl