Coverage Report

Created: 2026-10-14 06:45

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
184k
                    bool *gradient_only) {
46
184k
  *num_props = 0;
47
184k
  bool has_wp = false;
48
184k
  bool has_non_wp = false;
49
184k
  *gradient_only = true;
50
232k
  const auto mark_property = [&](int32_t p) {
51
232k
    if (p == kWPProp) {
52
19.9k
      has_wp = true;
53
212k
    } else if (p >= kNumStaticProperties) {
54
130k
      has_non_wp = true;
55
130k
    }
56
232k
    if (p >= kNumStaticProperties && p != kGradientProp) {
57
130k
      *gradient_only = false;
58
130k
    }
59
232k
  };
60
184k
  FlatTree output;
61
184k
  std::queue<size_t> nodes;
62
184k
  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
680k
  while (!nodes.empty()) {
70
496k
    size_t cur = nodes.front();
71
496k
    nodes.pop();
72
    // Skip nodes that we can decide now, by jumping directly to their children.
73
527k
    while (global_tree[cur].property < kNumStaticProperties &&
74
451k
           global_tree[cur].property != -1) {
75
31.5k
      if (static_props[global_tree[cur].property] > global_tree[cur].splitval) {
76
17.6k
        cur = global_tree[cur].lchild;
77
17.6k
      } else {
78
13.8k
        cur = global_tree[cur].rchild;
79
13.8k
      }
80
31.5k
    }
81
496k
    FlatDecisionNode flat;
82
496k
    if (global_tree[cur].property == -1) {
83
422k
      flat.property0 = -1;
84
422k
      flat.childID = global_tree[cur].lchild;
85
422k
      flat.predictor = global_tree[cur].predictor;
86
422k
      flat.predictor_offset = global_tree[cur].predictor_offset;
87
422k
      flat.multiplier = global_tree[cur].multiplier;
88
422k
      *gradient_only &= flat.predictor == Predictor::Gradient;
89
422k
      has_wp |= flat.predictor == Predictor::Weighted;
90
422k
      has_non_wp |= flat.predictor != Predictor::Weighted;
91
422k
      output.push_back(flat);
92
422k
      continue;
93
422k
    }
94
73.7k
    flat.childID = output.size() + nodes.size() + 1;
95
96
73.7k
    flat.property0 = global_tree[cur].property;
97
73.7k
    *num_props = std::max<size_t>(flat.property0 + 1, *num_props);
98
73.7k
    flat.splitval0 = global_tree[cur].splitval;
99
100
232k
    for (size_t i = 0; i < 2; i++) {
101
159k
      size_t cur_child =
102
159k
          i == 0 ? global_tree[cur].lchild : global_tree[cur].rchild;
103
      // Skip nodes that we can decide now.
104
176k
      while (global_tree[cur_child].property < kNumStaticProperties &&
105
103k
             global_tree[cur_child].property != -1) {
106
17.5k
        if (static_props[global_tree[cur_child].property] >
107
17.5k
            global_tree[cur_child].splitval) {
108
10.6k
          cur_child = global_tree[cur_child].lchild;
109
10.6k
        } else {
110
6.83k
          cur_child = global_tree[cur_child].rchild;
111
6.83k
        }
112
17.5k
      }
113
      // We ended up in a leaf, add a placeholder decision and two copies of the
114
      // leaf.
115
159k
      if (global_tree[cur_child].property == -1) {
116
87.0k
        flat.properties[i] = 0;
117
87.0k
        flat.splitvals[i] = 0;
118
87.0k
        nodes.push(cur_child);
119
87.0k
        nodes.push(cur_child);
120
87.0k
      } else {
121
72.1k
        flat.properties[i] = global_tree[cur_child].property;
122
72.1k
        flat.splitvals[i] = global_tree[cur_child].splitval;
123
72.1k
        nodes.push(global_tree[cur_child].lchild);
124
72.1k
        nodes.push(global_tree[cur_child].rchild);
125
72.1k
        *num_props = std::max<size_t>(flat.properties[i] + 1, *num_props);
126
72.1k
      }
127
159k
    }
128
129
156k
    for (int16_t property : flat.properties) mark_property(property);
130
73.7k
    mark_property(flat.property0);
131
73.7k
    output.push_back(flat);
132
73.7k
  }
133
184k
  if (*num_props > kNumNonrefProperties) {
134
677
    *num_props =
135
677
        DivCeil(*num_props - kNumNonrefProperties, kExtraPropsPerChannel) *
136
677
            kExtraPropsPerChannel +
137
677
        kNumNonrefProperties;
138
184k
  } else {
139
184k
    *num_props = kNumNonrefProperties;
140
184k
  }
141
184k
  *use_wp = has_wp;
142
184k
  *wp_only = has_wp && !has_non_wp;
143
144
184k
  return output;
145
184k
}
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
184k
                                 uint32_t &fl_v) {
157
184k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
184k
  Channel &channel = image->channel[chan];
159
160
184k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
184k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
184k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
184k
  bool tree_has_wp_prop_or_pred = false;
168
184k
  bool is_wp_only = false;
169
184k
  bool is_gradient_only = false;
170
184k
  size_t num_props;
171
184k
  FlatTree tree =
172
184k
      FilterTree(global_tree, static_props, &num_props,
173
184k
                 &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
512k
  for (auto &node : tree) {
178
512k
    if (node.property0 == -1) {
179
430k
      node.childID = context_map[node.childID];
180
430k
    }
181
512k
  }
182
183
184k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
184k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
50.5M
                             pixel_type_w offset) -> pixel_type {
188
50.5M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
50.5M
    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.5M
    return val * multiplier + offset;
192
50.5M
  };
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
9.19M
                             pixel_type_w offset) -> pixel_type {
188
9.19M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
9.19M
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
9.19M
    return val * multiplier + offset;
192
9.19M
  };
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
41.3M
                             pixel_type_w offset) -> pixel_type {
188
41.3M
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
41.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
41.3M
    return val * multiplier + offset;
192
41.3M
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
184k
  const bool global_tree_is_all_gradient_noop = [&] {
200
198k
    for (const auto& n : global_tree) {
201
198k
      if (n.property == -1) {
202
170k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
572
            n.multiplier != 1)
204
170k
          return false;
205
170k
      } else if (n.property >= kNumStaticProperties) {
206
13.9k
        return false;
207
13.9k
      }
208
198k
    }
209
597
    return true;
210
184k
  }();
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()#1}::operator()() const
Line
Count
Source
199
6.99k
  const bool global_tree_is_all_gradient_noop = [&] {
200
7.30k
    for (const auto& n : global_tree) {
201
7.30k
      if (n.property == -1) {
202
6.98k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
6
            n.multiplier != 1)
204
6.98k
          return false;
205
6.98k
      } else if (n.property >= kNumStaticProperties) {
206
6
        return false;
207
6
      }
208
7.30k
    }
209
5
    return true;
