Coverage Report

Created: 2026-10-27 06:57

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
183k
                    bool *gradient_only) {
46
183k
  *num_props = 0;
47
183k
  bool has_wp = false;
48
183k
  bool has_non_wp = false;
49
183k
  *gradient_only = true;
50
225k
  const auto mark_property = [&](int32_t p) {
51
225k
    if (p == kWPProp) {
52
19.0k
      has_wp = true;
53
206k
    } else if (p >= kNumStaticProperties) {
54
126k
      has_non_wp = true;
55
126k
    }
56
225k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
128k
      *gradient_only = false;
58
128k
    }
59
225k
  };
60
183k
  FlatTree output;
61
183k
  std::queue<size_t> nodes;
62
183k
  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
665k
  while (!nodes.empty()) {
70
481k
    size_t cur = nodes.front();
71
481k
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
511k
    while (global_tree[cur].property < kNumStaticProperties &&
74
439k
           global_tree[cur].property != -1) {
75
29.8k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
16.6k
        cur = global_tree[cur].lchild;
77
16.6k
      } else {
78
13.2k
        cur = global_tree[cur].rchild;
79
13.2k
      }
80
29.8k
    }
81
481k
    FlatDecisionNode flat;
82
481k
    if (global_tree[cur].property == -1) {
83
407k
      flat.property0 = -1;
84
407k
      flat.childID = global_tree[cur].lchild;
85
407k
      flat.predictor = global_tree[cur].predictor;
86
407k
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
407k
      flat.multiplier = global_tree[cur].multiplier;
88
407k
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
407k
      has_wp |= flat.predictor == Predictor::Weighted;
90
407k
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
407k
      output.push_back(flat);
92
407k
      continue;
93
407k
    }
94
73.8k
    flat.childID = output.size() + nodes.size() + 1;
95
96
73.8k
    flat.property0 = global_tree[cur].property;
97
73.8k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
73.8k
    flat.splitval0 = global_tree[cur].splitval;
99
100
224k
    for (size_t i = 0; i < 2; i++) {
101
150k
      size_t cur_child =
102
150k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
167k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
98.4k
             global_tree[cur_child].property != -1) {
106
16.2k
        if (static_props[global_tree[cur_child].property] >
107
16.2k
            global_tree[cur_child].splitval) {
108
9.96k
          cur_child = global_tree[cur_child].lchild;
109
9.96k
        } else {
110
6.24k
          cur_child = global_tree[cur_child].rchild;
111
6.24k
        }
112
16.2k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
150k
      if (global_tree[cur_child].property == -1) {
116
83.4k
        flat.properties[i] = 0;
117
83.4k
        flat.splitvals[i] = 0;
118
83.4k
        nodes.push(cur_child);
119
83.4k
        nodes.push(cur_child);
120
83.4k
      } else {
121
67.5k
        flat.properties[i] = global_tree[cur_child].property;
122
67.5k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
67.5k
        nodes.push(global_tree[cur_child].lchild);
124
67.5k
        nodes.push(global_tree[cur_child].rchild);
125
67.5k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
67.5k
      }
127
150k
    }
128
129
151k
    for (int16_t property : flat.properties) mark_property(property);
130
73.8k
    mark_property(flat.property0);
131
73.8k
    output.push_back(flat);
132
73.8k
  }
133
183k
  if (*num_props > kNumNonrefProperties) {
134
648
    *num_props =
135
648
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
648
            kExtraPropsPerChannel +
137
648
        kNumNonrefProperties;
138
183k
  } else {
139
183k
    *num_props = kNumNonrefProperties;
140
183k
  }
141
183k
  *use_wp = has_wp;
142
183k
  *wp_only = has_wp && !has_non_wp;
143
144
183k
  return output;
145
183k
}
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
183k
                                 uint32_t &fl_v) {
157
183k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
183k
  Channel &channel = image->channel[chan];
159
160
183k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
183k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
183k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
183k
  bool tree_has_wp_prop_or_pred = false;
168
183k
  bool is_wp_only = false;
169
183k
  bool is_gradient_only = false;
170
183k
  size_t num_props;
171
183k
  FlatTree tree =
172
183k
      FilterTree(global_tree, static_props, &num_props,
173
183k
                 &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
509k
  for (auto &node : tree) {
178
509k
    if (node.property0 == -1) {
179
428k
      node.childID = context_map[node.childID];
180
428k
    }
181
509k
  }
182
183
183k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
183k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
47.9M
                             pixel_type_w offset) -> pixel_type {
188
47.9M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
47.9M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
47.9M
    return val * multiplier + offset;
192
47.9M
  };
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
8.21M
                             pixel_type_w offset) -> pixel_type {
188
8.21M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
8.21M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
8.21M
    return val * multiplier + offset;
192
8.21M
  };
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
39.7M
                             pixel_type_w offset) -> pixel_type {
188
39.7M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
39.7M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
39.7M
    return val * multiplier + offset;
192
39.7M
  };
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
183k
  const bool global_tree_is_all_gradient_noop = [&] {
200
197k
    for (const auto& n : global_tree) {
201
197k
      if (n.property == -1) {
202
170k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
562
            n.multiplier != 1)
204
169k
          return false;
205
170k
      } else if (n.property >= kNumStaticProperties) {
206
13.6k
        return false;
207
13.6k
      }
208
197k
    }
