Coverage Report

Created: 2025-11-14 07:32

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
439k
                    bool *gradient_only) {
46
439k
  *num_props = 0;
47
439k
  bool has_wp = false;
48
439k
  bool has_non_wp = false;
49
439k
  *gradient_only = true;
50
1.01M
  const auto mark_property = [&](int32_t p) {
51
1.01M
    if (p == kWPProp) {
52
108k
      has_wp = true;
53
904k
    } else if (p >= kNumStaticProperties) {
54
543k
      has_non_wp = true;
55
543k
    }
56
1.01M
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
596k
      *gradient_only = false;
58
596k
    }
59
1.01M
  };
60
439k
  FlatTree output;
61
439k
  std::queue<size_t> nodes;
62
439k
  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
2.23M
  while (!nodes.empty()) {
70
1.79M
    size_t cur = nodes.front();
71
1.79M
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
1.84M
    while (global_tree[cur].property < kNumStaticProperties &&
74
1.51M
           global_tree[cur].property != -1) {
75
57.5k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
32.9k
        cur = global_tree[cur].lchild;
77
32.9k
      } else {
78
24.5k
        cur = global_tree[cur].rchild;
79
24.5k
      }
80
57.5k
    }
81
1.79M
    FlatDecisionNode flat;
82
1.79M
    if (global_tree[cur].property == -1) {
83
1.45M
      flat.property0 = -1;
84
1.45M
      flat.childID = global_tree[cur].lchild;
85
1.45M
      flat.predictor = global_tree[cur].predictor;
86
1.45M
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
1.45M
      flat.multiplier = global_tree[cur].multiplier;
88
1.45M
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
1.45M
      has_wp |= flat.predictor == Predictor::Weighted;
90
1.45M
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
1.45M
      output.push_back(flat);
92
1.45M
      continue;
93
1.45M
    }
94
337k
    flat.childID = output.size() + nodes.size() + 1;
95
96
337k
    flat.property0 = global_tree[cur].property;
97
337k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
337k
    flat.splitval0 = global_tree[cur].splitval;
99
100
1.01M
    for (size_t i = 0; i < 2; i++) {
101
675k
      size_t cur_child =
102
675k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
690k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
376k
             global_tree[cur_child].property != -1) {
106
14.7k
        if (static_props[global_tree[cur_child].property] >
107
14.7k
            global_tree[cur_child].splitval) {
108
9.92k
          cur_child = global_tree[cur_child].lchild;
109
9.92k
        } else {
110
4.81k
          cur_child = global_tree[cur_child].rchild;
111
4.81k
        }
112
14.7k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
675k
      if (global_tree[cur_child].property == -1) {
116
361k
        flat.properties[i] = 0;
117
361k
        flat.splitvals[i] = 0;
118
361k
        nodes.push(cur_child);
119
361k
        nodes.push(cur_child);
120
361k
      } else {
121
314k
        flat.properties[i] = global_tree[cur_child].property;
122
314k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
314k
        nodes.push(global_tree[cur_child].lchild);
124
314k
        nodes.push(global_tree[cur_child].rchild);
125
314k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
314k
      }
127
675k
    }
128
129
675k
    for (int16_t property : flat.properties) mark_property(property);
130
337k
    mark_property(flat.property0);
131
337k
    output.push_back(flat);
132
337k
  }
133
439k
  if (*num_props > kNumNonrefProperties) {
134
1.74k
    *num_props =
135
1.74k
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
1.74k
            kExtraPropsPerChannel +
137
1.74k
        kNumNonrefProperties;
138
438k
  } else {
139
438k
    *num_props = kNumNonrefProperties;
140
438k
  }
141
439k
  *use_wp = has_wp;
142
439k
  *wp_only = has_wp && !has_non_wp;
143
144
439k
  return output;
145
439k
}
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
412k
                                 uint32_t &fl_v) {
157
412k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
412k
  Channel &channel = image->channel[chan];
159
160
412k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
412k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
412k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
412k
  bool tree_has_wp_prop_or_pred = false;
168
412k
  bool is_wp_only = false;
169
412k
  bool is_gradient_only = false;
170
412k
  size_t num_props;
171
412k
  FlatTree tree =
172
412k
      FilterTree(global_tree, static_props, &num_props,
173
412k
                 &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
584k
  for (auto &node : tree) {
178
584k
    if (node.property0 == -1) {
179
541k
      node.childID = context_map[node.childID];
180
541k
    }
181
584k
  }
182
183
412k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
412k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
253M
                             pixel_type_w offset) -> pixel_type {
188
253M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
253M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
253M
    return val * multiplier + offset;
192
253M
  };
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
50.7M
                             pixel_type_w offset) -> pixel_type {
188
50.7M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
50.7M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
50.7M
    return val * multiplier + offset;
192
50.7M
  };
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
202M
                             pixel_type_w offset) -> pixel_type {
188
202M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
202M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
202M
    return val * multiplier + offset;
192
202M
  };
193
194
412k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
401k
    Predictor predictor = tree[0].predictor;
198
401k
    int64_t offset = tree[0].predictor_offset;
199
401k
    int32_t multiplier = tree[0].multiplier;
200
401k
    size_t ctx_id = tree[0].childID;
