Coverage Report

Created: 2026-01-20 07:37

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
362k
                    bool *gradient_only) {
46
362k
  *num_props = 0;
47
362k
  bool has_wp = false;
48
362k
  bool has_non_wp = false;
49
362k
  *gradient_only = true;
50
760k
  const auto mark_property = [&](int32_t p) {
51
760k
    if (p == kWPProp) {
52
145k
      has_wp = true;
53
614k
    } else if (p >= kNumStaticProperties) {
54
310k
      has_non_wp = true;
55
310k
    }
56
760k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
377k
      *gradient_only = false;
58
377k
    }
59
760k
  };
60
362k
  FlatTree output;
61
362k
  std::queue<size_t> nodes;
62
362k
  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
1.73M
  while (!nodes.empty()) {
70
1.37M
    size_t cur = nodes.front();
71
1.37M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.49M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.23M
           global_tree[cur].property != -1) {
75
115k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
63.5k
        cur = global_tree[cur].lchild;
77
63.5k
      } else {
78
52.2k
        cur = global_tree[cur].rchild;
79
52.2k
      }
80
115k
    }
81
1.37M
    FlatDecisionNode flat;
82
1.37M
    if (global_tree[cur].property == -1) {
83
1.12M
      flat.property0 = -1;
84
1.12M
      flat.childID = global_tree[cur].lchild;
85
1.12M
      flat.predictor = global_tree[cur].predictor;
86
1.12M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.12M
      flat.multiplier = global_tree[cur].multiplier;
88
1.12M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.12M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.12M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.12M
      output.push_back(flat);
92
1.12M
      continue;
93
1.12M
    }
94
253k
    flat.childID = output.size() + nodes.size() + 1;
95
96
253k
    flat.property0 = global_tree[cur].property;
97
253k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
253k
    flat.splitval0 = global_tree[cur].splitval;
99
100
760k
    for (size_t i = 0; i < 2; i++) {
101
507k
      size_t cur_child =
102
507k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
539k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
336k
             global_tree[cur_child].property != -1) {
106
32.2k
        if (static_props[global_tree[cur_child].property] >
107
32.2k
            global_tree[cur_child].splitval) {
108
17.3k
          cur_child = global_tree[cur_child].lchild;
109
17.3k
        } else {
110
14.9k
          cur_child = global_tree[cur_child].rchild;
111
14.9k
        }
112
32.2k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
507k
      if (global_tree[cur_child].property == -1) {
116
304k
        flat.properties[i] = 0;
117
304k
        flat.splitvals[i] = 0;
118
304k
        nodes.push(cur_child);
119
304k
        nodes.push(cur_child);
120
304k
      } else {
121
202k
        flat.properties[i] = global_tree[cur_child].property;
122
202k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
202k
        nodes.push(global_tree[cur_child].lchild);
124
202k
        nodes.push(global_tree[cur_child].rchild);
125
202k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
202k
      }
127
507k
    }
128
129
507k
    for (int16_t property : flat.properties) mark_property(property);
130
253k
    mark_property(flat.property0);
131
253k
    output.push_back(flat);
132
253k
  }
133
362k
  if (*num_props > kNumNonrefProperties) {
134
4.12k
    *num_props =
135
4.12k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
4.12k
            kExtraPropsPerChannel +
137
4.12k
        kNumNonrefProperties;
138
358k
  } else {
139
358k
    *num_props = kNumNonrefProperties;
140
358k
  }
141
362k
  *use_wp = has_wp;
142
362k
  *wp_only = has_wp && !has_non_wp;
143
144
362k
  return output;
145
362k
}
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
325k
                                 uint32_t &fl_v) {
157
325k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
325k
  Channel &channel = image->channel[chan];
159
160
325k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
325k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
325k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
325k
  bool tree_has_wp_prop_or_pred = false;
168
325k
  bool is_wp_only = false;
169
325k
  bool is_gradient_only = false;
170
325k
  size_t num_props;
171
325k
  FlatTree tree =
172
325k
      FilterTree(global_tree, static_props, &num_props,
173
325k
                 &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
864k
  for (auto &node : tree) {
178
864k
    if (node.property0 == -1) {
179
729k
      node.childID = context_map[node.childID];
180
729k
    }
181
864k
  }
182
183
325k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
325k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
324M
                             pixel_type_w offset) -> pixel_type {
188
324M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
324M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
324M
    return val * multiplier + offset;
192
324M
  };
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
45.3M
                             pixel_type_w offset) -> pixel_type {
188
45.3M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
45.3M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
45.3M
    return val * multiplier + offset;
192
45.3M
  };
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
279M
                             pixel_type_w offset) -> pixel_type {
188
279M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
279M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
279M
    return val * multiplier + offset;
192
279M
  };
193
194
325k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
283k
    Predictor predictor = tree[0].predictor;
198
283k
    int64_t offset = tree[0].predictor_offset;
199
283k
    int32_t multiplier = tree[0].multiplier;
200
283k
    size_t ctx_id = tree[0].childID;