209
562
    return true;
210
183k
  }();
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
6.68k
  const bool global_tree_is_all_gradient_noop = [&] {
200
6.98k
    for (const auto& n : global_tree) {
201
6.98k
      if (n.property == -1) {
202
6.68k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
0
            n.multiplier != 1)
204
6.68k
          return false;
205
6.68k
      } else if (n.property >= kNumStaticProperties) {
206
9
        return false;
207
9
      }
208
6.98k
    }
209
18.4E
    return true;
210
6.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
177k
  const bool global_tree_is_all_gradient_noop = [&] {
200
190k
    for (const auto& n : global_tree) {
201
190k
      if (n.property == -1) {
202
163k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
562
            n.multiplier != 1)
204
163k
          return false;
205
163k
      } else if (n.property >= kNumStaticProperties) {
206
13.6k
        return false;
207
13.6k
      }
208
190k
    }
209
566
    return true;
210
177k
  }();
211
212
183k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
171k
    Predictor predictor = tree[0].predictor;
216
171k
    int64_t offset = tree[0].predictor_offset;
217
171k
    int32_t multiplier = tree[0].multiplier;
218
171k
    size_t ctx_id = tree[0].childID;
219
171k
    if (predictor == Predictor::Zero) {
220
168k
      uint32_t value;
221
168k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
168k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
10.7k
        JXL_DEBUG_V(8, "Fastest track.");
226
10.7k
        pixel_type v = make_pixel(value, multiplier, offset);
227
948k
        for (size_t y = 0; y < channel.h; y++) {
228
938k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
938k
          std::fill(r, r + channel.w, v);
230
938k
        }
231
157k
      } else {
232
157k
        JXL_DEBUG_V(8, "Fast track.");
233
157k
        if (multiplier == 1 && offset == 0) {
234
3.91M
          for (size_t y = 0; y < channel.h; y++) {
235
3.75M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
324M
            for (size_t x = 0; x < channel.w; x++) {
237
320M
              uint32_t v =
238
320M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
320M
              r[x] = UnpackSigned(v);
240
320M
            }
241
3.75M
          }
242
157k
        } else {
243
21.8k
          for (size_t y = 0; y < channel.h; y++) {
244
21.4k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
5.17M
            for (size_t x = 0; x < channel.w; x++) {
246
5.14M
              uint32_t v =
247
5.14M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
5.14M
                                                                         br);
249
5.14M
              r[x] = make_pixel(v, multiplier, offset);
250
5.14M
            }
251
21.4k
          }
252
336
        }
253
157k
      }
254
168k
      return true;
255
168k
    } 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
2.85k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
583
               multiplier == 1) {
291
583
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
583
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
47.7k
      for (size_t y = 0; y < channel.h; y++) {
294
47.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
134k
        for (size_t x = 0; x < channel.w; x++) {
296
86.9k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
86.9k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
86.9k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
86.9k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
86.9k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
86.9k
              ctx_id, br);
302
86.9k
          r[x] = make_pixel(v, 1, guess);
303
86.9k
        }
304
47.1k
      }
305
583
      return true;
306
583
    }
307
171k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
14.8k
  if (is_wp_only) {
312
2.03k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
2.03k
  }
314
14.8k
  if (is_gradient_only) {
315
719
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
719
  }
