Coverage Report

Created: 2025-07-16 07:53

/src/libjxl/lib/jxl/dec_modular.cc
Line
Count
Source (jump to first uncovered line)
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/dec_modular.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <cstdint>
11
#include <vector>
12
13
#include "lib/jxl/frame_header.h"
14
15
#undef HWY_TARGET_INCLUDE
16
#define HWY_TARGET_INCLUDE "lib/jxl/dec_modular.cc"
17
#include <hwy/foreach_target.h>
18
#include <hwy/highway.h>
19
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/printf_macros.h"
22
#include "lib/jxl/base/rect.h"
23
#include "lib/jxl/base/status.h"
24
#include "lib/jxl/compressed_dc.h"
25
#include "lib/jxl/epf.h"
26
#include "lib/jxl/modular/encoding/encoding.h"
27
#include "lib/jxl/modular/modular_image.h"
28
#include "lib/jxl/modular/transform/transform.h"
29
30
HWY_BEFORE_NAMESPACE();
31
namespace jxl {
32
namespace HWY_NAMESPACE {
33
34
// These templates are not found via ADL.
35
using hwy::HWY_NAMESPACE::Add;
36
using hwy::HWY_NAMESPACE::Mul;
37
using hwy::HWY_NAMESPACE::Rebind;
38
39
void MultiplySum(const size_t xsize,
40
                 const pixel_type* const JXL_RESTRICT row_in,
41
                 const pixel_type* const JXL_RESTRICT row_in_Y,
42
215k
                 const float factor, float* const JXL_RESTRICT row_out) {
43
215k
  const HWY_FULL(float) df;
44
215k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
45
215k
  const auto factor_v = Set(df, factor);
46
27.3M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
47
27.1M
    const auto in = Add(Load(di, row_in + x), Load(di, row_in_Y + x));
48
27.1M
    const auto out = Mul(ConvertTo(df, in), factor_v);
49
27.1M
    Store(out, df, row_out + x);
50
27.1M
  }
51
215k
}
52
53
void RgbFromSingle(const size_t xsize,
54
                   const pixel_type* const JXL_RESTRICT row_in,
55
                   const float factor, float* out_r, float* out_g,
56
6.13k
                   float* out_b) {
57
6.13k
  const HWY_FULL(float) df;
58
6.13k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
59
60
6.13k
  const auto factor_v = Set(df, factor);
61
1.40M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
62
1.39M
    const auto in = Load(di, row_in + x);
63
1.39M
    const auto out = Mul(ConvertTo(df, in), factor_v);
64
1.39M
    Store(out, df, out_r + x);
65
1.39M
    Store(out, df, out_g + x);
66
1.39M
    Store(out, df, out_b + x);
67
1.39M
  }
68
6.13k
}
69
70
void SingleFromSingle(const size_t xsize,
71
                      const pixel_type* const JXL_RESTRICT row_in,
72
1.50M
                      const float factor, float* row_out) {
73
1.50M
  const HWY_FULL(float) df;
74
1.50M
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
75
76
1.50M
  const auto factor_v = Set(df, factor);
77
213M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
78
211M
    const auto in = Load(di, row_in + x);
79
211M
    const auto out = Mul(ConvertTo(df, in), factor_v);
80
211M
    Store(out, df, row_out + x);
81
211M
  }
