Coverage Report

Created: 2025-12-13 07:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/modular/encoding/encoding.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/modular/encoding/encoding.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <array>
12
#include <cstddef>
13
#include <cstdint>
14
#include <cstdlib>
15
#include <queue>
16
#include <utility>
17
#include <vector>
18
19
#include "lib/jxl/base/common.h"
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/printf_macros.h"
22
#include "lib/jxl/base/scope_guard.h"
23
#include "lib/jxl/base/status.h"
24
#include "lib/jxl/dec_ans.h"
25
#include "lib/jxl/dec_bit_reader.h"
26
#include "lib/jxl/fields.h"
27
#include "lib/jxl/frame_dimensions.h"
28
#include "lib/jxl/image_ops.h"
29
#include "lib/jxl/modular/encoding/context_predict.h"
30
#include "lib/jxl/modular/encoding/dec_ma.h"
31
#include "lib/jxl/modular/modular_image.h"
32
#include "lib/jxl/modular/options.h"
33
#include "lib/jxl/modular/transform/transform.h"
34
#include "lib/jxl/pack_signed.h"
35
36
namespace jxl {
37
38
// Removes all nodes that use a static property (i.e. channel or group ID) from
39
// the tree and collapses each node on even levels with its two children to
40
// produce a flatter tree. Also computes whether the resulting tree requires
41
// using the weighted predictor.
42
FlatTree FilterTree(const Tree &global_tree,
43
                    std::array<pixel_type, kNumStaticProperties> &static_props,
44
                    size_t *num_props, bool *use_wp, bool *wp_only,
45
363k
                    bool *gradient_only) {
46
363k
  *num_props = 0;
47
363k
  bool has_wp = false;
48
363k
  bool has_non_wp = false;
49
363k
  *gradient_only = true;
50
917k
  const auto mark_property = [&](int32_t p) {
51
917k
    if (p == kWPProp) {
52
93.0k
      has_wp = true;
53
824k
    } else if (p >= kNumStaticProperties) {
54
500k
      has_non_wp = true;
55
500k
    }
56
917k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
543k
      *gradient_only = false;
58
543k
    }
59
917k
  };
60
363k
  FlatTree output;
61
363k
  std::queue<size_t> nodes;
62
363k
  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.94M
  while (!nodes.empty()) {
70
1.58M
    size_t cur = nodes.front();
71
1.58M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.63M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.32M
           global_tree[cur].property != -1) {
75
44.8k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
25.8k
        cur = global_tree[cur].lchild;
77
25.8k
      } else {
78
19.0k
        cur = global_tree[cur].rchild;
79
19.0k
      }
80
44.8k
    }
81
1.58M
    FlatDecisionNode flat;
82
1.58M
    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
305k
    flat.childID = output.size() + nodes.size() + 1;
95
96
305k
    flat.property0 = global_tree[cur].property;
97
305k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
305k
    flat.splitval0 = global_tree[cur].splitval;
99
100
917k
    for (size_t i = 0; i < 2; i++) {
101
611k
      size_t cur_child =
102
611k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
624k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
337k
             global_tree[cur_child].property != -1) {
106
12.7k
        if (static_props[global_tree[cur_child].property] >
107
12.7k
            global_tree[cur_child].splitval) {
108
8.64k
          cur_child = global_tree[cur_child].lchild;
109
8.64k
        } else {
110
4.11k
          cur_child = global_tree[cur_child].rchild;
111
4.11k
        }
112
12.7k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
611k
      if (global_tree[cur_child].property == -1) {
116
324k
        flat.properties[i] = 0;
117
324k
        flat.splitvals[i] = 0;
118
324k
        nodes.push(cur_child);
119
324k
        nodes.push(cur_child);
120
324k
      } else {
121
287k
        flat.properties[i] = global_tree[cur_child].property;
122
287k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
287k
        nodes.push(global_tree[cur_child].lchild);
124
287k
        nodes.push(global_tree[cur_child].rchild);
125
287k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
287k
      }
127
611k
    }
128
129
611k
    for (int16_t property : flat.properties) mark_property(property);
130
305k
    mark_property(flat.property0);
131
305k
    output.push_back(flat);
132
305k
  }
133
363k
  if (*num_props > kNumNonrefProperties) {
134
1.22k
    *num_props =
135
1.22k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.22k
            kExtraPropsPerChannel +
137
1.22k
        kNumNonrefProperties;
138
362k
  } else {
139
362k
    *num_props = kNumNonrefProperties;
140
362k
  }
141
363k
  *use_wp = has_wp;
142
363k
  *wp_only = has_wp && !has_non_wp;
143
144
363k
  return output;