201
283k
    if (predictor == Predictor::Zero) {
202
168k
      uint32_t value;
203
168k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
168k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
52.9k
        JXL_DEBUG_V(8, "Fastest track.");
208
52.9k
        pixel_type v = make_pixel(value, multiplier, offset);
209
1.36M
        for (size_t y = 0; y < channel.h; y++) {
210
1.31M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
1.31M
          std::fill(r, r + channel.w, v);
212
1.31M
        }
213
115k
      } else {
214
115k
        JXL_DEBUG_V(8, "Fast track.");
215
115k
        if (multiplier == 1 && offset == 0) {
216
1.20M
          for (size_t y = 0; y < channel.h; y++) {
217
1.12M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
60.1M
            for (size_t x = 0; x < channel.w; x++) {
219
59.0M
              uint32_t v =
220
59.0M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
59.0M
              r[x] = UnpackSigned(v);
222
59.0M
            }
223
1.12M
          }
224
86.8k
        } else {
225
597k
          for (size_t y = 0; y < channel.h; y++) {
226
568k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
28.7M
            for (size_t x = 0; x < channel.w; x++) {
228
28.1M
              uint32_t v =
229
28.1M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
28.1M
                                                                         br);
231
28.1M
              r[x] = make_pixel(v, multiplier, offset);
232
28.1M
            }
233
568k
          }
234
28.4k
        }
235
115k
      }
236
168k
      return true;
237
168k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.54k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
90
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
90
      pixel_type_w sv = UnpackSigned(fl_v);
241
1.52k
      for (size_t y = 0; y < channel.h; y++) {
242
1.43k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
1.43k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
1.43k
        const pixel_type *JXL_RESTRICT rtopleft =
245
1.43k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
1.43k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
1.43k
        if (fl_run == 0) {
248
1.43k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
1.43k
                                                     &fl_run);
250
1.43k
          sv = UnpackSigned(fl_v);
251
1.43k
        } else {
252
0
          fl_run--;
253
0
        }
254
1.43k
        r[0] = sv + guess_0;
255
79.0k
        for (size_t x = 1; x < channel.w; x++) {
256
77.6k
          pixel_type left = r[x - 1];
257
77.6k
          pixel_type top = rtop[x];
258
77.6k
          pixel_type topleft = rtopleft[x];
259
77.6k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
77.6k
          if (!fl_run) {
261
77.6k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
77.6k
                                                       &fl_run);
263
77.6k
            sv = UnpackSigned(fl_v);
264
77.6k
          } else {
265
0
            fl_run--;
266
0
          }
267
77.6k
          r[x] = sv + guess;
268
77.6k
        }
269
1.43k
      }
270
90
      return true;
271
115k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
7.25k
               multiplier == 1) {
273
6.30k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
6.30k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
152k
      for (size_t y = 0; y < channel.h; y++) {
276
146k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
4.48M
        for (size_t x = 0; x < channel.w; x++) {
278
4.33M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
4.33M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
4.33M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
4.33M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
4.33M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
4.33M
              ctx_id, br);
284
4.33M
          r[x] = make_pixel(v, 1, guess);
285
4.33M
        }
286
146k
      }
287
6.30k
      return true;
288
6.30k
    }
289
283k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
150k
  if (is_wp_only) {
294
16.9k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
16.9k
  }
296
150k
  if (is_gradient_only) {
297
6.60k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
6.60k
  }
299
300
150k
  if (is_gradient_only) {
301
3.88k
    JXL_DEBUG_V(8, "Gradient fast track.");
302
3.88k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
181k
    for (size_t y = 0; y < channel.h; y++) {
304
178k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
3.49M
      for (size_t x = 0; x < channel.w; x++) {
306
3.31M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
3.31M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
3.31M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
3.31M
        int32_t guess = ClampedGradient(top, left, topleft);
310
3.31M
        uint32_t pos =
311
3.31M
            kPropRangeFast +
312
3.31M
            std::min<pixel_type_w>(
313
3.31M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
3.31M
                kPropRangeFast - 1);
315
3.31M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
3.31M
        uint64_t v =
317
3.31M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
3.31M
        r[x] = make_pixel(v, 1, guess);
319
3.31M
      }
320
178k
    }
321
146k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
8.11k
    JXL_DEBUG_V(8, "WP fast track.");
323
8.11k
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
8.11k
    Properties properties(1);
325
255k
    for (size_t y = 0; y < channel.h; y++) {
326
247k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
247k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
247k
      const pixel_type *JXL_RESTRICT rtoptop =
329
247k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
247k
      const pixel_type *JXL_RESTRICT rtopleft =
331
247k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
247k
      const pixel_type *JXL_RESTRICT rtopright =
333
247k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
247k
      size_t x = 0;
335
247k
      {
336
247k
        size_t offset = 0;
337
247k
        pixel_type_w left = y ? rtop[x] : 0;
338
247k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
247k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
247k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
247k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
247k
            offset);
343
247k
        uint32_t pos =
344
247k
            kPropRangeFast +
345
247k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
247k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
247k
        uint64_t v =
348
247k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
247k
        r[x] = make_pixel(v, 1, guess);
350
247k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
247k
      }
352
13.1M
      for (x = 1; x + 1 < channel.w; x++) {
353
12.8M
        size_t offset = 0;
354
12.8M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
12.8M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
12.8M
            rtoptop[x], &properties, offset);
357
12.8M
        uint32_t pos =
358
12.8M
            kPropRangeFast +
359
12.8M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
12.8M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
12.8M
        uint64_t v =
362
12.8M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
12.8M
        r[x] = make_pixel(v, 1, guess);
364
12.8M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
12.8M
      }
366
247k
      {
367
247k
        size_t offset = 0;
368
247k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
247k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
247k
            rtoptop[x], &properties, offset);
