Coverage Report

Created: 2025-10-12 07:48

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
360k
                    bool *gradient_only) {
46
360k
  *num_props = 0;
47
360k
  bool has_wp = false;
48
360k
  bool has_non_wp = false;
49
360k
  *gradient_only = true;
50
928k
  const auto mark_property = [&](int32_t p) {
51
928k
    if (p == kWPProp) {
52
92.8k
      has_wp = true;
53
835k
    } else if (p >= kNumStaticProperties) {
54
505k
      has_non_wp = true;
55
505k
    }
56
928k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
550k
      *gradient_only = false;
58
550k
    }
59
928k
  };
60
360k
  FlatTree output;
61
360k
  std::queue<size_t> nodes;
62
360k
  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.95M
  while (!nodes.empty()) {
70
1.59M
    size_t cur = nodes.front();
71
1.59M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.64M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.33M
           global_tree[cur].property != -1) {
75
48.9k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
27.9k
        cur = global_tree[cur].lchild;
77
27.9k
      } else {
78
20.9k
        cur = global_tree[cur].rchild;
79
20.9k
      }
80
48.9k
    }
81
1.59M
    FlatDecisionNode flat;
82
1.59M
    if (global_tree[cur].property == -1) {
83
1.28M
      flat.property0 = -1;
84
1.28M
      flat.childID = global_tree[cur].lchild;
85
1.28M
      flat.predictor = global_tree[cur].predictor;
86
1.28M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.28M
      flat.multiplier = global_tree[cur].multiplier;
88
1.28M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.28M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.28M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.28M
      output.push_back(flat);
92
1.28M
      continue;
93
1.28M
    }
94
309k
    flat.childID = output.size() + nodes.size() + 1;
95
96
309k
    flat.property0 = global_tree[cur].property;
97
309k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
309k
    flat.splitval0 = global_tree[cur].splitval;
99
100
928k
    for (size_t i = 0; i < 2; i++) {
101
618k
      size_t cur_child =
102
618k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
631k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
341k
             global_tree[cur_child].property != -1) {
106
12.2k
        if (static_props[global_tree[cur_child].property] >
107
12.2k
            global_tree[cur_child].splitval) {
108
8.43k
          cur_child = global_tree[cur_child].lchild;
109
8.43k
        } else {
110
3.80k
          cur_child = global_tree[cur_child].rchild;
111
3.80k
        }
112
12.2k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
618k
      if (global_tree[cur_child].property == -1) {
116
329k
        flat.properties[i] = 0;
117
329k
        flat.splitvals[i] = 0;
118
329k
        nodes.push(cur_child);
119
329k
        nodes.push(cur_child);
120
329k
      } else {
121
289k
        flat.properties[i] = global_tree[cur_child].property;
122
289k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
289k
        nodes.push(global_tree[cur_child].lchild);
124
289k
        nodes.push(global_tree[cur_child].rchild);
125
289k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
289k
      }
127
618k
    }
128
129
618k
    for (int16_t property : flat.properties) mark_property(property);
130
309k
    mark_property(flat.property0);
131
309k
    output.push_back(flat);
132
309k
  }
133
360k
  if (*num_props > kNumNonrefProperties) {
134
1.52k
    *num_props =
135
1.52k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.52k
            kExtraPropsPerChannel +
137
1.52k
        kNumNonrefProperties;
138
359k
  } else {
139
359k
    *num_props = kNumNonrefProperties;
140
359k
  }
141
360k
  *use_wp = has_wp;
142
360k
  *wp_only = has_wp && !has_non_wp;
143
144
360k
  return output;
145
360k
}
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
337k
                                 uint32_t &fl_v) {
157
337k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
337k
  Channel &channel = image->channel[chan];
159
160
337k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
337k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
337k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
337k
  bool tree_has_wp_prop_or_pred = false;
168
337k
  bool is_wp_only = false;
169
337k
  bool is_gradient_only = false;
170
337k
  size_t num_props;
171
337k
  FlatTree tree =
172
337k
      FilterTree(global_tree, static_props, &num_props,
173
337k
                 &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
488k
  for (auto &node : tree) {
178
488k
    if (node.property0 == -1) {
179
450k
      node.childID = context_map[node.childID];
180
450k
    }
181
488k
  }
182
183
337k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
337k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
219M
                             pixel_type_w offset) -> pixel_type {
188
219M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
219M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
219M
    return val * multiplier + offset;
192
219M
  };
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
35.2M
                             pixel_type_w offset) -> pixel_type {
188
35.2M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
35.2M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
35.2M
    return val * multiplier + offset;
192
35.2M
  };
jxl::detail::DecodeModularChannelMAANS<false>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)::{lambda(unsigned long, int, long)#1}::operator()(unsigned long, int, long) const
Line
Count
Source
187
184M
                             pixel_type_w offset) -> pixel_type {
188
184M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
184M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
184M
    return val * multiplier + offset;
192
184M
  };