210
6.99k
  }();
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()#1}::operator()() const
Line
Count
Source
199
177k
  const bool global_tree_is_all_gradient_noop = [&] {
200
191k
    for (const auto& n : global_tree) {
201
191k
      if (n.property == -1) {
202
163k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
566
            n.multiplier != 1)
204
163k
          return false;
205
163k
      } else if (n.property >= kNumStaticProperties) {
206
13.9k
        return false;
207
13.9k
      }
208
191k
    }
209
592
    return true;
210
177k
  }();
211
212
184k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
171k
    Predictor predictor = tree[0].predictor;
216
171k
    int64_t offset = tree[0].predictor_offset;
217
171k
    int32_t multiplier = tree[0].multiplier;
218
171k
    size_t ctx_id = tree[0].childID;
219
171k
    if (predictor == Predictor::Zero) {
220
168k
      uint32_t value;
221
168k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
168k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
12.9k
        JXL_DEBUG_V(8, "Fastest track.");
226
12.9k
        pixel_type v = make_pixel(value, multiplier, offset);
227
996k
        for (size_t y = 0; y < channel.h; y++) {
228
983k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
983k
          std::fill(r, r + channel.w, v);
230
983k
        }
231
155k
      } else {
232
155k
        JXL_DEBUG_V(8, "Fast track.");
233
155k
        if (multiplier == 1 && offset == 0) {
234
3.58M
          for (size_t y = 0; y < channel.h; y++) {
235
3.43M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
232M
            for (size_t x = 0; x < channel.w; x++) {
237
229M
              uint32_t v =
238
229M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
229M
              r[x] = UnpackSigned(v);
240
229M
            }
241
3.43M
          }
242
155k
        } else {
243
20.7k
          for (size_t y = 0; y < channel.h; y++) {
244
20.4k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
4.96M
            for (size_t x = 0; x < channel.w; x++) {
246
4.94M
              uint32_t v =
247
4.94M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
4.94M
                                                                         br);
249
4.94M
              r[x] = make_pixel(v, multiplier, offset);
250
4.94M
            }
251
20.4k
          }
252
282
        }
253
155k
      }
254
168k
      return true;
255
168k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
0
               global_tree_is_all_gradient_noop) {
257
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
0
      pixel_type_w sv = UnpackSigned(fl_v);
259
0
      for (size_t y = 0; y < channel.h; y++) {
260
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
0
        const pixel_type *JXL_RESTRICT rtopleft =
263
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
0
        if (fl_run == 0) {
266
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
0
                                                     &fl_run);
268
0
          sv = UnpackSigned(fl_v);
269
0
        } else {
270
0
          fl_run--;
271
0
        }
272
0
        r[0] = sv + guess_0;
273
0
        for (size_t x = 1; x < channel.w; x++) {
274
0
          pixel_type left = r[x - 1];
275
0
          pixel_type top = rtop[x];
276
0
          pixel_type topleft = rtopleft[x];
277
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
0
          if (!fl_run) {
279
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
0
                                                       &fl_run);
281
0
            sv = UnpackSigned(fl_v);
282
0
          } else {
283
0
            fl_run--;
284
0
          }
285
0
          r[x] = sv + guess;
286
0
        }
287
0
      }
288
0
      return true;
289
2.97k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
590
               multiplier == 1) {
291
590
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
590
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
63.4k
      for (size_t y = 0; y < channel.h; y++) {
294
62.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
165k
        for (size_t x = 0; x < channel.w; x++) {
296
102k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
102k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
102k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
102k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
102k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
102k
              ctx_id, br);
302
102k
          r[x] = make_pixel(v, 1, guess);
303
102k
        }
304
62.8k
      }
305
590
      return true;
306
590
    }
307
171k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
15.2k
  if (is_wp_only) {
312
2.24k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
2.24k
  }
314
15.2k
  if (is_gradient_only) {
315
850
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
850
  }
317
318
15.2k
  if (is_gradient_only) {
319
810
    JXL_DEBUG_V(8, "Gradient fast track.");
320
810
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
1.93k
    for (size_t y = 0; y < channel.h; y++) {
322
1.12k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
111k
      for (size_t x = 0; x < channel.w; x++) {
324
110k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
110k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
110k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
110k
        int32_t guess = ClampedGradient(top, left, topleft);
328
110k
        uint32_t pos =
329
110k
            kPropRangeFast +
330
110k
            std::min<pixel_type_w>(
331
110k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
110k
                kPropRangeFast - 1);
333
110k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
110k
        uint64_t v =
335
110k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
110k
        r[x] = make_pixel(v, 1, guess);
337
110k
      }
338
1.12k
    }
339
14.4k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
916
    JXL_DEBUG_V(8, "WP fast track.");
341
916
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
916
    Properties properties(1);
343
6.85k
    for (size_t y = 0; y < channel.h; y++) {
344
5.93k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
5.93k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
5.93k
      const pixel_type *JXL_RESTRICT rtoptop =
347
5.93k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
5.93k
      const pixel_type *JXL_RESTRICT rtopleft =
349
5.93k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
5.93k
      const pixel_type *JXL_RESTRICT rtopright =
351
5.93k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
5.93k
      size_t x = 0;
353
5.93k
      {
354
5.93k
        size_t offset = 0;
355
5.93k
        pixel_type_w left = y ? rtop[x] : 0;
356
5.93k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
5.93k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
5.93k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
5.93k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
5.93k
            offset);
361
5.93k
        uint32_t pos =
362
5.93k
            kPropRangeFast +
363
5.93k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
5.93k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
5.93k
        uint64_t v =
366
5.93k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
5.93k
        r[x] = make_pixel(v, 1, guess);
368
5.93k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
5.93k
      }
370
365k
      for (x = 1; x + 1 < channel.w; x++) {
371
359k
        size_t offset = 0;
372
359k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
359k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
359k
            rtoptop[x], &properties, offset);
375
359k
        uint32_t pos =
376
359k
            kPropRangeFast +
377
359k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
359k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
359k
        uint64_t v =
380
359k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
359k
        r[x] = make_pixel(v, 1, guess);
382
359k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
359k
      }
384
5.93k
      {
385
5.93k
        size_t offset = 0;
386
5.93k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
5.93k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
5.93k
            rtoptop[x], &properties, offset);
389
5.93k
        uint32_t pos =
390
5.93k
            kPropRangeFast +
391
5.93k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
5.93k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
5.93k
        uint64_t v =
394
5.93k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
5.93k
        r[x] = make_pixel(v, 1, guess);
396
5.93k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
5.93k
      }
398
5.93k
    }
399
13.4k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
6.05k
    JXL_DEBUG_V(8, "Slow track.");
403
6.05k
    MATreeLookup tree_lookup(tree);
404
6.05k
    Properties properties = Properties(num_props);
405
6.05k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
6.05k
    JXL_ASSIGN_OR_RETURN(
407
6.05k
        Channel references,
408
6.05k
        Channel::Create(memory_manager,
409
6.05k
                        properties.size() - kNumNonrefProperties, channel.w));
