Coverage Report

Created: 2026-05-24 07:45

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