193
194
337k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
327k
    Predictor predictor = tree[0].predictor;
198
327k
    int64_t offset = tree[0].predictor_offset;
199
327k
    int32_t multiplier = tree[0].multiplier;
200
327k
    size_t ctx_id = tree[0].childID;
201
327k
    if (predictor == Predictor::Zero) {
202
307k
      uint32_t value;
203
307k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
307k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
126k
        JXL_DEBUG_V(8, "Fastest track.");
208
126k
        pixel_type v = make_pixel(value, multiplier, offset);
209
3.20M
        for (size_t y = 0; y < channel.h; y++) {
210
3.07M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
3.07M
          std::fill(r, r + channel.w, v);
212
3.07M
        }
213
181k
      } else {
214
181k
        JXL_DEBUG_V(8, "Fast track.");
215
181k
        if (multiplier == 1 && offset == 0) {
216
3.06M
          for (size_t y = 0; y < channel.h; y++) {
217
2.90M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
235M
            for (size_t x = 0; x < channel.w; x++) {
219
232M
              uint32_t v =
220
232M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
232M
              r[x] = UnpackSigned(v);
222
232M
            }
223
2.90M
          }
224
153k
        } else {
225
1.24M
          for (size_t y = 0; y < channel.h; y++) {
226
1.22M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
141M
            for (size_t x = 0; x < channel.w; x++) {
228
140M
              uint32_t v =
229
140M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
140M
                                                                         br);
231
140M
              r[x] = make_pixel(v, multiplier, offset);
232
140M
            }
233
1.22M
          }
234
27.8k
        }
235
181k
      }
236
307k
      return true;
237
307k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.56k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
381
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
381
      pixel_type_w sv = UnpackSigned(fl_v);
241
12.1k
      for (size_t y = 0; y < channel.h; y++) {
242
11.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
11.7k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
11.7k
        const pixel_type *JXL_RESTRICT rtopleft =
245
11.7k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
11.7k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
11.7k
        if (fl_run == 0) {
248
5.14k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.14k
                                                     &fl_run);
250
5.14k
          sv = UnpackSigned(fl_v);
251
6.63k
        } else {
252
6.63k
          fl_run--;
253
6.63k
        }
254
11.7k
        r[0] = sv + guess_0;
255
369k
        for (size_t x = 1; x < channel.w; x++) {
256
357k
          pixel_type left = r[x - 1];
257
357k
          pixel_type top = rtop[x];
258
357k
          pixel_type topleft = rtopleft[x];
259
357k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
357k
          if (!fl_run) {
261
162k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
162k
                                                       &fl_run);
263
162k
            sv = UnpackSigned(fl_v);
264
195k
          } else {
265
195k
            fl_run--;
266
195k
          }
267
357k
          r[x] = sv + guess;
268
357k
        }
269
11.7k
      }
270
381
      return true;
271
19.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
2.86k
               multiplier == 1) {
273
2.44k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
2.44k
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
54.8k
      for (size_t y = 0; y < channel.h; y++) {
276
52.4k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.96M
        for (size_t x = 0; x < channel.w; x++) {
278
2.91M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.91M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.91M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.91M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.91M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.91M
              ctx_id, br);
284
2.91M
          r[x] = make_pixel(v, 1, guess);
285
2.91M
        }
286
52.4k
      }
287
2.44k
      return true;
288
2.44k
    }
289
327k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
27.6k
  if (is_wp_only) {
294
3.55k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
3.55k
  }
296
27.6k
  if (is_gradient_only) {
297
2.00k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
2.00k
  }
299
300
27.6k
  if (is_gradient_only) {
301
640
    JXL_DEBUG_V(8, "Gradient fast track.");
302
640
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
14.4k
    for (size_t y = 0; y < channel.h; y++) {
304
13.7k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
568k
      for (size_t x = 0; x < channel.w; x++) {
306
554k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
554k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
554k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
554k
        int32_t guess = ClampedGradient(top, left, topleft);
310
554k
        uint32_t pos =
311
554k
            kPropRangeFast +
312
554k
            std::min<pixel_type_w>(
313
554k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
554k
                kPropRangeFast - 1);
315
554k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
554k
        uint64_t v =
317
554k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
554k
        r[x] = make_pixel(v, 1, guess);
319
554k
      }
320
13.7k
    }
321
27.0k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
674
    JXL_DEBUG_V(8, "WP fast track.");
323
674
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
674
    Properties properties(1);
325
16.8k
    for (size_t y = 0; y < channel.h; y++) {
326
16.2k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
16.2k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
16.2k
      const pixel_type *JXL_RESTRICT rtoptop =
329
16.2k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
16.2k
      const pixel_type *JXL_RESTRICT rtopleft =
331
16.2k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
16.2k
      const pixel_type *JXL_RESTRICT rtopright =
333
16.2k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
16.2k
      size_t x = 0;
335
16.2k
      {
336
16.2k
        size_t offset = 0;
337
16.2k
        pixel_type_w left = y ? rtop[x] : 0;
338
16.2k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
16.2k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
16.2k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
16.2k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
16.2k
            offset);
343
16.2k
        uint32_t pos =
344
16.2k
            kPropRangeFast +
345
16.2k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
16.2k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
16.2k
        uint64_t v =
348
16.2k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
16.2k
        r[x] = make_pixel(v, 1, guess);
350
16.2k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
16.2k
      }
352
1.59M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.57M
        size_t offset = 0;
354
1.57M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.57M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.57M
            rtoptop[x], &properties, offset);
