Coverage Report

Created: 2026-09-13 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/modular/encoding/enc_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 <jxl/memory_manager.h>
7
8
#include <algorithm>
9
#include <array>
10
#include <cstddef>
11
#include <cstdint>
12
#include <cstdlib>
13
#include <limits>
14
#include <queue>
15
#include <utility>
16
#include <vector>
17
18
#include "lib/jxl/base/bits.h"
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/status.h"
23
#include "lib/jxl/enc_ans.h"
24
#include "lib/jxl/enc_ans_params.h"
25
#include "lib/jxl/enc_aux_out.h"
26
#include "lib/jxl/enc_bit_writer.h"
27
#include "lib/jxl/enc_fields.h"
28
#include "lib/jxl/fields.h"
29
#include "lib/jxl/image.h"
30
#include "lib/jxl/image_ops.h"
31
#include "lib/jxl/modular/encoding/context_predict.h"
32
#include "lib/jxl/modular/encoding/dec_ma.h"
33
#include "lib/jxl/modular/encoding/enc_ma.h"
34
#include "lib/jxl/modular/encoding/encoding.h"
35
#include "lib/jxl/modular/encoding/ma_common.h"
36
#include "lib/jxl/modular/modular_image.h"
37
#include "lib/jxl/modular/options.h"
38
#include "lib/jxl/pack_signed.h"
39
40
namespace jxl {
41
42
namespace {
43
// Plot tree (if enabled) and predictor usage map.
44
constexpr bool kWantDebug = true;
45
// constexpr bool kPrintTree = false;
46
47
378M
inline std::array<uint8_t, 3> PredictorColor(Predictor p) {
48
378M
  switch (p) {
49
24.1M
    case Predictor::Zero:
50
24.1M
      return {{0, 0, 0}};
51
7.38M
    case Predictor::Left:
52
7.38M
      return {{255, 0, 0}};
53
0
    case Predictor::Top:
54
0
      return {{0, 255, 0}};
55
0
    case Predictor::Average0:
56
0
      return {{0, 0, 255}};
57
0
    case Predictor::Average4:
58
0
      return {{192, 128, 128}};
59
0
    case Predictor::Select:
60
0
      return {{255, 255, 0}};
61
346M
    case Predictor::Gradient:
62
346M
      return {{255, 0, 255}};
63
25.6k
    case Predictor::Weighted:
64
25.6k
      return {{0, 255, 255}};
65
      // TODO(jon)
66
0
    default:
67
0
      return {{255, 255, 255}};
68
378M
  };
69
0
}
70
71
// `cutoffs` must be sorted.
72
Tree MakeFixedTree(int property, const std::vector<int32_t> &cutoffs,
73
2.87k
                   Predictor pred, size_t num_pixels, int bitdepth) {
74
2.87k
  size_t log_px = CeilLog2Nonzero(num_pixels);
75
2.87k
  size_t min_gap = 0;
76
  // Reduce fixed tree height when encoding small images.
77
2.87k
  if (log_px < 14) {
78
2.25k
    min_gap = 8 * (14 - log_px);
79
2.25k
  }
80
2.87k
  const int shift = bitdepth > 11 ? std::min(4, bitdepth - 11) : 0;
81
2.87k
  const int mul = 1 << shift;
82
2.87k
  Tree tree;
83
2.87k
  struct NodeInfo {
84
2.87k
    size_t begin, end, pos;
85
2.87k
  };
86
2.87k
  std::queue<NodeInfo> q;
87
  // Leaf IDs will be set by roundtrip decoding the tree.
88
2.87k
  tree.push_back(PropertyDecisionNode::Leaf(pred));
89
2.87k
  q.push(NodeInfo{0, cutoffs.size(), 0});
90
50.1k
  while (!q.empty()) {
91
47.2k
    NodeInfo info = q.front();
92
47.2k
    q.pop();
93
47.2k
    if (info.begin + min_gap >= info.end) continue;
94
22.1k
    uint32_t split = (info.begin + info.end) / 2;
95
22.1k
    int32_t cutoff = cutoffs[split] * mul;
96
22.1k
    tree[info.pos] = PropertyDecisionNode::Split(property, cutoff, tree.size());
97
22.1k
    q.push(NodeInfo{split + 1, info.end, tree.size()});
98
22.1k
    tree.push_back(PropertyDecisionNode::Leaf(pred));
99
22.1k
    q.push(NodeInfo{info.begin, split, tree.size()});
100
22.1k
    tree.push_back(PropertyDecisionNode::Leaf(pred));
101
22.1k
  }
102
2.87k
  return tree;
103
2.87k
}
104
105
Status GatherTreeData(const Image &image, pixel_type chan, size_t group_id,
106
                      const weighted::Header &wp_header,
107
                      const ModularOptions &options, TreeSamples &tree_samples,
108
7.24k
                      size_t *total_pixels) {
109
7.24k
  const Channel &channel = image.channel[chan];
110
7.24k
  JxlMemoryManager *memory_manager = channel.memory_manager();
111
112
7.24k
  JXL_DEBUG_V(7, "Learning %" PRIuS "x%" PRIuS " channel %d", channel.w,
113
7.24k
              channel.h, chan);
114
115
7.24k
  std::array<pixel_type, kNumStaticProperties> static_props = {
116
7.24k
      {chan, static_cast<int>(group_id)}};
117
7.24k
  Properties properties(kNumNonrefProperties +
118
7.24k
                        kExtraPropsPerChannel * options.max_properties);
119
7.24k
  double pixel_fraction = std::min(1.0f, options.nb_repeats);
120
  // a fraction of 0 is used to disable learning entirely.
121
7.24k
  if (pixel_fraction > 0) {
122
7.24k
    pixel_fraction = std::max(pixel_fraction,
123
7.24k
                              std::min(1.0, 1024.0 / (channel.w * channel.h)));
124
7.24k
  }
125
7.24k
  uint64_t threshold =
126
7.24k
      (std::numeric_limits<uint64_t>::max() >> 32) * pixel_fraction;
127
7.24k
  uint64_t s[2] = {static_cast<uint64_t>(0x94D049BB133111EBull),
128
7.24k
                   static_cast<uint64_t>(0xBF58476D1CE4E5B9ull)};
129
  // Xorshift128+ adapted from xorshift128+-inl.h
130
137M
  auto use_sample = [&]() {
131
137M
    auto s1 = s[0];
132
137M
    const auto s0 = s[1];
133
137M
    const auto bits = s1 + s0;  // b, c
134
137M
    s[0] = s0;
135
137M
    s1 ^= s1 << 23;
136
137M
    s1 ^= s0 ^ (s1 >> 18) ^ (s0 >> 5);
137
137M
    s[1] = s1;
138
137M
    return (bits >> 32) <= threshold;
139
137M
  };
140
141
7.24k
  const ptrdiff_t onerow = channel.plane.PixelsPerRow();
142
7.24k
  JXL_ASSIGN_OR_RETURN(
143
7.24k
      Channel references,
144
7.24k
      Channel::Create(memory_manager, properties.size() - kNumNonrefProperties,
145
7.24k
                      channel.w));
146
7.24k
  weighted::State wp_state(wp_header, channel.w, channel.h);
147
7.24k
  tree_samples.PrepareForSamples(pixel_fraction * channel.h * channel.w + 64);
148
7.24k
  const bool multiple_predictors = tree_samples.NumPredictors() != 1;
149
5.89M
  auto compute_sample = [&](const pixel_type *p, size_t x, size_t y) {
150
5.89M
    pixel_type_w pred[kNumModularPredictors];
151
5.89M
    if (multiple_predictors) {
152
0
      PredictLearnAll(&properties, channel.w, p + x, onerow, x, y, references,
153
0
                      &wp_state, pred);
154
5.89M
    } else {
155
5.89M
      pred[static_cast<int>(tree_samples.PredictorFromIndex(0))] =
156
5.89M
          PredictLearn(&properties, channel.w, p + x, onerow, x, y,
157
5.89M
                       tree_samples.PredictorFromIndex(0), references,
158
5.89M
                       &wp_state)
159
5.89M
              .guess;
160
5.89M
    }
161
5.89M
    (*total_pixels)++;
162
5.89M
    if (use_sample()) {
163
3.19M
      tree_samples.AddSample(p[x], properties, pred);
164
3.19M
    }
165
5.89M
    wp_state.UpdateErrors(p[x], x, y, channel.w);
166
5.89M
  };
167
168
764k
  for (size_t y = 0; y < channel.h; y++) {
169
757k
    const pixel_type *JXL_RESTRICT p = channel.Row(y);
170
757k
    PrecomputeReferences(channel, y, image, chan, &references);
171
757k
    InitPropsRow(&properties, static_props, y);
172
173
    // TODO(veluca): avoid computing WP if we don't use its property or
174
    // predictions.
175
757k
    if (y > 1 && channel.w > 8 && references.w == 0) {
176
2.19M
      for (size_t x = 0; x < 2; x++) {
177
1.46M
        compute_sample(p, x, y);
178
1.46M
      }
179
131M
      for (size_t x = 2; x < channel.w - 2; x++) {
180
131M
        pixel_type_w pred[kNumModularPredictors];
181
131M
        if (multiple_predictors) {
182
0
          PredictLearnAllNEC(&properties, channel.w, p + x, onerow, x, y,
183
0
                             references, &wp_state, pred);
184
131M
        } else {
185
131M
          pred[static_cast<int>(tree_samples.PredictorFromIndex(0))] =
186
131M
              PredictLearnNEC(&properties, channel.w, p + x, onerow, x, y,
187
131M
                              tree_samples.PredictorFromIndex(0), references,
188
131M
                              &wp_state)
189
131M
                  .guess;
190
131M
        }
191
131M
        (*total_pixels)++;
192
131M
        if (use_sample()) {
193
66.0M
          tree_samples.AddSample(p[x], properties, pred);
194
66.0M
        }
195
131M
        wp_state.UpdateErrors(p[x], x, y, channel.w);
196
131M
      }
197
2.19M
      for (size_t x = channel.w - 2; x < channel.w; x++) {
198
1.46M
        compute_sample(p, x, y);
199
1.46M
      }
200
733k
    } else {
201
2.98M
      for (size_t x = 0; x < channel.w; x++) {
202
2.96M
        compute_sample(p, x, y);
203
2.96M
      }
204
24.6k
    }
205
757k
  }
206
7.24k
  return true;
207
7.24k
}
208
209
StatusOr<Tree> LearnTree(
210
    TreeSamples &&tree_samples, size_t total_pixels,
211
    const ModularOptions &options,
212
    const std::vector<ModularMultiplierInfo> &multiplier_info = {},
213
3.24k
    StaticPropRange static_prop_range = {}) {
214
3.24k
  Tree tree;
215
9.72k
  for (size_t i = 0; i < kNumStaticProperties; i++) {
216
6.48k
    if (static_prop_range[i][1] == 0) {
217
0
      static_prop_range[i][1] = std::numeric_limits<uint32_t>::max();
218
0
    }
219
6.48k
  }
220
3.24k
  if (!tree_samples.HasSamples()) {
221
179
    tree.emplace_back();
222
179
    tree.back().predictor = tree_samples.PredictorFromIndex(0);
223
179
    tree.back().property = -1;
224
179
    tree.back().predictor_offset = 0;
225
179
    tree.back().multiplier = 1;
226
179
    return tree;
227
179
  }
228
3.06k
  float pixel_fraction = tree_samples.NumSamples() * 1.0f / total_pixels;
229
3.06k
  float required_cost = pixel_fraction * 0.9 + 0.1;
230
3.06k
  tree_samples.AllSamplesDone();
231
3.06k
  JXL_RETURN_IF_ERROR(ComputeBestTree(
232
3.06k
      tree_samples, options.splitting_heuristics_node_threshold * required_cost,
233
3.06k
      multiplier_info, static_prop_range, options.fast_decode_multiplier,
234
3.06k
      &tree));
235
3.06k
  return tree;
236
3.06k
}
237
238
Status EncodeModularChannelMAANS(const Image &image, pixel_type chan,
239
                                 const weighted::Header &wp_header,
240
                                 const Tree &global_tree, Token **tokenpp,
241
27.1k
                                 size_t group_id, bool skip_encoder_fast_path) {
242
27.1k
  const Channel &channel = image.channel[chan];
243
27.1k
  JxlMemoryManager *memory_manager = channel.memory_manager();
244
27.1k
  Token *tokenp = *tokenpp;
245
27.1k
  JXL_ENSURE(channel.w != 0 && channel.h != 0);
246
247
27.1k
  Image3F predictor_img;
248
27.1k
  if (kWantDebug) {
249
27.1k
    JXL_ASSIGN_OR_RETURN(predictor_img,
250
27.1k
                         Image3F::Create(memory_manager, channel.w, channel.h));
251
27.1k
  }
252
253
27.1k
  JXL_DEBUG_V(6,
254
27.1k
              "Encoding %" PRIuS "x%" PRIuS
255
27.1k
              " channel %d, "
256
27.1k
              "(shift=%i,%i)",
257
27.1k
              channel.w, channel.h, chan, channel.hshift, channel.vshift);
258
259
27.1k
  std::array<pixel_type, kNumStaticProperties> static_props = {
260
27.1k
      {chan, static_cast<int>(group_id)}};
261
27.1k
  bool use_wp;
262
27.1k
  bool is_wp_only;
263
27.1k
  bool is_gradient_only;
264
27.1k
  size_t num_props;
265
27.1k
  FlatTree tree = FilterTree(global_tree, static_props, &num_props, &use_wp,
266
27.1k
                             &is_wp_only, &is_gradient_only);
267
27.1k
  MATreeLookup tree_lookup(tree);
268
27.1k
  JXL_DEBUG_V(3, "Encoding using a MA tree with %" PRIuS " nodes", tree.size());
269
270
  // Check if this tree is a WP-only tree with a small enough property value
271
  // range.
272
  // Initialized to avoid clang-tidy complaining.
273
27.1k
  auto tree_lut = jxl::make_unique<TreeLut<uint16_t, false, false>>();
274
27.1k
  if (is_wp_only) {
275
8.54k
    is_wp_only = TreeToLookupTable(tree, *tree_lut);
276
8.54k
  }
277
27.1k
  if (is_gradient_only) {
278
4.54k
    is_gradient_only = TreeToLookupTable(tree, *tree_lut);
279
4.54k
  }
280
281
27.1k
  if (is_wp_only && !skip_encoder_fast_path) {
282
34.1k
    for (size_t c = 0; c < 3; c++) {
283
25.6k
      FillImage(static_cast<float>(PredictorColor(Predictor::Weighted)[c]),
284
25.6k
                &predictor_img.Plane(c));
285
25.6k
    }
286
8.54k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
287
8.54k
    weighted::State wp_state(wp_header, channel.w, channel.h);
288
8.54k
    Properties properties(1);
289
8.54k
    bool unhealthy = false;
290
335k
    for (size_t y = 0; y < channel.h; y++) {
291
326k
      const pixel_type *JXL_RESTRICT r = channel.Row(y);
292
17.6M
      for (size_t x = 0; x < channel.w; x++) {
293
17.3M
        size_t offset = 0;
294
17.3M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
295
17.3M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
296
17.3M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
297
17.3M
        pixel_type_w topright =
298
17.3M
            (x + 1 < channel.w && y ? *(r + x + 1 - onerow) : top);
299
17.3M
        pixel_type_w toptop = (y > 1 ? *(r + x - onerow - onerow) : top);
300
17.3M
        int32_t guess = wp_state.Predict</*compute_properties=*/true>(
301
17.3M
            x, y, channel.w, top, left, topright, topleft, toptop, &properties,
302
17.3M
            offset);
303
17.3M
        uint32_t pos =
304
17.3M
            kPropRangeFast +
305
17.3M
            jxl::Clamp1(properties[0], -kPropRangeFast, kPropRangeFast - 1);
306
17.3M
        uint32_t ctx_id = tree_lut->context_lookup[pos];
307
17.3M
        int32_t residual;
308
17.3M
        unhealthy |= SubOverflow(r[x], guess, residual);
309
17.3M
        *tokenp++ = Token(ctx_id, PackSigned(residual));
310
17.3M
        wp_state.UpdateErrors(r[x], x, y, channel.w);
311
17.3M
      }
312
326k
    }
313
8.54k
    if (unhealthy) {
314
0
      return JXL_FAILURE("Residual overflow");
315
0
    }
316
18.6k
  } else if (tree.size() == 1 && tree[0].predictor == Predictor::Gradient &&
317
3.88k
             tree[0].multiplier == 1 && tree[0].predictor_offset == 0 &&
318
3.88k
             !skip_encoder_fast_path) {
319
15.5k
    for (size_t c = 0; c < 3; c++) {
320
11.6k
      FillImage(static_cast<float>(PredictorColor(Predictor::Gradient)[c]),
321
11.6k
                &predictor_img.Plane(c));
322
11.6k
    }
323
3.88k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
324
3.88k
    bool unhealthy = false;
325
138k
    for (size_t y = 0; y < channel.h; y++) {
326
135k
      const pixel_type *JXL_RESTRICT r = channel.Row(y);
327
20.6M
      for (size_t x = 0; x < channel.w; x++) {
328
20.5M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
329
20.5M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
330
20.5M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
331
20.5M
        int32_t guess = ClampedGradient(top, left, topleft);
332
20.5M
        int32_t residual;
333
20.5M
        unhealthy |= SubOverflow(r[x], guess, residual);
334
20.5M
        *tokenp++ = Token(tree[0].childID, PackSigned(residual));
335
20.5M
      }
336
135k
    }
337
3.88k
    if (unhealthy) {
338
12
      return JXL_FAILURE("Residual overflow");
339
12
    }
340
14.7k
  } else if (is_gradient_only && !skip_encoder_fast_path) {
341
2.66k
    for (size_t c = 0; c < 3; c++) {
342
1.99k
      FillImage(static_cast<float>(PredictorColor(Predictor::Gradient)[c]),
343
1.99k
                &predictor_img.Plane(c));
344
1.99k
    }
345
665
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
346
665
    bool unhealthy = false;
347
18.9k
    for (size_t y = 0; y < channel.h; y++) {
348
18.2k
      const pixel_type *JXL_RESTRICT r = channel.Row(y);
349
1.19M
      for (size_t x = 0; x < channel.w; x++) {
350
1.17M
        pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0);
351
1.17M
        pixel_type_w top = (y ? *(r + x - onerow) : left);
352
1.17M
        pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left);
353
1.17M
        int32_t guess = ClampedGradient(top, left, topleft);
354
1.17M
        uint32_t pos =
355
1.17M
            kPropRangeFast +
356
1.17M
            std::min<pixel_type_w>(
357
1.17M
                std::max<pixel_type_w>(-kPropRangeFast, top + left - topleft),
358
1.17M
                kPropRangeFast - 1);
359
1.17M
        uint32_t ctx_id = tree_lut->context_lookup[pos];
360
1.17M
        int32_t residual;
361
1.17M
        unhealthy |= SubOverflow(r[x], guess, residual);
362
1.17M
        *tokenp++ = Token(ctx_id, PackSigned(residual));
363
1.17M
      }
364
18.2k
    }
365
665
    if (unhealthy) {
366
12
      return JXL_FAILURE("Residual overflow");
367
12
    }
368
14.0k
  } else if (tree.size() == 1 && tree[0].predictor == Predictor::Zero &&
369
0
             tree[0].multiplier == 1 && tree[0].predictor_offset == 0 &&
370
0
             !skip_encoder_fast_path) {
371
0
    for (size_t c = 0; c < 3; c++) {
372
0
      FillImage(static_cast<float>(PredictorColor(Predictor::Zero)[c]),
373
0
                &predictor_img.Plane(c));
374
0
    }
375
0
    for (size_t y = 0; y < channel.h; y++) {
376
0
      const pixel_type *JXL_RESTRICT p = channel.Row(y);
377
0
      for (size_t x = 0; x < channel.w; x++) {
378
0
        *tokenp++ = Token(tree[0].childID, PackSigned(p[x]));
379
0
      }
380
0
    }
381
14.0k
  } else if (tree.size() == 1 && tree[0].predictor != Predictor::Weighted &&
382
6.49k
             (tree[0].multiplier & (tree[0].multiplier - 1)) == 0 &&
383
6.49k
             tree[0].predictor_offset == 0 && !skip_encoder_fast_path) {
384
    // multiplier is a power of 2.
385
25.9k
    for (size_t c = 0; c < 3; c++) {
386
19.4k
      FillImage(static_cast<float>(PredictorColor(tree[0].predictor)[c]),
387
19.4k
                &predictor_img.Plane(c));
388
19.4k
    }
389
6.49k
    uint32_t mul_shift =
390
6.49k
        FloorLog2Nonzero(static_cast<uint32_t>(tree[0].multiplier));
391
6.49k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
392
34.3k
    for (size_t y = 0; y < channel.h; y++) {
393
27.8k
      const pixel_type *JXL_RESTRICT r = channel.Row(y);
394
285k
      for (size_t x = 0; x < channel.w; x++) {
395
257k
        PredictionResult pred = PredictNoTreeNoWP(channel.w, r + x, onerow, x,
396
257k
                                                  y, tree[0].predictor);
397
257k
        pixel_type_w residual = r[x] - pred.guess;
398
257k
        JXL_DASSERT((residual >> mul_shift) * tree[0].multiplier == residual);
399
257k
        *tokenp++ = Token(tree[0].childID, PackSigned(residual >> mul_shift));
400
257k
      }
401
27.8k
    }
402
403
7.59k
  } else if (!use_wp && !skip_encoder_fast_path) {
404
3.19k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
405
3.19k
    Properties properties(num_props);
406
3.19k
    JXL_ASSIGN_OR_RETURN(
407
3.19k
        Channel references,
408
3.19k
        Channel::Create(memory_manager,
409
3.19k
                        properties.size() - kNumNonrefProperties, channel.w));
410
143k
    for (size_t y = 0; y < channel.h; y++) {
411
140k
      const pixel_type *JXL_RESTRICT p = channel.Row(y);
412
140k
      PrecomputeReferences(channel, y, image, chan, &references);
413
140k
      float *pred_img_row[3];
414
140k
      if (kWantDebug) {
415
562k
        for (size_t c = 0; c < 3; c++) {
416
421k
          pred_img_row[c] = predictor_img.PlaneRow(c, y);
417
421k
        }
418
140k
      }
419
140k
      InitPropsRow(&properties, static_props, y);
420
14.8M
      for (size_t x = 0; x < channel.w; x++) {
421
14.7M
        PredictionResult res =
422
14.7M
            PredictTreeNoWP(&properties, channel.w, p + x, onerow, x, y,
423
14.7M
                            tree_lookup, references);
424
14.7M
        if (kWantDebug) {
425
58.9M
          for (size_t i = 0; i < 3; i++) {
426
44.2M
            pred_img_row[i][x] = PredictorColor(res.predictor)[i];
427
44.2M
          }
428
14.7M
        }
429
14.7M
        pixel_type_w residual = p[x] - res.guess;
430
14.7M
        JXL_DASSERT(residual % res.multiplier == 0);
431
14.7M
        *tokenp++ = Token(res.context, PackSigned(residual / res.multiplier));
432
14.7M
      }
433
140k
    }
434
4.40k
  } else {
435
4.40k
    const ptrdiff_t onerow = channel.plane.PixelsPerRow();
436
4.40k
    Properties properties(num_props);
437
4.40k
    JXL_ASSIGN_OR_RETURN(
438
4.40k
        Channel references,
439
4.40k
        Channel::Create(memory_manager,
440
4.40k
                        properties.size() - kNumNonrefProperties, channel.w));
441
4.40k
    weighted::State wp_state(wp_header, channel.w, channel.h);
442
584k
    for (size_t y = 0; y < channel.h; y++) {
443
580k
      const pixel_type *JXL_RESTRICT p = channel.Row(y);
444
580k
      PrecomputeReferences(channel, y, image, chan, &references);
445
580k
      float *pred_img_row[3];
446
580k
      if (kWantDebug) {
447
2.32M
        for (size_t c = 0; c < 3; c++) {
448
1.74M
          pred_img_row[c] = predictor_img.PlaneRow(c, y);
449
1.74M
        }
450
580k
      }
451
580k
      InitPropsRow(&properties, static_props, y);
452
111M
      for (size_t x = 0; x < channel.w; x++) {
453
111M
        PredictionResult res =
454
111M
            PredictTreeWP(&properties, channel.w, p + x, onerow, x, y,
455
111M
                          tree_lookup, references, &wp_state);
456
111M
        if (kWantDebug) {
457
444M
          for (size_t i = 0; i < 3; i++) {
458
333M
            pred_img_row[i][x] = PredictorColor(res.predictor)[i];
459
333M
          }
460
111M
        }
461
111M
        pixel_type_w residual = p[x] - res.guess;
462
111M
        JXL_DASSERT(residual % res.multiplier == 0);
463
111M
        *tokenp++ = Token(res.context, PackSigned(residual / res.multiplier));
464
111M
        wp_state.UpdateErrors(p[x], x, y, channel.w);
465
111M
      }
466
580k
    }
467
4.40k
  }
468
  /* TODO(szabadka): Add cparams to the call stack here.
469
  if (kWantDebug && WantDebugOutput(cparams)) {
470
    DumpImage(
471
        cparams,
472
        ("pred_" + ToString(group_id) + "_" + ToString(chan)).c_str(),
473
        predictor_img);
474
  }
475
  */
476
27.1k
  *tokenpp = tokenp;
477
27.1k
  return true;
478
27.1k
}
479
480
}  // namespace
481
482
Tree PredefinedTree(ModularOptions::TreeKind tree_kind, size_t total_pixels,
483
5.74k
                    int bitdepth, int prevprop) {
484
5.74k
  switch (tree_kind) {
485
0
    case ModularOptions::TreeKind::kJpegTranscodeACMeta:
486
      // All the data is 0, so no need for a fancy tree.
487
0
      return {PropertyDecisionNode::Leaf(Predictor::Zero)};
488
0
    case ModularOptions::TreeKind::kTrivialTreeNoPredictor:
489
      // All the data is 0, so no need for a fancy tree.
490
0
      return {PropertyDecisionNode::Leaf(Predictor::Zero)};
491
0
    case ModularOptions::TreeKind::kFalconACMeta:
492
      // All the data is 0 except the quant field. TODO(veluca): make that 0
493
      // too.
494
0
      return {PropertyDecisionNode::Leaf(Predictor::Left)};
495
2.87k
    case ModularOptions::TreeKind::kACMeta: {
496
      // Small image.
497
2.87k
      if (total_pixels < 1024) {
498
1.64k
        return {PropertyDecisionNode::Leaf(Predictor::Left)};
499
1.64k
      }
500
1.22k
      Tree tree;
501
      // 0: c > 1
502
1.22k
      tree.push_back(PropertyDecisionNode::Split(0, 1, 1));
503
      // 1: c > 2
504
1.22k
      tree.push_back(PropertyDecisionNode::Split(0, 2, 3));
505
      // 2: c > 0
506
1.22k
      tree.push_back(PropertyDecisionNode::Split(0, 0, 5));
507
      // 3: EPF control field (all 0 or 4), top > 3
508
1.22k
      tree.push_back(PropertyDecisionNode::Split(6, 3, 21));
509
      // 4: ACS+QF, y > 0
510
1.22k
      tree.push_back(PropertyDecisionNode::Split(2, 0, 7));
511
      // 5: CfL x
512
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Gradient));
513
      // 6: CfL b
514
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Gradient));
515
      // 7: QF: split according to the left quant value.