82
1.50M
}
83
// NOLINTNEXTLINE(google-readability-namespace-comments)
84
}  // namespace HWY_NAMESPACE
85
}  // namespace jxl
86
HWY_AFTER_NAMESPACE();
87
88
#if HWY_ONCE
89
namespace jxl {
90
HWY_EXPORT(MultiplySum);       // Local function
91
HWY_EXPORT(RgbFromSingle);     // Local function
92
HWY_EXPORT(SingleFromSingle);  // Local function
93
94
// Slow conversion using double precision multiplication, only
95
// needed when the bit depth is too high for single precision
96
void SingleFromSingleAccurate(const size_t xsize,
97
                              const pixel_type* const JXL_RESTRICT row_in,
98
516
                              const double factor, float* row_out) {
99
1.77k
  for (size_t x = 0; x < xsize; x++) {
100
1.25k
    row_out[x] = row_in[x] * factor;
101
1.25k
  }
102
516
}
103
104
// convert custom [bits]-bit float (with [exp_bits] exponent bits) stored as int
105
// back to binary32 float
106
Status int_to_float(const pixel_type* const JXL_RESTRICT row_in,
107
                    float* const JXL_RESTRICT row_out, const size_t xsize,
108
107k
                    const int bits, const int exp_bits) {
109
107k
  static_assert(sizeof(pixel_type) == sizeof(float));
110
107k
  if (bits == 32) {
111
107k
    JXL_ENSURE(exp_bits == 8);
112
107k
    memcpy(row_out, row_in, xsize * sizeof(float));
113
107k
    return true;
114
107k
  }
115
162
  int exp_bias = (1 << (exp_bits - 1)) - 1;
116
162
  int sign_shift = bits - 1;
117
162
  int mant_bits = bits - exp_bits - 1;
118
162
  int mant_shift = 23 - mant_bits;
119
6.43k
  for (size_t x = 0; x < xsize; ++x) {
120
6.26k
    uint32_t f;
121
6.26k
    memcpy(&f, &row_in[x], 4);
122
6.26k
    int signbit = (f >> sign_shift);
123
6.26k
    f &= (1 << sign_shift) - 1;
124
6.26k
    if (f == 0) {
125
1.18k
      row_out[x] = (signbit ? -0.f : 0.f);
126
1.18k
      continue;
127
1.18k
    }
128
5.08k
    int exp = (f >> mant_bits);
129
5.08k
    int mantissa = (f & ((1 << mant_bits) - 1));
130
5.08k
    mantissa <<= mant_shift;
131
    // Try to normalize only if there is space for maneuver.
132
5.08k
    if (exp == 0 && exp_bits < 8) {
133
      // subnormal number
134
111
      while ((mantissa & 0x800000) == 0) {
135
71
        mantissa <<= 1;
136
71
        exp--;
137
71
      }
138
40
      exp++;
139
      // remove leading 1 because it is implicit now
140
40
      mantissa &= 0x7fffff;
141
40
    }
142
5.08k
    exp -= exp_bias;
143
    // broke up the arbitrary float into its parts, now reassemble into
144
    // binary32
145
5.08k
    exp += 127;
146
5.08k
    JXL_ENSURE(exp >= 0);
147
5.08k
    f = (signbit ? 0x80000000 : 0);
148
5.08k
    f |= (exp << 23);
149
5.08k
    f |= mantissa;
150
5.08k
    memcpy(&row_out[x], &f, 4);
151
5.08k
  }
152
162
  return true;
153
162
}
154
155
#if JXL_DEBUG_V_LEVEL >= 1
156
std::string ModularStreamId::DebugString() const {
157
  std::ostringstream os;
158
  os << (kind == GlobalData   ? "ModularGlobal"
159
         : kind == VarDCTDC   ? "VarDCTDC"
160
         : kind == ModularDC  ? "ModularDC"
161
         : kind == ACMetadata ? "ACMeta"
162
         : kind == QuantTable ? "QuantTable"
163
         : kind == ModularAC  ? "ModularAC"
164
                              : "");
165
  if (kind == VarDCTDC || kind == ModularDC || kind == ACMetadata ||
166
      kind == ModularAC) {
167
    os << " group " << group_id;
168
  }
169
  if (kind == ModularAC) {
170
    os << " pass " << pass_id;
171
  }
172
  if (kind == QuantTable) {
173
    os << " " << quant_table_id;
174
  }
175
  return os.str();
176
}
177
#endif
178
179
Status ModularFrameDecoder::DecodeGlobalInfo(BitReader* reader,
180
                                             const FrameHeader& frame_header,
181
12.0k
                                             bool allow_truncated_group) {
182
12.0k
  JxlMemoryManager* memory_manager = this->memory_manager();
183
12.0k
  bool decode_color = frame_header.encoding == FrameEncoding::kModular;
184
12.0k
  const auto& metadata = frame_header.nonserialized_metadata->m;
185
12.0k
  bool is_gray = metadata.color_encoding.IsGray();
186
12.0k
  size_t nb_chans = 3;
187
12.0k
  if (is_gray && frame_header.color_transform == ColorTransform::kNone) {
188
53
    nb_chans = 1;
189
53
  }
190
12.0k
  do_color = decode_color;
191
12.0k
  size_t nb_extra = metadata.extra_channel_info.size();
192
12.0k
  bool has_tree = static_cast<bool>(reader->ReadBits(1));
193
12.0k
  if (!allow_truncated_group ||
194
12.0k
      reader->TotalBitsConsumed() < reader->TotalBytes() * kBitsPerByte) {
195
12.0k
    if (has_tree) {
196
8.81k
      size_t tree_size_limit =
197
8.81k
          std::min(static_cast<size_t>(1 << 22),
198
8.81k
                   1024 + frame_dim.xsize * frame_dim.ysize *
199
8.81k
                              (nb_chans + nb_extra) / 16);
200
8.81k
      JXL_RETURN_IF_ERROR(
201
8.81k
          DecodeTree(memory_manager, reader, &tree, tree_size_limit));
202
8.80k
      JXL_RETURN_IF_ERROR(DecodeHistograms(
203
8.80k
          memory_manager, reader, (tree.size() + 1) / 2, &code, &context_map));
204
8.80k
    }
205
12.0k
  }
206
12.0k
  if (!do_color) nb_chans = 0;
207
208
12.0k
  bool fp = metadata.bit_depth.floating_point_sample;
209
210
  // bits_per_sample is just metadata for XYB images.
211
12.0k
  if (metadata.bit_depth.bits_per_sample >= 32 && do_color &&
212
12.0k
      frame_header.color_transform != ColorTransform::kXYB) {
213
2.16k
    if (metadata.bit_depth.bits_per_sample == 32 && fp == false) {
214
0
      return JXL_FAILURE("uint32_t not supported in dec_modular");
215
2.16k
    } else if (metadata.bit_depth.bits_per_sample > 32) {
216
0
      return JXL_FAILURE("bits_per_sample > 32 not supported");
217
0
    }
218
2.16k
  }
219
220
24.0k
  JXL_ASSIGN_OR_RETURN(
221
24.0k
      Image gi,
222
24.0k
      Image::Create(memory_manager, frame_dim.xsize, frame_dim.ysize,
223
24.0k
                    metadata.bit_depth.bits_per_sample, nb_chans + nb_extra));
224
225
24.0k
  all_same_shift = true;
226
24.0k
  if (frame_header.color_transform == ColorTransform::kYCbCr) {
227
8.02k
    for (size_t c = 0; c < nb_chans; c++) {
228
6.02k
      gi.channel[c].hshift = frame_header.chroma_subsampling.HShift(c);
229
6.02k
      gi.channel[c].vshift = frame_header.chroma_subsampling.VShift(c);
230
6.02k
      size_t xsize_shifted =
231
6.02k
          DivCeil(frame_dim.xsize, 1 << gi.channel[c].hshift);
232
6.02k
      size_t ysize_shifted =
233
6.02k
          DivCeil(frame_dim.ysize, 1 << gi.channel[c].vshift);
234
6.02k
      JXL_RETURN_IF_ERROR(gi.channel[c].shrink(xsize_shifted, ysize_shifted));
235
6.02k
      if (gi.channel[c].hshift != gi.channel[0].hshift ||
236
6.02k
          gi.channel[c].vshift != gi.channel[0].vshift)
237
2.06k
        all_same_shift = false;
238
6.02k
    }
239
2.00k
  }
240
241
13.6k
  for (size_t ec = 0, c = nb_chans; ec < nb_extra; ec++, c++) {
242
1.61k
    size_t ecups = frame_header.extra_channel_upsampling[ec];
243
1.61k
    JXL_RETURN_IF_ERROR(
244
1.61k
        gi.channel[c].shrink(DivCeil(frame_dim.xsize_upsampled, ecups),
245
1.61k
                             DivCeil(frame_dim.ysize_upsampled, ecups)));
246
1.61k
    gi.channel[c].hshift = gi.channel[c].vshift =
247
1.61k
        CeilLog2Nonzero(ecups) - CeilLog2Nonzero(frame_header.upsampling);
248
1.61k
    if (gi.channel[c].hshift != gi.channel[0].hshift ||
249
1.61k
        gi.channel[c].vshift != gi.channel[0].vshift)
250
170
      all_same_shift = false;
251
1.61k
  }
252
253
12.0k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (w/o transforms) %s",
254
12.0k
              gi.DebugString().c_str());
255
12.0k
  ModularOptions options;
256
12.0k
  options.max_chan_size = frame_dim.group_dim;
257
12.0k
  options.group_dim = frame_dim.group_dim;
258
12.0k
  Status dec_status = ModularGenericDecompress(
259
12.0k
      reader, gi, &global_header, ModularStreamId::Global().ID(frame_dim),
260
12.0k
      &options,
261
12.0k
      /*undo_transforms=*/false, &tree, &code, &context_map,
262
12.0k
      allow_truncated_group);
263
12.0k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
264
12.0k
  if (dec_status.IsFatalError()) {
265
0
    return JXL_FAILURE("Failed to decode global modular info");
266
0
  }
267
268
  // TODO(eustas): are we sure this can be done after partial decode?
269
12.0k
  have_something = false;
270
53.8k
  for (size_t c = 0; c < gi.channel.size(); c++) {
271
41.8k
    Channel& gic = gi.channel[c];
272
41.8k
    if (c >= gi.nb_meta_channels && gic.w <= frame_dim.group_dim &&
273
41.8k
        gic.h <= frame_dim.group_dim)
274
36.5k
      have_something = true;
275
41.8k
  }
276
  // move global transforms to groups if possible
277
12.0k
  if (!have_something && all_same_shift) {
278
6.17k
    if (gi.transform.size() == 1 && gi.transform[0].id == TransformId::kRCT) {
279
17
      global_transform = gi.transform;
280
17
      gi.transform.clear();
281
      // TODO(jon): also move no-delta-palette out (trickier though)
282
17
    }
283
6.17k
  }
284
12.0k
  full_image = std::move(gi);
285
12.0k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (with transforms) %s",
286
12.0k
              full_image.DebugString().c_str());