201
401k
    if (predictor == Predictor::Zero) {
202
377k
      uint32_t value;
203
377k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
377k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
179k
        JXL_DEBUG_V(8, "Fastest track.");
208
179k
        pixel_type v = make_pixel(value, multiplier, offset);
209
4.95M
        for (size_t y = 0; y < channel.h; y++) {
210
4.77M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
4.77M
          std::fill(r, r + channel.w, v);
212
4.77M
        }
213
198k
      } else {
214
198k
        JXL_DEBUG_V(8, "Fast track.");
215
198k
        if (multiplier == 1 && offset == 0) {
216
3.38M
          for (size_t y = 0; y < channel.h; y++) {
217
3.22M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
263M
            for (size_t x = 0; x < channel.w; x++) {
219
259M
              uint32_t v =
220
259M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
259M
              r[x] = UnpackSigned(v);
222
259M
            }
223
3.22M
          }
224
162k
        } else {
225
1.51M
          for (size_t y = 0; y < channel.h; y++) {
226
1.47M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
162M
            for (size_t x = 0; x < channel.w; x++) {
228
161M
              uint32_t v =
229
161M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
161M
                                                                         br);
231
161M
              r[x] = make_pixel(v, multiplier, offset);
232
161M
            }
233
1.47M
          }
234
35.2k
        }
235
198k
      }
236
377k
      return true;
237
377k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.93k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
443
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
443
      pixel_type_w sv = UnpackSigned(fl_v);
241
14.1k
      for (size_t y = 0; y < channel.h; y++) {
242
13.6k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
13.6k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
13.6k
        const pixel_type *JXL_RESTRICT rtopleft =
245
13.6k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
13.6k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
13.6k
        if (fl_run == 0) {
248
5.59k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.59k
                                                     &fl_run);
250
5.59k
          sv = UnpackSigned(fl_v);
251
8.09k
        } else {
252
8.09k
          fl_run--;
253
8.09k
        }
254
13.6k
        r[0] = sv + guess_0;
255
426k
        for (size_t x = 1; x < channel.w; x++) {
256
412k
          pixel_type left = r[x - 1];
257
412k
          pixel_type top = rtop[x];
258
412k
          pixel_type topleft = rtopleft[x];
259
412k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
412k
          if (!fl_run) {
261
180k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
180k
                                                       &fl_run);
263
180k
            sv = UnpackSigned(fl_v);
264
232k
          } else {
265
232k
            fl_run--;
266
232k
          }
267
412k
          r[x] = sv + guess;
268
412k
        }
269
13.6k
      }
270
443
      return true;
271
23.5k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
3.26k
               multiplier == 1) {
273
2.70k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
2.70k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
59.4k
      for (size_t y = 0; y < channel.h; y++) {
276
56.7k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
3.03M
        for (size_t x = 0; x < channel.w; x++) {
278
2.97M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.97M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.97M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.97M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.97M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.97M
              ctx_id, br);
284
2.97M
          r[x] = make_pixel(v, 1, guess);
285
2.97M
        }
286
56.7k
      }
287
2.70k
      return true;
288
2.70k
    }
289
401k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
32.0k
  if (is_wp_only) {
294
4.64k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.64k
  }
296
32.0k
  if (is_gradient_only) {
297
2.39k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
2.39k
  }
299
300
32.0k
  if (is_gradient_only) {
301
737
    JXL_DEBUG_V(8, "Gradient fast track.");
302
737
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
16.5k
    for (size_t y = 0; y < channel.h; y++) {
304
15.8k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
644k
      for (size_t x = 0; x < channel.w; x++) {
306
629k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
629k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
629k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
629k
        int32_t guess = ClampedGradient(top, left, topleft);
310
629k
        uint32_t pos =
311
629k
            kPropRangeFast +
312
629k
            std::min<pixel_type_w>(
313
629k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
629k
                kPropRangeFast - 1);
315
629k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
629k
        uint64_t v =
317
629k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
629k
        r[x] = make_pixel(v, 1, guess);
319
629k
      }
320
15.8k
    }
321
31.2k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
811
    JXL_DEBUG_V(8, "WP fast track.");
323
811
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
811
    Properties properties(1);
325
22.2k
    for (size_t y = 0; y < channel.h; y++) {
326
21.4k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
21.4k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
21.4k
      const pixel_type *JXL_RESTRICT rtoptop =
329
21.4k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
21.4k
      const pixel_type *JXL_RESTRICT rtopleft =
331
21.4k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
21.4k
      const pixel_type *JXL_RESTRICT rtopright =
333
21.4k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
21.4k
      size_t x = 0;
335
21.4k
      {
336
21.4k
        size_t offset = 0;
337
21.4k
        pixel_type_w left = y ? rtop[x] : 0;
338
21.4k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
21.4k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
21.4k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
21.4k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
21.4k
            offset);
343
21.4k
        uint32_t pos =
344
21.4k
            kPropRangeFast +
345
21.4k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
21.4k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
21.4k
        uint64_t v =
348
21.4k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
21.4k
        r[x] = make_pixel(v, 1, guess);
350
21.4k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
21.4k
      }
352
2.06M
      for (x = 1; x + 1 < channel.w; x++) {
353
2.04M
        size_t offset = 0;
354
2.04M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
2.04M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
2.04M
            rtoptop[x], &properties, offset);
357
2.04M
        uint32_t pos =
358
2.04M
            kPropRangeFast +
359
2.04M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
2.04M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
2.04M
        uint64_t v =
362
2.04M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
2.04M
        r[x] = make_pixel(v, 1, guess);
364
2.04M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
2.04M
      }
