Coverage Report

Created: 2025-12-31 07:53

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
343k
                    bool *gradient_only) {
46
343k
  *num_props = 0;
47
343k
  bool has_wp = false;
48
343k
  bool has_non_wp = false;
49
343k
  *gradient_only = true;
50
755k
  const auto mark_property = [&](int32_t p) {
51
755k
    if (p == kWPProp) {
52
144k
      has_wp = true;
53
610k
    } else if (p >= kNumStaticProperties) {
54
308k
      has_non_wp = true;
55
308k
    }
56
755k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
375k
      *gradient_only = false;
58
375k
    }
59
755k
  };
60
343k
  FlatTree output;
61
343k
  std::queue<size_t> nodes;
62
343k
  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.69M
  while (!nodes.empty()) {
70
1.35M
    size_t cur = nodes.front();
71
1.35M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.46M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.21M
           global_tree[cur].property != -1) {
75
110k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
60.7k
        cur = global_tree[cur].lchild;
77
60.7k
      } else {
78
50.0k
        cur = global_tree[cur].rchild;
79
50.0k
      }
80
110k
    }
81
1.35M
    FlatDecisionNode flat;
82
1.35M
    if (global_tree[cur].property == -1) {
83
1.09M
      flat.property0 = -1;
84
1.09M
      flat.childID = global_tree[cur].lchild;
85
1.09M
      flat.predictor = global_tree[cur].predictor;
86
1.09M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.09M
      flat.multiplier = global_tree[cur].multiplier;
88
1.09M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.09M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.09M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.09M
      output.push_back(flat);
92
1.09M
      continue;
93
1.09M
    }
94
251k
    flat.childID = output.size() + nodes.size() + 1;
95
96
251k
    flat.property0 = global_tree[cur].property;
97
251k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
251k
    flat.splitval0 = global_tree[cur].splitval;
99
100
755k
    for (size_t i = 0; i < 2; i++) {
101
503k
      size_t cur_child =
102
503k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
535k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
334k
             global_tree[cur_child].property != -1) {
106
32.0k
        if (static_props[global_tree[cur_child].property] >
107
32.0k
            global_tree[cur_child].splitval) {
108
17.3k
          cur_child = global_tree[cur_child].lchild;
109
17.3k
        } else {
110
14.7k
          cur_child = global_tree[cur_child].rchild;
111
14.7k
        }
112
32.0k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
503k
      if (global_tree[cur_child].property == -1) {
116
302k
        flat.properties[i] = 0;
117
302k
        flat.splitvals[i] = 0;
118
302k
        nodes.push(cur_child);
119
302k
        nodes.push(cur_child);
120
302k
      } else {
121
201k
        flat.properties[i] = global_tree[cur_child].property;
122
201k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
201k
        nodes.push(global_tree[cur_child].lchild);
124
201k
        nodes.push(global_tree[cur_child].rchild);
125
201k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
201k
      }
127
503k
    }
128
129
503k
    for (int16_t property : flat.properties) mark_property(property);
130
251k
    mark_property(flat.property0);
131
251k
    output.push_back(flat);
132
251k
  }
133
343k
  if (*num_props > kNumNonrefProperties) {
134
4.06k
    *num_props =
135
4.06k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
4.06k
            kExtraPropsPerChannel +
137
4.06k
        kNumNonrefProperties;
138
339k
  } else {
139
339k
    *num_props = kNumNonrefProperties;
140
339k
  }
141
343k
  *use_wp = has_wp;
142
343k
  *wp_only = has_wp && !has_non_wp;
143
144
343k
  return output;
145
343k
}
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
307k
                                 uint32_t &fl_v) {
157
307k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
307k
  Channel &channel = image->channel[chan];
159
160
307k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
307k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
307k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
307k
  bool tree_has_wp_prop_or_pred = false;
168
307k
  bool is_wp_only = false;
169
307k
  bool is_gradient_only = false;
170
307k
  size_t num_props;
171
307k
  FlatTree tree =
172
307k
      FilterTree(global_tree, static_props, &num_props,
173
307k
                 &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
844k
  for (auto &node : tree) {
178
844k
    if (node.property0 == -1) {
179
710k
      node.childID = context_map[node.childID];
180
710k
    }
181
844k
  }
182
183
307k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
307k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
309M
                             pixel_type_w offset) -> pixel_type {
188
309M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
309M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
309M
    return val * multiplier + offset;
192
309M
  };
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
43.3M
                             pixel_type_w offset) -> pixel_type {
188
43.3M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
43.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
43.3M
    return val * multiplier + offset;
192
43.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
265M
                             pixel_type_w offset) -> pixel_type {
188
265M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
265M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
265M
    return val * multiplier + offset;
192
265M
  };
193
194
307k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
267k
    Predictor predictor = tree[0].predictor;