357
1.57M
        uint32_t pos =
358
1.57M
            kPropRangeFast +
359
1.57M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.57M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.57M
        uint64_t v =
362
1.57M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.57M
        r[x] = make_pixel(v, 1, guess);
364
1.57M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.57M
      }
366
16.2k
      {
367
16.2k
        size_t offset = 0;
368
16.2k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
16.2k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
16.2k
            rtoptop[x], &properties, offset);
371
16.2k
        uint32_t pos =
372
16.2k
            kPropRangeFast +
373
16.2k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
16.2k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
16.2k
        uint64_t v =
376
16.2k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
16.2k
        r[x] = make_pixel(v, 1, guess);
378
16.2k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
16.2k
      }
380
16.2k
    }
381
26.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
18.3k
    JXL_DEBUG_V(8, "Slow track.");
385
18.3k
    MATreeLookup tree_lookup(tree);
386
18.3k
    Properties properties = Properties(num_props);
387
18.3k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
18.3k
    JXL_ASSIGN_OR_RETURN(
389
18.3k
        Channel references,
390
18.3k
        Channel::Create(memory_manager,
391
18.3k
                        properties.size() - kNumNonrefProperties, channel.w));
392
610k
    for (size_t y = 0; y < channel.h; y++) {
393
591k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
591k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
591k
      InitPropsRow(&properties, static_props, y);
396
591k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.47M
        for (size_t x = 0; x < 2; x++) {
398
980k
          PredictionResult res =
399
980k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
980k
                              tree_lookup, references);
401
980k
          uint64_t v =
402
980k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
980k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
980k
        }
405
52.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
51.7M
          PredictionResult res =
407
51.7M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
51.7M
                                 tree_lookup, references);
409
51.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
51.7M
              res.context, br);
411
51.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
51.7M
        }
413
1.47M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
980k
          PredictionResult res =
415
980k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
980k
                              tree_lookup, references);
417
980k
          uint64_t v =
418
980k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
980k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
980k
        }
421
490k
      } else {
422
2.77M
        for (size_t x = 0; x < channel.w; x++) {
423
2.67M
          PredictionResult res =
424
2.67M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
2.67M
                              tree_lookup, references);
426
2.67M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
2.67M
              res.context, br);
428
2.67M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
2.67M
        }
430
101k
      }
431
591k
    }
432
18.3k
  } else {
433
7.97k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.97k
    MATreeLookup tree_lookup(tree);
435
7.97k
    Properties properties = Properties(num_props);
436
7.97k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
7.97k
    JXL_ASSIGN_OR_RETURN(
438
7.97k
        Channel references,
439
7.97k
        Channel::Create(memory_manager,
440
7.97k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.97k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
242k
    for (size_t y = 0; y < channel.h; y++) {
443
234k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
234k
      InitPropsRow(&properties, static_props, y);
445
234k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
234k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
581k
        for (size_t x = 0; x < 2; x++) {
448
387k
          PredictionResult res =
449
387k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
387k
                            tree_lookup, references, &wp_state);
451
387k
          uint64_t v =
452
387k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
387k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
387k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
387k
        }
456
14.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
14.2M
          PredictionResult res =
458
14.2M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
14.2M
                               tree_lookup, references, &wp_state);
460
14.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
14.2M
              res.context, br);
462
14.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
14.2M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
14.2M
        }
465
581k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
387k
          PredictionResult res =
467
387k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
387k
                            tree_lookup, references, &wp_state);
469
387k
          uint64_t v =
470
387k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
387k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
387k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
387k
        }
474
193k
      } else {
475
2.23M
        for (size_t x = 0; x < channel.w; x++) {
476
2.18M
          PredictionResult res =
477
2.18M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
2.18M
                            tree_lookup, references, &wp_state);
479
2.18M
          uint64_t v =
480
2.18M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
2.18M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
2.18M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
2.18M
        }