366
21.4k
      {
367
21.4k
        size_t offset = 0;
368
21.4k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
21.4k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
21.4k
            rtoptop[x], &properties, offset);
371
21.4k
        uint32_t pos =
372
21.4k
            kPropRangeFast +
373
21.4k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
21.4k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
21.4k
        uint64_t v =
376
21.4k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
21.4k
        r[x] = make_pixel(v, 1, guess);
378
21.4k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
21.4k
      }
380
21.4k
    }
381
30.4k
  } 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
20.9k
    JXL_DEBUG_V(8, "Slow track.");
385
20.9k
    MATreeLookup tree_lookup(tree);
386
20.9k
    Properties properties = Properties(num_props);
387
20.9k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
20.9k
    JXL_ASSIGN_OR_RETURN(
389
20.9k
        Channel references,
390
20.9k
        Channel::Create(memory_manager,
391
20.9k
                        properties.size() - kNumNonrefProperties, channel.w));
392
695k
    for (size_t y = 0; y < channel.h; y++) {
393
674k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
674k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
674k
      InitPropsRow(&properties, static_props, y);
396
674k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.66M
        for (size_t x = 0; x < 2; x++) {
398
1.11M
          PredictionResult res =
399
1.11M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
1.11M
                              tree_lookup, references);
401
1.11M
          uint64_t v =
402
1.11M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
1.11M
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
1.11M
        }
405
61.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
61.4M
          PredictionResult res =
407
61.4M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
61.4M
                                 tree_lookup, references);
409
61.4M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
61.4M
              res.context, br);
411
61.4M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
61.4M
        }
413
1.66M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
1.11M
          PredictionResult res =
415
1.11M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
1.11M
                              tree_lookup, references);
417
1.11M
          uint64_t v =
418
1.11M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
1.11M
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
1.11M
        }
421
556k
      } else {
422
2.65M
        for (size_t x = 0; x < channel.w; x++) {
423
2.53M
          PredictionResult res =
424
2.53M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
2.53M
                              tree_lookup, references);
426
2.53M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
2.53M
              res.context, br);
428
2.53M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
2.53M
        }
430
118k
      }
431
674k
    }
432
20.9k
  } else {
433
9.49k
    JXL_DEBUG_V(8, "Slowest track.");
434
9.49k
    MATreeLookup tree_lookup(tree);
435
9.49k
    Properties properties = Properties(num_props);
436
9.49k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
9.49k
    JXL_ASSIGN_OR_RETURN(
438
9.49k
        Channel references,
439
9.49k
        Channel::Create(memory_manager,
440
9.49k
                        properties.size() - kNumNonrefProperties, channel.w));
441
9.49k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
282k
    for (size_t y = 0; y < channel.h; y++) {
443
272k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
272k
      InitPropsRow(&properties, static_props, y);
445
272k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
272k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
676k
        for (size_t x = 0; x < 2; x++) {
448
450k
          PredictionResult res =
449
450k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
450k
                            tree_lookup, references, &wp_state);
451
450k
          uint64_t v =
452
450k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
450k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
450k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
450k
        }
456
16.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
16.7M
          PredictionResult res =
458
16.7M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
16.7M
                               tree_lookup, references, &wp_state);
460
16.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
16.7M
              res.context, br);
462
16.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
16.7M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
16.7M
        }
465
676k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
450k
          PredictionResult res =
467
450k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
450k
                            tree_lookup, references, &wp_state);
469
450k
          uint64_t v =
470
450k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
450k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
450k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
450k
        }
474
225k
      } else {
475
2.53M
        for (size_t x = 0; x < channel.w; x++) {
476
2.48M
          PredictionResult res =
477
2.48M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
2.48M
                            tree_lookup, references, &wp_state);
479
2.48M
          uint64_t v =
480
2.48M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
2.48M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
2.48M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
2.48M
        }
484
47.5k
      }
485
272k
    }
486
9.49k
  }
487
32.0k
  return true;