410
191k
    for (size_t y = 0; y < channel.h; y++) {
411
185k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
185k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
185k
      InitPropsRow(&properties, static_props, y);
414
185k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
381k
        for (size_t x = 0; x < 2; x++) {
416
254k
          PredictionResult res =
417
254k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
254k
                              tree_lookup, references);
419
254k
          uint64_t v =
420
254k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
254k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
254k
        }
423
17.2M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
17.1M
          PredictionResult res =
425
17.1M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
17.1M
                                 tree_lookup, references);
427
17.1M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
17.1M
              res.context, br);
429
17.1M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
17.1M
        }
431
381k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
254k
          PredictionResult res =
433
254k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
254k
                              tree_lookup, references);
435
254k
          uint64_t v =
436
254k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
254k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
254k
        }
439
127k
      } else {
440
4.41M
        for (size_t x = 0; x < channel.w; x++) {
441
4.35M
          PredictionResult res =
442
4.35M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
4.35M
                              tree_lookup, references);
444
4.35M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
4.35M
              res.context, br);
446
4.35M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
4.35M
        }
448
58.7k
      }
449
185k
    }
450
7.43k
  } else {
451
7.43k
    JXL_DEBUG_V(8, "Slowest track.");
452
7.43k
    MATreeLookup tree_lookup(tree);
453
7.43k
    Properties properties = Properties(num_props);
454
7.43k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
7.43k
    JXL_ASSIGN_OR_RETURN(
456
7.43k
        Channel references,
457
7.43k
        Channel::Create(memory_manager,
458
7.43k
                        properties.size() - kNumNonrefProperties, channel.w));
459
7.43k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
419k
    for (size_t y = 0; y < channel.h; y++) {
461
412k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
412k
      InitPropsRow(&properties, static_props, y);
463
412k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
412k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
710k
        for (size_t x = 0; x < 2; x++) {
466
473k
          PredictionResult res =
467
473k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
473k
                            tree_lookup, references, &wp_state);
469
473k
          uint64_t v =
470
473k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
473k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
473k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
473k
        }
474
18.5M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
18.3M
          PredictionResult res =
476
18.3M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
18.3M
                               tree_lookup, references, &wp_state);
478
18.3M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
18.3M
              res.context, br);
480
18.3M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
18.3M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
18.3M
        }
483
710k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
473k
          PredictionResult res =
485
473k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
473k
                            tree_lookup, references, &wp_state);
487
473k
          uint64_t v =
488
473k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
473k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
473k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
473k
        }
492
237k
      } else {
493
6.61M
        for (size_t x = 0; x < channel.w; x++) {
494
6.44M
          PredictionResult res =
495
6.44M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
6.44M
                            tree_lookup, references, &wp_state);
497
6.44M
          uint64_t v =
498
6.44M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
6.44M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
6.44M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
6.44M
        }
502
175k
      }
503
412k
    }
504
7.43k
  }
505
15.2k
  return true;
506
15.2k
}
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
6.98k
                                 uint32_t &fl_v) {
157
6.98k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
6.98k
  Channel &channel = image->channel[chan];
159
160
6.98k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
6.98k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
6.98k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
6.98k
  bool tree_has_wp_prop_or_pred = false;
168
6.98k
  bool is_wp_only = false;
169
6.98k
  bool is_gradient_only = false;
170
6.98k
  size_t num_props;
171
6.98k
  FlatTree tree =
172
6.98k
      FilterTree(global_tree, static_props, &num_props,
173
6.98k
                 &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
7.68k
  for (auto &node : tree) {
178
7.68k
    if (node.property0 == -1) {
179
7.51k
      node.childID = context_map[node.childID];
180
7.51k
    }
181
7.68k
  }
182
183
6.98k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
6.98k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
6.98k
                             pixel_type_w offset) -> pixel_type {
188
6.98k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
6.98k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
6.98k
    return val * multiplier + offset;
192
6.98k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
6.98k
  const bool global_tree_is_all_gradient_noop = [&] {
200
6.98k
    for (const auto& n : global_tree) {
201
6.98k
      if (n.property == -1) {
202
6.98k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
6.98k
            n.multiplier != 1)
204
6.98k
          return false;
205
6.98k
      } else if (n.property >= kNumStaticProperties) {
206
6.98k
        return false;
207
6.98k
      }
208
6.98k
    }
209
6.98k
    return true;
210
6.98k
  }();
211
212
6.99k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
6.99k
    Predictor predictor = tree[0].predictor;
216
6.99k
    int64_t offset = tree[0].predictor_offset;
217
6.99k
    int32_t multiplier = tree[0].multiplier;
218
6.99k
    size_t ctx_id = tree[0].childID;
219
6.99k
    if (predictor == Predictor::Zero) {
220
6.63k
      uint32_t value;
221
6.63k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
6.63k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
26
        JXL_DEBUG_V(8, "Fastest track.");
226
26
        pixel_type v = make_pixel(value, multiplier, offset);
227
1.63k
        for (size_t y = 0; y < channel.h; y++) {
228
1.60k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
1.60k
          std::fill(r, r + channel.w, v);
230
1.60k
        }
231
6.60k
      } else {
232
6.60k
        JXL_DEBUG_V(8, "Fast track.");
233
6.60k
        if (multiplier == 1 && offset == 0) {
234
801k
          for (size_t y = 0; y < channel.h; y++) {
235
794k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
44.3M
            for (size_t x = 0; x < channel.w; x++) {
237
43.5M
              uint32_t v =
238
43.5M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
43.5M
              r[x] = UnpackSigned(v);
240
43.5M
            }
241
794k
          }
242
6.46k
        } else {
243
18.9k
          for (size_t y = 0; y < channel.h; y++) {
244
18.7k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
4.48M
            for (size_t x = 0; x < channel.w; x++) {
246
4.46M
              uint32_t v =
247
4.46M
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
4.46M
                                                                         br);
249
4.46M
              r[x] = make_pixel(v, multiplier, offset);
250
4.46M
            }
251
18.7k
          }
252
142
        }
253
6.60k
      }
254
6.63k
      return true;
255
6.63k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
0
               global_tree_is_all_gradient_noop) {
257
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
0
      pixel_type_w sv = UnpackSigned(fl_v);
259
0
      for (size_t y = 0; y < channel.h; y++) {
260
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
0
        const pixel_type *JXL_RESTRICT rtopleft =
263
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
0
        if (fl_run == 0) {
266
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
0
                                                     &fl_run);
268
0
          sv = UnpackSigned(fl_v);
269
0
        } else {
270
0
          fl_run--;
271
0
        }
272
0
        r[0] = sv + guess_0;
273
0
        for (size_t x = 1; x < channel.w; x++) {
274
0
          pixel_type left = r[x - 1];
275
0
          pixel_type top = rtop[x];
276
0
          pixel_type topleft = rtopleft[x];
277
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
0
          if (!fl_run) {
279
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
0
                                                       &fl_run);
281
0
            sv = UnpackSigned(fl_v);
282
0
          } else {
283
0
            fl_run--;
284
0
          }
285
0
          r[x] = sv + guess;
286
0
        }
287
0
      }
288
0
      return true;