484
40.6k
      }
485
234k
    }
486
7.97k
  }
487
27.6k
  return true;
488
27.6k
}
jxl::Status jxl::detail::DecodeModularChannelMAANS<true>(jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> > const&, jxl::weighted::Header const&, int, unsigned long, jxl::TreeLut<unsigned char, false, false>&, jxl::Image*, unsigned int&, unsigned int&)
Line
Count
Source
156
26.7k
                                 uint32_t &fl_v) {
157
26.7k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
26.7k
  Channel &channel = image->channel[chan];
159
160
26.7k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
26.7k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
26.7k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
26.7k
  bool tree_has_wp_prop_or_pred = false;
168
26.7k
  bool is_wp_only = false;
169
26.7k
  bool is_gradient_only = false;
170
26.7k
  size_t num_props;
171
26.7k
  FlatTree tree =
172
26.7k
      FilterTree(global_tree, static_props, &num_props,
173
26.7k
                 &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
34.2k
  for (auto &node : tree) {
178
34.2k
    if (node.property0 == -1) {
179
32.3k
      node.childID = context_map[node.childID];
180
32.3k
    }
181
34.2k
  }
182
183
26.7k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
26.7k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
26.7k
                             pixel_type_w offset) -> pixel_type {
188
26.7k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
26.7k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
26.7k
    return val * multiplier + offset;
192
26.7k
  };
193
194
26.7k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
25.0k
    Predictor predictor = tree[0].predictor;
198
25.0k
    int64_t offset = tree[0].predictor_offset;
199
25.0k
    int32_t multiplier = tree[0].multiplier;
200
25.0k
    size_t ctx_id = tree[0].childID;
201
25.0k
    if (predictor == Predictor::Zero) {
202
18.9k
      uint32_t value;
203
18.9k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
18.9k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
6.12k
        JXL_DEBUG_V(8, "Fastest track.");
208
6.12k
        pixel_type v = make_pixel(value, multiplier, offset);
209
227k
        for (size_t y = 0; y < channel.h; y++) {
210
220k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
220k
          std::fill(r, r + channel.w, v);
212
220k
        }
213
12.7k
      } else {
214
12.7k
        JXL_DEBUG_V(8, "Fast track.");
215
12.7k
        if (multiplier == 1 && offset == 0) {
216
291k
          for (size_t y = 0; y < channel.h; y++) {
217
286k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
48.4M
            for (size_t x = 0; x < channel.w; x++) {
219
48.1M
              uint32_t v =
220
48.1M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
48.1M
              r[x] = UnpackSigned(v);
222
48.1M
            }
223
286k
          }
224
8.12k
        } else {
225
256k
          for (size_t y = 0; y < channel.h; y++) {
226
248k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
17.6M
            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
248k
          }
234
8.12k
        }
235
12.7k
      }
236
18.9k
      return true;
237
18.9k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.56k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
381
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
381
      pixel_type_w sv = UnpackSigned(fl_v);
241
12.1k
      for (size_t y = 0; y < channel.h; y++) {
242
11.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
11.7k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
11.7k
        const pixel_type *JXL_RESTRICT rtopleft =
245
11.7k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
11.7k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
11.7k
        if (fl_run == 0) {
248
5.14k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.14k
                                                     &fl_run);
250
5.14k
          sv = UnpackSigned(fl_v);
251
6.63k
        } else {
252
6.63k
          fl_run--;
253
6.63k
        }
254
11.7k
        r[0] = sv + guess_0;
255
369k
        for (size_t x = 1; x < channel.w; x++) {
256
357k
          pixel_type left = r[x - 1];
257
357k
          pixel_type top = rtop[x];
258
357k
          pixel_type topleft = rtopleft[x];
259
357k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
357k
          if (!fl_run) {
261
162k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
162k
                                                       &fl_run);
263
162k
            sv = UnpackSigned(fl_v);
264
195k
          } else {
265
195k
            fl_run--;
266
195k
          }
267
357k
          r[x] = sv + guess;
268
357k
        }
269
11.7k
      }
270
381
      return true;
271
5.80k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.18k
               multiplier == 1) {
273
1.07k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.07k
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
14.6k
      for (size_t y = 0; y < channel.h; y++) {
276
13.5k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
330k
        for (size_t x = 0; x < channel.w; x++) {
278
316k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
316k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
316k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
316k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
316k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
316k
              ctx_id, br);
284
316k
          r[x] = make_pixel(v, 1, guess);
285
316k
        }
286
13.5k
      }
287
1.07k
      return true;
288
1.07k
    }
289
25.0k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
6.40k
  if (is_wp_only) {
294
278
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
278
  }
296
6.40k
  if (is_gradient_only) {
297
692
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
692
  }