287
12.0k
  return dec_status;
288
12.0k
}
289
290
11.9k
void ModularFrameDecoder::MaybeDropFullImage() {
291
11.9k
  if (full_image.transform.empty() && !have_something && all_same_shift) {
292
6.15k
    use_full_image = false;
293
6.15k
    JXL_DEBUG_V(6, "Dropping full image");
294
6.15k
    for (auto& ch : full_image.channel) {
295
      // keep metadata on channels around, but dealloc their planes
296
319
      ch.plane = Plane<pixel_type>();
297
319
    }
298
6.15k
  }
299
11.9k
}
300
301
Status ModularFrameDecoder::DecodeGroup(
302
    const FrameHeader& frame_header, const Rect& rect, BitReader* reader,
303
    int minShift, int maxShift, const ModularStreamId& stream, bool zerofill,
304
    PassesDecoderState* dec_state, RenderPipelineInput* render_pipeline_input,
305
30.9k
    bool allow_truncated, bool* should_run_pipeline) {
306
30.9k
  JXL_DEBUG_V(6, "Decoding %s with rect %s and shift bracket %d..%d %s",
307
30.9k
              stream.DebugString().c_str(), Description(rect).c_str(), minShift,
308
30.9k
              maxShift, zerofill ? "using zerofill" : "");
309
30.9k
  JXL_ENSURE(stream.kind == ModularStreamId::Kind::ModularDC ||
310
30.9k
             stream.kind == ModularStreamId::Kind::ModularAC);
311
30.9k
  const size_t xsize = rect.xsize();
312
30.9k
  const size_t ysize = rect.ysize();
313
30.9k
  JXL_ASSIGN_OR_RETURN(Image gi, Image::Create(memory_manager_, xsize, ysize,
314
30.9k
                                               full_image.bitdepth, 0));
315
  // start at the first bigger-than-groupsize non-metachannel
316
30.9k
  size_t c = full_image.nb_meta_channels;
317
86.8k
  for (; c < full_image.channel.size(); c++) {
318
65.4k
    Channel& fc = full_image.channel[c];
319
65.4k
    if (fc.w > frame_dim.group_dim || fc.h > frame_dim.group_dim) break;
320
65.4k
  }
321
30.9k
  size_t beginc = c;
322
90.5k
  for (; c < full_image.channel.size(); c++) {
323
59.5k
    Channel& fc = full_image.channel[c];
324
59.5k
    int shift = std::min(fc.hshift, fc.vshift);
325
59.5k
    if (shift > maxShift) continue;
326
56.9k
    if (shift < minShift) continue;
327
38.2k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
328
38.2k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
329
38.2k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
330
38.2k
    if (zerofill && use_full_image) {
331
0
      for (size_t y = 0; y < r.ysize(); ++y) {
332
0
        pixel_type* const JXL_RESTRICT row_out = r.Row(&fc.plane, y);
333
0
        memset(row_out, 0, r.xsize() * sizeof(*row_out));
334
0
      }
335
38.2k
    } else {
336
38.2k
      JXL_ASSIGN_OR_RETURN(
337
38.2k
          Channel gc, Channel::Create(memory_manager_, r.xsize(), r.ysize()));
338
38.2k
      if (zerofill) ZeroFillImage(&gc.plane);
339
38.2k
      gc.hshift = fc.hshift;
340
38.2k
      gc.vshift = fc.vshift;
341
38.2k
      gi.channel.emplace_back(std::move(gc));
342
38.2k
    }
343
38.2k
  }
344
30.9k
  if (zerofill && use_full_image) return true;
345
  // Return early if there's nothing to decode. Otherwise there might be
346
  // problems later (in ModularImageToDecodedRect).
347
30.9k
  if (gi.channel.empty()) {
348
23.6k
    if (dec_state && should_run_pipeline) {
349
10.9k
      const auto* metadata = frame_header.nonserialized_metadata;
350
10.9k
      if (do_color || metadata->m.num_extra_channels > 0) {
351
        // Signal to FrameDecoder that we do not have some of the required input
352
        // for the render pipeline.
353
4.91k
        *should_run_pipeline = false;
354
4.91k
      }
355
10.9k
    }
356
23.6k
    JXL_DEBUG_V(6, "Nothing to decode, returning early.");
357
23.6k
    return true;
358
23.6k
  }
359
7.29k
  ModularOptions options;
360
7.29k
  if (!zerofill) {
361
7.27k
    auto status = ModularGenericDecompress(
362
7.27k
        reader, gi, /*header=*/nullptr, stream.ID(frame_dim), &options,
363
7.27k
        /*undo_transforms=*/true, &tree, &code, &context_map, allow_truncated);
364
7.31k
    if (!allow_truncated) JXL_RETURN_IF_ERROR(status);
365
7.19k
    if (status.IsFatalError()) return status;
366
7.19k
  }
367
  // Undo global transforms that have been pushed to the group level
368
7.22k
  if (!use_full_image) {
369
3.39k
    JXL_ENSURE(render_pipeline_input);
370
3.39k
    for (const auto& t : global_transform) {
371
2.03k
      JXL_RETURN_IF_ERROR(t.Inverse(gi, global_header.wp_header));
372
2.03k
    }
373
3.39k
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
374
3.39k
        frame_header, gi, dec_state, nullptr, *render_pipeline_input,
375
3.39k
        Rect(0, 0, gi.w, gi.h)));