198
267k
    int64_t offset = tree[0].predictor_offset;
199
267k
    int32_t multiplier = tree[0].multiplier;
200
267k
    size_t ctx_id = tree[0].childID;
201
267k
    if (predictor == Predictor::Zero) {
202
160k
      uint32_t value;
203
160k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
160k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
52.2k
        JXL_DEBUG_V(8, "Fastest track.");
208
52.2k
        pixel_type v = make_pixel(value, multiplier, offset);
209
1.36M
        for (size_t y = 0; y < channel.h; y++) {
210
1.30M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
1.30M
          std::fill(r, r + channel.w, v);
212
1.30M
        }
213
108k
      } else {
214
108k
        JXL_DEBUG_V(8, "Fast track.");
215
108k
        if (multiplier == 1 && offset == 0) {
216
1.18M
          for (size_t y = 0; y < channel.h; y++) {
217
1.10M
            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.10M
          }
224
79.6k
        } else {
225
608k
          for (size_t y = 0; y < channel.h; y++) {
226
580k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
29.9M
            for (size_t x = 0; x < channel.w; x++) {
228
29.3M
              uint32_t v =
229
29.3M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
29.3M
                                                                         br);
231
29.3M
              r[x] = make_pixel(v, multiplier, offset);
232
29.3M
            }
233
580k
          }
234
28.3k
        }
235
108k
      }
236
160k
      return true;
237
160k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.11k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
78
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
78
      pixel_type_w sv = UnpackSigned(fl_v);
241
1.14k
      for (size_t y = 0; y < channel.h; y++) {
242
1.07k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
1.07k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
1.07k
        const pixel_type *JXL_RESTRICT rtopleft =
245
1.07k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
1.07k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
1.07k
        if (fl_run == 0) {
248
1.07k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
1.07k
                                                     &fl_run);
250
1.07k
          sv = UnpackSigned(fl_v);
251
1.07k
        } else {
252
0
          fl_run--;
253
0
        }
254
1.07k
        r[0] = sv + guess_0;
255
62.8k
        for (size_t x = 1; x < channel.w; x++) {
256
61.8k
          pixel_type left = r[x - 1];
257
61.8k
          pixel_type top = rtop[x];
258
61.8k
          pixel_type topleft = rtopleft[x];
259
61.8k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
61.8k
          if (!fl_run) {
261
61.8k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
61.8k
                                                       &fl_run);
263
61.8k
            sv = UnpackSigned(fl_v);
264
61.8k
          } else {
265
0
            fl_run--;
266
0
          }
267
61.8k
          r[x] = sv + guess;
268
61.8k
        }
269
1.07k
      }
270
78
      return true;
271
107k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
6.71k
               multiplier == 1) {
273
5.79k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
5.79k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
173k
      for (size_t y = 0; y < channel.h; y++) {
276
167k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
4.00M
        for (size_t x = 0; x < channel.w; x++) {
278
3.83M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
3.83M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
3.83M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
3.83M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
3.83M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
3.83M
              ctx_id, br);
284
3.83M
          r[x] = make_pixel(v, 1, guess);
285
3.83M
        }
286
167k
      }
287
5.79k
      return true;
288
5.79k
    }
289
267k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
141k
  if (is_wp_only) {
294
16.1k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
16.1k
  }
296
141k
  if (is_gradient_only) {
297
5.91k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
5.91k
  }
299
300
141k
  if (is_gradient_only) {
301
3.54k
    JXL_DEBUG_V(8, "Gradient fast track.");
302
3.54k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
134k
    for (size_t y = 0; y < channel.h; y++) {
304
131k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
3.19M
      for (size_t x = 0; x < channel.w; x++) {
306
3.06M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
3.06M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
3.06M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
3.06M
        int32_t guess = ClampedGradient(top, left, topleft);
310
3.06M
        uint32_t pos =
311
3.06M
            kPropRangeFast +
312
3.06M
            std::min<pixel_type_w>(
313
3.06M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
3.06M
                kPropRangeFast - 1);
315
3.06M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
3.06M
        uint64_t v =
317
3.06M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
3.06M
        r[x] = make_pixel(v, 1, guess);
319
3.06M
      }
320
131k
    }
321
138k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
7.51k
    JXL_DEBUG_V(8, "WP fast track.");
323
7.51k
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
7.51k
    Properties properties(1);
325
214k
    for (size_t y = 0; y < channel.h; y++) {
326
206k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
206k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
206k
      const pixel_type *JXL_RESTRICT rtoptop =
329
206k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
206k
      const pixel_type *JXL_RESTRICT rtopleft =
331
206k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
206k
      const pixel_type *JXL_RESTRICT rtopright =
333
206k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
206k
      size_t x = 0;
335
206k
      {
336
206k
        size_t offset = 0;
337
206k
        pixel_type_w left = y ? rtop[x] : 0;
338
206k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
206k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
206k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
206k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
206k
            offset);
343
206k
        uint32_t pos =
344
206k
            kPropRangeFast +
345
206k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
206k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
206k
        uint64_t v =
348
206k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
206k
        r[x] = make_pixel(v, 1, guess);
350
206k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
206k
      }
352
10.5M
      for (x = 1; x + 1 < channel.w; x++) {
353
10.2M
        size_t offset = 0;
354
10.2M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
10.2M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
10.2M
            rtoptop[x], &properties, offset);
357
10.2M
        uint32_t pos =
358
10.2M
            kPropRangeFast +
359
10.2M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
10.2M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
10.2M
        uint64_t v =
362
10.2M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
10.2M
        r[x] = make_pixel(v, 1, guess);
364
10.2M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
10.2M
      }