299
300
6.40k
  if (is_gradient_only) {
301
104
    JXL_DEBUG_V(8, "Gradient fast track.");
302
104
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
3.31k
    for (size_t y = 0; y < channel.h; y++) {
304
3.20k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
258k
      for (size_t x = 0; x < channel.w; x++) {
306
255k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
255k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
255k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
255k
        int32_t guess = ClampedGradient(top, left, topleft);
310
255k
        uint32_t pos =
311
255k
            kPropRangeFast +
312
255k
            std::min<pixel_type_w>(
313
255k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
255k
                kPropRangeFast - 1);
315
255k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
255k
        uint64_t v =
317
255k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
255k
        r[x] = make_pixel(v, 1, guess);
319
255k
      }
320
3.20k
    }
321
6.30k
  } 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
6.30k
  } 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
5.80k
    JXL_DEBUG_V(8, "Slow track.");
385
5.80k
    MATreeLookup tree_lookup(tree);
386
5.80k
    Properties properties = Properties(num_props);
387
5.80k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
5.80k
    JXL_ASSIGN_OR_RETURN(
389
5.80k
        Channel references,
390
5.80k
        Channel::Create(memory_manager,
391
5.80k
                        properties.size() - kNumNonrefProperties, channel.w));
392
139k
    for (size_t y = 0; y < channel.h; y++) {
393
133k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
133k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
133k
      InitPropsRow(&properties, static_props, y);
396
133k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
332k
        for (size_t x = 0; x < 2; x++) {
398
221k
          PredictionResult res =
399
221k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
221k
                              tree_lookup, references);
401
221k
          uint64_t v =
402
221k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
221k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
221k
        }
405
15.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
15.1M
          PredictionResult res =
407
15.1M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
15.1M
                                 tree_lookup, references);
409
15.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
15.1M
              res.context, br);
411
15.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
15.1M
        }
413
332k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
221k
          PredictionResult res =
415
221k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
221k
                              tree_lookup, references);
417
221k
          uint64_t v =
418
221k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
221k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
221k
        }
421
110k
      } else {
422
753k
        for (size_t x = 0; x < channel.w; x++) {
423
731k
          PredictionResult res =
424
731k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
731k
                              tree_lookup, references);
426
731k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
731k
              res.context, br);
428
731k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
731k
        }
430
22.3k
      }
431
133k
    }
432
5.80k
  } else {
433
502
    JXL_DEBUG_V(8, "Slowest track.");
434
502
    MATreeLookup tree_lookup(tree);
435
502
    Properties properties = Properties(num_props);
436
502
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
502
    JXL_ASSIGN_OR_RETURN(
438
502
        Channel references,
439
502
        Channel::Create(memory_manager,
440
502
                        properties.size() - kNumNonrefProperties, channel.w));
441
502
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
8.79k
    for (size_t y = 0; y < channel.h; y++) {
443
8.29k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
8.29k
      InitPropsRow(&properties, static_props, y);
445
8.29k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
8.29k
      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
8.29k
      } else {
475
901k
        for (size_t x = 0; x < channel.w; x++) {
476
892k
          PredictionResult res =
477
892k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
892k
                            tree_lookup, references, &wp_state);
479
892k
          uint64_t v =
480
892k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
892k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
892k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
892k
        }
484
8.29k
      }
485
8.29k
    }
486
502
  }
487
6.40k
  return true;
488
6.40k
}
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
311k
                                 uint32_t &fl_v) {
157
311k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
311k
  Channel &channel = image->channel[chan];
159
160
311k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
311k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
311k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
311k
  bool tree_has_wp_prop_or_pred = false;
168
311k
  bool is_wp_only = false;
169
311k
  bool is_gradient_only = false;
170
311k
  size_t num_props;
171
311k
  FlatTree tree =
172
311k
      FilterTree(global_tree, static_props, &num_props,
173
311k
                 &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
454k
  for (auto &node : tree) {
178
454k
    if (node.property0 == -1) {
179
418k
      node.childID = context_map[node.childID];
180
418k
    }
181
454k
  }
182
183
311k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
311k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
311k
                             pixel_type_w offset) -> pixel_type {
188
311k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
311k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
311k
    return val * multiplier + offset;
192
311k
  };
193
194
311k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
302k
    Predictor predictor = tree[0].predictor;
198
302k
    int64_t offset = tree[0].predictor_offset;
199
302k
    int32_t multiplier = tree[0].multiplier;
200
302k
    size_t ctx_id = tree[0].childID;
201
302k
    if (predictor == Predictor::Zero) {
202
288k
      uint32_t value;
203
288k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
288k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
120k
        JXL_DEBUG_V(8, "Fastest track.");
208
120k
        pixel_type v = make_pixel(value, multiplier, offset);
209
2.97M
        for (size_t y = 0; y < channel.h; y++) {
210
2.85M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
2.85M
          std::fill(r, r + channel.w, v);
212
2.85M
        }
213
168k
      } else {
214
168k
        JXL_DEBUG_V(8, "Fast track.");
215
168k
        if (multiplier == 1 && offset == 0) {
216
2.77M
          for (size_t y = 0; y < channel.h; y++) {
217
2.62M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
186M
            for (size_t x = 0; x < channel.w; x++) {
219
184M
              uint32_t v =
220
184M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
184M
              r[x] = UnpackSigned(v);
222
184M
            }
223
2.62M
          }
224
148k
        } else {
225
992k
          for (size_t y = 0; y < channel.h; y++) {
226
972k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
124M
            for (size_t x = 0; x < channel.w; x++) {
228
123M
              uint32_t v =
229
123M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
123M
                                                                         br);
231
123M
              r[x] = make_pixel(v, multiplier, offset);
232
123M
            }
233
972k
          }
234
19.7k
        }
235
168k
      }