317
318
14.8k
  if (is_gradient_only) {
319
673
    JXL_DEBUG_V(8, "Gradient fast track.");
320
673
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
1.65k
    for (size_t y = 0; y < channel.h; y++) {
322
983
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
87.8k
      for (size_t x = 0; x < channel.w; x++) {
324
86.8k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
86.8k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
86.8k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
86.8k
        int32_t guess = ClampedGradient(top, left, topleft);
328
86.8k
        uint32_t pos =
329
86.8k
            kPropRangeFast +
330
86.8k
            std::min<pixel_type_w>(
331
86.8k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
86.8k
                kPropRangeFast - 1);
333
86.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
86.8k
        uint64_t v =
335
86.8k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
86.8k
        r[x] = make_pixel(v, 1, guess);
337
86.8k
      }
338
983
    }
339
14.1k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
855
    JXL_DEBUG_V(8, "WP fast track.");
341
855
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
855
    Properties properties(1);
343
6.25k
    for (size_t y = 0; y < channel.h; y++) {
344
5.39k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
5.39k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
5.39k
      const pixel_type *JXL_RESTRICT rtoptop =
347
5.39k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
5.39k
      const pixel_type *JXL_RESTRICT rtopleft =
349
5.39k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
5.39k
      const pixel_type *JXL_RESTRICT rtopright =
351
5.39k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
5.39k
      size_t x = 0;
353
5.39k
      {
354
5.39k
        size_t offset = 0;
355
5.39k
        pixel_type_w left = y ? rtop[x] : 0;
356
5.39k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
5.41k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
5.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
5.39k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
5.39k
            offset);
361
5.39k
        uint32_t pos =
362
5.39k
            kPropRangeFast +
363
5.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
5.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
5.39k
        uint64_t v =
366
5.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
5.39k
        r[x] = make_pixel(v, 1, guess);
368
5.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
5.39k
      }
370
276k
      for (x = 1; x + 1 < channel.w; x++) {
371
270k
        size_t offset = 0;
372
270k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
270k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
270k
            rtoptop[x], &properties, offset);
375
270k
        uint32_t pos =
376
270k
            kPropRangeFast +
377
270k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
270k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
270k
        uint64_t v =
380
270k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
270k
        r[x] = make_pixel(v, 1, guess);
382
270k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
270k
      }
384
5.39k
      {
385
5.39k
        size_t offset = 0;
386
5.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
5.39k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
5.39k
            rtoptop[x], &properties, offset);
389
5.39k
        uint32_t pos =
390
5.39k
            kPropRangeFast +
391
5.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
5.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
5.39k
        uint64_t v =
394
5.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
5.39k
        r[x] = make_pixel(v, 1, guess);
396
5.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
5.39k
      }
398
5.39k
    }
399
13.3k
  } 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
6.01k
    JXL_DEBUG_V(8, "Slow track.");
403
6.01k
    MATreeLookup tree_lookup(tree);
404
6.01k
    Properties properties = Properties(num_props);
405
6.01k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
6.01k
    JXL_ASSIGN_OR_RETURN(
407
6.01k
        Channel references,
408
6.01k
        Channel::Create(memory_manager,
409
6.01k
                        properties.size() - kNumNonrefProperties, channel.w));
410
184k
    for (size_t y = 0; y < channel.h; y++) {
411
178k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
178k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
178k
      InitPropsRow(&properties, static_props, y);
414
178k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
383k
        for (size_t x = 0; x < 2; x++) {
416
255k
          PredictionResult res =
417
255k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
255k
                              tree_lookup, references);
419
255k
          uint64_t v =
420
255k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
255k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
255k
        }
423
17.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
17.0M
          PredictionResult res =
425
17.0M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
17.0M
                                 tree_lookup, references);
427
17.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
17.0M
              res.context, br);
429
17.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
17.0M
        }
431
383k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
255k
          PredictionResult res =
433
255k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
255k
                              tree_lookup, references);
435
255k
          uint64_t v =
436
255k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
255k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
255k
        }
439
127k
      } else {
440
4.35M
        for (size_t x = 0; x < channel.w; x++) {
441
4.29M
          PredictionResult res =
442
4.29M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
4.29M
                              tree_lookup, references);
444
4.29M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
4.29M
              res.context, br);
446
4.29M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
4.29M
        }
448
50.4k
      }
449
178k
    }
450
7.30k
  } else {
451
7.30k
    JXL_DEBUG_V(8, "Slowest track.");
452
7.30k
    MATreeLookup tree_lookup(tree);
453
7.30k
    Properties properties = Properties(num_props);
454
7.30k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
7.30k
    JXL_ASSIGN_OR_RETURN(
456
7.30k
        Channel references,
457
7.30k
        Channel::Create(memory_manager,
458
7.30k
                        properties.size() - kNumNonrefProperties, channel.w));
459
7.30k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
355k
    for (size_t y = 0; y < channel.h; y++) {
461
348k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
348k
      InitPropsRow(&properties, static_props, y);
463
348k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
348k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
680k
        for (size_t x = 0; x < 2; x++) {
466
453k
          PredictionResult res =
467
453k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
453k
                            tree_lookup, references, &wp_state);
469
453k
          uint64_t v =
470
453k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
453k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
453k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
453k
        }
474
14.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
14.2M
          PredictionResult res =
476
14.2M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
14.2M
                               tree_lookup, references, &wp_state);