289
359
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
3
               multiplier == 1) {
291
3
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
3
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
99
      for (size_t y = 0; y < channel.h; y++) {
294
96
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
3.16k
        for (size_t x = 0; x < channel.w; x++) {
296
3.07k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
3.07k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
3.07k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
3.07k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
3.07k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
3.07k
              ctx_id, br);
302
3.07k
          r[x] = make_pixel(v, 1, guess);
303
3.07k
        }
304
96
      }
305
3
      return true;
306
3
    }
307
6.99k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
345
  if (is_wp_only) {
312
294
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
294
  }
314
345
  if (is_gradient_only) {
315
0
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
0
  }
317
318
345
  if (is_gradient_only) {
319
0
    JXL_DEBUG_V(8, "Gradient fast track.");
320
0
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
0
    for (size_t y = 0; y < channel.h; y++) {
322
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
0
      for (size_t x = 0; x < channel.w; x++) {
324
0
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
0
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
0
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
0
        int32_t guess = ClampedGradient(top, left, topleft);
328
0
        uint32_t pos =
329
0
            kPropRangeFast +
330
0
            std::min<pixel_type_w>(
331
0
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
0
                kPropRangeFast - 1);
333
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
0
        uint64_t v =
335
0
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
0
        r[x] = make_pixel(v, 1, guess);
337
0
      }
338
0
    }
339
345
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
0
    JXL_DEBUG_V(8, "WP fast track.");
341
0
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
0
    Properties properties(1);
343
0
    for (size_t y = 0; y < channel.h; y++) {
344
0
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
0
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
0
      const pixel_type *JXL_RESTRICT rtoptop =
347
0
          (y > 1 ? channel.Row(y - 2) : rtop);
348
0
      const pixel_type *JXL_RESTRICT rtopleft =
349
0
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
0
      const pixel_type *JXL_RESTRICT rtopright =
351
0
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
0
      size_t x = 0;
353
0
      {
354
0
        size_t offset = 0;
355
0
        pixel_type_w left = y ? rtop[x] : 0;
356
0
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
0
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
0
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
0
            offset);
361
0
        uint32_t pos =
362
0
            kPropRangeFast +
363
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
0
        uint64_t v =
366
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
0
        r[x] = make_pixel(v, 1, guess);
368
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
0
      }
370
0
      for (x = 1; x + 1 < channel.w; x++) {
371
0
        size_t offset = 0;
372
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
0
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
0
            rtoptop[x], &properties, offset);
375
0
        uint32_t pos =
376
0
            kPropRangeFast +
377
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
0
        uint64_t v =
380
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
0
        r[x] = make_pixel(v, 1, guess);
382
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
0
      }
384
0
      {
385
0
        size_t offset = 0;
386
0
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
0
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
0
            rtoptop[x], &properties, offset);
389
0
        uint32_t pos =
390
0
            kPropRangeFast +
391
0
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
0
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
0
        uint64_t v =
394
0
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
0
        r[x] = make_pixel(v, 1, guess);
396
0
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
0
      }
398
0
    }
399
345
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
61
    JXL_DEBUG_V(8, "Slow track.");
403
61
    MATreeLookup tree_lookup(tree);
404
61
    Properties properties = Properties(num_props);
405
61
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
61
    JXL_ASSIGN_OR_RETURN(
407
61
        Channel references,
408
61
        Channel::Create(memory_manager,
409
61
                        properties.size() - kNumNonrefProperties, channel.w));
410
4.08k
    for (size_t y = 0; y < channel.h; y++) {
411
4.01k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
4.01k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
4.01k
      InitPropsRow(&properties, static_props, y);
414
4.01k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
11.6k
        for (size_t x = 0; x < 2; x++) {
416
7.74k
          PredictionResult res =
417
7.74k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
7.74k
                              tree_lookup, references);
419
7.74k
          uint64_t v =
420
7.74k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
7.74k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
7.74k
        }
423
1.08M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
1.07M
          PredictionResult res =
425
1.07M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
1.07M
                                 tree_lookup, references);
427
1.07M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
1.07M
              res.context, br);
429
1.07M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
1.07M
        }
431
11.6k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
7.74k
          PredictionResult res =
433
7.74k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
7.74k
                              tree_lookup, references);
435
7.74k
          uint64_t v =
436
7.74k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
7.74k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
7.74k
        }
439
3.87k
      } else {
440
10.8k
        for (size_t x = 0; x < channel.w; x++) {
441
10.7k
          PredictionResult res =
442
10.7k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
10.7k
                              tree_lookup, references);
444
10.7k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
10.7k
              res.context, br);
446
10.7k
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
10.7k
        }
448
149
      }
449
4.01k
    }
450
284
  } else {
451
284
    JXL_DEBUG_V(8, "Slowest track.");
452
284
    MATreeLookup tree_lookup(tree);
453
284
    Properties properties = Properties(num_props);
454
284
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
284
    JXL_ASSIGN_OR_RETURN(
456
284
        Channel references,
457
284
        Channel::Create(memory_manager,
458
284
                        properties.size() - kNumNonrefProperties, channel.w));
459
284
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
21.4k
    for (size_t y = 0; y < channel.h; y++) {
461
21.1k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
21.1k
      InitPropsRow(&properties, static_props, y);
463
21.1k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
21.1k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
0
        for (size_t x = 0; x < 2; 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
0
        for (size_t x = 2; x < channel.w - 2; x++) {
475
0
          PredictionResult res =
476
0
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
0
                               tree_lookup, references, &wp_state);
478
0
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
0
              res.context, br);
480
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
0
        }
483
0
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
0
          PredictionResult res =
485
0
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
0
                            tree_lookup, references, &wp_state);
487
0
          uint64_t v =
488
0
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
0
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
0
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
0
        }
492
21.1k
      } else {
493
3.84M
        for (size_t x = 0; x < channel.w; x++) {
494
3.82M
          PredictionResult res =
495
3.82M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
3.82M
                            tree_lookup, references, &wp_state);
497
3.82M
          uint64_t v =
498
3.82M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
3.82M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
3.82M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
3.82M
        }
502
21.1k
      }
503
21.1k
    }
504
284
  }
505
345
  return true;