145
363k
}
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
345k
                                 uint32_t &fl_v) {
157
345k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
345k
  Channel &channel = image->channel[chan];
159
160
345k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
345k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
345k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
345k
  bool tree_has_wp_prop_or_pred = false;
168
345k
  bool is_wp_only = false;
169
345k
  bool is_gradient_only = false;
170
345k
  size_t num_props;
171
345k
  FlatTree tree =
172
345k
      FilterTree(global_tree, static_props, &num_props,
173
345k
                 &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
491k
  for (auto &node : tree) {
178
491k
    if (node.property0 == -1) {
179
455k
      node.childID = context_map[node.childID];
180
455k
    }
181
491k
  }
182
183
345k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
345k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
228M
                             pixel_type_w offset) -> pixel_type {
188
228M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
228M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
228M
    return val * multiplier + offset;
192
228M
  };
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
39.3M
                             pixel_type_w offset) -> pixel_type {
188
39.3M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
39.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
39.3M
    return val * multiplier + offset;
192
39.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
189M
                             pixel_type_w offset) -> pixel_type {
188
189M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
189M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
189M
    return val * multiplier + offset;
192
189M
  };
193
194
345k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
336k
    Predictor predictor = tree[0].predictor;
198
336k
    int64_t offset = tree[0].predictor_offset;
199
336k
    int32_t multiplier = tree[0].multiplier;
200
336k
    size_t ctx_id = tree[0].childID;
201
336k
    if (predictor == Predictor::Zero) {
202
318k
      uint32_t value;
203
318k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
318k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
143k
        JXL_DEBUG_V(8, "Fastest track.");
208
143k
        pixel_type v = make_pixel(value, multiplier, offset);
209
4.12M
        for (size_t y = 0; y < channel.h; y++) {
210
3.97M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
3.97M
          std::fill(r, r + channel.w, v);
212
3.97M
        }
213
175k
      } else {
214
175k
        JXL_DEBUG_V(8, "Fast track.");
215
175k
        if (multiplier == 1 && offset == 0) {
216
2.84M
          for (size_t y = 0; y < channel.h; y++) {
217
2.70M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
217M
            for (size_t x = 0; x < channel.w; x++) {
219
214M
              uint32_t v =
220
214M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
214M
              r[x] = UnpackSigned(v);
222
214M
            }
223
2.70M
          }
224
144k
        } else {
225
1.38M
          for (size_t y = 0; y < channel.h; y++) {
226
1.34M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
154M
            for (size_t x = 0; x < channel.w; x++) {
228
153M
              uint32_t v =
229
153M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
153M
                                                                         br);
231
153M
              r[x] = make_pixel(v, multiplier, offset);
232
153M
            }
233
1.34M
          }
234
30.2k
        }
235
175k
      }
236
318k
      return true;
237
318k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.06k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
342
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
342
      pixel_type_w sv = UnpackSigned(fl_v);
241
12.2k
      for (size_t y = 0; y < channel.h; y++) {
242
11.9k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
11.9k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
11.9k
        const pixel_type *JXL_RESTRICT rtopleft =
245
11.9k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
11.9k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
11.9k
        if (fl_run == 0) {
248
4.05k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
4.05k
                                                     &fl_run);
250
4.05k
          sv = UnpackSigned(fl_v);
251
7.87k
        } else {
252
7.87k
          fl_run--;
253
7.87k
        }
254
11.9k
        r[0] = sv + guess_0;
255
343k
        for (size_t x = 1; x < channel.w; x++) {
256
331k
          pixel_type left = r[x - 1];
257
331k
          pixel_type top = rtop[x];
258
331k
          pixel_type topleft = rtopleft[x];
259
331k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
331k
          if (!fl_run) {
261
113k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
113k
                                                       &fl_run);
263
113k
            sv = UnpackSigned(fl_v);
264
217k
          } else {
265
217k
            fl_run--;
266
217k
          }
267
331k
          r[x] = sv + guess;
268
331k
        }
269
11.9k
      }
270
342
      return true;
271
17.6k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
2.25k
               multiplier == 1) {
273
2.02k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
2.02k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
48.5k
      for (size_t y = 0; y < channel.h; y++) {
276
46.5k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.65M
        for (size_t x = 0; x < channel.w; x++) {
278
2.60M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.60M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.60M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.60M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.60M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.60M
              ctx_id, br);
284
2.60M
          r[x] = make_pixel(v, 1, guess);
285
2.60M
        }
286
46.5k
      }
287
2.02k
      return true;
288
2.02k
    }
289
336k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
24.3k
  if (is_wp_only) {
294
3.01k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
3.01k
  }
296
24.3k
  if (is_gradient_only) {
297
1.49k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.49k
  }