366
206k
      {
367
206k
        size_t offset = 0;
368
206k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
206k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
206k
            rtoptop[x], &properties, offset);
371
206k
        uint32_t pos =
372
206k
            kPropRangeFast +
373
206k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
206k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
206k
        uint64_t v =
376
206k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
206k
        r[x] = make_pixel(v, 1, guess);
378
206k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
206k
      }
380
206k
    }
381
130k
  } 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
107k
    JXL_DEBUG_V(8, "Slow track.");
385
107k
    MATreeLookup tree_lookup(tree);
386
107k
    Properties properties = Properties(num_props);
387
107k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
107k
    JXL_ASSIGN_OR_RETURN(
389
107k
        Channel references,
390
107k
        Channel::Create(memory_manager,
391
107k
                        properties.size() - kNumNonrefProperties, channel.w));
392
3.17M
    for (size_t y = 0; y < channel.h; y++) {
393
3.06M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
3.06M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
3.06M
      InitPropsRow(&properties, static_props, y);
396
3.06M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
7.56M
        for (size_t x = 0; x < 2; x++) {
398
5.04M
          PredictionResult res =
399
5.04M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
5.04M
                              tree_lookup, references);
401
5.04M
          uint64_t v =
402
5.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
5.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
5.04M
        }
405
178M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
176M
          PredictionResult res =
407
176M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
176M
                                 tree_lookup, references);
409
176M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
176M
              res.context, br);
411
176M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
176M
        }
413
7.56M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
5.04M
          PredictionResult res =
415
5.04M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
5.04M
                              tree_lookup, references);
417
5.04M
          uint64_t v =
418
5.04M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
5.04M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
5.04M
        }
421
2.52M
      } else {
422
16.4M
        for (size_t x = 0; x < channel.w; x++) {
423
15.8M
          PredictionResult res =
424
15.8M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
15.8M
                              tree_lookup, references);
426
15.8M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
15.8M
              res.context, br);
428
15.8M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
15.8M
        }
430
543k
      }
431
3.06M
    }
432
107k
  } else {
433
22.8k
    JXL_DEBUG_V(8, "Slowest track.");
434
22.8k
    MATreeLookup tree_lookup(tree);
435
22.8k
    Properties properties = Properties(num_props);
436
22.8k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
22.8k
    JXL_ASSIGN_OR_RETURN(
438
22.8k
        Channel references,
439
22.8k
        Channel::Create(memory_manager,
440
22.8k
                        properties.size() - kNumNonrefProperties, channel.w));
441
22.8k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
1.40M
    for (size_t y = 0; y < channel.h; y++) {
443
1.37M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
1.37M
      InitPropsRow(&properties, static_props, y);
445
1.37M
      PrecomputeReferences(channel, y, *image, chan, &references);
446
1.37M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
1.29M
        for (size_t x = 0; x < 2; x++) {
448
865k
          PredictionResult res =
449
865k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
865k
                            tree_lookup, references, &wp_state);
451
865k
          uint64_t v =
452
865k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
865k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
865k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
865k
        }
456
48.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
47.7M
          PredictionResult res =
458
47.7M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
47.7M
                               tree_lookup, references, &wp_state);
460
47.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
47.7M
              res.context, br);
462
47.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
47.7M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
47.7M
        }
465
1.29M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
865k
          PredictionResult res =
467
865k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
865k
                            tree_lookup, references, &wp_state);
469
865k
          uint64_t v =
470
865k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
865k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
865k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
865k
        }
474
944k
      } else {
475
11.1M
        for (size_t x = 0; x < channel.w; x++) {
476
10.2M
          PredictionResult res =
477
10.2M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
10.2M
                            tree_lookup, references, &wp_state);
479
10.2M
          uint64_t v =
480
10.2M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
10.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
10.2M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
10.2M
        }
484
944k
      }
485
1.37M
    }
486
22.8k
  }