516
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 5, 9));
517
      // 8: ACS: split in 4 segments (8x8 from 0 to 3, large square 4-5, large
518
      // rectangular 6-11, 8x8 12+), according to previous ACS value.
519
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 5, 15));
520
      // QF
521
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 11, 11));
522
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 3, 13));
523
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Left));
524
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Left));
525
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Left));
526
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Left));
527
      // ACS
528
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 11, 17));
529
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 3, 19));
530
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
531
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
532
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
533
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
534
      // EPF, left > 3
535
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 3, 23));
536
1.22k
      tree.push_back(PropertyDecisionNode::Split(7, 3, 25));
537
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
538
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
539
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
540
1.22k
      tree.push_back(PropertyDecisionNode::Leaf(Predictor::Zero));
541
1.22k
      return tree;
542
2.87k
    }
543
2.87k
    case ModularOptions::TreeKind::kWPFixedDC: {
544
2.87k
      std::vector<int32_t> cutoffs = {
545
2.87k
          -500, -392, -255, -191, -127, -95, -63, -47, -31, -23, -15,
546
2.87k
          -11,  -7,   -4,   -3,   -1,   0,   1,   3,   5,   7,   11,
547
2.87k
          15,   23,   31,   47,   63,   95,  127, 191, 255, 392, 500};
548
2.87k
      return MakeFixedTree(kWPProp, cutoffs, Predictor::Weighted, total_pixels,
549
2.87k
                           bitdepth);
550
2.87k
    }