371
247k
        uint32_t pos =
372
247k
            kPropRangeFast +
373
247k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
247k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
247k
        uint64_t v =
376
247k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
247k
        r[x] = make_pixel(v, 1, guess);
378
247k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
247k
      }
380
247k
    }
381
138k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
115k
    JXL_DEBUG_V(8, "Slow track.");
385
115k
    MATreeLookup tree_lookup(tree);
386
115k
    Properties properties = Properties(num_props);
387
115k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
115k
    JXL_ASSIGN_OR_RETURN(
389
115k
        Channel references,
390
115k
        Channel::Create(memory_manager,
391
115k
                        properties.size() - kNumNonrefProperties, channel.w));
392
3.48M
    for (size_t y = 0; y < channel.h; y++) {
393
3.37M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
3.37M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
3.37M
      InitPropsRow(&properties, static_props, y);
396
3.37M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
8.37M
        for (size_t x = 0; x < 2; x++) {
398
5.58M
          PredictionResult res =
399
5.58M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
5.58M
                              tree_lookup, references);
401
5.58M
          uint64_t v =
402
5.58M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
5.58M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
5.58M
        }
405
192M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
189M
          PredictionResult res =
407
189M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
189M
                                 tree_lookup, references);
409
189M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
189M
              res.context, br);
411
189M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
189M
        }
413
8.37M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
5.58M
          PredictionResult res =
415
5.58M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
5.58M
                              tree_lookup, references);
417
5.58M
          uint64_t v =
418
5.58M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
5.58M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
5.58M
        }
421
2.79M
      } else {
422
17.4M
        for (size_t x = 0; x < channel.w; x++) {
423
16.8M
          PredictionResult res =
424
16.8M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
16.8M
                              tree_lookup, references);
426
16.8M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
16.8M
              res.context, br);
428
16.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
16.8M
        }
430
581k
      }
431
3.37M
    }
432
115k
  } else {
433
23.5k
    JXL_DEBUG_V(8, "Slowest track.");
434
23.5k
    MATreeLookup tree_lookup(tree);
435
23.5k
    Properties properties = Properties(num_props);
436
23.5k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
23.5k
    JXL_ASSIGN_OR_RETURN(
438
23.5k
        Channel references,
439
23.5k
        Channel::Create(memory_manager,
440
23.5k
                        properties.size() - kNumNonrefProperties, channel.w));
441
23.5k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
1.35M
    for (size_t y = 0; y < channel.h; y++) {
443
1.33M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
1.33M
      InitPropsRow(&properties, static_props, y);
445
1.33M
      PrecomputeReferences(channel, y, *image, chan, &references);
446
1.33M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
1.29M
        for (size_t x = 0; x < 2; x++) {
448
860k
          PredictionResult res =
449
860k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
860k
                            tree_lookup, references, &wp_state);
451
860k
          uint64_t v =
452
860k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
860k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
860k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
860k
        }
456
47.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
46.7M
          PredictionResult res =
458
46.7M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
46.7M
                               tree_lookup, references, &wp_state);
460
46.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
46.7M
              res.context, br);
462
46.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
46.7M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
46.7M
        }
465
1.29M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
860k
          PredictionResult res =
467
860k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
860k
                            tree_lookup, references, &wp_state);
469
860k
          uint64_t v =
470
860k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
860k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
860k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
860k
        }
474
904k
      } else {
475
10.5M
        for (size_t x = 0; x < channel.w; x++) {
476
9.63M
          PredictionResult res =
477
9.63M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
9.63M
                            tree_lookup, references, &wp_state);
479
9.63M
          uint64_t v =
480
9.63M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
9.63M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
9.63M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
9.63M
        }
484
904k
      }
485
1.33M
    }
486
23.5k
  }
487
150k
  return true;
488
150k
}
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
70.5k
                                 uint32_t &fl_v) {
157
70.5k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
70.5k
  Channel &channel = image->channel[chan];
159
160
70.5k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
70.5k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
70.5k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
70.5k
  bool tree_has_wp_prop_or_pred = false;
168
70.5k
  bool is_wp_only = false;
169
70.5k
  bool is_gradient_only = false;
170
70.5k
  size_t num_props;
171
70.5k
  FlatTree tree =
172
70.5k
      FilterTree(global_tree, static_props, &num_props,
173
70.5k
                 &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
92.5k
  for (auto &node : tree) {
178
92.5k
    if (node.property0 == -1) {
179
87.0k
      node.childID = context_map[node.childID];
180
87.0k
    }
181
92.5k
  }
182
183
70.5k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
70.5k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
70.5k
                             pixel_type_w offset) -> pixel_type {
188
70.5k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
70.5k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
70.5k
    return val * multiplier + offset;
192
70.5k
  };
193
194
70.5k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
65.9k
    Predictor predictor = tree[0].predictor;
198
65.9k
    int64_t offset = tree[0].predictor_offset;
199
65.9k
    int32_t multiplier = tree[0].multiplier;
200
65.9k
    size_t ctx_id = tree[0].childID;
201
65.9k
    if (predictor == Predictor::Zero) {
202
50.1k
      uint32_t value;
203
50.1k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
50.1k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
25.3k
        JXL_DEBUG_V(8, "Fastest track.");
208
25.3k
        pixel_type v = make_pixel(value, multiplier, offset);
209
637k
        for (size_t y = 0; y < channel.h; y++) {
210
611k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
611k
          std::fill(r, r + channel.w, v);
212
611k
        }
213
25.3k
      } else {
214
24.7k
        JXL_DEBUG_V(8, "Fast track.");
215
24.7k
        if (multiplier == 1 && offset == 0) {
216
103k
          for (size_t y = 0; y < channel.h; y++) {
217
89.2k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
6.43M
            for (size_t x = 0; x < channel.w; x++) {
219
6.34M
              uint32_t v =
220
6.34M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
6.34M
              r[x] = UnpackSigned(v);
222
6.34M
            }
223
89.2k
          }
224
14.3k
        } else {
225
232k
          for (size_t y = 0; y < channel.h; y++) {
226
221k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
10.9M
            for (size_t x = 0; x < channel.w; x++) {
228
10.6M
              uint32_t v =
229
10.6M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
10.6M
                                                                         br);
231
10.6M
              r[x] = make_pixel(v, multiplier, offset);
232
10.6M
            }
233
221k
          }
234
10.4k
        }
235
24.7k
      }