299
300
24.3k
  if (is_gradient_only) {
301
531
    JXL_DEBUG_V(8, "Gradient fast track.");
302
531
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
11.5k
    for (size_t y = 0; y < channel.h; y++) {
304
10.9k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
284k
      for (size_t x = 0; x < channel.w; x++) {
306
273k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
273k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
273k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
273k
        int32_t guess = ClampedGradient(top, left, topleft);
310
273k
        uint32_t pos =
311
273k
            kPropRangeFast +
312
273k
            std::min<pixel_type_w>(
313
273k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
273k
                kPropRangeFast - 1);
315
273k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
273k
        uint64_t v =
317
273k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
273k
        r[x] = make_pixel(v, 1, guess);
319
273k
      }
320
10.9k
    }
321
23.8k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
521
    JXL_DEBUG_V(8, "WP fast track.");
323
521
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
521
    Properties properties(1);
325
11.6k
    for (size_t y = 0; y < channel.h; y++) {
326
11.1k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
11.1k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
11.1k
      const pixel_type *JXL_RESTRICT rtoptop =
329
11.1k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
11.1k
      const pixel_type *JXL_RESTRICT rtopleft =
331
11.1k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
11.1k
      const pixel_type *JXL_RESTRICT rtopright =
333
11.1k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
11.1k
      size_t x = 0;
335
11.1k
      {
336
11.1k
        size_t offset = 0;
337
11.1k
        pixel_type_w left = y ? rtop[x] : 0;
338
11.1k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
11.1k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
11.1k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
11.1k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
11.1k
            offset);
343
11.1k
        uint32_t pos =
344
11.1k
            kPropRangeFast +
345
11.1k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
11.1k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
11.1k
        uint64_t v =
348
11.1k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
11.1k
        r[x] = make_pixel(v, 1, guess);
350
11.1k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
11.1k
      }
352
1.01M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.00M
        size_t offset = 0;
354
1.00M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.00M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.00M
            rtoptop[x], &properties, offset);
357
1.00M
        uint32_t pos =
358
1.00M
            kPropRangeFast +
359
1.00M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.00M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.00M
        uint64_t v =
362
1.00M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.00M
        r[x] = make_pixel(v, 1, guess);
364
1.00M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.00M
      }
366
11.1k
      {
367
11.1k
        size_t offset = 0;
368
11.1k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
11.1k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
11.1k
            rtoptop[x], &properties, offset);
371
11.1k
        uint32_t pos =
372
11.1k
            kPropRangeFast +
373
11.1k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
11.1k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
11.1k
        uint64_t v =
376
11.1k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
11.1k
        r[x] = make_pixel(v, 1, guess);
378
11.1k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
11.1k
      }
380
11.1k
    }
381
23.3k
  } else if (!tree_has_wp_prop_or_pred) {
382
    // special optimized case: the weighted predictor and its properties are not
383
    // used, so no need to compute weights and properties.
384
16.2k
    JXL_DEBUG_V(8, "Slow track.");
385
16.2k
    MATreeLookup tree_lookup(tree);
386
16.2k
    Properties properties = Properties(num_props);
387
16.2k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
16.2k
    JXL_ASSIGN_OR_RETURN(
389
16.2k
        Channel references,
390
16.2k
        Channel::Create(memory_manager,
391
16.2k
                        properties.size() - kNumNonrefProperties, channel.w));
392
575k
    for (size_t y = 0; y < channel.h; y++) {
393
559k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
559k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
559k
      InitPropsRow(&properties, static_props, y);
396
559k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.42M
        for (size_t x = 0; x < 2; x++) {
398
951k
          PredictionResult res =
399
951k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
951k
                              tree_lookup, references);
401
951k
          uint64_t v =
402
951k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
951k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
951k
        }
405
51.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
51.2M
          PredictionResult res =
407
51.2M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
51.2M
                                 tree_lookup, references);
409
51.2M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
51.2M
              res.context, br);
411
51.2M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
51.2M
        }
413
1.42M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
951k
          PredictionResult res =
415
951k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
951k
                              tree_lookup, references);
417
951k
          uint64_t v =
418
951k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
951k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
951k
        }
421
475k
      } else {
422
1.70M
        for (size_t x = 0; x < channel.w; x++) {
423
1.61M
          PredictionResult res =
424
1.61M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.61M
                              tree_lookup, references);
426
1.61M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.61M
              res.context, br);
428
1.61M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.61M
        }
430
83.7k
      }
431
559k
    }
432
16.2k
  } else {
433
7.12k
    JXL_DEBUG_V(8, "Slowest track.");
434
7.12k
    MATreeLookup tree_lookup(tree);
435
7.12k
    Properties properties = Properties(num_props);
436
7.12k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
7.12k
    JXL_ASSIGN_OR_RETURN(
438
7.12k
        Channel references,
439
7.12k
        Channel::Create(memory_manager,
440
7.12k
                        properties.size() - kNumNonrefProperties, channel.w));
441
7.12k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
227k
    for (size_t y = 0; y < channel.h; y++) {
443
220k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
220k
      InitPropsRow(&properties, static_props, y);
445
220k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
220k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
549k
        for (size_t x = 0; x < 2; x++) {
448
366k
          PredictionResult res =
449
366k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
366k
                            tree_lookup, references, &wp_state);
451
366k
          uint64_t v =
452
366k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
366k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
366k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
366k
        }
456
13.8M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
13.6M
          PredictionResult res =
458
13.6M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
13.6M
                               tree_lookup, references, &wp_state);