506
345
}
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
177k
                                 uint32_t &fl_v) {
157
177k
  JxlMemoryManager *memory_manager = image->memory_manager();
158
177k
  Channel &channel = image->channel[chan];
159
160
177k
  std::array<pixel_type, kNumStaticProperties> static_props = {
161
177k
      {chan, static_cast<int>(group_id)}};
162
  // TODO(veluca): filter the tree according to static_props.
163
164
  // zero pixel channel? could happen
165
177k
  if (channel.w == 0 || channel.h == 0) return true;
166
167
177k
  bool tree_has_wp_prop_or_pred = false;
168
177k
  bool is_wp_only = false;
169
177k
  bool is_gradient_only = false;
170
177k
  size_t num_props;
171
177k
  FlatTree tree =
172
177k
      FilterTree(global_tree, static_props, &num_props,
173
177k
                 &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
504k
  for (auto &node : tree) {
178
504k
    if (node.property0 == -1) {
179
423k
      node.childID = context_map[node.childID];
180
423k
    }
181
504k
  }
182
183
177k
  JXL_DEBUG_V(3, "Decoded MA tree with %" PRIuS " nodes", tree.size());
184
185
  // MAANS decode
186
177k
  const auto make_pixel = [](uint64_t v, pixel_type multiplier,
187
177k
                             pixel_type_w offset) -> pixel_type {
188
177k
    JXL_DASSERT((v & 0xFFFFFFFF) == v);
189
177k
    pixel_type_w val = static_cast<pixel_type_w>(UnpackSigned(v));
190
    // if it overflows, it overflows, and we have a problem anyway
191
177k
    return val * multiplier + offset;
192
177k
  };
193
194
  // True iff every decision node in global_tree splits on a static property
195
  // (channel or group_id) and every leaf has Gradient predictor with identity
196
  // transform. When this holds, all channels collapse to a single-leaf
197
  // Gradient+noop tree regardless of channel index, so the shared fl_run/fl_v
198
  // RLE state remains consistent across channel calls.
199
177k
  const bool global_tree_is_all_gradient_noop = [&] {
200
177k
    for (const auto& n : global_tree) {
201
177k
      if (n.property == -1) {
202
177k
        if (n.predictor != Predictor::Gradient || n.predictor_offset != 0 ||
203
177k
            n.multiplier != 1)
204
177k
          return false;
205
177k
      } else if (n.property >= kNumStaticProperties) {
206
177k
        return false;
207
177k
      }
208
177k
    }
209
177k
    return true;
210
177k
  }();
211
212
177k
  if (tree.size() == 1) {
213
    // special optimized case: no meta-adaptation, so no need
214
    // to compute properties.
215
164k
    Predictor predictor = tree[0].predictor;
216
164k
    int64_t offset = tree[0].predictor_offset;
217
164k
    int32_t multiplier = tree[0].multiplier;
218
164k
    size_t ctx_id = tree[0].childID;
219
164k
    if (predictor == Predictor::Zero) {
220
162k
      uint32_t value;
221
162k
      if (reader->IsSingleValueAndAdvance(ctx_id, &value,
222
162k
                                          channel.w * channel.h)) {
223
        // Special-case: histogram has a single symbol, with no extra bits, and
224
        // we use ANS mode.
225
12.9k
        JXL_DEBUG_V(8, "Fastest track.");
226
12.9k
        pixel_type v = make_pixel(value, multiplier, offset);
227
995k
        for (size_t y = 0; y < channel.h; y++) {
228
982k
          pixel_type *JXL_RESTRICT r = channel.Row(y);
229
982k
          std::fill(r, r + channel.w, v);
230
982k
        }
231
149k
      } else {
232
149k
        JXL_DEBUG_V(8, "Fast track.");
233
149k
        if (multiplier == 1 && offset == 0) {
234
2.78M
          for (size_t y = 0; y < channel.h; y++) {
235
2.63M
            pixel_type *JXL_RESTRICT r = channel.Row(y);
236
188M
            for (size_t x = 0; x < channel.w; x++) {
237
185M
              uint32_t v =
238
185M
                  reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
239
185M
              r[x] = UnpackSigned(v);
240
185M
            }
241
2.63M
          }
242
149k
        } else {
243
1.80k
          for (size_t y = 0; y < channel.h; y++) {
244
1.66k
            pixel_type *JXL_RESTRICT r = channel.Row(y);
245
478k
            for (size_t x = 0; x < channel.w; x++) {
246
476k
              uint32_t v =
247
476k
                  reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id,
248
476k
                                                                         br);
249
476k
              r[x] = make_pixel(v, multiplier, offset);
250
476k
            }
251
1.66k
          }
252
140
        }
253
149k
      }
254
162k
      return true;
255
162k
    } else if (uses_lz77 && reader->IsHuffRleOnly() &&
256
0
               global_tree_is_all_gradient_noop) {
257
0
      JXL_DEBUG_V(8, "Gradient RLE (fjxl) very fast track.");
258
0
      pixel_type_w sv = UnpackSigned(fl_v);
259
0
      for (size_t y = 0; y < channel.h; y++) {
260
0
        pixel_type *JXL_RESTRICT r = channel.Row(y);
261
0
        const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
262
0
        const pixel_type *JXL_RESTRICT rtopleft =
263
0
            (y ? channel.Row(y - 1) - 1 : r - 1);
264
0
        pixel_type_w guess_0 = (y ? rtop[0] : 0);
265
0
        if (fl_run == 0) {
266
0
          reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
267
0
                                                     &fl_run);
268
0
          sv = UnpackSigned(fl_v);
269
0
        } else {
270
0
          fl_run--;
271
0
        }
272
0
        r[0] = sv + guess_0;
273
0
        for (size_t x = 1; x < channel.w; x++) {
274
0
          pixel_type left = r[x - 1];
275
0
          pixel_type top = rtop[x];
276
0
          pixel_type topleft = rtopleft[x];
277
0
          pixel_type_w guess = ClampedGradient(top, left, topleft);
278
0
          if (!fl_run) {
279
0
            reader->ReadHybridUintClusteredHuffRleOnly(ctx_id, br, &fl_v,
280
0
                                                       &fl_run);
281
0
            sv = UnpackSigned(fl_v);
282
0
          } else {
283
0
            fl_run--;
284
0
          }
285
0
          r[x] = sv + guess;
286
0
        }
287
0
      }
288
0
      return true;
289
2.61k
    } else if (predictor == Predictor::Gradient && offset == 0 &&
290
587
               multiplier == 1) {
291
587
      JXL_DEBUG_V(8, "Gradient very fast track.");
292
587
      const ptrdiff_t onerow = channel.plane.PixelsPerRow();
293
63.3k
      for (size_t y = 0; y < channel.h; y++) {
294
62.8k
        pixel_type *JXL_RESTRICT r = channel.Row(y);
295
162k
        for (size_t x = 0; x < channel.w; x++) {
296
99.8k
          pixel_type left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
297
99.8k
          pixel_type top = (y ? *(r + x - onerow) : left);
298
99.8k
          pixel_type topleft = (x && y ? *(r + x - 1 - onerow) : left);
299
99.8k
          pixel_type guess = ClampedGradient(top, left, topleft);
300
99.8k
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
301
99.8k
              ctx_id, br);
302
99.8k
          r[x] = make_pixel(v, 1, guess);
303
99.8k
        }
304
62.8k
      }
305
587
      return true;
306
587
    }
307
164k
  }
308
309
  // Check if this tree is a WP-only tree with a small enough property value
310
  // range.
311
14.8k
  if (is_wp_only) {
312
1.94k
    is_wp_only = TreeToLookupTable(tree, tree_lut);
313
1.94k
  }
314
14.8k
  if (is_gradient_only) {
315
850
    is_gradient_only = TreeToLookupTable(tree, tree_lut);
316
850
  }