487
141k
  return true;
488
141k
}
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
66.6k
                                 uint32_t &fl_v) {
157
66.6k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
66.6k
  Channel &channel = image->channel[chan];
159
160
66.6k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
66.6k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
66.6k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
66.6k
  bool tree_has_wp_prop_or_pred = false;
168
66.6k
  bool is_wp_only = false;
169
66.6k
  bool is_gradient_only = false;
170
66.6k
  size_t num_props;
171
66.6k
  FlatTree tree =
172
66.6k
      FilterTree(global_tree, static_props, &num_props,
173
66.6k
                 &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
87.2k
  for (auto &node : tree) {
178
87.2k
    if (node.property0 == -1) {
179
82.0k
      node.childID = context_map[node.childID];
180
82.0k
    }
181
87.2k
  }
182
183
66.6k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
66.6k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
66.6k
                             pixel_type_w offset) -> pixel_type {
188
66.6k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
66.6k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
66.6k
    return val * multiplier + offset;
192
66.6k
  };
193
194
66.6k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
62.2k
    Predictor predictor = tree[0].predictor;
198
62.2k
    int64_t offset = tree[0].predictor_offset;
199
62.2k
    int32_t multiplier = tree[0].multiplier;
200
62.2k
    size_t ctx_id = tree[0].childID;
201
62.2k
    if (predictor == Predictor::Zero) {
202
47.5k
      uint32_t value;
203
47.5k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
47.5k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
25.2k
        JXL_DEBUG_V(8, "Fastest track.");
208
25.2k
        pixel_type v = make_pixel(value, multiplier, offset);
209
683k
        for (size_t y = 0; y < channel.h; y++) {
210
658k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
658k
          std::fill(r, r + channel.w, v);
212
658k
        }
213
25.2k
      } else {
214
22.3k
        JXL_DEBUG_V(8, "Fast track.");
215
22.3k
        if (multiplier == 1 && offset == 0) {
216
97.7k
          for (size_t y = 0; y < channel.h; y++) {
217
85.7k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
6.28M
            for (size_t x = 0; x < channel.w; x++) {
219
6.20M
              uint32_t v =
220
6.20M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
6.20M
              r[x] = UnpackSigned(v);
222
6.20M
            }
223
85.7k
          }
224
12.0k
        } else {
225
231k
          for (size_t y = 0; y < channel.h; y++) {
226
221k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
10.8M
            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.3k
        }
235
22.3k
      }
236
47.5k
      return true;
237
47.5k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.11k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
78
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
78
      pixel_type_w sv = UnpackSigned(fl_v);
241
1.14k
      for (size_t y = 0; y < channel.h; y++) {
242
1.07k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
1.07k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
1.07k
        const pixel_type *JXL_RESTRICT rtopleft =
245
1.07k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
1.07k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
1.07k
        if (fl_run == 0) {
248
1.07k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
1.07k
                                                     &fl_run);
250
1.07k
          sv = UnpackSigned(fl_v);
251
1.07k
        } else {
252
0
          fl_run--;
253
0
        }
254
1.07k
        r[0] = sv + guess_0;
255
62.8k
        for (size_t x = 1; x < channel.w; x++) {
256
61.8k
          pixel_type left = r[x - 1];
257
61.8k
          pixel_type top = rtop[x];
258
61.8k
          pixel_type topleft = rtopleft[x];
259
61.8k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
61.8k
          if (!fl_run) {
261
61.8k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
61.8k
                                                       &fl_run);
263
61.8k
            sv = UnpackSigned(fl_v);
264
61.8k
          } else {
265
0
            fl_run--;
266
0
          }
267
61.8k
          r[x] = sv + guess;
268
61.8k
        }
269
1.07k
      }
270
78
      return true;
271
14.7k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.03k
               multiplier == 1) {
273
625
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
625
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
13.6k
      for (size_t y = 0; y < channel.h; y++) {
276
13.0k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
1.31M
        for (size_t x = 0; x < channel.w; x++) {
278
1.30M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
1.30M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
1.30M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
1.30M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
1.30M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
1.30M
              ctx_id, br);
284
1.30M
          r[x] = make_pixel(v, 1, guess);
285
1.30M
        }
286
13.0k
      }
287
625
      return true;
288
625
    }
289
62.2k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
18.3k
  if (is_wp_only) {
294
1.46k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
1.46k
  }
296
18.3k
  if (is_gradient_only) {
297
1.16k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.16k
  }