478
14.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
14.2M
              res.context, br);
480
14.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
14.2M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
14.2M
        }
483
680k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
453k
          PredictionResult res =
485
453k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
453k
                            tree_lookup, references, &wp_state);
487
453k
          uint64_t v =
488
453k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
453k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
453k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
453k
        }
492
227k
      } else {
493
6.03M
        for (size_t x = 0; x < channel.w; x++) {
494
5.91M
          PredictionResult res =
495
5.91M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
5.91M
                            tree_lookup, references, &wp_state);
497
5.91M
          uint64_t v =
498
5.91M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
5.91M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
5.91M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
5.91M
        }
502
121k
      }
503
348k
    }
504
7.30k
  }
505
14.8k
  return true;
506
14.8k
}
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
6.65k
                                 uint32_t &fl_v) {
157
6.65k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
6.65k
  Channel &channel = image->channel[chan];
159
160
6.65k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
6.65k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
6.66k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
6.65k
  bool tree_has_wp_prop_or_pred = false;
168
6.65k
  bool is_wp_only = false;
169
6.65k
  bool is_gradient_only = false;
170
6.65k
  size_t num_props;
171
6.65k
  FlatTree tree =
172
6.65k
      FilterTree(global_tree, static_props, &num_props,
173
6.65k
                 &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
7.39k
  for (auto &node : tree) {
178
7.39k
    if (node.property0 == -1) {
179
7.21k
      node.childID = context_map[node.childID];
180
7.21k
    }
181
7.39k
  }
182
183
6.65k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
6.65k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
6.65k
                             pixel_type_w offset) -> pixel_type {
188
6.65k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
6.65k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
6.65k
    return val * multiplier + offset;
192
6.65k
  };
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
6.65k
  const bool global_tree_is_all_gradient_noop = [&] {
200
6.65k
    for (const auto& n : global_tree) {
201
6.65k
      if (n.property == -1) {
202
6.65k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
6.65k
            n.multiplier != 1)
204
6.65k
          return false;
205
6.65k
      } else if (n.property >= kNumStaticProperties) {
206
6.65k
        return false;
207
6.65k
      }
208
6.65k
    }
209
6.65k
    return true;
210
6.65k
  }();
211
212
6.67k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
6.67k
    Predictor predictor = tree[0].predictor;
216
6.67k
    int64_t offset = tree[0].predictor_offset;
217
6.67k
    int32_t multiplier = tree[0].multiplier;
218
6.67k
    size_t ctx_id = tree[0].childID;
219
6.67k
    if (predictor == Predictor::Zero) {
220
6.33k
      uint32_t value;
221
6.33k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
6.33k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
104
        JXL_DEBUG_V(8, "Fastest track.");
226
104
        pixel_type v = make_pixel(value, multiplier, offset);
227
2.83k
        for (size_t y = 0; y < channel.h; y++) {
228
2.73k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
2.73k
          std::fill(r, r + channel.w, v);
230
2.73k
        }
231
6.22k
      } else {
232
6.22k
        JXL_DEBUG_V(8, "Fast track.");
233
6.22k
        if (multiplier == 1 && offset == 0) {
234
481k
          for (size_t y = 0; y < channel.h; y++) {
235
475k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
31.7M
            for (size_t x = 0; x < channel.w; x++) {
237
31.2M
              uint32_t v =
238
31.2M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
31.2M
              r[x] = UnpackSigned(v);
240
31.2M
            }
241
475k
          }
242
6.08k
        } else {
243
17.2k
          for (size_t y = 0; y < channel.h; y++) {
244
17.1k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
4.09M
            for (size_t x = 0; x < channel.w; x++) {
246
4.08M
              uint32_t v =
247
4.08M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
4.08M
                                                                         br);
249
4.08M
              r[x] = make_pixel(v, multiplier, offset);
250
4.08M
            }
251
17.1k
          }
252
143
        }
253
6.22k
      }
254
6.33k
      return true;
255
6.33k
    } 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
345
    } 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
6.67k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
321
  if (is_wp_only) {
312
286
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
286
  }
314
321
  if (is_gradient_only) {
315
0
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
0
  }
317
318
321
  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
321
  } 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
321
  } 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
62
    JXL_DEBUG_V(8, "Slow track.");
403
62
    MATreeLookup tree_lookup(tree);
404
62
    Properties properties = Properties(num_props);
405
62
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
62
    JXL_ASSIGN_OR_RETURN(
407
62
        Channel references,
408
62
        Channel::Create(memory_manager,
409
62
                        properties.size() - kNumNonrefProperties, channel.w));