488
32.0k
}
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
33.8k
                                 uint32_t &fl_v) {
157
33.8k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
33.8k
  Channel &channel = image->channel[chan];
159
160
33.8k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
33.8k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
33.8k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
33.8k
  bool tree_has_wp_prop_or_pred = false;
168
33.8k
  bool is_wp_only = false;
169
33.8k
  bool is_gradient_only = false;
170
33.8k
  size_t num_props;
171
33.8k
  FlatTree tree =
172
33.8k
      FilterTree(global_tree, static_props, &num_props,
173
33.8k
                 &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
42.2k
  for (auto &node : tree) {
178
42.2k
    if (node.property0 == -1) {
179
40.1k
      node.childID = context_map[node.childID];
180
40.1k
    }
181
42.2k
  }
182
183
33.8k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
33.8k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
33.8k
                             pixel_type_w offset) -> pixel_type {
188
33.8k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
33.8k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
33.8k
    return val * multiplier + offset;
192
33.8k
  };
193
194
33.8k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
31.9k
    Predictor predictor = tree[0].predictor;
198
31.9k
    int64_t offset = tree[0].predictor_offset;
199
31.9k
    int32_t multiplier = tree[0].multiplier;
200
31.9k
    size_t ctx_id = tree[0].childID;
201
31.9k
    if (predictor == Predictor::Zero) {
202
24.2k
      uint32_t value;
203
24.2k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
24.2k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
5.98k
        JXL_DEBUG_V(8, "Fastest track.");
208
5.98k
        pixel_type v = make_pixel(value, multiplier, offset);
209
236k
        for (size_t y = 0; y < channel.h; y++) {
210
230k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
230k
          std::fill(r, r + channel.w, v);
212
230k
        }
213
18.2k
      } else {
214
18.2k
        JXL_DEBUG_V(8, "Fast track.");
215
18.2k
        if (multiplier == 1 && offset == 0) {
216
296k
          for (size_t y = 0; y < channel.h; y++) {
217
291k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
44.4M
            for (size_t x = 0; x < channel.w; x++) {
219
44.1M
              uint32_t v =
220
44.1M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
44.1M
              r[x] = UnpackSigned(v);
222
44.1M
            }
223
291k
          }
224
13.1k
        } else {
225
412k
          for (size_t y = 0; y < channel.h; y++) {
226
399k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
25.3M
            for (size_t x = 0; x < channel.w; x++) {
228
24.9M
              uint32_t v =
229
24.9M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
24.9M
                                                                         br);
231
24.9M
              r[x] = make_pixel(v, multiplier, offset);
232
24.9M
            }
233
399k
          }
234
13.1k
        }
235
18.2k
      }
236
24.2k
      return true;
237
24.2k
    } else if (uses_lz77 && predictor == Predictor::Gradient && offset == 0 &&
238
1.93k
               multiplier == 1 && reader->IsHuffRleOnly()) {
239
443
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
240
443
      pixel_type_w sv = UnpackSigned(fl_v);
241
14.1k
      for (size_t y = 0; y < channel.h; y++) {
242
13.6k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
243
13.6k
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
244
13.6k
        const pixel_type *JXL_RESTRICT rtopleft =
245
13.6k
            (y ? channel.Row(y - 1) - 1 : r - 1);
246
13.6k
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
247
13.6k
        if (fl_run == 0) {
248
5.59k
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
249
5.59k
                                                     &fl_run);
250
5.59k
          sv = UnpackSigned(fl_v);
251
8.09k
        } else {
252
8.09k
          fl_run--;
253
8.09k
        }
254
13.6k
        r[0] = sv + guess_0;
255
426k
        for (size_t x = 1; x < channel.w; x++) {
256
412k
          pixel_type left = r[x - 1];
257
412k
          pixel_type top = rtop[x];
258
412k
          pixel_type topleft = rtopleft[x];
259
412k
          pixel_type_w guess = ClampedGradient(top, left, topleft);
260
412k
          if (!fl_run) {
261
180k
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
262
180k
                                                       &fl_run);
263
180k
            sv = UnpackSigned(fl_v);
264
232k
          } else {
265
232k
            fl_run--;
266
232k
          }
267
412k
          r[x] = sv + guess;
268
412k
        }
269
13.6k
      }
270
443
      return true;
271
7.29k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.49k
               multiplier == 1) {
273
1.23k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.23k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
17.3k
      for (size_t y = 0; y < channel.h; y++) {
276
16.1k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
393k
        for (size_t x = 0; x < channel.w; x++) {
278
377k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
377k
          pixel_type top = (y ? *(r + x - onerow) : left);
280
377k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
377k
          pixel_type guess = ClampedGradient(top, left, topleft);
282
377k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
377k
              ctx_id, br);
284
377k
          r[x] = make_pixel(v, 1, guess);
285
377k
        }
286
16.1k
      }
287
1.23k
      return true;
288
1.23k
    }
289
31.9k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
7.92k
  if (is_wp_only) {
294
320
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
320
  }
296
7.92k
  if (is_gradient_only) {
297
987
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
987
  }
299
300
7.92k
  if (is_gradient_only) {
301
119
    JXL_DEBUG_V(8, "Gradient fast track.");
302
119
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
3.64k
    for (size_t y = 0; y < channel.h; y++) {
304
3.52k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
277k
      for (size_t x = 0; x < channel.w; x++) {
306
274k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
274k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
274k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
274k
        int32_t guess = ClampedGradient(top, left, topleft);
310
274k
        uint32_t pos =
311
274k
            kPropRangeFast +
312
274k
            std::min<pixel_type_w>(
313
274k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
274k
                kPropRangeFast - 1);
315
274k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
274k
        uint64_t v =
317
274k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
274k
        r[x] = make_pixel(v, 1, guess);
319
274k
      }
320
3.52k
    }
321
7.80k
  } 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
7.80k
  } 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
7.25k
    JXL_DEBUG_V(8, "Slow track.");
385
7.25k
    MATreeLookup tree_lookup(tree);
386
7.25k
    Properties properties = Properties(num_props);
387
7.25k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
7.25k
    JXL_ASSIGN_OR_RETURN(
389
7.25k
        Channel references,
390
7.25k
        Channel::Create(memory_manager,
391
7.25k
                        properties.size() - kNumNonrefProperties, channel.w));
392
178k
    for (size_t y = 0; y < channel.h; y++) {
393
170k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
170k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
170k
      InitPropsRow(&properties, static_props, y);
396
170k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
435k
        for (size_t x = 0; x < 2; x++) {
398
290k
          PredictionResult res =
399
290k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
290k
                              tree_lookup, references);
401
290k
          uint64_t v =
402
290k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
290k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
290k
        }