299
300
18.3k
  if (is_gradient_only) {
301
7
    JXL_DEBUG_V(8, "Gradient fast track.");
302
7
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
326
    for (size_t y = 0; y < channel.h; y++) {
304
319
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
54.5k
      for (size_t x = 0; x < channel.w; x++) {
306
54.2k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
54.2k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
54.2k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
54.2k
        int32_t guess = ClampedGradient(top, left, topleft);
310
54.2k
        uint32_t pos =
311
54.2k
            kPropRangeFast +
312
54.2k
            std::min<pixel_type_w>(
313
54.2k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
54.2k
                kPropRangeFast - 1);
315
54.2k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
54.2k
        uint64_t v =
317
54.2k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
54.2k
        r[x] = make_pixel(v, 1, guess);
319
54.2k
      }
320
319
    }
321
18.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
18.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
15.9k
    JXL_DEBUG_V(8, "Slow track.");
385
15.9k
    MATreeLookup tree_lookup(tree);
386
15.9k
    Properties properties = Properties(num_props);
387
15.9k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
15.9k
    JXL_ASSIGN_OR_RETURN(
389
15.9k
        Channel references,
390
15.9k
        Channel::Create(memory_manager,
391
15.9k
                        properties.size() - kNumNonrefProperties, channel.w));
392
356k
    for (size_t y = 0; y < channel.h; y++) {
393
340k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
340k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
340k
      InitPropsRow(&properties, static_props, y);
396
340k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
828k
        for (size_t x = 0; x < 2; x++) {
398
552k
          PredictionResult res =
399
552k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
552k
                              tree_lookup, references);
401
552k
          uint64_t v =
402
552k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
552k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
552k
        }
405
21.6M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
21.3M
          PredictionResult res =
407
21.3M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
21.3M
                                 tree_lookup, references);
409
21.3M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
21.3M
              res.context, br);
411
21.3M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
21.3M
        }
413
828k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
552k
          PredictionResult res =
415
552k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
552k
                              tree_lookup, references);
417
552k
          uint64_t v =
418
552k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
552k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
552k
        }
421
276k
      } else {
422
4.80M
        for (size_t x = 0; x < channel.w; x++) {
423
4.74M
          PredictionResult res =
424
4.74M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
4.74M
                              tree_lookup, references);
426
4.74M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
4.74M
              res.context, br);
428
4.74M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
4.74M
        }
430
64.4k
      }
431
340k
    }
432
15.9k
  } else {
433
2.40k
    JXL_DEBUG_V(8, "Slowest track.");
434
2.40k
    MATreeLookup tree_lookup(tree);
435
2.40k
    Properties properties = Properties(num_props);
436
2.40k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
2.40k
    JXL_ASSIGN_OR_RETURN(
438
2.40k
        Channel references,
439
2.40k
        Channel::Create(memory_manager,
440
2.40k
                        properties.size() - kNumNonrefProperties, channel.w));
441
2.40k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
67.0k
    for (size_t y = 0; y < channel.h; y++) {
443
64.6k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
64.6k
      InitPropsRow(&properties, static_props, y);
445
64.6k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
64.6k
      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
64.6k
      } else {
475
4.20M
        for (size_t x = 0; x < channel.w; x++) {
476
4.14M
          PredictionResult res =
477
4.14M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
4.14M
                            tree_lookup, references, &wp_state);
479
4.14M
          uint64_t v =
480
4.14M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
4.14M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
4.14M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
4.14M
        }
484
64.6k
      }
485
64.6k
    }
486
2.40k
  }
487
18.3k
  return true;
488
18.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
241k
                                 uint32_t &fl_v) {
157
241k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
241k
  Channel &channel = image->channel[chan];
159
160
241k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
241k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
241k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
241k
  bool tree_has_wp_prop_or_pred = false;
168
241k
  bool is_wp_only = false;
169
241k
  bool is_gradient_only = false;
170
241k
  size_t num_props;
171
241k
  FlatTree tree =
172
241k
      FilterTree(global_tree, static_props, &num_props,
173
241k
                 &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
757k
  for (auto &node : tree) {
178
757k
    if (node.property0 == -1) {
179
628k
      node.childID = context_map[node.childID];
180
628k
    }
181
757k
  }
182
183
241k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
241k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
241k
                             pixel_type_w offset) -> pixel_type {
188
241k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
241k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
241k
    return val * multiplier + offset;
192
241k
  };
193
194
241k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
205k
    Predictor predictor = tree[0].predictor;
198
205k
    int64_t offset = tree[0].predictor_offset;
199
205k
    int32_t multiplier = tree[0].multiplier;
200
205k
    size_t ctx_id = tree[0].childID;
201
205k
    if (predictor == Predictor::Zero) {
202
112k
      uint32_t value;
203
112k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
112k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
27.0k
        JXL_DEBUG_V(8, "Fastest track.");
208
27.0k
        pixel_type v = make_pixel(value, multiplier, offset);
209
677k
        for (size_t y = 0; y < channel.h; y++) {
210
650k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
650k
          std::fill(r, r + channel.w, v);
212
650k
        }
213
85.7k
      } else {
214
85.7k
        JXL_DEBUG_V(8, "Fast track.");
215
85.7k
        if (multiplier == 1 && offset == 0) {
216
1.08M
          for (size_t y = 0; y < channel.h; y++) {
217
1.01M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
53.8M
            for (size_t x = 0; x < channel.w; x++) {
219
52.8M
              uint32_t v =
220
52.8M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
52.8M
              r[x] = UnpackSigned(v);
222
52.8M
            }
223
1.01M
          }
224
67.6k
        } else {
225
377k
          for (size_t y = 0; y < channel.h; y++) {
226
359k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
19.1M
            for (size_t x = 0; x < channel.w; x++) {
228
18.7M
              uint32_t v =
229
18.7M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
18.7M
                                                                         br);
231
18.7M
              r[x] = make_pixel(v, multiplier, offset);
232
18.7M
            }
233
359k
          }
234
18.0k
        }
235
85.7k
      }