410
4.11k
    for (size_t y = 0; y < channel.h; y++) {
411
4.05k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
4.05k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
4.05k
      InitPropsRow(&properties, static_props, y);
414
4.05k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
11.6k
        for (size_t x = 0; x < 2; x++) {
416
7.74k
          PredictionResult res =
417
7.74k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
7.74k
                              tree_lookup, references);
419
7.74k
          uint64_t v =
420
7.74k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
7.74k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
7.74k
        }
423
1.08M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
1.07M
          PredictionResult res =
425
1.07M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
1.07M
                                 tree_lookup, references);
427
1.07M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
1.07M
              res.context, br);
429
1.07M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
1.07M
        }
431
11.6k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
7.74k
          PredictionResult res =
433
7.74k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
7.74k
                              tree_lookup, references);
435
7.74k
          uint64_t v =
436
7.74k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
7.74k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
7.74k
        }
439
3.87k
      } else {
440
11.9k
        for (size_t x = 0; x < channel.w; x++) {
441
11.7k
          PredictionResult res =
442
11.7k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
11.7k
                              tree_lookup, references);
444
11.7k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
11.7k
              res.context, br);
446
11.7k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
11.7k
        }
448
181
      }
449
4.05k
    }
450
259
  } else {
451
259
    JXL_DEBUG_V(8, "Slowest track.");
452
259
    MATreeLookup tree_lookup(tree);
453
259
    Properties properties = Properties(num_props);
454
259
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
259
    JXL_ASSIGN_OR_RETURN(
456
259
        Channel references,
457
259
        Channel::Create(memory_manager,
458
259
                        properties.size() - kNumNonrefProperties, channel.w));
459
259
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
20.4k
    for (size_t y = 0; y < channel.h; y++) {
461
20.2k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
20.2k
      InitPropsRow(&properties, static_props, y);
463
20.2k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
20.2k
      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
20.2k
      } else {
493
3.06M
        for (size_t x = 0; x < channel.w; x++) {
494
3.04M
          PredictionResult res =
495
3.04M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
3.04M
                            tree_lookup, references, &wp_state);
497
3.04M
          uint64_t v =
498
3.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
3.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
3.04M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
3.04M
        }
502
20.2k
      }
503
20.2k
    }
504
259
  }
505
321
  return true;
506
321
}
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
177k
                                 uint32_t &fl_v) {
157
177k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
177k
  Channel &channel = image->channel[chan];
159
160
177k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
177k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
177k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
177k
  bool tree_has_wp_prop_or_pred = false;
168
177k
  bool is_wp_only = false;
169
177k
  bool is_gradient_only = false;
170
177k
  size_t num_props;
171
177k
  FlatTree tree =
172
177k
      FilterTree(global_tree, static_props, &num_props,
173
177k
                 &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
502k
  for (auto &node : tree) {
178
502k
    if (node.property0 == -1) {
179
421k
      node.childID = context_map[node.childID];
180
421k
    }
181
502k
  }
182
183
177k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
177k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
177k
                             pixel_type_w offset) -> pixel_type {
188
177k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
177k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
177k
    return val * multiplier + offset;
192
177k
  };
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
177k
  const bool global_tree_is_all_gradient_noop = [&] {
200
177k
    for (const auto& n : global_tree) {
201
177k
      if (n.property == -1) {
202
177k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
177k
            n.multiplier != 1)
204
177k
          return false;
205
177k
      } else if (n.property >= kNumStaticProperties) {
206
177k
        return false;
207
177k
      }
208
177k
    }
209
177k
    return true;
210
177k
  }();
211
212
177k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
164k
    Predictor predictor = tree[0].predictor;
216
164k
    int64_t offset = tree[0].predictor_offset;
217
164k
    int32_t multiplier = tree[0].multiplier;
218
164k
    size_t ctx_id = tree[0].childID;
219
164k
    if (predictor == Predictor::Zero) {
220
162k
      uint32_t value;
221
162k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
162k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
10.6k
        JXL_DEBUG_V(8, "Fastest track.");
226
10.6k
        pixel_type v = make_pixel(value, multiplier, offset);
227
946k
        for (size_t y = 0; y < channel.h; y++) {
228
935k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
935k
          std::fill(r, r + channel.w, v);
230
935k
        }
231
151k
      } else {
232
151k
        JXL_DEBUG_V(8, "Fast track.");
233
151k
        if (multiplier == 1 && offset == 0) {
234
3.43M
          for (size_t y = 0; y < channel.h; y++) {
235
3.28M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
292M
            for (size_t x = 0; x < channel.w; x++) {
237
289M
              uint32_t v =
238
289M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
289M
              r[x] = UnpackSigned(v);
240
289M
            }
241
3.28M
          }
242
151k
        } else {
243
4.53k
          for (size_t y = 0; y < channel.h; y++) {
244
4.34k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
1.07M
            for (size_t x = 0; x < channel.w; x++) {
246
1.06M
              uint32_t v =
247
1.06M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
1.06M
                                                                         br);
249
1.06M
              r[x] = make_pixel(v, multiplier, offset);
250
1.06M
            }
251
4.34k
          }
252
193
        }