317
318
14.8k
  if (is_gradient_only) {
319
810
    JXL_DEBUG_V(8, "Gradient fast track.");
320
810
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
321
1.93k
    for (size_t y = 0; y < channel.h; y++) {
322
1.12k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
323
111k
      for (size_t x = 0; x < channel.w; x++) {
324
110k
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
325
110k
        pixel_type_w top = (y ? *(r + x - onerow) : left);
326
110k
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
327
110k
        int32_t guess = ClampedGradient(top, left, topleft);
328
110k
        uint32_t pos =
329
110k
            kPropRangeFast +
330
110k
            std::min<pixel_type_w>(
331
110k
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
332
110k
                kPropRangeFast - 1);
333
110k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
334
110k
        uint64_t v =
335
110k
            reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(ctx_id, br);
336
110k
        r[x] = make_pixel(v, 1, guess);
337
110k
      }
338
1.12k
    }
339
14.0k
  } else if (!uses_lz77 && is_wp_only && channel.w > 8) {
340
916
    JXL_DEBUG_V(8, "WP fast track.");
341
916
    weighted::State wp_state(wp_header, channel.w, channel.h);
342
916
    Properties properties(1);
343
6.85k
    for (size_t y = 0; y < channel.h; y++) {
344
5.93k
      pixel_type *JXL_RESTRICT r = channel.Row(y);
345
5.93k
      const pixel_type *JXL_RESTRICT rtop = (y ? channel.Row(y - 1) : r - 1);
346
5.93k
      const pixel_type *JXL_RESTRICT rtoptop =
347
5.93k
          (y > 1 ? channel.Row(y - 2) : rtop);
348
5.93k
      const pixel_type *JXL_RESTRICT rtopleft =
349
5.93k
          (y ? channel.Row(y - 1) - 1 : r - 1);
350
5.93k
      const pixel_type *JXL_RESTRICT rtopright =
351
5.93k
          (y ? channel.Row(y - 1) + 1 : r - 1);
352
5.93k
      size_t x = 0;
353
5.93k
      {
354
5.93k
        size_t offset = 0;
355
5.93k
        pixel_type_w left = y ? rtop[x] : 0;
356
5.93k
        pixel_type_w toptop = y ? rtoptop[x] : 0;
357
5.93k
        pixel_type_w topright = (x + 1 < channel.w && y ? rtop[x + 1] : left);
358
5.93k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
359
5.93k
            x, y, channel.w, left, left, topright, left, toptop, &properties,
360
5.93k
            offset);
361
5.93k
        uint32_t pos =
362
5.93k
            kPropRangeFast +
363
5.93k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
364
5.93k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
365
5.93k
        uint64_t v =
366
5.93k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
367
5.93k
        r[x] = make_pixel(v, 1, guess);
368
5.93k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
369
5.93k
      }
370
365k
      for (x = 1; x + 1 < channel.w; x++) {
371
359k
        size_t offset = 0;
372
359k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
373
359k
            x, y, channel.w, rtop[x], r[x - 1], rtopright[x], rtopleft[x],
374
359k
            rtoptop[x], &properties, offset);
375
359k
        uint32_t pos =
376
359k
            kPropRangeFast +
377
359k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
378
359k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
379
359k
        uint64_t v =
380
359k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
381
359k
        r[x] = make_pixel(v, 1, guess);
382
359k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
383
359k
      }
384
5.93k
      {
385
5.93k
        size_t offset = 0;
386
5.93k
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
387
5.93k
            x, y, channel.w, rtop[x], r[x - 1], rtop[x], rtopleft[x],
388
5.93k
            rtoptop[x], &properties, offset);
389
5.93k
        uint32_t pos =
390
5.93k
            kPropRangeFast +
391
5.93k
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
392
5.93k
        uint32_t ctx_id = tree_lut.context_lookup[pos];
393
5.93k
        uint64_t v =
394
5.93k
            reader->ReadHybridUintClusteredInlined<uses_lz77>(ctx_id, br);
395
5.93k
        r[x] = make_pixel(v, 1, guess);
396
5.93k
        wp_state.UpdateErrors(r[x], x, y, channel.w);
397
5.93k
      }
398
5.93k
    }
399
13.1k
  } else if (!tree_has_wp_prop_or_pred) {
400
    // special optimized case: the weighted predictor and its properties are not
401
    // used, so no need to compute weights and properties.
402
5.99k
    JXL_DEBUG_V(8, "Slow track.");
403
5.99k
    MATreeLookup tree_lookup(tree);
404
5.99k
    Properties properties = Properties(num_props);
405
5.99k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
406
5.99k
    JXL_ASSIGN_OR_RETURN(
407
5.99k
        Channel references,
408
5.99k
        Channel::Create(memory_manager,
409
5.99k
                        properties.size() - kNumNonrefProperties, channel.w));
410
187k
    for (size_t y = 0; y < channel.h; y++) {
411
181k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
412
181k
      PrecomputeReferences(channel, y, *image, chan, &references);
413
181k
      InitPropsRow(&properties, static_props, y);
414
181k
      if (y > 1 && channel.w > 8 && references.w == 0) {
415
369k
        for (size_t x = 0; x < 2; x++) {
416
246k
          PredictionResult res =
417
246k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
418
246k
                              tree_lookup, references);
419
246k
          uint64_t v =
420
246k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
421
246k
          p[x] = make_pixel(v, res.multiplier, res.guess);
422
246k
        }
423
16.1M
        for (size_t x = 2; x < channel.w - 2; x++) {
424
16.0M
          PredictionResult res =
425
16.0M
              PredictTreeNoWPNEC(&properties, channel.w, p + x, onerow, x, y,
426
16.0M
                                 tree_lookup, references);
427
16.0M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
428
16.0M
              res.context, br);
429
16.0M
          p[x] = make_pixel(v, res.multiplier, res.guess);
430
16.0M
        }
431
369k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
432
246k
          PredictionResult res =
433
246k
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
434
246k
                              tree_lookup, references);
435
246k
          uint64_t v =
436
246k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
437
246k
          p[x] = make_pixel(v, res.multiplier, res.guess);
438
246k
        }
439
123k
      } else {
440
4.39M
        for (size_t x = 0; x < channel.w; x++) {
441
4.34M
          PredictionResult res =
442
4.34M
              PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
443
4.34M
                              tree_lookup, references);
444
4.34M
          uint64_t v = reader->ReadHybridUintClusteredMaybeInlined<uses_lz77>(
445
4.34M
              res.context, br);
446
4.34M
          p[x] = make_pixel(v, res.multiplier, res.guess);
447
4.34M
        }
448
58.6k
      }
449
181k
    }
