Coverage Report

Created: 2025-08-11 08:01

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