376
3.39k
    return true;
377
3.39k
  }
378
3.82k
  int gic = 0;
379
43.2k
  for (c = beginc; c < full_image.channel.size(); c++) {
380
39.4k
    Channel& fc = full_image.channel[c];
381
39.4k
    int shift = std::min(fc.hshift, fc.vshift);
382
39.4k
    if (shift > maxShift) continue;
383
36.8k
    if (shift < minShift) continue;
384
25.5k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
385
25.5k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
386
25.5k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
387
25.5k
    JXL_ENSURE(use_full_image);
388
25.5k
    JXL_RETURN_IF_ERROR(
389
25.5k
        CopyImageTo(/*rect_from=*/Rect(0, 0, r.xsize(), r.ysize()),
390
25.5k
                    /*from=*/gi.channel[gic].plane,
391
25.5k
                    /*rect_to=*/r, /*to=*/&fc.plane));
392
25.5k
    gic++;
393
25.5k
  }
394
3.82k
  return true;
395
3.82k
}
396
397
Status ModularFrameDecoder::DecodeVarDCTDC(const FrameHeader& frame_header,
398
                                           size_t group_id, BitReader* reader,
399
6.06k
                                           PassesDecoderState* dec_state) {
400
6.06k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
401
6.06k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
402
6.06k
  JXL_DEBUG_V(6, "Decoding VarDCT DC with rect %s", Description(r).c_str());
403
  // TODO(eustas): investigate if we could reduce the impact of
404
  //               EvalRationalPolynomial; generally speaking, the limit is
405
  //               2**(128/(3*magic)), where 128 comes from IEEE 754 exponent,
406
  //               3 comes from XybToRgb that cubes the values, and "magic" is
407
  //               the sum of all other contributions. 2**18 is known to lead
408
  //               to NaN on input found by fuzzing (see commit message).
409
6.06k
  JXL_ASSIGN_OR_RETURN(Image image,
410
6.06k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
411
6.06k
                                     full_image.bitdepth, 3));
412
6.06k
  size_t stream_id = ModularStreamId::VarDCTDC(group_id).ID(frame_dim);
413
6.06k
  reader->Refill();
414
6.06k
  size_t extra_precision = reader->ReadFixedBits<2>();
415
6.06k
  float mul = 1.0f / (1 << extra_precision);
416
6.06k
  ModularOptions options;
417
24.2k
  for (size_t c = 0; c < 3; c++) {
418
18.2k
    Channel& ch = image.channel[c < 2 ? c ^ 1 : c];
419
18.2k
    ch.w >>= frame_header.chroma_subsampling.HShift(c);
420
18.2k
    ch.h >>= frame_header.chroma_subsampling.VShift(c);
421
18.2k
    JXL_RETURN_IF_ERROR(ch.shrink());
422
18.2k
  }