551
0
    case ModularOptions::TreeKind::kGradientFixedDC: {
552
0
      std::vector<int32_t> cutoffs = {
553
0
          -500, -392, -255, -191, -127, -95, -63, -47, -31, -23, -15,
554
0
          -11,  -7,   -4,   -3,   -1,   0,   1,   3,   5,   7,   11,
555
0
          15,   23,   31,   47,   63,   95,  127, 191, 255, 392, 500};
556
0
      return MakeFixedTree(
557
0
          prevprop > 0 ? kNumNonrefProperties + 2 : kGradientProp, cutoffs,
558
0
          Predictor::Gradient, total_pixels, bitdepth);
559
2.87k
    }
560
0
    case ModularOptions::TreeKind::kLearn: {
561
0
      JXL_DEBUG_ABORT("internal: kLearn is not predefined tree");
562
0
      return {};
563
2.87k
    }
564
5.74k
  }
565
0
  JXL_DEBUG_ABORT("internal: unexpected TreeKind: %d",
566
0
                  static_cast<int>(tree_kind));
567
0
  return {};
568
5.74k
}
569
570
StatusOr<Tree> LearnTree(
571
    const Image *images, const ModularOptions *options, const uint32_t start,
572
    const uint32_t stop,
573
3.24k
    const std::vector<ModularMultiplierInfo> &multiplier_info = {}) {
574
3.24k
  TreeSamples tree_samples;
575
3.24k
  JXL_RETURN_IF_ERROR(tree_samples.SetPredictor(options[start].predictor,
576
3.24k
                                                options[start].wp_tree_mode));
577
3.24k
  JXL_RETURN_IF_ERROR(
578
3.24k
      tree_samples.SetProperties(options[start].splitting_heuristics_properties,
579
3.24k
                                 options[start].wp_tree_mode));
580
3.24k
  uint32_t max_c = 0;
581
3.24k
  std::vector<pixel_type> pixel_samples;
582
3.24k
  std::vector<pixel_type> diff_samples;
583
3.24k
  std::vector<uint32_t> group_pixel_count;
584
3.24k
  std::vector<uint32_t> channel_pixel_count;
585
7.71k
  for (uint32_t i = start; i < stop; i++) {
586
4.47k
    max_c = std::max<uint32_t>(images[i].channel.size(), max_c);
587
4.47k
    CollectPixelSamples(images[i], options[i], i, group_pixel_count,
588
4.47k
                        channel_pixel_count, pixel_samples, diff_samples);
589
4.47k
  }
590
3.24k
  StaticPropRange range;
591
3.24k
  range[0] = {{0, max_c}};
592
3.24k
  range[1] = {{start, stop}};
593
594
3.24k
  tree_samples.PreQuantizeProperties(
595
3.24k
      range, multiplier_info, group_pixel_count, channel_pixel_count,
596
3.24k
      pixel_samples, diff_samples, options[start].max_property_values);
597
598
3.24k
  size_t total_pixels = 0;
599
9.05k
  for (size_t i = 0; i < images[start].channel.size(); i++) {
600
6.28k
    if (i >= images[start].nb_meta_channels &&
601
5.44k
        (images[start].channel[i].w > options[start].max_chan_size ||
602
4.99k
         images[start].channel[i].h > options[start].max_chan_size)) {
603
470
      break;
604
470
    }
605
5.81k
    total_pixels += images[start].channel[i].w * images[start].channel[i].h;
606
5.81k
  }
607
3.24k
  total_pixels = std::max<size_t>(total_pixels, 1);
608
609
3.24k
  weighted::Header wp_header;
610
611
7.71k
  for (size_t i = start; i < stop; i++) {
612
4.47k
    size_t nb_channels = images[i].channel.size();
613
614
4.47k
    if (images[i].w == 0 || images[i].h == 0 || nb_channels < 1)
615
0
      continue;  // is there any use for a zero-channel image?
616
4.47k
    if (images[i].error) return JXL_FAILURE("Invalid image");
617
4.47k
    JXL_ENSURE(options[i].tree_kind == ModularOptions::TreeKind::kLearn);
618
619
4.47k
    JXL_DEBUG_V(
620
4.47k
        2, "Encoding %" PRIuS "-channel, %i-bit, %" PRIuS "x%" PRIuS " image.",
621
4.47k
        nb_channels, images[i].bitdepth, images[i].w, images[i].h);
622
623
    // encode transforms
624
4.47k
    Bundle::Init(&wp_header);
625
4.47k
    if (PredictorHasWeighted(options[i].predictor)) {
626
0
      weighted::PredictorMode(options[i].wp_mode, &wp_header);
627
0
    }
628
629
    // Gather tree data
630
11.7k
    for (size_t c = 0; c < nb_channels; c++) {
631
7.71k
      if (c >= images[i].nb_meta_channels &&
632
6.67k
          (images[i].channel[c].w > options[i].max_chan_size ||
633
6.22k
           images[i].channel[c].h > options[i].max_chan_size)) {
634
470
        break;
635
470
      }
636
7.24k
      if (!images[i].channel[c].w || !images[i].channel[c].h) {
637
0
        continue;  // skip empty channels
638
0
      }
639
7.24k
      JXL_RETURN_IF_ERROR(GatherTreeData(images[i], c, i, wp_header, options[i],
640
7.24k
                                         tree_samples, &total_pixels));
641
7.24k
    }
642
4.47k
  }
643
644
  // TODO(veluca): parallelize more.
645
3.24k
  JXL_ASSIGN_OR_RETURN(Tree tree,
646
3.24k
                       LearnTree(std::move(tree_samples), total_pixels,
647
3.24k
                                 options[start], multiplier_info, range));
648
3.24k
  return tree;
649
3.24k
}
650
651
Status ModularCompress(const Image &image, const ModularOptions &options,
652
                       size_t group_id, const Tree &tree, GroupHeader &header,
653
83.0k
                       std::vector<Token> &tokens, size_t *width) {
654
83.0k
  size_t nb_channels = image.channel.size();
655
656
83.0k
  if (image.w == 0 || image.h == 0 || nb_channels < 1)
657
72.8k
    return true;  // is there any use for a zero-channel image?
658
10.1k
  if (image.error) return JXL_FAILURE("Invalid image");
659
660
10.1k
  JXL_DEBUG_V(
661
10.1k
      2, "Encoding %" PRIuS "-channel, %i-bit, %" PRIuS "x%" PRIuS " image.",
662
10.1k
      nb_channels, image.bitdepth, image.w, image.h);
663
664
  // encode transforms
665
10.1k
  Bundle::Init(&header);
666
10.1k
  if (PredictorHasWeighted(options.predictor)) {
667
2.84k
    weighted::PredictorMode(options.wp_mode, &header.wp_header);
668
2.84k
  }
669
10.1k
  header.transforms = image.transform;
670
10.1k
  header.use_global_tree = true;
671
672
10.1k
  size_t image_width = 0;
673
10.1k
  size_t total_tokens = 0;
674
37.3k
  for (size_t i = 0; i < nb_channels; i++) {
675
27.6k
    if (i >= image.nb_meta_channels &&
676
26.6k
        (image.channel[i].w > options.max_chan_size ||
677
26.1k
         image.channel[i].h > options.max_chan_size)) {
678
470
      break;
679
470
    }
680
27.1k
    if (image.channel[i].w > image_width) image_width = image.channel[i].w;
681
27.1k
    total_tokens += image.channel[i].w * image.channel[i].h;
682
27.1k
  }
683
10.1k
  if (options.zero_tokens) {
684
0
    tokens.resize(tokens.size() + total_tokens, {0, 0});
685
10.1k
  } else {
686
    // Do one big allocation for all the tokens we'll need,
687
    // to avoid reallocs that might require copying.
688
10.1k
    size_t pos = tokens.size();
689
10.1k
    tokens.resize(pos + total_tokens);
690
10.1k
    Token *tokenp = tokens.data() + pos;
691
37.3k
    for (size_t i = 0; i < nb_channels; i++) {
692
27.6k
      if (i >= image.nb_meta_channels &&
693
26.6k
          (image.channel[i].w > options.max_chan_size ||
694
26.1k
           image.channel[i].h > options.max_chan_size)) {
695
470
        break;
696
470
      }
697
27.1k
      if (!image.channel[i].w || !image.channel[i].h) {
698
0
        continue;  // skip empty channels
699
0
      }
700
27.1k
      JXL_RETURN_IF_ERROR(
701
27.1k
          EncodeModularChannelMAANS(image, i, header.wp_header, tree, &tokenp,
702
27.1k
                                    group_id, options.skip_encoder_fast_path));
703
27.1k
    }
704
    // Make sure we actually wrote all tokens
705
10.1k
    JXL_ENSURE(tokenp == tokens.data() + tokens.size());
706
10.1k
  }
707
708
10.1k
  *width = image_width;
709
710
10.1k
  return true;
711
10.1k
}
712
713
Status ModularGenericCompress(const Image &image, const ModularOptions &opts,
714
                              BitWriter &writer, AuxOut *aux_out,
715
1.38k
                              LayerType layer, size_t group_id) {
716
1.38k
  size_t nb_channels = image.channel.size();
717
718
1.38k
  if (image.w == 0 || image.h == 0 || nb_channels < 1)
719
0
    return true;  // is there any use for a zero-channel image?
720
1.38k
  if (image.error) return JXL_FAILURE("Invalid image");
721
722
1.38k
  ModularOptions options = opts;  // Make a copy to modify it.
723
1.38k
  if (options.predictor == kUndefinedPredictor) {
724
0
    options.predictor = Predictor::Gradient;
725
0
  }
726
727
1.38k
  size_t bits = writer.BitsWritten();
728
729
1.38k
  JxlMemoryManager *memory_manager = image.memory_manager();
730
1.38k
  JXL_DEBUG_V(
731
1.38k
      2, "Encoding %" PRIuS "-channel, %i-bit, %" PRIuS "x%" PRIuS " image.",
732
1.38k
      nb_channels, image.bitdepth, image.w, image.h);
733
734
  // encode transforms
735
1.38k
  GroupHeader header;
736
1.38k
  Bundle::Init(&header);
737
1.38k
  if (PredictorHasWeighted(options.predictor)) {
738
184
    weighted::PredictorMode(options.wp_mode, &header.wp_header);
739
184
  }
740
1.38k
  header.transforms = image.transform;
741
742
1.38k
  JXL_RETURN_IF_ERROR(Bundle::Write(header, &writer, layer, aux_out));
743
744
  // Compute tree.
745
1.38k
  Tree tree;
746
1.38k
  if (options.tree_kind == ModularOptions::TreeKind::kLearn) {
747
1.02k
    JXL_ASSIGN_OR_RETURN(tree, LearnTree(&image, &options, 0, 1));
748
1.02k
  } else {
749
368
    size_t total_pixels = 0;
750
1.65k
    for (size_t i = 0; i < nb_channels; i++) {
751
1.28k
      if (i >= image.nb_meta_channels &&
752
1.28k
          (image.channel[i].w > options.max_chan_size ||
753
1.28k
           image.channel[i].h > options.max_chan_size)) {
754
0
        break;
755
0
      }
756
1.28k
      total_pixels += image.channel[i].w * image.channel[i].h;
757
1.28k
    }
758
368
    total_pixels = std::max<size_t>(total_pixels, 1);
759
760
368
    tree = PredefinedTree(options.tree_kind, total_pixels, image.bitdepth,
761
368
                          options.max_properties);
762
368
  }
763
764
1.38k
  Tree decoded_tree;
765
1.38k
  std::vector<std::vector<Token>> tree_tokens(1);
766
1.38k
  JXL_RETURN_IF_ERROR(TokenizeTree(tree, tree_tokens.data(), &decoded_tree));
767
1.38k
  JXL_ENSURE(tree.size() == decoded_tree.size());
768
1.38k
  tree = std::move(decoded_tree);
769
770
  /* TODO(szabadka) Add text output callback
771
  if (kWantDebug && kPrintTree && WantDebugOutput(aux_out)) {
772
    PrintTree(*tree, aux_out->debug_prefix + "/tree_" + ToString(group_id));
773
  } */
774
775
  // Write tree
776
1.38k
  EntropyEncodingData code;
777
1.38k
  JXL_ASSIGN_OR_RETURN(
778
1.38k
      size_t cost,
779
1.38k
      BuildAndEncodeHistograms(memory_manager, options.histogram_params,
780
1.38k
                               kNumTreeContexts, tree_tokens, &code, &writer,
781
1.38k
                               LayerType::ModularTree, aux_out));
782
1.38k
  JXL_RETURN_IF_ERROR(WriteTokens(tree_tokens[0], code, 0, &writer,
783
1.38k
                                  LayerType::ModularTree, aux_out));
784
785
1.38k
  size_t image_width = 0;
786
1.38k
  std::vector<std::vector<Token>> tokens(1);
787
  // it puts `use_global_tree = true` in the header, but this is not used
788
  // further
789
1.38k
  JXL_RETURN_IF_ERROR(ModularCompress(image, options, group_id, tree, header,
790
1.38k
                                      tokens[0], &image_width));
791
792
  // Write data
793
1.38k
  code = {};
794
1.38k
  HistogramParams histo_params = options.histogram_params;
795
1.38k
  histo_params.image_widths.push_back(image_width);
796
1.38k
  JXL_ASSIGN_OR_RETURN(
797
1.38k
      cost, BuildAndEncodeHistograms(memory_manager, histo_params,
798
1.38k
                                     (tree.size() + 1) / 2, tokens, &code,
799
1.38k
                                     &writer, layer, aux_out));
800
1.38k
  (void)cost;
801
1.38k
  JXL_RETURN_IF_ERROR(WriteTokens(tokens[0], code, 0, &writer, layer, aux_out));
802
803
1.38k
  bits = writer.BitsWritten() - bits;
804
1.38k
  JXL_DEBUG_V(4,
805
1.38k
              "Modular-encoded a %" PRIuS "x%" PRIuS
806
1.38k
              " bitdepth=%i nbchans=%" PRIuS " image in %" PRIuS " bytes",
807
1.38k
              image.w, image.h, image.bitdepth, image.channel.size(), bits / 8);
808
1.38k
  (void)bits;
809
810
1.38k
  return true;
811
1.38k
}
812
813
}  // namespace jxl