236
50.1k
      return true;
237
50.1k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.54k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
90
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
90
      pixel_type_w sv = UnpackSigned(fl_v);
241
1.52k
      for (size_t y = 0; y < channel.h; y++) {
242
1.43k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
1.43k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
1.43k
        const pixel_type *JXL_RESTRICT rtopleft =
245
1.43k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
1.43k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
1.43k
        if (fl_run == 0) {
248
1.43k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
1.43k
                                                     &fl_run);
250
1.43k
          sv = UnpackSigned(fl_v);
251
1.43k
        } else {
252
0
          fl_run--;
253
0
        }
254
1.43k
        r[0] = sv + guess_0;
255
79.0k
        for (size_t x = 1; x < channel.w; x++) {
256
77.6k
          pixel_type left = r[x - 1];
257
77.6k
          pixel_type top = rtop[x];
258
77.6k
          pixel_type topleft = rtopleft[x];
259
77.6k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
77.6k
          if (!fl_run) {
261
77.6k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
77.6k
                                                       &fl_run);
263
77.6k
            sv = UnpackSigned(fl_v);
264
77.6k
          } else {
265
0
            fl_run--;
266
0
          }
267
77.6k
          r[x] = sv + guess;
268
77.6k
        }
269
1.43k
      }
270
90
      return true;
271
15.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.45k
               multiplier == 1) {
273
1.05k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.05k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
20.0k
      for (size_t y = 0; y < channel.h; y++) {
276
19.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
1.70M
        for (size_t x = 0; x < channel.w; x++) {
278
1.69M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
1.69M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
1.69M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
1.69M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
1.69M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
1.69M
              ctx_id, br);
284
1.69M
          r[x] = make_pixel(v, 1, guess);
285
1.69M
        }
286
19.0k
      }
287
1.05k
      return true;
288
1.05k
    }
289
65.9k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
19.3k
  if (is_wp_only) {
294
1.50k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
1.50k
  }
296
19.3k
  if (is_gradient_only) {
297
1.40k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.40k
  }
299
300
19.3k
  if (is_gradient_only) {
301
9
    JXL_DEBUG_V(8, "Gradient fast track.");
302
9
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
840
    for (size_t y = 0; y < channel.h; y++) {
304
831
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
162k
      for (size_t x = 0; x < channel.w; x++) {
306
161k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
161k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
161k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
161k
        int32_t guess = ClampedGradient(top, left, topleft);
310
161k
        uint32_t pos =
311
161k
            kPropRangeFast +
312
161k
            std::min<pixel_type_w>(
313
161k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
161k
                kPropRangeFast - 1);
315
161k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
161k
        uint64_t v =
317
161k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
161k
        r[x] = make_pixel(v, 1, guess);
319
161k
      }
320
831
    }
321
19.3k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
0
    JXL_DEBUG_V(8, "WP fast track.");
323
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
0
    Properties properties(1);
325
0
    for (size_t y = 0; y < channel.h; y++) {
326
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
0
      const pixel_type *JXL_RESTRICT rtoptop =
329
0
          (y > 1 ? channel.Row(y - 2) : rtop);
330
0
      const pixel_type *JXL_RESTRICT rtopleft =
331
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
0
      const pixel_type *JXL_RESTRICT rtopright =
333
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
0
      size_t x = 0;
335
0
      {
336
0
        size_t offset = 0;
337
0
        pixel_type_w left = y ? rtop[x] : 0;
338
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
0
            offset);
343
0
        uint32_t pos =
344
0
            kPropRangeFast +
345
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
0
        uint64_t v =
348
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
0
        r[x] = make_pixel(v, 1, guess);
350
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
0
      }
352
0
      for (x = 1; x + 1 < channel.w; x++) {
353
0
        size_t offset = 0;
354
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
0
            rtoptop[x], &properties, offset);
357
0
        uint32_t pos =
358
0
            kPropRangeFast +
359
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
0
        uint64_t v =
362
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
0
        r[x] = make_pixel(v, 1, guess);
364
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
0
      }
366
0
      {
367
0
        size_t offset = 0;
368
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
0
            rtoptop[x], &properties, offset);
371
0
        uint32_t pos =
372
0
            kPropRangeFast +
373
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
0
        uint64_t v =
376
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
0
        r[x] = make_pixel(v, 1, guess);