450
7.15k
  } else {
451
7.15k
    JXL_DEBUG_V(8, "Slowest track.");
452
7.15k
    MATreeLookup tree_lookup(tree);
453
7.15k
    Properties properties = Properties(num_props);
454
7.15k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
455
7.15k
    JXL_ASSIGN_OR_RETURN(
456
7.15k
        Channel references,
457
7.15k
        Channel::Create(memory_manager,
458
7.15k
                        properties.size() - kNumNonrefProperties, channel.w));
459
7.15k
    weighted::State wp_state(wp_header, channel.w, channel.h);
460
398k
    for (size_t y = 0; y < channel.h; y++) {
461
391k
      pixel_type *JXL_RESTRICT p = channel.Row(y);
462
391k
      InitPropsRow(&properties, static_props, y);
463
391k
      PrecomputeReferences(channel, y, *image, chan, &references);
464
398k
      if (!uses_lz77 && y > 1 && channel.w > 8 && references.w == 0) {
465
710k
        for (size_t x = 0; x < 2; x++) {
466
473k
          PredictionResult res =
467
473k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
468
473k
                            tree_lookup, references, &wp_state);
469
473k
          uint64_t v =
470
473k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
471
473k
          p[x] = make_pixel(v, res.multiplier, res.guess);
472
473k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
473
473k
        }
474
18.5M
        for (size_t x = 2; x < channel.w - 2; x++) {
475
18.3M
          PredictionResult res =
476
18.3M
              PredictTreeWPNEC(&properties, channel.w, p + x, onerow, x, y,
477
18.3M
                               tree_lookup, references, &wp_state);
478
18.3M
          uint64_t v = reader->ReadHybridUintClusteredInlined<uses_lz77>(
479
18.3M
              res.context, br);
480
18.3M
          p[x] = make_pixel(v, res.multiplier, res.guess);
481
18.3M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
482
18.3M
        }
483
710k
        for (size_t x = channel.w - 2; x < channel.w; x++) {
484
473k
          PredictionResult res =
485
473k
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
486
473k
                            tree_lookup, references, &wp_state);
487
473k
          uint64_t v =
488
473k
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
489
473k
          p[x] = make_pixel(v, res.multiplier, res.guess);
490
473k
          wp_state.UpdateErrors(p[x], x, y, channel.w);
491
473k
        }
492
237k
      } else {
493
2.77M
        for (size_t x = 0; x < channel.w; x++) {
494
2.61M
          PredictionResult res =
495
2.61M
              PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
496
2.61M
                            tree_lookup, references, &wp_state);
497
2.61M
          uint64_t v =
498
2.61M
              reader->ReadHybridUintClustered<uses_lz77>(res.context, br);
499
2.61M
          p[x] = make_pixel(v, res.multiplier, res.guess);
500
2.61M
          wp_state.UpdateErrors(p[x], x, y, channel.w);
501
2.61M
        }
502
154k
      }
503
391k
    }
504
7.15k
  }
505
14.8k
  return true;
506
14.8k
}
507
}  // namespace detail
508
509
Status DecodeModularChannelMAANS(BitReader *br, ANSSymbolReader *reader,
510
                                 const std::vector<uint8_t> &context_map,
511
                                 const Tree &global_tree,
512
                                 const weighted::Header &wp_header,
513
                                 pixel_type chan, size_t group_id,
514
                                 TreeLut<uint8_t, false, false> &tree_lut,
515
                                 Image *image, uint32_t &fl_run,
516
184k
                                 uint32_t &fl_v) {
517
184k
  if (reader->UsesLZ77()) {
518
6.98k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/true>(
519
6.98k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
520
6.98k
        tree_lut, image, fl_run, fl_v);
521
177k
  } else {
522
177k
    return detail::DecodeModularChannelMAANS</*uses_lz77=*/false>(
523
177k
        br, reader, context_map, global_tree, wp_header, chan, group_id,
524
177k
        tree_lut, image, fl_run, fl_v);
525
177k
  }
526
184k
}
527
528
307k
GroupHeader::GroupHeader() { Bundle::Init(this); }
529
530
Status ValidateChannelDimensions(const Image &image,
531
32.7k
                                 const ModularOptions &options) {
532
32.7k
  size_t nb_channels = image.channel.size();
533
65.3k
  for (bool is_dc : {true, false}) {
534
65.3k
    size_t group_dim = options.group_dim * (is_dc ? kBlockDim : 1);
535
65.3k
    size_t c = image.nb_meta_channels;
536
438k
    for (; c < nb_channels; c++) {
537
375k
      const Channel &ch = image.channel[c];
538
375k
      if (ch.w > options.group_dim || ch.h > options.group_dim) break;
539
375k
    }
540
83.5k
    for (; c < nb_channels; c++) {
541
18.1k
      const Channel &ch = image.channel[c];
542
18.1k
      if (ch.w == 0 || ch.h == 0) continue;  // skip empty
543
18.1k
      bool is_dc_channel = std::min(ch.hshift, ch.vshift) >= 3;
544
18.1k
      if (is_dc_channel != is_dc) continue;
545
9.08k
      size_t tile_dim = group_dim >> std::max(ch.hshift, ch.vshift);
546
9.08k
      if (tile_dim == 0) {
547
0
        return JXL_FAILURE("Inconsistent transforms");
548
0
      }
549
9.08k
    }
550
65.3k
  }
551
32.7k
  return true;
552
32.7k
}
553
554
Status ModularDecode(BitReader *br, Image &image, GroupHeader &header,
555
                     size_t group_id, ModularOptions *options,
556
                     const Tree *global_tree, const ANSCode *global_code,
557
                     const std::vector<uint8_t> *global_ctx_map,
558
39.8k
                     const bool allow_truncated_group) {
559
39.8k
  if (image.channel.empty()) return true;
560
32.7k
  JxlMemoryManager *memory_manager = image.memory_manager();
561
562
  // decode transforms
563
32.7k
  Status status = Bundle::Read(br, &header);
564
32.7k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(status);
565
32.7k
  if (status.IsFatalError()) return status;
566
32.7k
  if (!br->AllReadsWithinBounds()) {
567
    // Don't do/undo transforms if header is incomplete.
568
0
    header.transforms.clear();
569
0
    image.transform = header.transforms;
570
0
    for (auto &ch : image.channel) {
571
0
      ZeroFillImage(&ch.plane);
572
0
    }
573
0
    return JXL_NOT_ENOUGH_BYTES("Read overrun before ModularDecode");
574
0
  }
575
576
32.7k
  JXL_DEBUG_V(3, "Image data underwent %" PRIuS " transformations: ",
577
32.7k
              header.transforms.size());
578
32.7k
  image.transform = header.transforms;
579
32.7k
  for (Transform &transform : image.transform) {
580
14.6k
    JXL_RETURN_IF_ERROR(transform.MetaApply(image));
581
14.6k
  }
582
32.6k
  if (image.error) {
583
0
    return JXL_FAILURE("Corrupt file. Aborting.");
584
0
  }
585
32.6k
  JXL_RETURN_IF_ERROR(ValidateChannelDimensions(image, *options));
586
587
32.6k
  size_t nb_channels = image.channel.size();
588
589
32.6k
  size_t num_chans = 0;
590
32.6k
  size_t distance_multiplier = 0;
591
224k
  for (size_t i = 0; i < nb_channels; i++) {
592
193k
    Channel &channel = image.channel[i];
593
193k
    if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
594
187k
                                        channel.h > options->max_chan_size)) {
595
1.06k
      break;
596
1.06k
    }