423
6.06k
  if (!ModularGenericDecompress(
424
6.06k
          reader, image, /*header=*/nullptr, stream_id, &options,
425
6.06k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
426
5
    return JXL_FAILURE("Failed to decode VarDCT DC group (DC group id %d)",
427
5
                       static_cast<int>(group_id));
428
5
  }
429
6.06k
  DequantDC(r, &dec_state->shared_storage.dc_storage,
430
6.06k
            &dec_state->shared_storage.quant_dc, image,
431
6.06k
            dec_state->shared->quantizer.MulDC(), mul,
432
6.06k
            dec_state->shared->cmap.base().DCFactors(),
433
6.06k
            frame_header.chroma_subsampling, dec_state->shared->block_ctx_map);
434
6.06k
  return true;
435
6.06k
}
436
437
Status ModularFrameDecoder::DecodeAcMetadata(const FrameHeader& frame_header,
438
                                             size_t group_id, BitReader* reader,
439
6.06k
                                             PassesDecoderState* dec_state) {
440
6.06k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
441
6.06k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
442
6.06k
  JXL_DEBUG_V(6, "Decoding AcMetadata with rect %s", Description(r).c_str());
443
6.06k
  size_t upper_bound = r.xsize() * r.ysize();
444
6.06k
  reader->Refill();
445
6.06k
  size_t count = reader->ReadBits(CeilLog2Nonzero(upper_bound)) + 1;
446
6.06k
  size_t stream_id = ModularStreamId::ACMetadata(group_id).ID(frame_dim);
447
  // YToX, YToB, ACS + QF, EPF
448
6.06k
  JXL_ASSIGN_OR_RETURN(Image image,
449
6.06k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
450
6.06k
                                     full_image.bitdepth, 4));
451
6.06k
  static_assert(kColorTileDimInBlocks == 8, "Color tile size changed");
452
6.06k
  Rect cr(r.x0() >> 3, r.y0() >> 3, (r.xsize() + 7) >> 3, (r.ysize() + 7) >> 3);