460
13.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
13.6M
              res.context, br);
462
13.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
13.6M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
13.6M
        }
465
549k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
366k
          PredictionResult res =
467
366k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
366k
                            tree_lookup, references, &wp_state);
469
366k
          uint64_t v =
470
366k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
366k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
366k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
366k
        }
474
183k
      } else {
475
2.14M
        for (size_t x = 0; x < channel.w; x++) {
476
2.10M
          PredictionResult res =
477
2.10M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
2.10M
                            tree_lookup, references, &wp_state);
479
2.10M
          uint64_t v =
480
2.10M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
2.10M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
2.10M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
2.10M
        }
484
37.0k
      }
485
220k
    }
486
7.12k
  }
487
24.3k
  return true;
488
24.3k
}
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
27.0k
                                 uint32_t &fl_v) {
157
27.0k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
27.0k
  Channel &channel = image->channel[chan];
159
160
27.0k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
27.0k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
27.0k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
27.0k
  bool tree_has_wp_prop_or_pred = false;
168
27.0k
  bool is_wp_only = false;
169
27.0k
  bool is_gradient_only = false;
170
27.0k
  size_t num_props;
171
27.0k
  FlatTree tree =
172
27.0k
      FilterTree(global_tree, static_props, &num_props,
173
27.0k
                 &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
33.0k
  for (auto &node : tree) {
178
33.0k
    if (node.property0 == -1) {
179
31.5k
      node.childID = context_map[node.childID];
180
31.5k
    }
181
33.0k
  }
182
183
27.0k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
27.0k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
27.0k
                             pixel_type_w offset) -> pixel_type {
188
27.0k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
27.0k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
27.0k
    return val * multiplier + offset;
192
27.0k
  };
193
194
27.0k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
25.6k
    Predictor predictor = tree[0].predictor;
198
25.6k
    int64_t offset = tree[0].predictor_offset;
199
25.6k
    int32_t multiplier = tree[0].multiplier;
200
25.6k
    size_t ctx_id = tree[0].childID;
201
25.6k
    if (predictor == Predictor::Zero) {
202
19.9k
      uint32_t value;
203
19.9k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
19.9k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
5.21k
        JXL_DEBUG_V(8, "Fastest track.");
208
5.21k
        pixel_type v = make_pixel(value, multiplier, offset);
209
213k
        for (size_t y = 0; y < channel.h; y++) {
210
208k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
208k
          std::fill(r, r + channel.w, v);
212
208k
        }
213
14.7k
      } else {
214
14.7k
        JXL_DEBUG_V(8, "Fast track.");
215
14.7k
        if (multiplier == 1 && offset == 0) {
216
278k
          for (size_t y = 0; y < channel.h; y++) {
217
273k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
43.9M
            for (size_t x = 0; x < channel.w; x++) {
219
43.6M
              uint32_t v =
220
43.6M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
43.6M
              r[x] = UnpackSigned(v);
222
43.6M
            }
223
273k
          }
224
10.3k
        } else {
225
325k
          for (size_t y = 0; y < channel.h; y++) {
226
315k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
20.2M
            for (size_t x = 0; x < channel.w; x++) {
228
19.9M
              uint32_t v =
229
19.9M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
19.9M
                                                                         br);
231
19.9M
              r[x] = make_pixel(v, multiplier, offset);
232
19.9M
            }
233
315k
          }
234
10.3k
        }
235
14.7k
      }
236
19.9k
      return true;
237
19.9k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.06k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
342
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
342
      pixel_type_w sv = UnpackSigned(fl_v);
241
12.2k
      for (size_t y = 0; y < channel.h; y++) {
242
11.9k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
11.9k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
11.9k
        const pixel_type *JXL_RESTRICT rtopleft =
245
11.9k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
11.9k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
11.9k
        if (fl_run == 0) {
248
4.05k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
4.05k
                                                     &fl_run);
250
4.05k
          sv = UnpackSigned(fl_v);
251
7.87k
        } else {
252
7.87k
          fl_run--;
253
7.87k
        }
254
11.9k
        r[0] = sv + guess_0;
255
343k
        for (size_t x = 1; x < channel.w; x++) {
256
331k
          pixel_type left = r[x - 1];
257
331k
          pixel_type top = rtop[x];
258
331k
          pixel_type topleft = rtopleft[x];
259
331k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
331k
          if (!fl_run) {
261
113k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
113k
                                                       &fl_run);
263
113k
            sv = UnpackSigned(fl_v);
264
217k
          } else {
265
217k
            fl_run--;
266
217k
          }