378
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
0
      }
380
0
    }
381
19.3k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
16.6k
    JXL_DEBUG_V(8, "Slow track.");
385
16.6k
    MATreeLookup tree_lookup(tree);
386
16.6k
    Properties properties = Properties(num_props);
387
16.6k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
16.6k
    JXL_ASSIGN_OR_RETURN(
389
16.6k
        Channel references,
390
16.6k
        Channel::Create(memory_manager,
391
16.6k
                        properties.size() - kNumNonrefProperties, channel.w));
392
381k
    for (size_t y = 0; y < channel.h; y++) {
393
365k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
365k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
365k
      InitPropsRow(&properties, static_props, y);
396
365k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
900k
        for (size_t x = 0; x < 2; x++) {
398
600k
          PredictionResult res =
399
600k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
600k
                              tree_lookup, references);
401
600k
          uint64_t v =
402
600k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
600k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
600k
        }
405
23.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
22.9M
          PredictionResult res =
407
22.9M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
22.9M
                                 tree_lookup, references);
409
22.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
22.9M
              res.context, br);
411
22.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
22.9M
        }
413
900k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
600k
          PredictionResult res =
415
600k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
600k
                              tree_lookup, references);
417
600k
          uint64_t v =
418
600k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
600k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
600k
        }
421
300k
      } else {
422
4.94M
        for (size_t x = 0; x < channel.w; x++) {
423
4.88M
          PredictionResult res =
424
4.88M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
4.88M
                              tree_lookup, references);
426
4.88M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
4.88M
              res.context, br);
428
4.88M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
4.88M
        }
430
64.9k
      }
431
365k
    }
432
16.6k
  } else {
433
2.68k
    JXL_DEBUG_V(8, "Slowest track.");
434
2.68k
    MATreeLookup tree_lookup(tree);
435
2.68k
    Properties properties = Properties(num_props);
436
2.68k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
2.68k
    JXL_ASSIGN_OR_RETURN(
438
2.68k
        Channel references,
439
2.68k
        Channel::Create(memory_manager,
440
2.68k
                        properties.size() - kNumNonrefProperties, channel.w));
441
2.68k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
65.4k
    for (size_t y = 0; y < channel.h; y++) {
443
62.7k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
62.7k
      InitPropsRow(&properties, static_props, y);
445
62.7k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
62.7k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
0
        for (size_t x = 0; x < 2; x++) {
448
0
          PredictionResult res =
449
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
0
                            tree_lookup, references, &wp_state);
451
0
          uint64_t v =
452
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
0
        }
456
0
        for (size_t x = 2; x < channel.w - 2; x++) {
457
0
          PredictionResult res =
458
0
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
0
                               tree_lookup, references, &wp_state);
460
0
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
0
              res.context, br);
462
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
0
        }
465
0
        for (size_t x = channel.w - 2; x < channel.w; 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
62.7k
      } else {
475
3.77M
        for (size_t x = 0; x < channel.w; x++) {
476
3.71M
          PredictionResult res =
477
3.71M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
3.71M
                            tree_lookup, references, &wp_state);
479
3.71M
          uint64_t v =
480
3.71M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
3.71M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
3.71M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
3.71M
        }
484
62.7k
      }
485
62.7k
    }
486
2.68k
  }
487
19.3k
  return true;
488
19.3k
}
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
254k
                                 uint32_t &fl_v) {
157
254k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
254k
  Channel &channel = image->channel[chan];
159
160
254k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
254k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
254k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
254k
  bool tree_has_wp_prop_or_pred = false;
168
254k
  bool is_wp_only = false;
169
254k
  bool is_gradient_only = false;
170
254k
  size_t num_props;
171
254k
  FlatTree tree =
172
254k
      FilterTree(global_tree, static_props, &num_props,
173
254k
                 &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
771k
  for (auto &node : tree) {
178
771k
    if (node.property0 == -1) {
179
642k
      node.childID = context_map[node.childID];
180
642k
    }
181
771k
  }
182
183
254k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
254k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
254k
                             pixel_type_w offset) -> pixel_type {
188
254k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
254k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
254k
    return val * multiplier + offset;
192
254k
  };
193
194
254k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
218k
    Predictor predictor = tree[0].predictor;
198
218k
    int64_t offset = tree[0].predictor_offset;
199
218k
    int32_t multiplier = tree[0].multiplier;
200
218k
    size_t ctx_id = tree[0].childID;
201
218k
    if (predictor == Predictor::Zero) {
202
118k
      uint32_t value;
203
118k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
118k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
27.6k
        JXL_DEBUG_V(8, "Fastest track.");
208
27.6k
        pixel_type v = make_pixel(value, multiplier, offset);
209
727k
        for (size_t y = 0; y < channel.h; y++) {
210
699k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
699k
          std::fill(r, r + channel.w, v);
212
699k
        }
213
90.5k
      } else {
214
90.5k
        JXL_DEBUG_V(8, "Fast track.");
215
90.5k
        if (multiplier == 1 && offset == 0) {
216
1.10M
          for (size_t y = 0; y < channel.h; y++) {
217
1.03M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
53.6M
            for (size_t x = 0; x < channel.w; x++) {
219
52.6M
              uint32_t v =
220
52.6M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
52.6M
              r[x] = UnpackSigned(v);
222
52.6M
            }
223
1.03M
          }
224
72.5k
        } else {
225
364k
          for (size_t y = 0; y < channel.h; y++) {
226
346k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
17.8M
            for (size_t x = 0; x < channel.w; x++) {
228
17.4M
              uint32_t v =
229
17.4M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
17.4M
                                                                         br);
231
17.4M
              r[x] = make_pixel(v, multiplier, offset);
232
17.4M
            }
233
346k
          }
234
17.9k
        }
235
90.5k
      }