405
22.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
22.7M
          PredictionResult res =
407
22.7M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
22.7M
                                 tree_lookup, references);
409
22.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
22.7M
              res.context, br);
411
22.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
22.7M
        }
413
435k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
290k
          PredictionResult res =
415
290k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
290k
                              tree_lookup, references);
417
290k
          uint64_t v =
418
290k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
290k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
290k
        }
421
145k
      } else {
422
834k
        for (size_t x = 0; x < channel.w; x++) {
423
809k
          PredictionResult res =
424
809k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
809k
                              tree_lookup, references);
426
809k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
809k
              res.context, br);
428
809k
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
809k
        }
430
25.6k
      }
431
170k
    }
432
7.25k
  } else {
433
555
    JXL_DEBUG_V(8, "Slowest track.");
434
555
    MATreeLookup tree_lookup(tree);
435
555
    Properties properties = Properties(num_props);
436
555
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
555
    JXL_ASSIGN_OR_RETURN(
438
555
        Channel references,
439
555
        Channel::Create(memory_manager,
440
555
                        properties.size() - kNumNonrefProperties, channel.w));
441
555
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
10.1k
    for (size_t y = 0; y < channel.h; y++) {
443
9.61k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
9.61k
      InitPropsRow(&properties, static_props, y);
445
9.61k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
9.61k
      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
9.61k
      } else {
475
967k
        for (size_t x = 0; x < channel.w; x++) {
476
957k
          PredictionResult res =
477
957k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
957k
                            tree_lookup, references, &wp_state);
479
957k
          uint64_t v =
480
957k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
957k
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
957k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
957k
        }
484
9.61k
      }
485
9.61k
    }
486
555
  }
487
7.92k
  return true;
488
7.92k
}
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
378k
                                 uint32_t &fl_v) {
157
378k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
378k
  Channel &channel = image->channel[chan];
159
160
378k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
378k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
378k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
378k
  bool tree_has_wp_prop_or_pred = false;
168
378k
  bool is_wp_only = false;
169
378k
  bool is_gradient_only = false;
170
378k
  size_t num_props;
171
378k
  FlatTree tree =
172
378k
      FilterTree(global_tree, static_props, &num_props,
173
378k
                 &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
541k
  for (auto &node : tree) {
178
541k
    if (node.property0 == -1) {
179
501k
      node.childID = context_map[node.childID];
180
501k
    }
181
541k
  }
182
183
378k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
378k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
378k
                             pixel_type_w offset) -> pixel_type {
188
378k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
378k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
378k
    return val * multiplier + offset;
192
378k
  };
193
194
378k
  if (tree.size() == 1) {
195
    // special optimized case: no meta-adaptation, so no need
196
    // to compute properties.
197
369k
    Predictor predictor = tree[0].predictor;
198
369k
    int64_t offset = tree[0].predictor_offset;
199
369k
    int32_t multiplier = tree[0].multiplier;
200
369k
    size_t ctx_id = tree[0].childID;
201
369k
    if (predictor == Predictor::Zero) {
202
353k
      uint32_t value;
203
353k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
204
353k
                                          channel.w * channel.h)) {
205
        // Special-case: histogram has a single symbol, with no extra bits, and
206
        // we use ANS mode.
207
173k
        JXL_DEBUG_V(8, "Fastest track.");
208
173k
        pixel_type v = make_pixel(value, multiplier, offset);
209
4.71M
        for (size_t y = 0; y < channel.h; y++) {
210
4.54M
          pixel_type *JXL_RESTRICT r = channel.Row(y);
211
4.54M
          std::fill(r, r + channel.w, v);
212
4.54M
        }
213
179k
      } else {
214
179k
        JXL_DEBUG_V(8, "Fast track.");
215
179k
        if (multiplier == 1 && offset == 0) {
216
3.08M
          for (size_t y = 0; y < channel.h; y++) {
217
2.93M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
218
218M
            for (size_t x = 0; x < channel.w; x++) {
219
215M
              uint32_t v =
220
215M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
221
215M
              r[x] = UnpackSigned(v);
222
215M
            }
223
2.93M
          }
224
157k
        } else {
225
1.10M
          for (size_t y = 0; y < channel.h; y++) {
226
1.07M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
227
137M
            for (size_t x = 0; x < channel.w; x++) {
228
136M
              uint32_t v =
229
136M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
230
136M
                                                                         br);
231
136M
              r[x] = make_pixel(v, multiplier, offset);
232
136M
            }
233
1.07M
          }
234
22.0k
        }
235
179k
      }
236
353k
      return true;
237
353k
    } 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
16.2k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
272
1.77k
               multiplier == 1) {
273
1.46k
      JXL_DEBUG_V(8, "Gradient very fast track.");
274
1.46k
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
275
42.1k
      for (size_t y = 0; y < channel.h; y++) {
276
40.6k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
277
2.63M
        for (size_t x = 0; x < channel.w; x++) {
278
2.59M
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
279
2.59M
          pixel_type top = (y ? *(r + x - onerow) : left);
280
2.59M
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
281
2.59M
          pixel_type guess = ClampedGradient(top, left, topleft);
282
2.59M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
283
2.59M
              ctx_id, br);
284
2.59M
          r[x] = make_pixel(v, 1, guess);
285
2.59M
        }
286
40.6k
      }