267
331k
          r[x] = sv + guess;
268
331k
        }
269
11.9k
      }
270
342
      return true;
271
5.34k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
720
               multiplier == 1) {
273
711
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
711
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
9.41k
      for (size_t y = 0; y < channel.h; y++) {
276
8.70k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
212k
        for (size_t x = 0; x < channel.w; x++) {
278
203k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
203k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
203k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
203k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
203k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
203k
              ctx_id, br);
284
203k
          r[x] = make_pixel(v, 1, guess);
285
203k
        }
286
8.70k
      }
287
711
      return true;
288
711
    }
289
25.6k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
6.01k
  if (is_wp_only) {
294
199
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
199
  }
296
6.01k
  if (is_gradient_only) {
297
430
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
430
  }
299
300
6.01k
  if (is_gradient_only) {
301
49
    JXL_DEBUG_V(8, "Gradient fast track.");
302
49
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
1.30k
    for (size_t y = 0; y < channel.h; y++) {
304
1.25k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
19.7k
      for (size_t x = 0; x < channel.w; x++) {
306
18.5k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
18.5k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
18.5k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
18.5k
        int32_t guess = ClampedGradient(top, left, topleft);
310
18.5k
        uint32_t pos =
311
18.5k
            kPropRangeFast +
312
18.5k
            std::min<pixel_type_w>(
313
18.5k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
18.5k
                kPropRangeFast - 1);
315
18.5k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
18.5k
        uint64_t v =
317
18.5k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
18.5k
        r[x] = make_pixel(v, 1, guess);
319
18.5k
      }
320
1.25k
    }
321
5.96k
  } 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
5.96k
  } 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.56k
    JXL_DEBUG_V(8, "Slow track.");
385
5.56k
    MATreeLookup tree_lookup(tree);
386
5.56k
    Properties properties = Properties(num_props);
387
5.56k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
5.56k
    JXL_ASSIGN_OR_RETURN(
389
5.56k
        Channel references,
390
5.56k
        Channel::Create(memory_manager,
391
5.56k
                        properties.size() - kNumNonrefProperties, channel.w));
392
138k
    for (size_t y = 0; y < channel.h; y++) {
393
132k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
132k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
132k
      InitPropsRow(&properties, static_props, y);
396
132k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
339k
        for (size_t x = 0; x < 2; x++) {
398
226k
          PredictionResult res =
399
226k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
226k
                              tree_lookup, references);
401
226k
          uint64_t v =
402
226k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
226k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
226k
        }
405
17.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
16.9M
          PredictionResult res =
407
16.9M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
16.9M
                                 tree_lookup, references);
409
16.9M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
16.9M
              res.context, br);
411
16.9M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
16.9M
        }
413
339k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
226k
          PredictionResult res =
415
226k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
226k
                              tree_lookup, references);
417
226k
          uint64_t v =
418
226k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
226k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
226k
        }
421
113k
      } else {
422
666k
        for (size_t x = 0; x < channel.w; x++) {
423
647k
          PredictionResult res =
424
647k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
647k
                              tree_lookup, references);
426
647k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
647k
              res.context, br);
428
647k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
647k
        }
430
19.2k
      }
431
132k
    }
432
5.56k
  } else {
433
400
    JXL_DEBUG_V(8, "Slowest track.");
434
400
    MATreeLookup tree_lookup(tree);
435
400
    Properties properties = Properties(num_props);
436
400
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
400
    JXL_ASSIGN_OR_RETURN(
438
400
        Channel references,
439
400
        Channel::Create(memory_manager,
440
400
                        properties.size() - kNumNonrefProperties, channel.w));
441
400
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
8.96k
    for (size_t y = 0; y < channel.h; y++) {
443
8.56k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
8.56k
      InitPropsRow(&properties, static_props, y);
445
8.56k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
8.56k
      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.56k
      } else {
475
1.13M
        for (size_t x = 0; x < channel.w; x++) {
476
1.12M
          PredictionResult res =
477
1.12M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.12M
                            tree_lookup, references, &wp_state);
479
1.12M
          uint64_t v =
480
1.12M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.12M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.12M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.12M
        }
484
8.56k
      }
485
8.56k
    }
486
400
  }
487
6.01k
  return true;