253
151k
      }
254
162k
      return true;
255
162k
    } 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
2.51k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
583
               multiplier == 1) {
291
583
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
583
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
47.7k
      for (size_t y = 0; y < channel.h; y++) {
294
47.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
134k
        for (size_t x = 0; x < channel.w; x++) {
296
86.9k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
86.9k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
86.9k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
86.9k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
86.9k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
86.9k
              ctx_id, br);
302
86.9k
          r[x] = make_pixel(v, 1, guess);
303
86.9k
        }
304
47.1k
      }
305
583
      return true;
306
583
    }
307
164k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
14.5k
  if (is_wp_only) {
312
1.74k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
1.74k
  }
314
14.5k
  if (is_gradient_only) {
315
719
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
719
  }
317
318
14.5k
  if (is_gradient_only) {
319
673
    JXL_DEBUG_V(8, "Gradient fast track.");
320
673
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
1.65k
    for (size_t y = 0; y < channel.h; y++) {
322
983
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
87.8k
      for (size_t x = 0; x < channel.w; x++) {
324
86.8k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
86.8k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
86.8k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
86.8k
        int32_t guess = ClampedGradient(top, left, topleft);
328
86.8k
        uint32_t pos =
329
86.8k
            kPropRangeFast +
330
86.8k
            std::min<pixel_type_w>(
331
86.8k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
86.8k
                kPropRangeFast - 1);
333
86.8k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
86.8k
        uint64_t v =
335
86.8k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
86.8k
        r[x] = make_pixel(v, 1, guess);
337
86.8k
      }
338
983
    }
339
13.8k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
855
    JXL_DEBUG_V(8, "WP fast track.");
341
855
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
855
    Properties properties(1);
343
6.25k
    for (size_t y = 0; y < channel.h; y++) {
344
5.39k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
5.39k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
5.39k
      const pixel_type *JXL_RESTRICT rtoptop =
347
5.39k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
5.39k
      const pixel_type *JXL_RESTRICT rtopleft =
349
5.39k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
5.39k
      const pixel_type *JXL_RESTRICT rtopright =
351
5.39k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
5.39k
      size_t x = 0;
353
5.39k
      {
354
5.39k
        size_t offset = 0;
355
5.39k
        pixel_type_w left = y ? rtop[x] : 0;
356
5.39k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
5.41k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
5.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
5.39k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
5.39k
            offset);
361
5.39k
        uint32_t pos =
362
5.39k
            kPropRangeFast +
363
5.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
5.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
5.39k
        uint64_t v =
366
5.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
5.39k
        r[x] = make_pixel(v, 1, guess);
368
5.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
5.39k
      }
370
276k
      for (x = 1; x + 1 < channel.w; x++) {
371
270k
        size_t offset = 0;
372
270k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
270k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
270k
            rtoptop[x], &properties, offset);
375
270k
        uint32_t pos =
376
270k
            kPropRangeFast +
377
270k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
270k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
270k
        uint64_t v =
380
270k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
270k
        r[x] = make_pixel(v, 1, guess);
382
270k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
270k
      }
384
5.39k
      {
385
5.39k
        size_t offset = 0;
386
5.39k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
5.39k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
5.39k
            rtoptop[x], &properties, offset);
389
5.39k
        uint32_t pos =
390
5.39k
            kPropRangeFast +
391
5.39k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
5.39k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
5.39k
        uint64_t v =
394
5.39k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
5.39k
        r[x] = make_pixel(v, 1, guess);
396
5.39k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
5.39k
      }
398
5.39k
    }
399
13.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
5.95k
    JXL_DEBUG_V(8, "Slow track.");
403
5.95k
    MATreeLookup tree_lookup(tree);
404
5.95k
    Properties properties = Properties(num_props);
405
5.95k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
5.95k
    JXL_ASSIGN_OR_RETURN(
407
5.95k
        Channel references,
408
5.95k
        Channel::Create(memory_manager,
409
5.95k
                        properties.size() - kNumNonrefProperties, channel.w));
410
180k
    for (size_t y = 0; y < channel.h; y++) {
411
174k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
174k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
174k
      InitPropsRow(&properties, static_props, y);
414
174k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
371k
        for (size_t x = 0; x < 2; x++) {
416
247k
          PredictionResult res =
417
247k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
247k
                              tree_lookup, references);
419
247k
          uint64_t v =
420
247k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
247k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
247k
        }