236
288k
      return true;
237
288k
    } 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
13.9k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.68k
               multiplier == 1) {
273
1.37k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.37k
      const intptr_t onerow = channel.plane.PixelsPerRow();
275
40.2k
      for (size_t y = 0; y < channel.h; y++) {
276
38.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.63M
        for (size_t x = 0; x < channel.w; x++) {
278
2.59M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.59M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.59M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.59M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.59M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.59M
              ctx_id, br);
284
2.59M
          r[x] = make_pixel(v, 1, guess);
285
2.59M
        }
286
38.8k
      }
287
1.37k
      return true;
288
1.37k
    }
289
302k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
21.2k
  if (is_wp_only) {
294
3.27k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
3.27k
  }
296
21.2k
  if (is_gradient_only) {
297
1.31k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.31k
  }
299
300
21.2k
  if (is_gradient_only) {
301
536
    JXL_DEBUG_V(8, "Gradient fast track.");
302
536
    const intptr_t onerow = channel.plane.PixelsPerRow();
303
11.1k
    for (size_t y = 0; y < channel.h; y++) {
304
10.5k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
309k
      for (size_t x = 0; x < channel.w; x++) {
306
299k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
299k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
299k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
299k
        int32_t guess = ClampedGradient(top, left, topleft);
310
299k
        uint32_t pos =
311
299k
            kPropRangeFast +
312
299k
            std::min<pixel_type_w>(
313
299k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
299k
                kPropRangeFast - 1);
315
299k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
299k
        uint64_t v =
317
299k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
299k
        r[x] = make_pixel(v, 1, guess);
319
299k
      }
320
10.5k
    }
321
20.7k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
674
    JXL_DEBUG_V(8, "WP fast track.");
323
674
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
674
    Properties properties(1);
325
16.8k
    for (size_t y = 0; y < channel.h; y++) {
326
16.2k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
16.2k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
16.2k
      const pixel_type *JXL_RESTRICT rtoptop =
329
16.2k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
16.2k
      const pixel_type *JXL_RESTRICT rtopleft =
331
16.2k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
16.2k
      const pixel_type *JXL_RESTRICT rtopright =
333
16.2k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
16.2k
      size_t x = 0;
335
16.2k
      {
336
16.2k
        size_t offset = 0;
337
16.2k
        pixel_type_w left = y ? rtop[x] : 0;
338
16.2k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
16.2k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
16.2k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
16.2k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
16.2k
            offset);
343
16.2k
        uint32_t pos =
344
16.2k
            kPropRangeFast +
345
16.2k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
16.2k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
16.2k
        uint64_t v =
348
16.2k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
16.2k
        r[x] = make_pixel(v, 1, guess);
350
16.2k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
16.2k
      }
352
1.59M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.57M
        size_t offset = 0;
354
1.57M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.57M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.57M
            rtoptop[x], &properties, offset);
357
1.57M
        uint32_t pos =
358
1.57M
            kPropRangeFast +
359
1.57M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.57M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.57M
        uint64_t v =
362
1.57M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.57M
        r[x] = make_pixel(v, 1, guess);
364
1.57M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.57M
      }
366
16.2k
      {
367
16.2k
        size_t offset = 0;
368
16.2k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
16.2k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
16.2k
            rtoptop[x], &properties, offset);
371
16.2k
        uint32_t pos =
372
16.2k
            kPropRangeFast +
373
16.2k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
16.2k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
16.2k
        uint64_t v =
376
16.2k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
16.2k
        r[x] = make_pixel(v, 1, guess);
378
16.2k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
16.2k
      }
380
16.2k
    }
381
20.0k
  } 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
12.5k
    JXL_DEBUG_V(8, "Slow track.");
385
12.5k
    MATreeLookup tree_lookup(tree);
386
12.5k
    Properties properties = Properties(num_props);