236
112k
      return true;
237
112k
    } 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
92.6k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
5.67k
               multiplier == 1) {
273
5.17k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
5.17k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
159k
      for (size_t y = 0; y < channel.h; y++) {
276
154k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.68M
        for (size_t x = 0; x < channel.w; x++) {
278
2.53M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.53M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.53M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.53M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.53M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.53M
              ctx_id, br);
284
2.53M
          r[x] = make_pixel(v, 1, guess);
285
2.53M
        }
286
154k
      }
287
5.17k
      return true;
288
5.17k
    }
289
205k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
123k
  if (is_wp_only) {
294
14.7k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
14.7k
  }
296
123k
  if (is_gradient_only) {
297
4.75k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
4.75k
  }
299
300
123k
  if (is_gradient_only) {
301
3.53k
    JXL_DEBUG_V(8, "Gradient fast track.");
302
3.53k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
134k
    for (size_t y = 0; y < channel.h; y++) {
304
131k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
3.14M
      for (size_t x = 0; x < channel.w; x++) {
306
3.01M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
3.01M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
3.01M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
3.01M
        int32_t guess = ClampedGradient(top, left, topleft);
310
3.01M
        uint32_t pos =
311
3.01M
            kPropRangeFast +
312
3.01M
            std::min<pixel_type_w>(
313
3.01M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
3.01M
                kPropRangeFast - 1);
315
3.01M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
3.01M
        uint64_t v =
317
3.01M
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
3.01M
        r[x] = make_pixel(v, 1, guess);
319
3.01M
      }
320
131k
    }
321
119k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
7.51k
    JXL_DEBUG_V(8, "WP fast track.");
323
7.51k
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
7.51k
    Properties properties(1);
325
214k
    for (size_t y = 0; y < channel.h; y++) {
326
206k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
206k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
206k
      const pixel_type *JXL_RESTRICT rtoptop =
329
206k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
206k
      const pixel_type *JXL_RESTRICT rtopleft =
331
206k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
206k
      const pixel_type *JXL_RESTRICT rtopright =
333
206k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
206k
      size_t x = 0;
335
206k
      {
336
206k
        size_t offset = 0;
337
206k
        pixel_type_w left = y ? rtop[x] : 0;
338
206k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
206k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
206k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
206k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
206k
            offset);
343
206k
        uint32_t pos =
344
206k
            kPropRangeFast +
345
206k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
206k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
206k
        uint64_t v =
348
206k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
206k
        r[x] = make_pixel(v, 1, guess);
350
206k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
206k
      }
352
10.5M
      for (x = 1; x + 1 < channel.w; x++) {
353
10.2M
        size_t offset = 0;
354
10.2M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
10.2M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
10.2M
            rtoptop[x], &properties, offset);
357
10.2M
        uint32_t pos =
358
10.2M
            kPropRangeFast +
359
10.2M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
10.2M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
10.2M
        uint64_t v =
362
10.2M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
10.2M
        r[x] = make_pixel(v, 1, guess);
364
10.2M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
10.2M
      }
366
206k
      {
367
206k
        size_t offset = 0;
368
206k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
206k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
206k
            rtoptop[x], &properties, offset);
371
206k
        uint32_t pos =
372
206k
            kPropRangeFast +
373
206k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
206k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
206k
        uint64_t v =
376
206k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
206k
        r[x] = make_pixel(v, 1, guess);
378
206k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
206k
      }
380
206k
    }
381
112k
  } 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
91.8k
    JXL_DEBUG_V(8, "Slow track.");
385
91.8k
    MATreeLookup tree_lookup(tree);
386
91.8k
    Properties properties = Properties(num_props);
387
91.8k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
91.8k
    JXL_ASSIGN_OR_RETURN(
389
91.8k
        Channel references,
390
91.8k
        Channel::Create(memory_manager,
391
91.8k
                        properties.size() - kNumNonrefProperties, channel.w));