423
16.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
15.9M
          PredictionResult res =
425
15.9M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
15.9M
                                 tree_lookup, references);
427
15.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
15.9M
              res.context, br);
429
15.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
15.9M
        }
431
371k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
247k
          PredictionResult res =
433
247k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
247k
                              tree_lookup, references);
435
247k
          uint64_t v =
436
247k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
247k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
247k
        }
439
123k
      } else {
440
4.33M
        for (size_t x = 0; x < channel.w; x++) {
441
4.28M
          PredictionResult res =
442
4.28M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
4.28M
                              tree_lookup, references);
444
4.28M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
4.28M
              res.context, br);
446
4.28M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
4.28M
        }
448
50.2k
      }
449
174k
    }
450
7.04k
  } else {
451
7.04k
    JXL_DEBUG_V(8, "Slowest track.");
452
7.04k
    MATreeLookup tree_lookup(tree);
453
7.04k
    Properties properties = Properties(num_props);
454
7.04k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
7.04k
    JXL_ASSIGN_OR_RETURN(
456
7.04k
        Channel references,
457
7.04k
        Channel::Create(memory_manager,
458
7.04k
                        properties.size() - kNumNonrefProperties, channel.w));
459
7.04k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
335k
    for (size_t y = 0; y < channel.h; y++) {
461
328k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
328k
      InitPropsRow(&properties, static_props, y);
463
328k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
328k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
680k
        for (size_t x = 0; x < 2; x++) {
466
453k
          PredictionResult res =
467
453k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
453k
                            tree_lookup, references, &wp_state);
469
453k
          uint64_t v =
470
453k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
453k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
453k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
453k
        }
474
14.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
14.2M
          PredictionResult res =
476
14.2M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
14.2M
                               tree_lookup, references, &wp_state);
478
14.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
14.2M
              res.context, br);
480
14.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
14.2M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
14.2M
        }
483
680k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
453k
          PredictionResult res =
485
453k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
453k
                            tree_lookup, references, &wp_state);
487
453k
          uint64_t v =
488
453k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
453k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
453k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
453k
        }
492
227k
      } else {
493
2.96M
        for (size_t x = 0; x < channel.w; x++) {
494
2.86M
          PredictionResult res =
495
2.86M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.86M
                            tree_lookup, references, &wp_state);
497
2.86M
          uint64_t v =
498
2.86M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.86M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.86M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.86M
        }
502
100k
      }
503
328k
    }
504
7.04k
  }
505
14.5k
  return true;
506
14.5k
}
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
183k
                                 uint32_t &fl_v) {
517
183k
  if (reader->UsesLZ77()) {
518
6.63k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
6.63k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
6.63k
        tree_lut, image, fl_run, fl_v);
521
177k
  } else {
522
177k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
177k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
177k
        tree_lut, image, fl_run, fl_v);
525
177k
  }
526
183k
}
527
528
118k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
30.6k
                                 const ModularOptions &options) {
532
30.6k
  size_t nb_channels = image.channel.size();
533
61.2k
  for (bool is_dc : {true, false}) {
534
61.2k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
61.2k
    size_t c = image.nb_meta_channels;
536
432k
    for (; c < nb_channels; c++) {
537
373k
      const Channel &ch = image.channel[c];
538
373k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
373k
    }
540
77.9k
    for (; c < nb_channels; c++) {
541
16.6k
      const Channel &ch = image.channel[c];
542
16.6k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
16.6k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
16.6k
      if (is_dc_channel != is_dc) continue;
545
8.30k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
8.30k
      if (tile_dim == 0) {
547
0
        return JXL_FAILURE("Inconsistent transforms");
548
0
      }
549
8.30k
    }
550
61.2k
  }
551
30.6k
  return true;
552
30.6k
}
553
554
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
555
                     size_t group_id, ModularOptions *options,
556
                     const Tree *global_tree, const ANSCode *global_code,
557
                     const std::vector<uint8_t> *global_ctx_map,
558
36.8k
                     const bool allow_truncated_group) {
559
36.8k
  if (image.channel.empty()) return true;
560
30.7k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
30.7k
  Status status = Bundle::Read(br, &header);
564
30.7k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
30.6k
  if (status.IsFatalError()) return status;
566
30.6k
  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
30.6k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
30.6k
              header.transforms.size());
578
30.6k
  image.transform = header.transforms;
579
30.6k
  for (Transform &transform : image.transform) {
580
13.8k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
13.8k
  }
582
30.6k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
30.6k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
30.6k
  size_t nb_channels = image.channel.size();