287
1.46k
      return true;
288
1.46k
    }
289
369k
  }
290
291
  // Check if this tree is a WP-only tree with a small enough property value
292
  // range.
293
24.0k
  if (is_wp_only) {
294
4.32k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
295
4.32k
  }
296
24.0k
  if (is_gradient_only) {
297
1.41k
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
298
1.41k
  }
299
300
24.0k
  if (is_gradient_only) {
301
618
    JXL_DEBUG_V(8, "Gradient fast track.");
302
618
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
303
12.9k
    for (size_t y = 0; y < channel.h; y++) {
304
12.3k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
305
367k
      for (size_t x = 0; x < channel.w; x++) {
306
354k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
307
354k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
308
354k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
309
354k
        int32_t guess = ClampedGradient(top, left, topleft);
310
354k
        uint32_t pos =
311
354k
            kPropRangeFast +
312
354k
            std::min<pixel_type_w>(
313
354k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
314
354k
                kPropRangeFast - 1);
315
354k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
316
354k
        uint64_t v =
317
354k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
318
354k
        r[x] = make_pixel(v, 1, guess);
319
354k
      }
320
12.3k
    }
321
23.4k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
322
811
    JXL_DEBUG_V(8, "WP fast track.");
323
811
    weighted::State wp_state(wp_header, channel.w, channel.h);
324
811
    Properties properties(1);
325
22.2k
    for (size_t y = 0; y < channel.h; y++) {
326
21.4k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
327
21.4k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
328
21.4k
      const pixel_type *JXL_RESTRICT rtoptop =
329
21.4k
          (y > 1 ? channel.Row(y - 2) : rtop);
330
21.4k
      const pixel_type *JXL_RESTRICT rtopleft =
331
21.4k
          (y ? channel.Row(y - 1) - 1 : r - 1);
332
21.4k
      const pixel_type *JXL_RESTRICT rtopright =
333
21.4k
          (y ? channel.Row(y - 1) + 1 : r - 1);
334
21.4k
      size_t x = 0;
335
21.4k
      {
336
21.4k
        size_t offset = 0;
337
21.4k
        pixel_type_w left = y ? rtop[x] : 0;
338
21.4k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
339
21.4k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
340
21.4k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
341
21.4k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
342
21.4k
            offset);
343
21.4k
        uint32_t pos =
344
21.4k
            kPropRangeFast +
345
21.4k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
346
21.4k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
347
21.4k
        uint64_t v =
348
21.4k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
349
21.4k
        r[x] = make_pixel(v, 1, guess);
350
21.4k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
351
21.4k
      }
352
2.06M
      for (x = 1; x + 1 < channel.w; x++) {
353
2.04M
        size_t offset = 0;
354
2.04M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
355
2.04M
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
356
2.04M
            rtoptop[x], &properties, offset);
357
2.04M
        uint32_t pos =
358
2.04M
            kPropRangeFast +
359
2.04M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
360
2.04M
        uint32_t ctx_id = tree_lut.context_lookup[pos];
361
2.04M
        uint64_t v =
362
2.04M
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
363
2.04M
        r[x] = make_pixel(v, 1, guess);
364
2.04M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
365
2.04M
      }
366
21.4k
      {
367
21.4k
        size_t offset = 0;
368
21.4k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
369
21.4k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
370
21.4k
            rtoptop[x], &properties, offset);
371
21.4k
        uint32_t pos =
372
21.4k
            kPropRangeFast +
373
21.4k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
374
21.4k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
375
21.4k
        uint64_t v =
376
21.4k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
377
21.4k
        r[x] = make_pixel(v, 1, guess);
378
21.4k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
379
21.4k
      }
380
21.4k
    }
381
22.6k
  } 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
13.7k
    JXL_DEBUG_V(8, "Slow track.");
385
13.7k
    MATreeLookup tree_lookup(tree);
386
13.7k
    Properties properties = Properties(num_props);
387
13.7k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
388
13.7k
    JXL_ASSIGN_OR_RETURN(
389
13.7k
        Channel references,
390
13.7k
        Channel::Create(memory_manager,
391
13.7k
                        properties.size() - kNumNonrefProperties, channel.w));
392
517k
    for (size_t y = 0; y < channel.h; y++) {
393
504k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
394
504k
      PrecomputeReferences(channel, y, *image, chan, &references);
395
504k
      InitPropsRow(&properties, static_props, y);
396
504k
      if (y > 1 && channel.w > 8 && references.w == 0) {
397
1.23M
        for (size_t x = 0; x < 2; x++) {
398
822k
          PredictionResult res =
399
822k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
400
822k
                              tree_lookup, references);
401
822k
          uint64_t v =
402
822k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
403
822k
          p[x] = make_pixel(v, res.multiplier, res.guess);
404
822k
        }
405
39.0M
        for (size_t x = 2; x < channel.w - 2; x++) {
406
38.6M
          PredictionResult res =
407
38.6M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
408
38.6M
                                 tree_lookup, references);
409
38.6M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
410
38.6M
              res.context, br);
411
38.6M
          p[x] = make_pixel(v, res.multiplier, res.guess);
412
38.6M
        }