387
12.5k
    const intptr_t onerow = channel.plane.PixelsPerRow();
388
12.5k
    JXL_ASSIGN_OR_RETURN(
389
12.5k
        Channel references,
390
12.5k
        Channel::Create(memory_manager,
391
12.5k
                        properties.size() - kNumNonrefProperties, channel.w));
392
471k
    for (size_t y = 0; y < channel.h; y++) {
393
458k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
458k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
458k
      InitPropsRow(&properties, static_props, y);
396
458k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.13M
        for (size_t x = 0; x < 2; x++) {
398
758k
          PredictionResult res =
399
758k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
758k
                              tree_lookup, references);
401
758k
          uint64_t v =
402
758k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
758k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
758k
        }
405
36.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
36.5M
          PredictionResult res =
407
36.5M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
36.5M
                                 tree_lookup, references);
409
36.5M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
36.5M
              res.context, br);
411
36.5M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
36.5M
        }
413
1.13M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
758k
          PredictionResult res =
415
758k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
758k
                              tree_lookup, references);
417
758k
          uint64_t v =
418
758k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
758k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
758k
        }
421
379k
      } else {
422
2.01M
        for (size_t x = 0; x < channel.w; x++) {
423
1.94M
          PredictionResult res =
424
1.94M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.94M
                              tree_lookup, references);
426
1.94M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.94M
              res.context, br);
428
1.94M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.94M
        }
430
79.1k
      }
431
458k
    }
432
12.5k
  } else {
433
7.47k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.47k
    MATreeLookup tree_lookup(tree);
435
7.47k
    Properties properties = Properties(num_props);
436
7.47k
    const intptr_t onerow = channel.plane.PixelsPerRow();
437
7.47k
    JXL_ASSIGN_OR_RETURN(
438
7.47k
        Channel references,
439
7.47k
        Channel::Create(memory_manager,
440
7.47k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.47k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
233k
    for (size_t y = 0; y < channel.h; y++) {
443
226k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
226k
      InitPropsRow(&properties, static_props, y);
445
226k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
226k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
581k
        for (size_t x = 0; x < 2; x++) {
448
387k
          PredictionResult res =
449
387k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
387k
                            tree_lookup, references, &wp_state);
451
387k
          uint64_t v =
452
387k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
387k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
387k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
387k
        }
456
14.4M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
14.2M
          PredictionResult res =
458
14.2M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
14.2M
                               tree_lookup, references, &wp_state);
460
14.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
14.2M
              res.context, br);
462
14.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
14.2M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
14.2M
        }
465
581k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
387k
          PredictionResult res =
467
387k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
387k
                            tree_lookup, references, &wp_state);
469
387k
          uint64_t v =
470
387k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
387k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
387k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
387k
        }
474
193k
      } else {
475
1.32M
        for (size_t x = 0; x < channel.w; x++) {
476
1.29M
          PredictionResult res =
477
1.29M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.29M
                            tree_lookup, references, &wp_state);
479
1.29M
          uint64_t v =
480
1.29M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.29M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.29M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.29M
        }
484
32.3k
      }
485
226k
    }
486
7.47k
  }
487
21.2k
  return true;
488
21.2k
}
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
337k
                                 uint32_t &fl_v) {
499
337k
  if (reader->UsesLZ77()) {
500
26.7k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
26.7k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
26.7k
        tree_lut, image, fl_run, fl_v);
503
311k
  } else {
504
311k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
311k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
311k
        tree_lut, image, fl_run, fl_v);
507
311k
  }
508
337k
}
509
510
192k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
41.7k
                                 const ModularOptions &options) {
514
41.7k
  size_t nb_channels = image.channel.size();
515
83.4k
  for (bool is_dc : {true, false}) {
516
83.4k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
83.4k
    size_t c = image.nb_meta_channels;
518
779k
    for (; c < nb_channels; c++) {
519
699k
      const Channel &ch = image.channel[c];
520
699k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
699k
    }
522
108k
    for (; c < nb_channels; c++) {
523
25.4k
      const Channel &ch = image.channel[c];
524
25.4k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
24.7k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
24.7k
      if (is_dc_channel != is_dc) continue;
527
12.3k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
12.3k
      if (tile_dim == 0) {
529
1
        return JXL_FAILURE("Inconsistent transforms");
530
1
      }
531
12.3k
    }
532
83.4k
  }
533
41.7k
  return true;
534
41.7k
}
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
45.8k
                     const bool allow_truncated_group) {
541
45.8k
  if (image.channel.empty()) return true;
542
40.5k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
40.5k
  Status status = Bundle::Read(br, &header);
546
40.5k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
40.1k
  if (status.IsFatalError()) return status;
548
40.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
40.1k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
40.1k
              header.transforms.size());