588
589
30.6k
  size_t num_chans = 0;
590
30.6k
  size_t distance_multiplier = 0;
591
222k
  for (size_t i = 0; i < nb_channels; i++) {
592
192k
    Channel &channel = image.channel[i];
593
192k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
186k
                                        channel.h > options->max_chan_size)) {
595
1.07k
      break;
596
1.07k
    }
597
191k
    if (!channel.w || !channel.h) {
598
5.65k
      continue;  // skip empty channels
599
5.65k
    }
600
185k
    if (channel.w > distance_multiplier) {
601
43.8k
      distance_multiplier = channel.w;
602
43.8k
    }
603
185k
    num_chans++;
604
185k
  }
605
30.6k
  if (num_chans == 0) return true;
606
607
30.2k
  size_t next_channel = 0;
608
30.2k
  auto scope_guard = MakeScopeGuard([&]() {
609
2.21k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
2.11k
      ZeroFillImage(&image.channel[c].plane);
611
2.11k
    }
612
102
  });
613
  // Do not do anything if truncated groups are not allowed.
614
30.2k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
30.2k
  Tree tree_storage;
618
30.2k
  std::vector<uint8_t> context_map_storage;
619
30.2k
  ANSCode code_storage;
620
30.2k
  const Tree *tree = &tree_storage;
621
30.2k
  const ANSCode *code = &code_storage;
622
30.2k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
30.2k
  if (!header.use_global_tree) {
624
5.42k
    uint64_t max_tree_size = 1024;
625
29.6k
    for (size_t i = 0; i < nb_channels; i++) {
626
24.2k
      Channel &channel = image.channel[i];
627
24.2k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
23.3k
                                          channel.h > options->max_chan_size)) {
629
8
        break;
630
8
      }
631
24.2k
      uint64_t pixels = channel.w * channel.h;
632
24.2k
      max_tree_size += pixels;
633
24.2k
    }
634
5.42k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
5.42k
    JXL_RETURN_IF_ERROR(
636
5.42k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
5.39k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
5.39k
                                         (tree_storage.size() + 1) / 2,
639
5.39k
                                         &code_storage, &context_map_storage));
640
24.8k
  } else {
641
24.8k
    if (!global_tree || !global_code || !global_ctx_map ||
642
24.8k
        global_tree->empty()) {
643
10
      return JXL_FAILURE("No global tree available but one was requested");
644
10
    }
645
24.8k
    tree = global_tree;
646
24.8k
    code = global_code;
647
24.8k
    context_map = global_ctx_map;
648
24.8k
  }
649
650
  // Read channels
651
60.4k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
60.4k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
60.4k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
60.4k
  uint32_t fl_run = 0;
655
60.4k
  uint32_t fl_v = 0;
656
219k
  for (; next_channel < nb_channels; next_channel++) {
657
190k
    Channel &channel = image.channel[next_channel];
658
190k
    if (next_channel >= image.nb_meta_channels &&
659
184k
        (channel.w > options->max_chan_size ||
660
183k
         channel.h > options->max_chan_size)) {
661
715
      break;
662
715
    }
663
189k
    if (!channel.w || !channel.h) {
664
5.65k
      continue;  // skip empty channels
665
5.65k
    }
666
183k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
183k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
183k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
183k
    if (!br->AllReadsWithinBounds()) {
672
61
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
61
    }
675
183k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
30.1k
  scope_guard.Disarm();
679
680
30.1k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
30.1k
  return true;
684
30.1k
}
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
36.9k
                                bool allow_truncated_group) {
692
36.9k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
36.9k
  req_sizes.reserve(image.channel.size());
694
113k
  for (const auto &c : image.channel) {
695
113k
    req_sizes.emplace_back(c.w, c.h);
696
113k
  }
697
36.9k
  GroupHeader local_header;
698
36.9k
  if (header == nullptr) header = &local_header;
699
36.9k
  size_t bit_pos = br->TotalBitsConsumed();
700
36.9k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
36.9k
                                  code, ctx_map, allow_truncated_group);
702
36.9k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
36.7k
  if (dec_status.IsFatalError()) return dec_status;
704
36.7k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
36.7k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
36.7k
  JXL_DEBUG_V(4,
707
36.7k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
36.7k
              " image from %" PRIuS " bytes",
709
36.7k
              image.w, image.h, image.channel.size(),
710
36.7k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
36.7k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
36.7k
  (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
36.7k
  if (undo_transforms) {
717
20.2k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
95.1k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
74.8k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
74.8k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
74.8k
    }
722
20.2k
  }
723
36.7k
  return dec_status;
724
36.7k
}
725
726
}  // namespace jxl