488
6.01k
}
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
318k
                                 uint32_t &fl_v) {
157
318k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
318k
  Channel &channel = image->channel[chan];
159
160
318k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
318k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
318k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
318k
  bool tree_has_wp_prop_or_pred = false;
168
318k
  bool is_wp_only = false;
169
318k
  bool is_gradient_only = false;
170
318k
  size_t num_props;
171
318k
  FlatTree tree =
172
318k
      FilterTree(global_tree, static_props, &num_props,
173
318k
                 &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
458k
  for (auto &node : tree) {
178
458k
    if (node.property0 == -1) {
179
423k
      node.childID = context_map[node.childID];
180
423k
    }
181
458k
  }
182
183
318k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
318k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
318k
                             pixel_type_w offset) -> pixel_type {
188
318k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
318k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
318k
    return val * multiplier + offset;
192
318k
  };
193
194
318k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
310k
    Predictor predictor = tree[0].predictor;
198
310k
    int64_t offset = tree[0].predictor_offset;
199
310k
    int32_t multiplier = tree[0].multiplier;
200
310k
    size_t ctx_id = tree[0].childID;
201
310k
    if (predictor == Predictor::Zero) {
202
298k
      uint32_t value;
203
298k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
298k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
138k
        JXL_DEBUG_V(8, "Fastest track.");
208
138k
        pixel_type v = make_pixel(value, multiplier, offset);
209
3.90M
        for (size_t y = 0; y < channel.h; y++) {
210
3.77M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
3.77M
          std::fill(r, r + channel.w, v);
212
3.77M
        }
213
160k
      } else {
214
160k
        JXL_DEBUG_V(8, "Fast track.");
215
160k
        if (multiplier == 1 && offset == 0) {
216
2.56M
          for (size_t y = 0; y < channel.h; y++) {
217
2.42M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
173M
            for (size_t x = 0; x < channel.w; x++) {
219
170M
              uint32_t v =
220
170M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
170M
              r[x] = UnpackSigned(v);
222
170M
            }
223
2.42M
          }
224
140k
        } else {
225
1.05M
          for (size_t y = 0; y < channel.h; y++) {
226
1.03M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
134M
            for (size_t x = 0; x < channel.w; x++) {
228
133M
              uint32_t v =
229
133M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
133M
                                                                         br);
231
133M
              r[x] = make_pixel(v, multiplier, offset);
232
133M
            }
233
1.03M
          }
234
19.9k
        }
235
160k
      }
236
298k
      return true;
237
298k
    } 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
12.2k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.53k
               multiplier == 1) {
273
1.31k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.31k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
39.1k
      for (size_t y = 0; y < channel.h; y++) {
276
37.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.44M
        for (size_t x = 0; x < channel.w; x++) {
278
2.40M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.40M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.40M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.40M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.40M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.40M
              ctx_id, br);
284
2.40M
          r[x] = make_pixel(v, 1, guess);
285
2.40M
        }
286
37.8k
      }
287
1.31k
      return true;
288
1.31k
    }
289
310k
  }
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
2.82k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
2.82k
  }
296
18.3k
  if (is_gradient_only) {
297
1.06k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.06k
  }
299
300
18.3k
  if (is_gradient_only) {
301
482
    JXL_DEBUG_V(8, "Gradient fast track.");
302
482
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
10.2k
    for (size_t y = 0; y < channel.h; y++) {
304
9.72k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
265k
      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
9.72k
    }
321
17.8k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
521
    JXL_DEBUG_V(8, "WP fast track.");
323
521
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
521
    Properties properties(1);
325
11.6k
    for (size_t y = 0; y < channel.h; y++) {
326
11.1k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
11.1k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
11.1k
      const pixel_type *JXL_RESTRICT rtoptop =
329
11.1k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
11.1k
      const pixel_type *JXL_RESTRICT rtopleft =
331
11.1k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
11.1k
      const pixel_type *JXL_RESTRICT rtopright =
333
11.1k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
11.1k
      size_t x = 0;
335
11.1k
      {
336
11.1k
        size_t offset = 0;
337
11.1k
        pixel_type_w left = y ? rtop[x] : 0;
338
11.1k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
11.1k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
11.1k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
11.1k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
11.1k
            offset);
343
11.1k
        uint32_t pos =
344
11.1k
            kPropRangeFast +
345
11.1k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
11.1k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
11.1k
        uint64_t v =
348
11.1k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
11.1k
        r[x] = make_pixel(v, 1, guess);
350
11.1k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
11.1k
      }
352
1.01M
      for (x = 1; x + 1 < channel.w; x++) {
353
1.00M
        size_t offset = 0;
354
1.00M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
1.00M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
1.00M
            rtoptop[x], &properties, offset);
357
1.00M
        uint32_t pos =
358
1.00M
            kPropRangeFast +
359
1.00M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
1.00M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
1.00M
        uint64_t v =
362
1.00M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
1.00M
        r[x] = make_pixel(v, 1, guess);
364
1.00M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
1.00M
      }
366
11.1k
      {
367
11.1k
        size_t offset = 0;
368
11.1k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
11.1k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
11.1k
            rtoptop[x], &properties, offset);
371
11.1k
        uint32_t pos =
372
11.1k
            kPropRangeFast +
373
11.1k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
11.1k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
11.1k
        uint64_t v =
376
11.1k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
11.1k
        r[x] = make_pixel(v, 1, guess);
378
11.1k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
11.1k
      }
380
11.1k
    }
381
17.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
10.6k
    JXL_DEBUG_V(8, "Slow track.");