392
2.81M
    for (size_t y = 0; y < channel.h; y++) {
393
2.72M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
2.72M
      PrecomputeReferences(channel, y, *image, chan, &references);
395
2.72M
      InitPropsRow(&properties, static_props, y);
396
2.72M
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
6.73M
        for (size_t x = 0; x < 2; x++) {
398
4.49M
          PredictionResult res =
399
4.49M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
4.49M
                              tree_lookup, references);
401
4.49M
          uint64_t v =
402
4.49M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
4.49M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
4.49M
        }
405
157M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
155M
          PredictionResult res =
407
155M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
155M
                                 tree_lookup, references);
409
155M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
155M
              res.context, br);
411
155M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
155M
        }
413
6.73M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
4.49M
          PredictionResult res =
415
4.49M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
4.49M
                              tree_lookup, references);
417
4.49M
          uint64_t v =
418
4.49M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
4.49M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
4.49M
        }
421
2.24M
      } else {
422
11.6M
        for (size_t x = 0; x < channel.w; x++) {
423
11.1M
          PredictionResult res =
424
11.1M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
11.1M
                              tree_lookup, references);
426
11.1M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
11.1M
              res.context, br);
428
11.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
11.1M
        }
430
479k
      }
431
2.72M
    }
432
91.8k
  } else {
433
20.4k
    JXL_DEBUG_V(8, "Slowest track.");
434
20.4k
    MATreeLookup tree_lookup(tree);
435
20.4k
    Properties properties = Properties(num_props);
436
20.4k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
20.4k
    JXL_ASSIGN_OR_RETURN(
438
20.4k
        Channel references,
439
20.4k
        Channel::Create(memory_manager,
440
20.4k
                        properties.size() - kNumNonrefProperties, channel.w));
441
20.4k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
1.33M
    for (size_t y = 0; y < channel.h; y++) {
443
1.31M
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
1.31M
      InitPropsRow(&properties, static_props, y);
445
1.31M
      PrecomputeReferences(channel, y, *image, chan, &references);
446
1.31M
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
1.29M
        for (size_t x = 0; x < 2; x++) {
448
865k
          PredictionResult res =
449
865k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
865k
                            tree_lookup, references, &wp_state);
451
865k
          uint64_t v =
452
865k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
865k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
865k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
865k
        }
456
48.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
47.7M
          PredictionResult res =
458
47.7M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
47.7M
                               tree_lookup, references, &wp_state);
460
47.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
47.7M
              res.context, br);
462
47.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
47.7M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
47.7M
        }
465
1.29M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
865k
          PredictionResult res =
467
865k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
865k
                            tree_lookup, references, &wp_state);
469
865k
          uint64_t v =
470
865k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
865k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
865k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
865k
        }
474
880k
      } else {
475
6.94M
        for (size_t x = 0; x < channel.w; x++) {
476
6.06M
          PredictionResult res =
477
6.06M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
6.06M
                            tree_lookup, references, &wp_state);
479
6.06M
          uint64_t v =
480
6.06M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
6.06M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
6.06M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
6.06M
        }
484
880k
      }
485
1.31M
    }
486
20.4k
  }
487
123k
  return true;
488
123k
}
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
307k
                                 uint32_t &fl_v) {
499
307k
  if (reader->UsesLZ77()) {
500
66.6k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
66.6k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
66.6k
        tree_lut, image, fl_run, fl_v);
503
241k
  } else {
504
241k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
241k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
241k
        tree_lut, image, fl_run, fl_v);
507
241k
  }
508
307k
}
509
510
462k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
73.6k
                                 const ModularOptions &options) {
514
73.6k
  size_t nb_channels = image.channel.size();
515
147k
  for (bool is_dc : {true, false}) {
516
147k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
147k
    size_t c = image.nb_meta_channels;
518
938k
    for (; c < nb_channels; c++) {
519
793k
      const Channel &ch = image.channel[c];
520
793k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
793k
    }
522
158k
    for (; c < nb_channels; c++) {
523
11.5k
      const Channel &ch = image.channel[c];
524
11.5k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
10.9k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
10.9k
      if (is_dc_channel != is_dc) continue;
527
5.49k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
5.49k
      if (tile_dim == 0) {
529
7
        return JXL_FAILURE("Inconsistent transforms");
530
7
      }
531
5.49k
    }
532
147k
  }
533
73.6k
  return true;
534
73.6k
}
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
119k
                     const bool allow_truncated_group) {
541
119k
  if (image.channel.empty()) return true;
542
85.7k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
85.7k
  Status status = Bundle::Read(br, &header);
546
85.7k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
72.3k
  if (status.IsFatalError()) return status;
548
72.3k
  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
72.3k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
72.3k
              header.transforms.size());