236
118k
      return true;
237
118k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
0
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
0
      pixel_type_w sv = UnpackSigned(fl_v);
241
0
      for (size_t y = 0; y < channel.h; y++) {
242
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
0
        const pixel_type *JXL_RESTRICT rtopleft =
245
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
0
        if (fl_run == 0) {
248
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
0
                                                     &fl_run);
250
0
          sv = UnpackSigned(fl_v);
251
0
        } else {
252
0
          fl_run--;
253
0
        }
254
0
        r[0] = sv + guess_0;
255
0
        for (size_t x = 1; x < channel.w; x++) {
256
0
          pixel_type left = r[x - 1];
257
0
          pixel_type top = rtop[x];
258
0
          pixel_type topleft = rtopleft[x];
259
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
0
          if (!fl_run) {
261
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
0
                                                       &fl_run);
263
0
            sv = UnpackSigned(fl_v);
264
0
          } else {
265
0
            fl_run--;
266
0
          }
267
0
          r[x] = sv + guess;
268
0
        }
269
0
      }
270
0
      return true;
271
99.8k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
5.80k
               multiplier == 1) {
273
5.25k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
5.25k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
132k
      for (size_t y = 0; y < channel.h; y++) {
276
127k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.77M
        for (size_t x = 0; x < channel.w; x++) {
278
2.64M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.64M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.64M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.64M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.64M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.64M
              ctx_id, br);
284
2.64M
          r[x] = make_pixel(v, 1, guess);
285
2.64M
        }
286
127k
      }
287
5.25k
      return true;
288
5.25k
    }
289
218k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
131k
  if (is_wp_only) {
294
15.4k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
15.4k
  }
296
131k
  if (is_gradient_only) {
297
5.19k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
5.19k
  }
299
300
131k
  if (is_gradient_only) {
301
3.87k
    JXL_DEBUG_V(8, "Gradient fast track.");
302
3.87k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
181k
    for (size_t y = 0; y < channel.h; y++) {
304
177k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
3.33M
      for (size_t x = 0; x < channel.w; x++) {
306
3.15M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
3.15M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
3.15M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
3.15M
        int32_t guess = ClampedGradient(top, left, topleft);
310
3.15M
        uint32_t pos =
311
3.15M
            kPropRangeFast +
312
3.15M
            std::min<pixel_type_w>(
313
3.15M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
3.15M
                kPropRangeFast - 1);
315
3.15M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
3.15M
        uint64_t v =
317
3.15M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
3.15M
        r[x] = make_pixel(v, 1, guess);
319
3.15M
      }
320
177k
    }
321
127k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
8.11k
    JXL_DEBUG_V(8, "WP fast track.");
323
8.11k
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
8.11k
    Properties properties(1);
325
255k
    for (size_t y = 0; y < channel.h; y++) {
326
247k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
247k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
247k
      const pixel_type *JXL_RESTRICT rtoptop =
329
247k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
247k
      const pixel_type *JXL_RESTRICT rtopleft =
331
247k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
247k
      const pixel_type *JXL_RESTRICT rtopright =
333
247k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
247k
      size_t x = 0;
335
247k
      {
336
247k
        size_t offset = 0;
337
247k
        pixel_type_w left = y ? rtop[x] : 0;
338
247k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
247k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
247k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
247k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
247k
            offset);
343
247k
        uint32_t pos =
344
247k
            kPropRangeFast +
345
247k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
247k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
247k
        uint64_t v =
348
247k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
247k
        r[x] = make_pixel(v, 1, guess);
350
247k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
247k
      }
352
13.1M
      for (x = 1; x + 1 < channel.w; x++) {
353
12.8M
        size_t offset = 0;
354
12.8M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
12.8M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
12.8M
            rtoptop[x], &properties, offset);
357
12.8M
        uint32_t pos =
358
12.8M
            kPropRangeFast +
359
12.8M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
12.8M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
12.8M
        uint64_t v =
362
12.8M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
12.8M
        r[x] = make_pixel(v, 1, guess);
364
12.8M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
12.8M
      }
366
247k
      {
367
247k
        size_t offset = 0;
368
247k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
247k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
247k
            rtoptop[x], &properties, offset);
371
247k
        uint32_t pos =
372
247k
            kPropRangeFast +
373
247k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
247k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
247k
        uint64_t v =
376
247k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
247k
        r[x] = make_pixel(v, 1, guess);
378
247k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
247k
      }
380
247k
    }
381
119k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
98.5k
    JXL_DEBUG_V(8, "Slow track.");
385
98.5k
    MATreeLookup tree_lookup(tree);
386
98.5k
    Properties properties = Properties(num_props);
387
98.5k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
98.5k
    JXL_ASSIGN_OR_RETURN(
389
98.5k
        Channel references,
390
98.5k
        Channel::Create(memory_manager,
391
98.5k
                        properties.size() - kNumNonrefProperties, channel.w));