453
6.06k
  JXL_ASSIGN_OR_RETURN(
454
6.06k
      image.channel[0],
455
6.06k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
456
6.06k
  JXL_ASSIGN_OR_RETURN(
457
6.06k
      image.channel[1],
458
6.06k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
459
6.06k
  JXL_ASSIGN_OR_RETURN(image.channel[2],
460
6.06k
                       Channel::Create(memory_manager, count, 2, 0, 0));
461
6.06k
  ModularOptions options;
462
6.06k
  if (!ModularGenericDecompress(
463
6.06k
          reader, image, /*header=*/nullptr, stream_id, &options,
464
6.06k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
465
3
    return JXL_FAILURE("Failed to decode AC metadata");
466
3
  }
467
6.06k
  JXL_RETURN_IF_ERROR(
468
6.06k
      ConvertPlaneAndClamp(Rect(image.channel[0].plane), image.channel[0].plane,
469
6.06k
                           cr, &dec_state->shared_storage.cmap.ytox_map));
470
6.06k
  JXL_RETURN_IF_ERROR(
471
6.06k
      ConvertPlaneAndClamp(Rect(image.channel[1].plane), image.channel[1].plane,
472
6.06k
                           cr, &dec_state->shared_storage.cmap.ytob_map));
473
6.06k
  size_t num = 0;
474
6.06k
  bool is444 = frame_header.chroma_subsampling.Is444();
475
6.06k
  auto& ac_strategy = dec_state->shared_storage.ac_strategy;
476
6.06k
  size_t xlim = std::min(ac_strategy.xsize(), r.x0() + r.xsize());
477
6.06k
  size_t ylim = std::min(ac_strategy.ysize(), r.y0() + r.ysize());
478
6.06k
  uint32_t local_used_acs = 0;
479
18.3k
  for (size_t iy = 0; iy < r.ysize(); iy++) {
480
12.2k
    size_t y = r.y0() + iy;
481
12.2k
    int32_t* row_qf = r.Row(&dec_state->shared_storage.raw_quant_field, iy);
482
12.2k
    uint8_t* row_epf = r.Row(&dec_state->shared_storage.epf_sharpness, iy);
483
12.2k
    int32_t* row_in_1 = image.channel[2].plane.Row(0);
484
12.2k
    int32_t* row_in_2 = image.channel[2].plane.Row(1);
485
12.2k
    int32_t* row_in_3 = image.channel[3].plane.Row(iy);
486
104k
    for (size_t ix = 0; ix < r.xsize(); ix++) {
487
92.3k
      size_t x = r.x0() + ix;
488
92.3k
      int sharpness = row_in_3[ix];
489
92.3k
      if (sharpness < 0 || sharpness >= LoopFilter::kEpfSharpEntries) {
490
2
        return JXL_FAILURE("Corrupted sharpness field");
491
2
      }
492
92.3k
      row_epf[ix] = sharpness;
493
92.3k
      if (ac_strategy.IsValid(x, y)) {
494
15.1k
        continue;
495
15.1k
      }
496
497
77.2k
      if (num >= count) return JXL_FAILURE("Corrupted stream");
498
499
77.2k
      if (!AcStrategy::IsRawStrategyValid(row_in_1[num])) {
500
0
        return JXL_FAILURE("Invalid AC strategy");
501
0
      }
502
77.2k
      local_used_acs |= 1u << row_in_1[num];
503
77.2k
      AcStrategy acs = AcStrategy::FromRawStrategy(row_in_1[num]);
504
77.2k
      if ((acs.covered_blocks_x() > 1 || acs.covered_blocks_y() > 1) &&
505
77.2k
          !is444) {
506
0
        return JXL_FAILURE(
507
0
            "AC strategy not compatible with chroma subsampling");
508
0
      }
509
      // Ensure that blocks do not overflow *AC* groups.
510
77.2k
      size_t next_x_ac_block = (x / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
511
77.2k
      size_t next_y_ac_block = (y / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
512
77.2k
      size_t next_x_dct_block = x + acs.covered_blocks_x();
513
77.2k
      size_t next_y_dct_block = y + acs.covered_blocks_y();
514
77.2k
      if (next_x_dct_block > next_x_ac_block || next_x_dct_block > xlim) {
515
1
        return JXL_FAILURE("Invalid AC strategy, x overflow");
516
1
      }
517
77.2k
      if (next_y_dct_block > next_y_ac_block || next_y_dct_block > ylim) {
518
0
        return JXL_FAILURE("Invalid AC strategy, y overflow");
519
0
      }
520
77.2k
      JXL_RETURN_IF_ERROR(
521
77.2k
          ac_strategy.SetNoBoundsCheck(x, y, AcStrategyType(row_in_1[num])));
522
77.2k
      row_qf[ix] = 1 + std::max<int32_t>(0, std::min(Quantizer::kQuantMax - 1,
523
77.2k
                                                     row_in_2[num]));
524
77.2k
      num++;
525
77.2k
    }
526
12.2k
  }
527
6.05k
  dec_state->used_acs |= local_used_acs;
528
6.05k
  if (frame_header.loop_filter.epf_iters > 0) {
529
6.05k
    JXL_RETURN_IF_ERROR(ComputeSigma(frame_header.loop_filter, r, dec_state));
530
6.05k
  }
531
6.05k
  return true;
532
6.05k
}
533
534
Status ModularFrameDecoder::ModularImageToDecodedRect(
535
    const FrameHeader& frame_header, Image& gi, PassesDecoderState* dec_state,
536
    jxl::ThreadPool* pool, RenderPipelineInput& render_pipeline_input,
537
10.4k
    Rect modular_rect) const {
538
10.4k
  const auto* metadata = frame_header.nonserialized_metadata;
539
10.4k
  JXL_ENSURE(gi.transform.empty());
540
541
1.75M
  auto get_row = [&](size_t c, size_t y) {
542
1.75M
    const auto& buffer = render_pipeline_input.GetBuffer(c);
543
1.75M
    return buffer.second.Row(buffer.first, y);
544
1.75M
  };
545
546
10.4k
  size_t c = 0;
547
10.4k
  if (do_color) {
548
10.4k
    const bool rgb_from_gray =
549
10.4k
        metadata->m.color_encoding.IsGray() &&
550
10.4k
        frame_header.color_transform == ColorTransform::kNone;
551
10.4k
    const bool fp = metadata->m.bit_depth.floating_point_sample &&
552
10.4k
                    frame_header.color_transform != ColorTransform::kXYB;
553
41.7k
    for (; c < 3; c++) {
554
31.3k
      double factor = full_image.bitdepth < 32
555
31.3k
                          ? 1.0 / ((1u << full_image.bitdepth) - 1)
556
31.3k
                          : 0;
557
31.3k
      size_t c_in = c;
558
31.3k
      if (frame_header.color_transform == ColorTransform::kXYB) {
559
12.3k
        factor = dec_state->shared->matrices.DCQuants()[c];
560
        // XYB is encoded as YX(B-Y)
561
12.3k
        if (c < 2) c_in = 1 - c;
562
18.9k
      } else if (rgb_from_gray) {
563
48
        c_in = 0;
564
48
      }
565
31.3k
      JXL_ENSURE(c_in < gi.channel.size());
566
31.3k
      Channel& ch_in = gi.channel[c_in];
567
      // TODO(eustas): could we detect it on earlier stage?
568
31.3k
      if (ch_in.w == 0 || ch_in.h == 0) {
569
0
        return JXL_FAILURE("Empty image");
570
0
      }
571
31.3k
      JXL_ENSURE(ch_in.hshift <= 3 && ch_in.vshift <= 3);
572
31.3k
      Rect r = render_pipeline_input.GetBuffer(c).second;
573
31.3k
      Rect mr(modular_rect.x0() >> ch_in.hshift,
574
31.3k
              modular_rect.y0() >> ch_in.vshift,
575
31.3k
              DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
576
31.3k
              DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
577
31.3k
      mr = mr.Crop(ch_in.plane);
578
31.3k
      size_t xsize_shifted = r.xsize();
579
31.3k
      size_t ysize_shifted = r.ysize();
580
31.3k
      if (r.ysize() != mr.ysize() || r.xsize() != mr.xsize()) {
581
0
        return JXL_FAILURE("Dimension mismatch: trying to fit a %" PRIuS
582
0
                           "x%" PRIuS
583
0
                           " modular channel into "
584
0
                           "a %" PRIuS "x%" PRIuS " rect",
585
0
                           mr.xsize(), mr.ysize(), r.xsize(), r.ysize());
586
0
      }
587
31.3k
      if (frame_header.color_transform == ColorTransform::kXYB && c == 2) {
588
4.12k
        JXL_ENSURE(!fp);
589
4.12k
        const auto process_row = [&](const uint32_t task,
590
215k
                                     size_t /* thread */) -> Status {
591
215k
          const size_t y = task;
592
215k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
593
215k
          const pixel_type* const JXL_RESTRICT row_in_Y =
594
215k
              mr.Row(&gi.channel[0].plane, y);
595
215k
          float* const JXL_RESTRICT row_out = get_row(c, y);
596
215k
          HWY_DYNAMIC_DISPATCH(MultiplySum)
597
215k
          (xsize_shifted, row_in, row_in_Y, factor, row_out);
598
215k
          return true;
599
215k
        };
600
4.12k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
601
4.12k
                                      ThreadPool::NoInit, process_row,
602
4.12k
                                      "ModularIntToFloat"));
603
27.2k
      } else if (fp) {
604
6.48k
        int bits = metadata->m.bit_depth.bits_per_sample;
605
6.48k
        int exp_bits = metadata->m.bit_depth.exponent_bits_per_sample;
606
6.48k
        const auto process_row = [&](const uint32_t task,
607
101k
                                     size_t /* thread */) -> Status {
608
101k
          const size_t y = task;
609
101k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
610
101k
          if (rgb_from_gray) {
611
9.21k
            for (size_t cc = 0; cc < 3; cc++) {
612
6.91k
              float* const JXL_RESTRICT row_out = get_row(cc, y);
613
6.91k
              JXL_RETURN_IF_ERROR(
614
6.91k
                  int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
615
6.91k
            }
616
99.5k
          } else {
617
99.5k
            float* const JXL_RESTRICT row_out = get_row(c, y);
618
99.5k
            JXL_RETURN_IF_ERROR(
619
99.5k
                int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
620
99.5k
          }
621
101k
          return true;
622
101k
        };
623
6.48k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
624
6.48k
                                      ThreadPool::NoInit, process_row,
625
6.48k
                                      "ModularIntToFloat_losslessfloat"));
626
20.7k
      } else {
627
20.7k
        const auto process_row = [&](const uint32_t task,
628
1.43M
                                     size_t /* thread */) -> Status {
629
1.43M
          const size_t y = task;
630
1.43M
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
631
1.43M
          if (rgb_from_gray) {
632
6.13k
            if (full_image.bitdepth < 23) {
633
6.13k
              HWY_DYNAMIC_DISPATCH(RgbFromSingle)
634
6.13k
              (xsize_shifted, row_in, factor, get_row(0, y), get_row(1, y),
635
6.13k
               get_row(2, y));
636
6.13k
            } else {
637
0
              SingleFromSingleAccurate(xsize_shifted, row_in, factor,
638
0
                                       get_row(0, y));
639
0
              SingleFromSingleAccurate(xsize_shifted, row_in, factor,
640
0
                                       get_row(1, y));
641
0
              SingleFromSingleAccurate(xsize_shifted, row_in, factor,
642
0
                                       get_row(2, y));
643
0
            }
644
1.43M
          } else {
645
1.43M
            float* const JXL_RESTRICT row_out = get_row(c, y);
646
1.43M
            if (full_image.bitdepth < 23) {
647
1.34M
              HWY_DYNAMIC_DISPATCH(SingleFromSingle)
648
1.34M
              (xsize_shifted, row_in, factor, row_out);
649
1.34M
            } else {
650
89.4k
              SingleFromSingleAccurate(xsize_shifted, row_in, factor, row_out);
651
89.4k
            }
652
1.43M
          }
653
1.43M
          return true;
654
1.43M
        };
655
20.7k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
656
20.7k
                                      ThreadPool::NoInit, process_row,
657
20.7k
                                      "ModularIntToFloat"));
658
20.7k
      }
659
31.3k
      if (rgb_from_gray) {
660
48
        break;
661
48
      }
662
31.3k
    }
663
10.4k
    if (rgb_from_gray) {
664
48
      c = 1;
665
48
    }
666
10.4k
  }
667
10.4k
  size_t num_extra_channels = metadata->m.num_extra_channels;
668
11.8k
  for (size_t ec = 0; ec < num_extra_channels; ec++, c++) {
669
1.39k
    const ExtraChannelInfo& eci = metadata->m.extra_channel_info[ec];
670
1.39k
    int bits = eci.bit_depth.bits_per_sample;
671
1.39k
    int exp_bits = eci.bit_depth.exponent_bits_per_sample;
672
1.39k
    bool fp = eci.bit_depth.floating_point_sample;
673
1.39k
    JXL_ENSURE(fp || bits < 32);
674
1.39k
    const double factor = fp ? 0 : (1.0 / ((1u << bits) - 1));
675
1.39k
    JXL_ENSURE(c < gi.channel.size());
676
1.39k
    Channel& ch_in = gi.channel[c];
677
1.39k
    const auto& buffer = render_pipeline_input.GetBuffer(3 + ec);
678
1.39k
    Rect r = buffer.second;
679
1.39k
    Rect mr(modular_rect.x0() >> ch_in.hshift,
680
1.39k
            modular_rect.y0() >> ch_in.vshift,
681
1.39k
            DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
682
1.39k
            DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
683
1.39k
    mr = mr.Crop(ch_in.plane);
684
1.39k
    if (r.ysize() != mr.ysize() || r.xsize() != mr.xsize()) {
685
0
      return JXL_FAILURE("Dimension mismatch: trying to fit a %" PRIuS
686
0
                         "x%" PRIuS
687
0
                         " modular channel into "
688
0
                         "a %" PRIuS "x%" PRIuS " rect",
689
0
                         mr.xsize(), mr.ysize(), r.xsize(), r.ysize());
690
0
    }
691
156k
    for (size_t y = 0; y < r.ysize(); ++y) {
692
154k
      float* const JXL_RESTRICT row_out = r.Row(buffer.first, y);
693
154k
      const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
694
154k
      if (fp) {
695
974
        JXL_RETURN_IF_ERROR(
696
974
            int_to_float(row_in, row_out, r.xsize(), bits, exp_bits));
697
153k
      } else {
698
153k
        if (full_image.bitdepth < 23) {
699
153k
          HWY_DYNAMIC_DISPATCH(SingleFromSingle)
700
153k
          (r.xsize(), row_in, factor, row_out);
701
153k
        } else {
702
510
          SingleFromSingleAccurate(r.xsize(), row_in, factor, row_out);
703
510
        }
704
153k
      }
705
154k
    }
706
1.39k
  }
707
10.4k
  return true;
708
10.4k
}
709
710
Status ModularFrameDecoder::FinalizeDecoding(const FrameHeader& frame_header,
711
                                             PassesDecoderState* dec_state,
712
                                             jxl::ThreadPool* pool,
713
11.9k
                                             bool inplace) {
714
11.9k
  if (!use_full_image) return true;
715
5.82k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
716
5.82k
  Image gi{memory_manager};
717
5.82k
  if (inplace) {
718
5.82k
    gi = std::move(full_image);
719
5.82k
  } else {
720
0
    JXL_ASSIGN_OR_RETURN(gi, Image::Clone(full_image));
721
0
  }
722
5.82k
  size_t xsize = gi.w;
723
5.82k
  size_t ysize = gi.h;
724
725
5.82k
  JXL_DEBUG_V(3, "Finalizing decoding for modular image: %s",
726
5.82k
              gi.DebugString().c_str());
727
728
  // Don't use threads if total image size is smaller than a group
729
5.82k
  if (xsize * ysize < frame_dim.group_dim * frame_dim.group_dim) pool = nullptr;
730
731
  // Undo the global transforms
732
5.82k
  gi.undo_transforms(global_header.wp_header, pool);
733
5.82k
  JXL_ENSURE(global_transform.empty());
734
5.82k
  if (gi.error) return JXL_FAILURE("Undoing transforms failed");
735
736
12.9k
  for (size_t i = 0; i < dec_state->shared->frame_dim.num_groups; i++) {
737
7.10k
    dec_state->render_pipeline->ClearDone(i);
738
7.10k
  }
739
740
5.82k
  const auto init = [&](size_t num_threads) -> Status {
741
5.82k
    bool use_group_ids = (frame_header.encoding == FrameEncoding::kVarDCT ||
742
5.82k
                          (frame_header.flags & FrameHeader::kNoise));
743
5.82k
    JXL_RETURN_IF_ERROR(dec_state->render_pipeline->PrepareForThreads(
744
5.82k
        num_threads, use_group_ids));
745
5.82k
    return true;
746
5.82k
  };
747
5.82k
  const auto process_group = [&](const uint32_t group,
748
7.10k
                                 size_t thread_id) -> Status {
749
7.10k
    RenderPipelineInput input =
750
7.10k
        dec_state->render_pipeline->GetInputBuffers(group, thread_id);
751
7.10k
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
752
7.10k
        frame_header, gi, dec_state, nullptr, input,
753
7.10k
        dec_state->shared->frame_dim.GroupRect(group)));
754
7.10k
    JXL_RETURN_IF_ERROR(input.Done());
755
7.10k
    return true;
756
7.10k
  };
757
5.82k
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0,
758
5.82k
                                dec_state->shared->frame_dim.num_groups, init,
759
5.82k
                                process_group, "ModularToRect"));