413
1.23M
        for (size_t x = channel.w - 2; x < channel.w; x++) {
414
822k
          PredictionResult res =
415
822k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
416
822k
                              tree_lookup, references);
417
822k
          uint64_t v =
418
822k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
419
822k
          p[x] = make_pixel(v, res.multiplier, res.guess);
420
822k
        }
421
411k
      } else {
422
1.81M
        for (size_t x = 0; x < channel.w; x++) {
423
1.72M
          PredictionResult res =
424
1.72M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
425
1.72M
                              tree_lookup, references);
426
1.72M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
427
1.72M
              res.context, br);
428
1.72M
          p[x] = make_pixel(v, res.multiplier, res.guess);
429
1.72M
        }
430
92.8k
      }
431
504k
    }
432
13.7k
  } else {
433
8.94k
    JXL_DEBUG_V(8, "Slowest track.");
434
8.94k
    MATreeLookup tree_lookup(tree);
435
8.94k
    Properties properties = Properties(num_props);
436
8.94k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
437
8.94k
    JXL_ASSIGN_OR_RETURN(
438
8.94k
        Channel references,
439
8.94k
        Channel::Create(memory_manager,
440
8.94k
                        properties.size() - kNumNonrefProperties, channel.w));
441
8.94k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
272k
    for (size_t y = 0; y < channel.h; y++) {
443
263k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
444
263k
      InitPropsRow(&properties, static_props, y);
445
263k
      PrecomputeReferences(channel, y, *image, chan, &references);
446
263k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
447
676k
        for (size_t x = 0; x < 2; x++) {
448
450k
          PredictionResult res =
449
450k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
450
450k
                            tree_lookup, references, &wp_state);
451
450k
          uint64_t v =
452
450k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
453
450k
          p[x] = make_pixel(v, res.multiplier, res.guess);
454
450k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
455
450k
        }
456
16.9M
        for (size_t x = 2; x < channel.w - 2; x++) {
457
16.7M
          PredictionResult res =
458
16.7M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
459
16.7M
                               tree_lookup, references, &wp_state);
460
16.7M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
461
16.7M
              res.context, br);
462
16.7M
          p[x] = make_pixel(v, res.multiplier, res.guess);
463
16.7M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
464
16.7M
        }
465
676k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
466
450k
          PredictionResult res =
467
450k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
450k
                            tree_lookup, references, &wp_state);
469
450k
          uint64_t v =
470
450k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
450k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
450k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
450k
        }
474
225k
      } else {
475
1.56M
        for (size_t x = 0; x < channel.w; x++) {
476
1.52M
          PredictionResult res =
477
1.52M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
478
1.52M
                            tree_lookup, references, &wp_state);
479
1.52M
          uint64_t v =
480
1.52M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
481
1.52M
          p[x] = make_pixel(v, res.multiplier, res.guess);
482
1.52M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
483
1.52M
        }
484
37.9k
      }
485
263k
    }
486
8.94k
  }
487
24.0k
  return true;
488
24.0k
}
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
412k
                                 uint32_t &fl_v) {
499
412k
  if (reader->UsesLZ77()) {
500
33.8k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
501
33.8k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
502
33.8k
        tree_lut, image, fl_run, fl_v);
503
378k
  } else {
504
378k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
505
378k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
506
378k
        tree_lut, image, fl_run, fl_v);
507
378k
  }
508
412k
}
509
510
215k
GroupHeader::GroupHeader() { Bundle::Init(this); }
511
512
Status ValidateChannelDimensions(const Image &image,
513
47.1k
                                 const ModularOptions &options) {
514
47.1k
  size_t nb_channels = image.channel.size();
515
94.2k
  for (bool is_dc : {true, false}) {
516
94.2k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
517
94.2k
    size_t c = image.nb_meta_channels;
518
944k
    for (; c < nb_channels; c++) {
519
853k
      const Channel &ch = image.channel[c];
520
853k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
521
853k
    }
522
122k
    for (; c < nb_channels; c++) {
523
27.7k
      const Channel &ch = image.channel[c];
524
27.7k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
525
27.0k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
526
27.0k
      if (is_dc_channel != is_dc) continue;
527
13.5k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
528
13.5k
      if (tile_dim == 0) {
529
1
        return JXL_FAILURE("Inconsistent transforms");
530
1
      }
531
13.5k
    }
532
94.2k
  }
533
47.1k
  return true;
534
47.1k
}
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
52.0k
                     const bool allow_truncated_group) {
541
52.0k
  if (image.channel.empty()) return true;
542
45.8k
  JxlMemoryManager *memory_manager = image.memory_manager();
543
544
  // decode transforms
545
45.8k
  Status status = Bundle::Read(br, &header);
546
45.8k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
547
45.2k
  if (status.IsFatalError()) return status;
548
45.2k
  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
45.2k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
559
45.2k
              header.transforms.size());
560
45.2k
  image.transform = header.transforms;
561
45.2k
  for (Transform &transform : image.transform) {
562
27.4k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
563
27.4k
  }
564
45.1k
  if (image.error) {
565
0
    return JXL_FAILURE("Corrupt file. Aborting.");
566
0
  }
567
45.1k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
568
569
45.1k
  size_t nb_channels = image.channel.size();
570
571
45.1k
  size_t num_chans = 0;
572
45.1k
  size_t distance_multiplier = 0;