392
3.10M
    for (size_t y = 0; y < channel.h; y++) {
393
3.00M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
3.00M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
3.00M
      InitPropsRow(&properties, static_props, y);
396
3.00M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
7.47M
        for (size_t x = 0; x < 2; x++) {
398
4.98M
          PredictionResult res =
399
4.98M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
4.98M
                              tree_lookup, references);
401
4.98M
          uint64_t v =
402
4.98M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
4.98M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
4.98M
        }
405
168M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
166M
          PredictionResult res =
407
166M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
166M
                                 tree_lookup, references);
409
166M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
166M
              res.context, br);
411
166M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
166M
        }
413
7.47M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
4.98M
          PredictionResult res =
415
4.98M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
4.98M
                              tree_lookup, references);
417
4.98M
          uint64_t v =
418
4.98M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
4.98M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
4.98M
        }
421
2.49M
      } else {
422
12.4M
        for (size_t x = 0; x < channel.w; x++) {
423
11.9M
          PredictionResult res =
424
11.9M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
11.9M
                              tree_lookup, references);
426
11.9M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
11.9M
              res.context, br);
428
11.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
11.9M
        }
430
517k
      }
431
3.00M
    }
432
98.5k
  } else {
433
20.8k
    JXL_DEBUG_V(8, "Slowest track.");
434
20.8k
    MATreeLookup tree_lookup(tree);
435
20.8k
    Properties properties = Properties(num_props);
436
20.8k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
20.8k
    JXL_ASSIGN_OR_RETURN(
438
20.8k
        Channel references,
439
20.8k
        Channel::Create(memory_manager,
440
20.8k
                        properties.size() - kNumNonrefProperties, channel.w));
441
20.8k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
1.29M
    for (size_t y = 0; y < channel.h; y++) {
443
1.27M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
1.27M
      InitPropsRow(&properties, static_props, y);
445
1.27M
      PrecomputeReferences(channel, y, *image, chan, &references);
446
1.27M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
1.29M
        for (size_t x = 0; x < 2; x++) {
448
860k
          PredictionResult res =
449
860k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
860k
                            tree_lookup, references, &wp_state);
451
860k
          uint64_t v =
452
860k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
860k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
860k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
860k
        }
456
47.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
46.7M
          PredictionResult res =
458
46.7M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
46.7M
                               tree_lookup, references, &wp_state);
460
46.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
46.7M
              res.context, br);
462
46.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
46.7M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
46.7M
        }
465
1.29M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
860k
          PredictionResult res =
467
860k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
860k
                            tree_lookup, references, &wp_state);
469
860k
          uint64_t v =
470
860k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
860k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
860k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
860k
        }
474
841k
      } else {
475
6.75M
        for (size_t x = 0; x < channel.w; x++) {
476
5.91M
          PredictionResult res =
477
5.91M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
5.91M
                            tree_lookup, references, &wp_state);
479
5.91M
          uint64_t v =
480
5.91M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
5.91M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
5.91M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
5.91M
        }
484
841k
      }
485
1.27M
    }
486
20.8k
  }
487
131k
  return true;
488
131k
}
489
}  // namespace detail
490
491
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
492
                                 const std::vector<uint8_t> &context_map,
493
                                 const Tree &global_tree,
494
                                 const weighted::Header &wp_header,
495
                                 pixel_type chan, size_t group_id,
496
                                 TreeLut<uint8_t, false, false> &tree_lut,
497
                                 Image *image, uint32_t &fl_run,
498
325k
                                 uint32_t &fl_v) {
499
325k
  if (reader->UsesLZ77()) {
500
70.5k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
70.5k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
70.5k
        tree_lut, image, fl_run, fl_v);
503
254k
  } else {
504
254k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
254k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
254k
        tree_lut, image, fl_run, fl_v);
507
254k
  }
508
325k
}
509
510
498k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
79.3k
                                 const ModularOptions &options) {
514
79.3k
  size_t nb_channels = image.channel.size();
515
158k
  for (bool is_dc : {true, false}) {
516
158k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
158k
    size_t c = image.nb_meta_channels;
518
1.01M
    for (; c < nb_channels; c++) {
519
860k
      const Channel &ch = image.channel[c];
520
860k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
860k
    }
522
172k
    for (; c < nb_channels; c++) {
523
13.5k
      const Channel &ch = image.channel[c];
524
13.5k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
12.9k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
12.9k
      if (is_dc_channel != is_dc) continue;
527
6.48k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
6.48k
      if (tile_dim == 0) {
529
7
        return JXL_FAILURE("Inconsistent transforms");
530
7
      }
531
6.48k
    }
532
158k
  }
533
79.3k
  return true;
534
79.3k
}
535
536
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
537
                     size_t group_id, ModularOptions *options,
538
                     const Tree *global_tree, const ANSCode *global_code,
539
                     const std::vector<uint8_t> *global_ctx_map,
540
134k
                     const bool allow_truncated_group) {
541
134k
  if (image.channel.empty()) return true;
542
94.6k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
94.6k
  Status status = Bundle::Read(br, &header);
546
94.6k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
78.1k
  if (status.IsFatalError()) return status;
548
78.1k
  if (!br->AllReadsWithinBounds()) {
549
    // Don't do/undo transforms if header is incomplete.
550
0
    header.transforms.clear();
551
0
    image.transform = header.transforms;
552
0
    for (auto &ch : image.channel) {
553
0
      ZeroFillImage(&ch.plane);
554
0
    }
555
0
    return JXL_NOT_ENOUGH_BYTES("Read overrun before ModularDecode");
556
0
  }
557
558
78.1k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
78.1k
              header.transforms.size());