760
5.82k
  return true;
761
5.82k
}
762
763
static constexpr const float kAlmostZero = 1e-8f;
764
765
Status ModularFrameDecoder::DecodeQuantTable(
766
    JxlMemoryManager* memory_manager, size_t required_size_x,
767
    size_t required_size_y, BitReader* br, QuantEncoding* encoding, size_t idx,
768
1
    ModularFrameDecoder* modular_frame_decoder) {
769
1
  JXL_RETURN_IF_ERROR(F16Coder::Read(br, &encoding->qraw.qtable_den));
770
1
  if (encoding->qraw.qtable_den < kAlmostZero) {
771
    // qtable[] values are already checked for <= 0 so the denominator may not
772
    // be negative.
773
0
    return JXL_FAILURE("Invalid qtable_den: value too small");
774
0
  }
775
2
  JXL_ASSIGN_OR_RETURN(
776
2
      Image image,
777
2
      Image::Create(memory_manager, required_size_x, required_size_y, 8, 3));
778
2
  ModularOptions options;
779
2
  if (modular_frame_decoder) {
780
1
    JXL_ASSIGN_OR_RETURN(ModularStreamId qt, ModularStreamId::QuantTable(idx));
781
1
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(
782
1
        br, image, /*header=*/nullptr, qt.ID(modular_frame_decoder->frame_dim),
783
1
        &options, /*undo_transforms=*/true, &modular_frame_decoder->tree,
784
1
        &modular_frame_decoder->code, &modular_frame_decoder->context_map));
785
1
  } else {
786
0
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(br, image, /*header=*/nullptr,
787
0
                                                 0, &options,
788
0
                                                 /*undo_transforms=*/true));
789
0
  }
790
0
  if (!encoding->qraw.qtable) {
791
0
    encoding->qraw.qtable =
792
0
        new std::vector<int>(required_size_x * required_size_y * 3);
793
0
  } else {
794
0
    JXL_ENSURE(encoding->qraw.qtable->size() ==
795
0
               required_size_x * required_size_y * 3);
796
0
  }
797
0
  int* qtable = encoding->qraw.qtable->data();
798
0
  for (size_t c = 0; c < 3; c++) {
799
0
    for (size_t y = 0; y < required_size_y; y++) {
800
0
      int32_t* JXL_RESTRICT row = image.channel[c].Row(y);
801
0
      for (size_t x = 0; x < required_size_x; x++) {
802
0
        qtable[c * required_size_x * required_size_y + y * required_size_x +
803
0
               x] = row[x];
804
0
        if (row[x] <= 0) {
805
0
          return JXL_FAILURE("Invalid raw quantization table");
806
0
        }
807
0
      }
808
0
    }
809
0
  }
810
0
  return true;
811
0
}
812
813
}  // namespace jxl
814
#endif  // HWY_ONCE