385
10.6k
    MATreeLookup tree_lookup(tree);
386
10.6k
    Properties properties = Properties(num_props);
387
10.6k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
10.6k
    JXL_ASSIGN_OR_RETURN(
389
10.6k
        Channel references,
390
10.6k
        Channel::Create(memory_manager,
391
10.6k
                        properties.size() - kNumNonrefProperties, channel.w));
392
437k
    for (size_t y = 0; y < channel.h; y++) {
393
426k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
426k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
426k
      InitPropsRow(&properties, static_props, y);
396
426k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.08M
        for (size_t x = 0; x < 2; x++) {
398
724k
          PredictionResult res =
399
724k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
724k
                              tree_lookup, references);
401
724k
          uint64_t v =
402
724k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
724k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
724k
        }
405
34.7M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
34.3M
          PredictionResult res =
407
34.3M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
34.3M
                                 tree_lookup, references);
409
34.3M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
34.3M
              res.context, br);
411
34.3M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
34.3M
        }
413
1.08M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
724k
          PredictionResult res =
415
724k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
724k
                              tree_lookup, references);
417
724k
          uint64_t v =
418
724k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
724k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
724k
        }
421
362k
      } else {
422
1.03M
        for (size_t x = 0; x < channel.w; x++) {
423
971k
          PredictionResult res =
424
971k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
971k
                              tree_lookup, references);
426
971k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
971k
              res.context, br);
428
971k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
971k
        }
430
64.5k
      }
431
426k
    }
432
10.6k
  } else {
433
6.72k
    JXL_DEBUG_V(8, "Slowest track.");
434
6.72k
    MATreeLookup tree_lookup(tree);
435
6.72k
    Properties properties = Properties(num_props);
436
6.72k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
6.72k
    JXL_ASSIGN_OR_RETURN(
438
6.72k
        Channel references,
439
6.72k
        Channel::Create(memory_manager,
440
6.72k
                        properties.size() - kNumNonrefProperties, channel.w));
441
6.72k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
218k
    for (size_t y = 0; y < channel.h; y++) {
443
211k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
211k
      InitPropsRow(&properties, static_props, y);
445
211k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
211k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
549k
        for (size_t x = 0; x < 2; x++) {
448
366k
          PredictionResult res =
449
366k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
366k
                            tree_lookup, references, &wp_state);
451
366k
          uint64_t v =
452
366k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
366k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
366k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
366k
        }
456
13.8M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
13.6M
          PredictionResult res =
458
13.6M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
13.6M
                               tree_lookup, references, &wp_state);
460
13.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
13.6M
              res.context, br);
462
13.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
13.6M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
13.6M
        }
465
549k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
366k
          PredictionResult res =
467
366k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
366k
                            tree_lookup, references, &wp_state);
469
366k
          uint64_t v =
470
366k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
366k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
366k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
366k
        }
474
183k
      } else {
475
1.01M
        for (size_t x = 0; x < channel.w; x++) {
476
987k
          PredictionResult res =
477
987k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
987k
                            tree_lookup, references, &wp_state);
479
987k
          uint64_t v =
480
987k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
987k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
987k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
987k
        }
484
28.5k
      }
485
211k
    }
486
6.72k
  }
487
18.3k
  return true;
488
18.3k
}
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
345k
                                 uint32_t &fl_v) {
499
345k
  if (reader->UsesLZ77()) {
500
27.0k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
27.0k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
27.0k
        tree_lut, image, fl_run, fl_v);
503
318k
  } else {
504
318k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
318k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
318k
        tree_lut, image, fl_run, fl_v);
507
318k
  }
508
345k
}
509
510
157k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
38.0k
                                 const ModularOptions &options) {
514
38.0k
  size_t nb_channels = image.channel.size();
515
76.1k
  for (bool is_dc : {true, false}) {
516
76.1k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
76.1k
    size_t c = image.nb_meta_channels;
518
783k
    for (; c < nb_channels; c++) {
519
710k
      const Channel &ch = image.channel[c];
520
710k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
710k
    }
522
100k
    for (; c < nb_channels; c++) {
523
24.5k
      const Channel &ch = image.channel[c];
524
24.5k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
23.9k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
23.9k
      if (is_dc_channel != is_dc) continue;
527
11.9k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
11.9k
      if (tile_dim == 0) {
529
1
        return JXL_FAILURE("Inconsistent transforms");
530
1
      }
531
11.9k
    }
532
76.1k
  }
533
38.0k
  return true;
534
38.0k
}
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
42.2k
                     const bool allow_truncated_group) {
541
42.2k
  if (image.channel.empty()) return true;
542
36.7k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
36.7k
  Status status = Bundle::Read(br, &header);
546
36.7k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
36.4k
  if (status.IsFatalError()) return status;
548
36.4k
  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
36.4k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
36.4k
              header.transforms.size());