560
78.1k
  image.transform = header.transforms;
561
78.1k
  for (Transform &transform : image.transform) {
562
24.5k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
24.5k
  }
564
77.0k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
77.0k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
77.0k
  size_t nb_channels = image.channel.size();
570
571
77.0k
  size_t num_chans = 0;
572
77.0k
  size_t distance_multiplier = 0;
573
504k
  for (size_t i = 0; i < nb_channels; i++) {
574
428k
    Channel &channel = image.channel[i];
575
428k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
422k
                                        channel.h > options->max_chan_size)) {
577
1.11k
      break;
578
1.11k
    }
579
426k
    if (!channel.w || !channel.h) {
580
26.7k
      continue;  // skip empty channels
581
26.7k
    }
582
400k
    if (channel.w > distance_multiplier) {
583
101k
      distance_multiplier = channel.w;
584
101k
    }
585
400k
    num_chans++;
586
400k
  }
587
77.0k
  if (num_chans == 0) return true;
588
589
76.2k
  size_t next_channel = 0;
590
76.2k
  auto scope_guard = MakeScopeGuard([&]() {
591
104k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
83.0k
      ZeroFillImage(&image.channel[c].plane);
593
83.0k
    }
594
21.0k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
76.2k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
76.2k
  Tree tree_storage;
600
76.2k
  std::vector<uint8_t> context_map_storage;
601
76.2k
  ANSCode code_storage;
602
76.2k
  const Tree *tree = &tree_storage;
603
76.2k
  const ANSCode *code = &code_storage;
604
76.2k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
76.2k
  if (!header.use_global_tree) {
606
55.7k
    uint64_t max_tree_size = 1024;
607
352k
    for (size_t i = 0; i < nb_channels; i++) {
608
296k
      Channel &channel = image.channel[i];
609
296k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
293k
                                          channel.h > options->max_chan_size)) {
611
127
        break;
612
127
      }
613
296k
      uint64_t pixels = channel.w * channel.h;
614
296k
      max_tree_size += pixels;
615
296k
    }
616
55.7k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
55.7k
    JXL_RETURN_IF_ERROR(
618
55.7k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
42.3k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
42.3k
                                         (tree_storage.size() + 1) / 2,
621
42.3k
                                         &code_storage, &context_map_storage));
622
42.3k
  } else {
623
20.5k
    if (!global_tree || !global_code || !global_ctx_map ||
624
20.5k
        global_tree->empty()) {
625
1.37k
      return JXL_FAILURE("No global tree available but one was requested");
626
1.37k
    }
627
19.1k
    tree = global_tree;
628
19.1k
    code = global_code;
629
19.1k
    context_map = global_ctx_map;
630
19.1k
  }
631
632
  // Read channels
633
122k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
122k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
122k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
122k
  uint32_t fl_run = 0;
637
122k
  uint32_t fl_v = 0;
638
405k
  for (; next_channel < nb_channels; next_channel++) {
639
350k
    Channel &channel = image.channel[next_channel];
640
350k
    if (next_channel >= image.nb_meta_channels &&
641
346k
        (channel.w > options->max_chan_size ||
642
346k
         channel.h > options->max_chan_size)) {
643
223
      break;
644
223
    }
645
350k
    if (!channel.w || !channel.h) {
646
25.1k
      continue;  // skip empty channels
647
25.1k
    }
648
325k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
325k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
325k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
325k
    if (!br->AllReadsWithinBounds()) {
654
5.93k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
5.93k
    }
657
325k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
55.1k
  scope_guard.Disarm();
661
662
55.1k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
55.1k
  return true;
666
55.1k
}
667
668
Status ModularGenericDecompress(BitReader *br, Image &image,
669
                                GroupHeader *header, size_t group_id,
670
                                ModularOptions *options, bool undo_transforms,
671
                                const Tree *tree, const ANSCode *code,
672
                                const std::vector<uint8_t> *ctx_map,
673
134k
                                bool allow_truncated_group) {
674
134k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
134k
  req_sizes.reserve(image.channel.size());
676
305k
  for (const auto &c : image.channel) {
677
305k
    req_sizes.emplace_back(c.w, c.h);
678
305k
  }
679
134k
  GroupHeader local_header;
680
134k
  if (header == nullptr) header = &local_header;
681
134k
  size_t bit_pos = br->TotalBitsConsumed();
682
134k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
134k
                                  code, ctx_map, allow_truncated_group);
684
134k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
95.8k
  if (dec_status.IsFatalError()) return dec_status;
686
95.8k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
95.8k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
95.8k
  JXL_DEBUG_V(4,
689
95.8k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
95.8k
              " image from %" PRIuS " bytes",
691
95.8k
              image.w, image.h, image.channel.size(),
692
95.8k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
95.8k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
95.8k
  (void)bit_pos;
695
  // Check that after applying all transforms we are back to the requested
696
  // image sizes, otherwise there's a programming error with the
697
  // transformations.
698
95.8k
  if (undo_transforms) {
699
23.2k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
98.5k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
75.2k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
75.2k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
75.2k
    }
704
23.2k
  }
705
95.8k
  return dec_status;
706
95.8k
}
707
708
}  // namespace jxl