573
471k
  for (size_t i = 0; i < nb_channels; i++) {
574
427k
    Channel &channel = image.channel[i];
575
427k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
576
422k
                                        channel.h > options->max_chan_size)) {
577
1.36k
      break;
578
1.36k
    }
579
426k
    if (!channel.w || !channel.h) {
580
4.77k
      continue;  // skip empty channels
581
4.77k
    }
582
421k
    if (channel.w > distance_multiplier) {
583
73.7k
      distance_multiplier = channel.w;
584
73.7k
    }
585
421k
    num_chans++;
586
421k
  }
587
45.1k
  if (num_chans == 0) return true;
588
589
44.7k
  size_t next_channel = 0;
590
44.7k
  auto scope_guard = MakeScopeGuard([&]() {
591
12.9k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
592
11.0k
      ZeroFillImage(&image.channel[c].plane);
593
11.0k
    }
594
1.85k
  });
595
  // Do not do anything if truncated groups are not allowed.
596
44.7k
  if (allow_truncated_group) scope_guard.Disarm();
597
598
  // Read tree.
599
44.7k
  Tree tree_storage;
600
44.7k
  std::vector<uint8_t> context_map_storage;
601
44.7k
  ANSCode code_storage;
602
44.7k
  const Tree *tree = &tree_storage;
603
44.7k
  const ANSCode *code = &code_storage;
604
44.7k
  const std::vector<uint8_t> *context_map = &context_map_storage;
605
44.7k
  if (!header.use_global_tree) {
606
25.8k
    uint64_t max_tree_size = 1024;
607
325k
    for (size_t i = 0; i < nb_channels; i++) {
608
299k
      Channel &channel = image.channel[i];
609
299k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
610
297k
                                          channel.h > options->max_chan_size)) {
611
43
        break;
612
43
      }
613
299k
      uint64_t pixels = channel.w * channel.h;
614
299k
      max_tree_size += pixels;
615
299k
    }
616
25.8k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
617
25.8k
    JXL_RETURN_IF_ERROR(
618
25.8k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
619
25.6k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
620
25.6k
                                         (tree_storage.size() + 1) / 2,
621
25.6k
                                         &code_storage, &context_map_storage));
622
25.6k
  } else {
623
18.8k
    if (!global_tree || !global_code || !global_ctx_map ||
624
18.8k
        global_tree->empty()) {
625
43
      return JXL_FAILURE("No global tree available but one was requested");
626
43
    }
627
18.7k
    tree = global_tree;
628
18.7k
    code = global_code;
629
18.7k
    context_map = global_ctx_map;
630
18.7k
  }
631
632
  // Read channels
633
88.8k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
634
88.8k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
635
88.8k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
636
88.8k
  uint32_t fl_run = 0;
637
88.8k
  uint32_t fl_v = 0;
638
460k
  for (; next_channel < nb_channels; next_channel++) {
639
418k
    Channel &channel = image.channel[next_channel];
640
418k
    if (next_channel >= image.nb_meta_channels &&
641
413k
        (channel.w > options->max_chan_size ||
642
413k
         channel.h > options->max_chan_size)) {
643
898
      break;
644
898
    }
645
417k
    if (!channel.w || !channel.h) {
646
4.54k
      continue;  // skip empty channels
647
4.54k
    }
648
412k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
649
412k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
650
412k
        group_id, *tree_lut, &image, fl_run, fl_v));
651
652
    // Truncated group.
653
412k
    if (!br->AllReadsWithinBounds()) {
654
1.57k
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
655
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
656
1.57k
    }
657
412k
  }
658
659
  // Make sure no zero-filling happens even if next_channel < nb_channels.
660
42.8k
  scope_guard.Disarm();
661
662
42.8k
  if (!reader.CheckANSFinalState()) {
663
0
    return JXL_FAILURE("ANS decode final state failed");
664
0
  }
665
42.8k
  return true;
666
42.8k
}
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
52.0k
                                bool allow_truncated_group) {
674
52.0k
  std::vector<std::pair<size_t, size_t>> req_sizes;
675
52.0k
  req_sizes.reserve(image.channel.size());
676
169k
  for (const auto &c : image.channel) {
677
169k
    req_sizes.emplace_back(c.w, c.h);
678
169k
  }
679
52.0k
  GroupHeader local_header;
680
52.0k
  if (header == nullptr) header = &local_header;
681
52.0k
  size_t bit_pos = br->TotalBitsConsumed();
682
52.0k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
683
52.0k
                                  code, ctx_map, allow_truncated_group);
684
52.0k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
685
49.5k
  if (dec_status.IsFatalError()) return dec_status;
686
49.5k
  if (undo_transforms) image.undo_transforms(header->wp_header);
687
49.5k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
688
49.5k
  JXL_DEBUG_V(4,
689
49.5k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
690
49.5k
              " image from %" PRIuS " bytes",
691
49.5k
              image.w, image.h, image.channel.size(),
692
49.5k
              (br->TotalBitsConsumed() - bit_pos) / 8);
693
49.5k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
694
49.5k
  (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
49.5k
  if (undo_transforms) {
699
14.4k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
700
73.3k
    for (size_t c = 0; c < req_sizes.size(); c++) {
701
58.9k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
702
58.9k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
703
58.9k
    }
704
14.4k
  }
705
49.5k
  return dec_status;
706
49.5k
}
707
708
}  // namespace jxl