560
36.4k
  image.transform = header.transforms;
561
36.4k
  for (Transform &transform : image.transform) {
562
21.9k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
21.9k
  }
564
36.4k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
36.4k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
36.4k
  size_t nb_channels = image.channel.size();
570
571
36.4k
  size_t num_chans = 0;
572
36.4k
  size_t distance_multiplier = 0;
573
390k
  for (size_t i = 0; i < nb_channels; i++) {
574
355k
    Channel &channel = image.channel[i];
575
355k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
351k
                                        channel.h > options->max_chan_size)) {
577
1.19k
      break;
578
1.19k
    }
579
354k
    if (!channel.w || !channel.h) {
580
3.84k
      continue;  // skip empty channels
581
3.84k
    }
582
350k
    if (channel.w > distance_multiplier) {
583
59.4k
      distance_multiplier = channel.w;
584
59.4k
    }
585
350k
    num_chans++;
586
350k
  }
587
36.4k
  if (num_chans == 0) return true;
588
589
36.0k
  size_t next_channel = 0;
590
36.0k
  auto scope_guard = MakeScopeGuard([&]() {
591
6.83k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
6.39k
      ZeroFillImage(&image.channel[c].plane);
593
6.39k
    }
594
443
  });
595
  // Do not do anything if truncated groups are not allowed.
596
36.0k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
36.0k
  Tree tree_storage;
600
36.0k
  std::vector<uint8_t> context_map_storage;
601
36.0k
  ANSCode code_storage;
602
36.0k
  const Tree *tree = &tree_storage;
603
36.0k
  const ANSCode *code = &code_storage;
604
36.0k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
36.0k
  if (!header.use_global_tree) {
606
18.8k
    uint64_t max_tree_size = 1024;
607
259k
    for (size_t i = 0; i < nb_channels; i++) {
608
240k
      Channel &channel = image.channel[i];
609
240k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
239k
                                          channel.h > options->max_chan_size)) {
611
35
        break;
612
35
      }
613
240k
      uint64_t pixels = channel.w * channel.h;
614
240k
      max_tree_size += pixels;
615
240k
    }
616
18.8k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
18.8k
    JXL_RETURN_IF_ERROR(
618
18.8k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
18.7k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
18.7k
                                         (tree_storage.size() + 1) / 2,
621
18.7k
                                         &code_storage, &context_map_storage));
622
18.7k
  } else {
623
17.1k
    if (!global_tree || !global_code || !global_ctx_map ||
624
17.1k
        global_tree->empty()) {
625
20
      return JXL_FAILURE("No global tree available but one was requested");
626
20
    }
627
17.1k
    tree = global_tree;
628
17.1k
    code = global_code;
629
17.1k
    context_map = global_ctx_map;
630
17.1k
  }
631
632
  // Read channels
633
71.7k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
71.7k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
71.7k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
71.7k
  uint32_t fl_run = 0;
637
71.7k
  uint32_t fl_v = 0;
638
384k
  for (; next_channel < nb_channels; next_channel++) {
639
349k
    Channel &channel = image.channel[next_channel];
640
349k
    if (next_channel >= image.nb_meta_channels &&
641
346k
        (channel.w > options->max_chan_size ||
642
345k
         channel.h > options->max_chan_size)) {
643
794
      break;
644
794
    }
645
348k
    if (!channel.w || !channel.h) {
646
3.71k
      continue;  // skip empty channels
647
3.71k
    }
648
345k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
345k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
345k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
345k
    if (!br->AllReadsWithinBounds()) {
654
284
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
284
    }
657
345k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
35.5k
  scope_guard.Disarm();
661
662
35.5k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
35.5k
  return true;
666
35.5k
}
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
42.2k
                                bool allow_truncated_group) {
674
42.2k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
42.2k
  req_sizes.reserve(image.channel.size());
676
137k
  for (const auto &c : image.channel) {
677
137k
    req_sizes.emplace_back(c.w, c.h);
678
137k
  }
679
42.2k
  GroupHeader local_header;
680
42.2k
  if (header == nullptr) header = &local_header;
681
42.2k
  size_t bit_pos = br->TotalBitsConsumed();
682
42.2k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
42.2k
                                  code, ctx_map, allow_truncated_group);
684
42.2k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
41.4k
  if (dec_status.IsFatalError()) return dec_status;
686
41.4k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
41.4k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
41.4k
  JXL_DEBUG_V(4,
689
41.4k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
41.4k
              " image from %" PRIuS " bytes",
691
41.4k
              image.w, image.h, image.channel.size(),
692
41.4k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
41.4k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
41.4k
  (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
41.4k
  if (undo_transforms) {
699
13.5k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
68.6k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
55.0k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
55.0k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
55.0k
    }
704
13.5k
  }
705
41.4k
  return dec_status;
706
41.4k
}
707
708
}  // namespace jxl