560
40.1k
  image.transform = header.transforms;
561
40.1k
  for (Transform &transform : image.transform) {
562
23.9k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
23.9k
  }
564
40.0k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
40.0k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
40.0k
  size_t nb_channels = image.channel.size();
570
571
40.0k
  size_t num_chans = 0;
572
40.0k
  size_t distance_multiplier = 0;
573
389k
  for (size_t i = 0; i < nb_channels; i++) {
574
350k
    Channel &channel = image.channel[i];
575
350k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
345k
                                        channel.h > options->max_chan_size)) {
577
1.25k
      break;
578
1.25k
    }
579
349k
    if (!channel.w || !channel.h) {
580
4.18k
      continue;  // skip empty channels
581
4.18k
    }
582
345k
    if (channel.w > distance_multiplier) {
583
61.3k
      distance_multiplier = channel.w;
584
61.3k
    }
585
345k
    num_chans++;
586
345k
  }
587
40.0k
  if (num_chans == 0) return true;
588
589
39.5k
  size_t next_channel = 0;
590
39.5k
  auto scope_guard = MakeScopeGuard([&]() {
591
10.6k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
9.16k
      ZeroFillImage(&image.channel[c].plane);
593
9.16k
    }
594
1.49k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
39.5k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
39.5k
  Tree tree_storage;
600
39.5k
  std::vector<uint8_t> context_map_storage;
601
39.5k
  ANSCode code_storage;
602
39.5k
  const Tree *tree = &tree_storage;
603
39.5k
  const ANSCode *code = &code_storage;
604
39.5k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
39.5k
  if (!header.use_global_tree) {
606
22.7k
    uint64_t max_tree_size = 1024;
607
258k
    for (size_t i = 0; i < nb_channels; i++) {
608
235k
      Channel &channel = image.channel[i];
609
235k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
234k
                                          channel.h > options->max_chan_size)) {
611
42
        break;
612
42
      }
613
235k
      uint64_t pixels = channel.w * channel.h;
614
235k
      max_tree_size += pixels;
615
235k
    }
616
22.7k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
22.7k
    JXL_RETURN_IF_ERROR(
618
22.7k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
22.5k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
22.5k
                                         (tree_storage.size() + 1) / 2,
621
22.5k
                                         &code_storage, &context_map_storage));
622
22.5k
  } else {
623
16.8k
    if (!global_tree || !global_code || !global_ctx_map ||
624
16.8k
        global_tree->empty()) {
625
35
      return JXL_FAILURE("No global tree available but one was requested");
626
35
    }
627
16.7k
    tree = global_tree;
628
16.7k
    code = global_code;
629
16.7k
    context_map = global_ctx_map;
630
16.7k
  }
631
632
  // Read channels
633
78.7k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
78.7k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
78.7k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
78.7k
  uint32_t fl_run = 0;
637
78.7k
  uint32_t fl_v = 0;
638
380k
  for (; next_channel < nb_channels; next_channel++) {
639
342k
    Channel &channel = image.channel[next_channel];
640
342k
    if (next_channel >= image.nb_meta_channels &&
641
338k
        (channel.w > options->max_chan_size ||
642
338k
         channel.h > options->max_chan_size)) {
643
792
      break;
644
792
    }
645
341k
    if (!channel.w || !channel.h) {
646
3.99k
      continue;  // skip empty channels
647
3.99k
    }
648
337k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
337k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
337k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
337k
    if (!br->AllReadsWithinBounds()) {
654
1.27k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
1.27k
    }
657
337k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
38.0k
  scope_guard.Disarm();
661
662
38.0k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
38.0k
  return true;
666
38.0k
}
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
45.8k
                                bool allow_truncated_group) {
674
45.8k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
45.8k
  req_sizes.reserve(image.channel.size());
676
150k
  for (const auto &c : image.channel) {
677
150k
    req_sizes.emplace_back(c.w, c.h);
678
150k
  }
679
45.8k
  GroupHeader local_header;
680
45.8k
  if (header == nullptr) header = &local_header;
681
45.8k
  size_t bit_pos = br->TotalBitsConsumed();
682
45.8k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
45.8k
                                  code, ctx_map, allow_truncated_group);
684
45.8k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
43.8k
  if (dec_status.IsFatalError()) return dec_status;
686
43.8k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
43.8k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
43.8k
  JXL_DEBUG_V(4,
689
43.8k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
43.8k
              " image from %" PRIuS " bytes",
691
43.8k
              image.w, image.h, image.channel.size(),
692
43.8k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
43.8k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
43.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
43.8k
  if (undo_transforms) {
699
12.8k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
65.2k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
52.4k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
52.4k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
52.4k
    }
704
12.8k
  }
705
43.8k
  return dec_status;
706
43.8k
}
707
708
}  // namespace jxl