560
72.3k
  image.transform = header.transforms;
561
72.3k
  for (Transform &transform : image.transform) {
562
22.9k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
22.9k
  }
564
71.5k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
71.5k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
71.5k
  size_t nb_channels = image.channel.size();
570
571
71.5k
  size_t num_chans = 0;
572
71.5k
  size_t distance_multiplier = 0;
573
465k
  for (size_t i = 0; i < nb_channels; i++) {
574
394k
    Channel &channel = image.channel[i];
575
394k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
389k
                                        channel.h > options->max_chan_size)) {
577
962
      break;
578
962
    }
579
393k
    if (!channel.w || !channel.h) {
580
19.2k
      continue;  // skip empty channels
581
19.2k
    }
582
374k
    if (channel.w > distance_multiplier) {
583
94.8k
      distance_multiplier = channel.w;
584
94.8k
    }
585
374k
    num_chans++;
586
374k
  }
587
71.5k
  if (num_chans == 0) return true;
588
589
70.8k
  size_t next_channel = 0;
590
70.8k
  auto scope_guard = MakeScopeGuard([&]() {
591
92.5k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
74.0k
      ZeroFillImage(&image.channel[c].plane);
593
74.0k
    }
594
18.4k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
70.8k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
70.8k
  Tree tree_storage;
600
70.8k
  std::vector<uint8_t> context_map_storage;
601
70.8k
  ANSCode code_storage;
602
70.8k
  const Tree *tree = &tree_storage;
603
70.8k
  const ANSCode *code = &code_storage;
604
70.8k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
70.8k
  if (!header.use_global_tree) {
606
51.7k
    uint64_t max_tree_size = 1024;
607
328k
    for (size_t i = 0; i < nb_channels; i++) {
608
277k
      Channel &channel = image.channel[i];
609
277k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
273k
                                          channel.h > options->max_chan_size)) {
611
123
        break;
612
123
      }
613
277k
      uint64_t pixels = channel.w * channel.h;
614
277k
      max_tree_size += pixels;
615
277k
    }
616
51.7k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
51.7k
    JXL_RETURN_IF_ERROR(
618
51.7k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
40.7k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
40.7k
                                         (tree_storage.size() + 1) / 2,
621
40.7k
                                         &code_storage, &context_map_storage));
622
40.7k
  } else {
623
19.0k
    if (!global_tree || !global_code || !global_ctx_map ||
624
19.0k
        global_tree->empty()) {
625
1.35k
      return JXL_FAILURE("No global tree available but one was requested");
626
1.35k
    }
627
17.7k
    tree = global_tree;
628
17.7k
    code = global_code;
629
17.7k
    context_map = global_ctx_map;
630
17.7k
  }
631
632
  // Read channels
633
116k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
116k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
116k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
116k
  uint32_t fl_run = 0;
637
116k
  uint32_t fl_v = 0;
638
378k
  for (; next_channel < nb_channels; next_channel++) {
639
326k
    Channel &channel = image.channel[next_channel];
640
326k
    if (next_channel >= image.nb_meta_channels &&
641
321k
        (channel.w > options->max_chan_size ||
642
321k
         channel.h > options->max_chan_size)) {
643
213
      break;
644
213
    }
645
326k
    if (!channel.w || !channel.h) {
646
18.1k
      continue;  // skip empty channels
647
18.1k
    }
648
307k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
307k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
307k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
307k
    if (!br->AllReadsWithinBounds()) {
654
5.81k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
5.81k
    }
657
307k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
52.3k
  scope_guard.Disarm();
661
662
52.3k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
52.3k
  return true;
666
52.3k
}
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
119k
                                bool allow_truncated_group) {
674
119k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
119k
  req_sizes.reserve(image.channel.size());
676
275k
  for (const auto &c : image.channel) {
677
275k
    req_sizes.emplace_back(c.w, c.h);
678
275k
  }
679
119k
  GroupHeader local_header;
680
119k
  if (header == nullptr) header = &local_header;
681
119k
  size_t bit_pos = br->TotalBitsConsumed();
682
119k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
119k
                                  code, ctx_map, allow_truncated_group);
684
119k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
86.7k
  if (dec_status.IsFatalError()) return dec_status;
686
86.7k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
86.7k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
86.7k
  JXL_DEBUG_V(4,
689
86.7k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
86.7k
              " image from %" PRIuS " bytes",
691
86.7k
              image.w, image.h, image.channel.size(),
692
86.7k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
86.7k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
86.7k
  (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
86.7k
  if (undo_transforms) {
699
21.7k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
91.8k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
70.0k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
70.0k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
70.0k
    }
704
21.7k
  }
705
86.7k
  return dec_status;
706
86.7k
}
707
708
}  // namespace jxl