597
192k
    if (!channel.w || !channel.h) {
598
5.68k
      continue;  // skip empty channels
599
5.68k
    }
600
186k
    if (channel.w > distance_multiplier) {
601
45.8k
      distance_multiplier = channel.w;
602
45.8k
    }
603
186k
    num_chans++;
604
186k
  }
605
32.6k
  if (num_chans == 0) return true;
606
607
32.4k
  size_t next_channel = 0;
608
32.4k
  auto scope_guard = MakeScopeGuard([&]() {
609
2.14k
    for (size_t c = next_channel; c < image.channel.size(); c++) {
610
2.04k
      ZeroFillImage(&image.channel[c].plane);
611
2.04k
    }
612
101
  });
613
  // Do not do anything if truncated groups are not allowed.
614
32.4k
  if (allow_truncated_group) scope_guard.Disarm();
615
616
  // Read tree.
617
32.4k
  Tree tree_storage;
618
32.4k
  std::vector<uint8_t> context_map_storage;
619
32.4k
  ANSCode code_storage;
620
32.4k
  const Tree *tree = &tree_storage;
621
32.4k
  const ANSCode *code = &code_storage;
622
32.4k
  const std::vector<uint8_t> *context_map = &context_map_storage;
623
32.4k
  if (!header.use_global_tree) {
624
5.88k
    uint64_t max_tree_size = 1024;
625
32.8k
    for (size_t i = 0; i < nb_channels; i++) {
626
26.9k
      Channel &channel = image.channel[i];
627
26.9k
      if (i >= image.nb_meta_channels && (channel.w > options->max_chan_size ||
628
25.9k
                                          channel.h > options->max_chan_size)) {
629
6
        break;
630
6
      }
631
26.9k
      uint64_t pixels = channel.w * channel.h;
632
26.9k
      max_tree_size += pixels;
633
26.9k
    }
634
5.88k
    max_tree_size = std::min(static_cast<uint64_t>(1 << 20), max_tree_size);
635
5.88k
    JXL_RETURN_IF_ERROR(
636
5.88k
        DecodeTree(memory_manager, br, &tree_storage, max_tree_size));
637
5.85k
    JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br,
638
5.85k
                                         (tree_storage.size() + 1) / 2,
639
5.85k
                                         &code_storage, &context_map_storage));
640
26.5k
  } else {
641
26.5k
    if (!global_tree || !global_code || !global_ctx_map ||
642
26.5k
        global_tree->empty()) {
643
9
      return JXL_FAILURE("No global tree available but one was requested");
644
9
    }
645
26.5k
    tree = global_tree;
646
26.5k
    code = global_code;
647
26.5k
    context_map = global_ctx_map;
648
26.5k
  }
649
650
  // Read channels
651
64.8k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader reader,
652
64.8k
                       ANSSymbolReader::Create(code, br, distance_multiplier));
653
64.8k
  auto tree_lut = jxl::make_unique<TreeLut<uint8_t, false, false>>();
654
64.8k
  uint32_t fl_run = 0;
655
64.8k
  uint32_t fl_v = 0;
656
222k
  for (; next_channel < nb_channels; next_channel++) {
657
191k
    Channel &channel = image.channel[next_channel];
658
191k
    if (next_channel >= image.nb_meta_channels &&
659
185k
        (channel.w > options->max_chan_size ||
660
185k
         channel.h > options->max_chan_size)) {
661
830
      break;
662
830
    }
663
190k
    if (!channel.w || !channel.h) {
664
5.68k
      continue;  // skip empty channels
665
5.68k
    }
666
184k
    JXL_RETURN_IF_ERROR(DecodeModularChannelMAANS(
667
184k
        br, &reader, *context_map, *tree, header.wp_header, next_channel,
668
184k
        group_id, *tree_lut, &image, fl_run, fl_v));
669
670
    // Truncated group.
671
184k
    if (!br->AllReadsWithinBounds()) {
672
61
      if (!allow_truncated_group) return JXL_FAILURE("Truncated input");
673
0
      return JXL_NOT_ENOUGH_BYTES("Read overrun in ModularDecode");
674
61
    }
675
184k
  }
676
677
  // Make sure no zero-filling happens even if next_channel < nb_channels.
678
32.3k
  scope_guard.Disarm();
679
680
32.3k
  if (!reader.CheckANSFinalState()) {
681
0
    return JXL_FAILURE("ANS decode final state failed");
682
0
  }
683
32.3k
  return true;
684
32.3k
}
685
686
Status ModularGenericDecompress(BitReader *br, Image &image,
687
                                GroupHeader *header, size_t group_id,
688
                                ModularOptions *options, bool undo_transforms,
689
                                const Tree *tree, const ANSCode *code,
690
                                const std::vector<uint8_t> *ctx_map,
691
39.8k
                                bool allow_truncated_group) {
692
39.8k
  std::vector<std::pair<size_t, size_t>> req_sizes;
693
39.8k
  req_sizes.reserve(image.channel.size());
694
121k
  for (const auto &c : image.channel) {
695
121k
    req_sizes.emplace_back(c.w, c.h);
696
121k
  }
697
39.8k
  GroupHeader local_header;
698
39.8k
  if (header == nullptr) header = &local_header;
699
39.8k
  size_t bit_pos = br->TotalBitsConsumed();
700
39.8k
  auto dec_status = ModularDecode(br, image, *header, group_id, options, tree,
701
39.8k
                                  code, ctx_map, allow_truncated_group);
702
39.8k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
703
39.7k
  if (dec_status.IsFatalError()) return dec_status;
704
39.7k
  if (undo_transforms) image.undo_transforms(header->wp_header);
705
39.7k
  if (image.error) return JXL_FAILURE("Corrupt file. Aborting.");
706
39.7k
  JXL_DEBUG_V(4,
707
39.7k
              "Modular-decoded a %" PRIuS "x%" PRIuS " nbchans=%" PRIuS
708
39.7k
              " image from %" PRIuS " bytes",
709
39.7k
              image.w, image.h, image.channel.size(),
710
39.7k
              (br->TotalBitsConsumed() - bit_pos) / 8);
711
39.7k
  JXL_DEBUG_V(5, "Modular image: %s", image.DebugString().c_str());
712
39.7k
  (void)bit_pos;
713
  // Check that after applying all transforms we are back to the requested
714
  // image sizes, otherwise there's a programming error with the
715
  // transformations.
716
39.7k
  if (undo_transforms) {
717
22.4k
    JXL_ENSURE(image.channel.size() == req_sizes.size());
718
105k
    for (size_t c = 0; c < req_sizes.size(); c++) {
719
83.2k
      JXL_ENSURE(req_sizes[c].first == image.channel[c].w);
720
83.2k
      JXL_ENSURE(req_sizes[c].second == image.channel[c].h);
721
83.2k
    }
722
22.4k
  }
723
39.7k
  return dec_status;
724
39.7k
}
725
726
}  // namespace jxl