Coverage Report

Created: 2025-07-23 08:18

/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
399k
                 const float factor, float* const JXL_RESTRICT row_out) {
65
399k
  const HWY_FULL(float) df;
66
399k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
67
399k
  const auto factor_v = Set(df, factor);
68
4.71M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
69
4.31M
    const auto in = Add(Load(di, row_in + x), Load(di, row_in_Y + x));
70
4.31M
    const auto out = Mul(ConvertTo(df, in), factor_v);
71
4.31M
    Store(out, df, row_out + x);
72
4.31M
  }
73
399k
}
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
399k
                 const float factor, float* const JXL_RESTRICT row_out) {
65
399k
  const HWY_FULL(float) df;
66
399k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
67
399k
  const auto factor_v = Set(df, factor);
68
4.71M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
69
4.31M
    const auto in = Add(Load(di, row_in + x), Load(di, row_in_Y + x));
70
4.31M
    const auto out = Mul(ConvertTo(df, in), factor_v);
71
4.31M
    Store(out, df, row_out + x);
72
4.31M
  }
73
399k
}
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
29.4k
                   float* out_b) {
79
29.4k
  const HWY_FULL(float) df;
80
29.4k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
81
82
29.4k
  const auto factor_v = Set(df, factor);
83
456k
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
84
427k
    const auto in = Load(di, row_in + x);
85
427k
    const auto out = Mul(ConvertTo(df, in), factor_v);
86
427k
    Store(out, df, out_r + x);
87
427k
    Store(out, df, out_g + x);
88
427k
    Store(out, df, out_b + x);
89
427k
  }
90
29.4k
}
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
29.4k
                   float* out_b) {
79
29.4k
  const HWY_FULL(float) df;
80
29.4k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
81
82
29.4k
  const auto factor_v = Set(df, factor);
83
456k
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
84
427k
    const auto in = Load(di, row_in + x);
85
427k
    const auto out = Mul(ConvertTo(df, in), factor_v);
86
427k
    Store(out, df, out_r + x);
87
427k
    Store(out, df, out_g + x);
88
427k
    Store(out, df, out_b + x);
89
427k
  }
90
29.4k
}
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
2.82M
                      const float factor, float* row_out) {
95
2.82M
  const HWY_FULL(float) df;
96
2.82M
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
97
98
2.82M
  const auto factor_v = Set(df, factor);
99
25.7M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
100
22.9M
    const auto in = Load(di, row_in + x);
101
22.9M
    const auto out = Mul(ConvertTo(df, in), factor_v);
102
22.9M
    Store(out, df, row_out + x);
103
22.9M
  }
104
2.82M
}
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
2.82M
                      const float factor, float* row_out) {
95
2.82M
  const HWY_FULL(float) df;
96
2.82M
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
97
98
2.82M
  const auto factor_v = Set(df, factor);
99
25.7M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
100
22.9M
    const auto in = Load(di, row_in + x);
101
22.9M
    const auto out = Mul(ConvertTo(df, in), factor_v);
102
22.9M
    Store(out, df, row_out + x);
103
22.9M
  }
104
2.82M
}
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
1.00k
                              const double factor, float* row_out) {
121
19.8k
  for (size_t x = 0; x < xsize; x++) {
122
18.8k
    row_out[x] = row_in[x] * factor;
123
18.8k
  }
124
1.00k
}
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
122k
                    const int bits, const int exp_bits) {
131
122k
  static_assert(sizeof(pixel_type) == sizeof(float), "32-bit input is assumed");
132
122k
  if (bits == 32) {
133
112k
    JXL_ENSURE(exp_bits == 8);
134
112k
    memcpy(row_out, row_in, xsize * sizeof(float));
135
112k
    return true;
136
112k
  }
137
9.44k
  int exp_bias = (1 << (exp_bits - 1)) - 1;
138
9.44k
  int sign_shift = bits - 1;
139
9.44k
  int mant_bits = bits - exp_bits - 1;
140
9.44k
  int mant_shift = 23 - mant_bits;
141
895k
  for (size_t x = 0; x < xsize; ++x) {
142
886k
    uint32_t f;
143
886k
    memcpy(&f, &row_in[x], 4);
144
886k
    int signbit = (f >> sign_shift);
145
886k
    f &= (1 << sign_shift) - 1;
146
886k
    if (f == 0) {
147
618k
      row_out[x] = (signbit ? -0.f : 0.f);
148
618k
      continue;
149
618k
    }
150
267k
    int exp = (f >> mant_bits);
151
267k
    int mantissa = (f & ((1 << mant_bits) - 1));
152
267k
    mantissa <<= mant_shift;
153
    // Try to normalize only if there is space for maneuver.
154
267k
    if (exp == 0 && exp_bits < 8) {
155
      // subnormal number
156
41.1k
      while ((mantissa & 0x800000) == 0) {
157
35.2k
        mantissa <<= 1;
158
35.2k
        exp--;
159
35.2k
      }
160
5.87k
      exp++;
161
      // remove leading 1 because it is implicit now
162
5.87k
      mantissa &= 0x7fffff;
163
5.87k
    }
164
267k
    exp -= exp_bias;
165
    // broke up the arbitrary float into its parts, now reassemble into
166
    // binary32
167
267k
    exp += 127;
168
267k
    JXL_ENSURE(exp >= 0);
169
267k
    f = (signbit ? 0x80000000 : 0);
170
267k
    f |= (exp << 23);
171
267k
    f |= mantissa;
172
267k
    memcpy(&row_out[x], &f, 4);
173
267k
  }
174
9.44k
  return true;
175
9.44k
}
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
47.7k
                                             bool allow_truncated_group) {
204
47.7k
  JxlMemoryManager* memory_manager = this->memory_manager();
205
47.7k
  bool decode_color = frame_header.encoding == FrameEncoding::kModular;
206
47.7k
  const auto& metadata = frame_header.nonserialized_metadata->m;
207
47.7k
  bool is_gray = metadata.color_encoding.IsGray();
208
47.7k
  size_t nb_chans = 3;
209
47.7k
  if (is_gray && frame_header.color_transform == ColorTransform::kNone) {
210
482
    nb_chans = 1;
211
482
  }
212
47.7k
  do_color = decode_color;
213
47.7k
  size_t nb_extra = metadata.extra_channel_info.size();
214
47.7k
  bool has_tree = static_cast<bool>(reader->ReadBits(1));
215
47.7k
  if (!allow_truncated_group ||
216
47.7k
      reader->TotalBitsConsumed() < reader->TotalBytes() * kBitsPerByte) {
217
47.7k
    if (has_tree) {
218
9.44k
      size_t tree_size_limit =
219
9.44k
          std::min(static_cast<size_t>(1 << 22),
220
9.44k
                   1024 + frame_dim.xsize * frame_dim.ysize *
221
9.44k
                              (nb_chans + nb_extra) / 16);
222
9.44k
      JXL_RETURN_IF_ERROR(
223
9.44k
          DecodeTree(memory_manager, reader, &tree, tree_size_limit));
224
7.31k
      JXL_RETURN_IF_ERROR(DecodeHistograms(
225
7.31k
          memory_manager, reader, (tree.size() + 1) / 2, &code, &context_map));
226
7.31k
    }
227
47.7k
  }
228
45.5k
  if (!do_color) nb_chans = 0;
229
230
45.5k
  bool fp = metadata.bit_depth.floating_point_sample;
231
232
  // bits_per_sample is just metadata for XYB images.
233
45.5k
  if (metadata.bit_depth.bits_per_sample >= 32 && do_color &&
234
45.5k
      frame_header.color_transform != ColorTransform::kXYB) {
235
4.76k
    if (metadata.bit_depth.bits_per_sample == 32 && fp == false) {
236
0
      return JXL_FAILURE("uint32_t not supported in dec_modular");
237
4.76k
    } else if (metadata.bit_depth.bits_per_sample > 32) {
238
0
      return JXL_FAILURE("bits_per_sample > 32 not supported");
239
0
    }
240
4.76k
  }
241
242
91.0k
  JXL_ASSIGN_OR_RETURN(
243
91.0k
      Image gi,
244
91.0k
      Image::Create(memory_manager, frame_dim.xsize, frame_dim.ysize,
245
91.0k
                    metadata.bit_depth.bits_per_sample, nb_chans + nb_extra));
246
247
91.0k
  all_same_shift = true;
248
91.0k
  if (frame_header.color_transform == ColorTransform::kYCbCr) {
249
7.75k
    for (size_t c = 0; c < nb_chans; c++) {
250
5.65k
      gi.channel[c].hshift = frame_header.chroma_subsampling.HShift(c);
251
5.65k
      gi.channel[c].vshift = frame_header.chroma_subsampling.VShift(c);
252
5.65k
      size_t xsize_shifted =
253
5.65k
          DivCeil(frame_dim.xsize, 1 << gi.channel[c].hshift);
254
5.65k
      size_t ysize_shifted =
255
5.65k
          DivCeil(frame_dim.ysize, 1 << gi.channel[c].vshift);
256
5.65k
      JXL_RETURN_IF_ERROR(gi.channel[c].shrink(xsize_shifted, ysize_shifted));
257
5.65k
      if (gi.channel[c].hshift != gi.channel[0].hshift ||
258
5.65k
          gi.channel[c].vshift != gi.channel[0].vshift)
259
3.08k
        all_same_shift = false;
260
5.65k
    }
261
2.10k
  }
262
263
48.4k
  for (size_t ec = 0, c = nb_chans; ec < nb_extra; ec++, c++) {
264
2.95k
    size_t ecups = frame_header.extra_channel_upsampling[ec];
265
2.95k
    JXL_RETURN_IF_ERROR(
266
2.95k
        gi.channel[c].shrink(DivCeil(frame_dim.xsize_upsampled, ecups),
267
2.95k
                             DivCeil(frame_dim.ysize_upsampled, ecups)));
268
2.95k
    gi.channel[c].hshift = gi.channel[c].vshift =
269
2.95k
        CeilLog2Nonzero(ecups) - CeilLog2Nonzero(frame_header.upsampling);
270
2.95k
    if (gi.channel[c].hshift != gi.channel[0].hshift ||
271
2.95k
        gi.channel[c].vshift != gi.channel[0].vshift)
272
1.63k
      all_same_shift = false;
273
2.95k
  }
274
275
45.5k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (w/o transforms) %s",
276
45.5k
              gi.DebugString().c_str());
277
45.5k
  ModularOptions options;
278
45.5k
  options.max_chan_size = frame_dim.group_dim;
279
45.5k
  options.group_dim = frame_dim.group_dim;
280
45.5k
  Status dec_status = ModularGenericDecompress(
281
45.5k
      reader, gi, &global_header, ModularStreamId::Global().ID(frame_dim),
282
45.5k
      &options,
283
45.5k
      /*undo_transforms=*/false, &tree, &code, &context_map,
284
45.5k
      allow_truncated_group);
285
45.5k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
286
35.9k
  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
35.9k
  have_something = false;
292
168k
  for (size_t c = 0; c < gi.channel.size(); c++) {
293
132k
    Channel& gic = gi.channel[c];
294
132k
    if (c >= gi.nb_meta_channels && gic.w <= frame_dim.group_dim &&
295
132k
        gic.h <= frame_dim.group_dim)
296
130k
      have_something = true;
297
132k
  }
298
  // move global transforms to groups if possible
299
35.9k
  if (!have_something && all_same_shift) {
300
8.68k
    if (gi.transform.size() == 1 && gi.transform[0].id == TransformId::kRCT) {
301
38
      global_transform = gi.transform;
302
38
      gi.transform.clear();
303
      // TODO(jon): also move no-delta-palette out (trickier though)
304
38
    }
305
8.68k
  }
306
35.9k
  full_image = std::move(gi);
307
35.9k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (with transforms) %s",
308
35.9k
              full_image.DebugString().c_str());
309
35.9k
  return dec_status;
310
35.9k
}
311
312
28.9k
void ModularFrameDecoder::MaybeDropFullImage() {
313
28.9k
  if (full_image.transform.empty() && !have_something && all_same_shift) {
314
1.73k
    use_full_image = false;
315
1.73k
    JXL_DEBUG_V(6, "Dropping full image");
316
1.73k
    for (auto& ch : full_image.channel) {
317
      // keep metadata on channels around, but dealloc their planes
318
526
      ch.plane = Plane<pixel_type>();
319
526
    }
320
1.73k
  }
321
28.9k
}
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
62.2k
    bool allow_truncated, bool* should_run_pipeline) {
328
62.2k
  JXL_DEBUG_V(6, "Decoding %s with rect %s and shift bracket %d..%d %s",
329
62.2k
              stream.DebugString().c_str(), Description(rect).c_str(), minShift,
330
62.2k
              maxShift, zerofill ? "using zerofill" : "");
331
62.2k
  JXL_ENSURE(stream.kind == ModularStreamId::Kind::ModularDC ||
332
62.2k
             stream.kind == ModularStreamId::Kind::ModularAC);
333
62.2k
  const size_t xsize = rect.xsize();
334
62.2k
  const size_t ysize = rect.ysize();
335
62.2k
  JXL_ASSIGN_OR_RETURN(Image gi, Image::Create(memory_manager_, xsize, ysize,
336
62.2k
                                               full_image.bitdepth, 0));
337
  // start at the first bigger-than-groupsize non-metachannel
338
62.2k
  size_t c = full_image.nb_meta_channels;
339
391k
  for (; c < full_image.channel.size(); c++) {
340
331k
    Channel& fc = full_image.channel[c];
341
331k
    if (fc.w > frame_dim.group_dim || fc.h > frame_dim.group_dim) break;
342
331k
  }
343
62.2k
  size_t beginc = c;
344
69.4k
  for (; c < full_image.channel.size(); c++) {
345
7.20k
    Channel& fc = full_image.channel[c];
346
7.20k
    int shift = std::min(fc.hshift, fc.vshift);
347
7.20k
    if (shift > maxShift) continue;
348
7.20k
    if (shift < minShift) continue;
349
3.50k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
350
3.50k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
351
3.50k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
352
3.24k
    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.24k
    } else {
358
3.24k
      JXL_ASSIGN_OR_RETURN(
359
3.24k
          Channel gc, Channel::Create(memory_manager_, r.xsize(), r.ysize()));
360
3.24k
      if (zerofill) ZeroFillImage(&gc.plane);
361
3.24k
      gc.hshift = fc.hshift;
362
3.24k
      gc.vshift = fc.vshift;
363
3.24k
      gi.channel.emplace_back(std::move(gc));
364
3.24k
    }
365
3.24k
  }
366
62.2k
  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
62.2k
  if (gi.channel.empty()) {
370
61.3k
    if (dec_state && should_run_pipeline) {
371
30.8k
      const auto* metadata = frame_header.nonserialized_metadata;
372
30.8k
      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
30.0k
        *should_run_pipeline = false;
376
30.0k
      }
377
30.8k
    }
378
61.3k
    JXL_DEBUG_V(6, "Nothing to decode, returning early.");
379
61.3k
    return true;
380
61.3k
  }
381
876
  ModularOptions options;
382
876
  if (!zerofill) {
383
876
    auto status = ModularGenericDecompress(
384
876
        reader, gi, /*header=*/nullptr, stream.ID(frame_dim), &options,
385
876
        /*undo_transforms=*/true, &tree, &code, &context_map, allow_truncated);
386
876
    if (!allow_truncated) JXL_RETURN_IF_ERROR(status);
387
783
    if (status.IsFatalError()) return status;
388
783
  }
389
  // Undo global transforms that have been pushed to the group level
390
783
  if (!use_full_image) {
391
654
    JXL_ENSURE(render_pipeline_input);
392
654
    for (const auto& t : global_transform) {
393
257
      JXL_RETURN_IF_ERROR(t.Inverse(gi, global_header.wp_header));
394
257
    }
395
654
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
396
654
        frame_header, gi, dec_state, nullptr, *render_pipeline_input,
397
654
        Rect(0, 0, gi.w, gi.h)));
398
654
    return true;
399
654
  }
400
129
  int gic = 0;
401
1.25k
  for (c = beginc; c < full_image.channel.size(); c++) {
402
1.12k
    Channel& fc = full_image.channel[c];
403
1.12k
    int shift = std::min(fc.hshift, fc.vshift);
404
1.12k
    if (shift > maxShift) continue;
405
1.12k
    if (shift < minShift) continue;
406
1.02k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
407
1.02k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
408
1.02k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
409
891
    JXL_ENSURE(use_full_image);
410
891
    JXL_RETURN_IF_ERROR(
411
891
        CopyImageTo(/*rect_from=*/Rect(0, 0, r.xsize(), r.ysize()),
412
891
                    /*from=*/gi.channel[gic].plane,
413
891
                    /*rect_to=*/r, /*to=*/&fc.plane));
414
891
    gic++;
415
891
  }
416
129
  return true;
417
129
}
418
419
Status ModularFrameDecoder::DecodeVarDCTDC(const FrameHeader& frame_header,
420
                                           size_t group_id, BitReader* reader,
421
8.13k
                                           PassesDecoderState* dec_state) {
422
8.13k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
423
8.13k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
424
8.13k
  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
8.13k
  JXL_ASSIGN_OR_RETURN(Image image,
432
8.13k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
433
8.13k
                                     full_image.bitdepth, 3));
434
8.13k
  size_t stream_id = ModularStreamId::VarDCTDC(group_id).ID(frame_dim);
435
8.13k
  reader->Refill();
436
8.13k
  size_t extra_precision = reader->ReadFixedBits<2>();
437
8.13k
  float mul = 1.0f / (1 << extra_precision);
438
8.13k
  ModularOptions options;
439
32.5k
  for (size_t c = 0; c < 3; c++) {
440
24.3k
    Channel& ch = image.channel[c < 2 ? c ^ 1 : c];
441
24.3k
    ch.w >>= frame_header.chroma_subsampling.HShift(c);
442
24.3k
    ch.h >>= frame_header.chroma_subsampling.VShift(c);
443
24.3k
    JXL_RETURN_IF_ERROR(ch.shrink());
444
24.3k
  }
445
8.13k
  if (!ModularGenericDecompress(
446
8.13k
          reader, image, /*header=*/nullptr, stream_id, &options,
447
8.13k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
448
5.32k
    return JXL_FAILURE("Failed to decode VarDCT DC group (DC group id %d)",
449
5.32k
                       static_cast<int>(group_id));
450
5.32k
  }
451
2.80k
  DequantDC(r, &dec_state->shared_storage.dc_storage,
452
2.80k
            &dec_state->shared_storage.quant_dc, image,
453
2.80k
            dec_state->shared->quantizer.MulDC(), mul,
454
2.80k
            dec_state->shared->cmap.base().DCFactors(),
455
2.80k
            frame_header.chroma_subsampling, dec_state->shared->block_ctx_map);
456
2.80k
  return true;
457
8.13k
}
458
459
Status ModularFrameDecoder::DecodeAcMetadata(const FrameHeader& frame_header,
460
                                             size_t group_id, BitReader* reader,
461
2.80k
                                             PassesDecoderState* dec_state) {
462
2.80k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
463
2.80k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
464
2.80k
  JXL_DEBUG_V(6, "Decoding AcMetadata with rect %s", Description(r).c_str());
465
2.80k
  size_t upper_bound = r.xsize() * r.ysize();
466
2.80k
  reader->Refill();
467
2.80k
  size_t count = reader->ReadBits(CeilLog2Nonzero(upper_bound)) + 1;
468
2.80k
  size_t stream_id = ModularStreamId::ACMetadata(group_id).ID(frame_dim);
469
  // YToX, YToB, ACS + QF, EPF
470
2.80k
  JXL_ASSIGN_OR_RETURN(Image image,
471
2.80k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
472
2.80k
                                     full_image.bitdepth, 4));
473
2.80k
  static_assert(kColorTileDimInBlocks == 8, "Color tile size changed");
474
2.80k
  Rect cr(r.x0() >> 3, r.y0() >> 3, (r.xsize() + 7) >> 3, (r.ysize() + 7) >> 3);
475
2.80k
  JXL_ASSIGN_OR_RETURN(
476
2.80k
      image.channel[0],
477
2.80k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
478
2.80k
  JXL_ASSIGN_OR_RETURN(
479
2.80k
      image.channel[1],
480
2.80k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
481
2.80k
  JXL_ASSIGN_OR_RETURN(image.channel[2],
482
2.80k
                       Channel::Create(memory_manager, count, 2, 0, 0));
483
2.80k
  ModularOptions options;
484
2.80k
  if (!ModularGenericDecompress(
485
2.80k
          reader, image, /*header=*/nullptr, stream_id, &options,
486
2.80k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
487
662
    return JXL_FAILURE("Failed to decode AC metadata");
488
662
  }
489
2.14k
  JXL_RETURN_IF_ERROR(
490
2.14k
      ConvertPlaneAndClamp(Rect(image.channel[0].plane), image.channel[0].plane,
491
2.14k
                           cr, &dec_state->shared_storage.cmap.ytox_map));
492
2.14k
  JXL_RETURN_IF_ERROR(
493
2.14k
      ConvertPlaneAndClamp(Rect(image.channel[1].plane), image.channel[1].plane,
494
2.14k
                           cr, &dec_state->shared_storage.cmap.ytob_map));
495
2.14k
  size_t num = 0;
496
2.14k
  bool is444 = frame_header.chroma_subsampling.Is444();
497
2.14k
  auto& ac_strategy = dec_state->shared_storage.ac_strategy;
498
2.14k
  size_t xlim = std::min(ac_strategy.xsize(), r.x0() + r.xsize());
499
2.14k
  size_t ylim = std::min(ac_strategy.ysize(), r.y0() + r.ysize());
500
2.14k
  uint32_t local_used_acs = 0;
501
15.7k
  for (size_t iy = 0; iy < r.ysize(); iy++) {
502
14.2k
    size_t y = r.y0() + iy;
503
14.2k
    int32_t* row_qf = r.Row(&dec_state->shared_storage.raw_quant_field, iy);
504
14.2k
    uint8_t* row_epf = r.Row(&dec_state->shared_storage.epf_sharpness, iy);
505
14.2k
    int32_t* row_in_1 = image.channel[2].plane.Row(0);
506
14.2k
    int32_t* row_in_2 = image.channel[2].plane.Row(1);
507
14.2k
    int32_t* row_in_3 = image.channel[3].plane.Row(iy);
508
277k
    for (size_t ix = 0; ix < r.xsize(); ix++) {
509
264k
      size_t x = r.x0() + ix;
510
264k
      int sharpness = row_in_3[ix];
511
264k
      if (sharpness < 0 || sharpness >= LoopFilter::kEpfSharpEntries) {
512
427
        return JXL_FAILURE("Corrupted sharpness field");
513
427
      }
514
263k
      row_epf[ix] = sharpness;
515
263k
      if (ac_strategy.IsValid(x, y)) {
516
6.38k
        continue;
517
6.38k
      }
518
519
257k
      if (num >= count) return JXL_FAILURE("Corrupted stream");
520
521
257k
      if (!AcStrategy::IsRawStrategyValid(row_in_1[num])) {
522
20
        return JXL_FAILURE("Invalid AC strategy");
523
20
      }
524
257k
      local_used_acs |= 1u << row_in_1[num];
525
257k
      AcStrategy acs = AcStrategy::FromRawStrategy(row_in_1[num]);
526
257k
      if ((acs.covered_blocks_x() > 1 || acs.covered_blocks_y() > 1) &&
527
257k
          !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
257k
      size_t next_x_ac_block = (x / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
533
257k
      size_t next_y_ac_block = (y / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
534
257k
      size_t next_x_dct_block = x + acs.covered_blocks_x();
535
257k
      size_t next_y_dct_block = y + acs.covered_blocks_y();
536
257k
      if (next_x_dct_block > next_x_ac_block || next_x_dct_block > xlim) {
537
4
        return JXL_FAILURE("Invalid AC strategy, x overflow");
538
4
      }
539
257k
      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
257k
      JXL_RETURN_IF_ERROR(
543
257k
          ac_strategy.SetNoBoundsCheck(x, y, AcStrategyType(row_in_1[num])));
544
257k
      row_qf[ix] = 1 + std::max<int32_t>(0, std::min(Quantizer::kQuantMax - 1,
545
257k
                                                     row_in_2[num]));
546
257k
      num++;
547
257k
    }
548
14.2k
  }
549
1.55k
  dec_state->used_acs |= local_used_acs;
550
1.55k
  if (frame_header.loop_filter.epf_iters > 0) {
551
483
    JXL_RETURN_IF_ERROR(ComputeSigma(frame_header.loop_filter, r, dec_state));
552
483
  }
553
1.55k
  return true;
554
1.55k
}
555
556
Status ModularFrameDecoder::ModularImageToDecodedRect(
557
    const FrameHeader& frame_header, Image& gi, PassesDecoderState* dec_state,
558
    jxl::ThreadPool* pool, RenderPipelineInput& render_pipeline_input,
559
28.0k
    Rect modular_rect) const {
560
28.0k
  const auto* metadata = frame_header.nonserialized_metadata;
561
28.0k
  JXL_ENSURE(gi.transform.empty());
562
563
3.38M
  auto get_row = [&](size_t c, size_t y) {
564
3.38M
    const auto& buffer = render_pipeline_input.GetBuffer(c);
565
3.38M
    return buffer.second.Row(buffer.first, y);
566
3.38M
  };
567
568
28.0k
  size_t c = 0;
569
28.0k
  if (do_color) {
570
28.0k
    const bool rgb_from_gray =
571
28.0k
        metadata->m.color_encoding.IsGray() &&
572
28.0k
        frame_header.color_transform == ColorTransform::kNone;
573
28.0k
    const bool fp = metadata->m.bit_depth.floating_point_sample &&
574
28.0k
                    frame_header.color_transform != ColorTransform::kXYB;
575
110k
    for (; c < 3; c++) {
576
83.3k
      double factor = full_image.bitdepth < 32
577
83.3k
                          ? 1.0 / ((1u << full_image.bitdepth) - 1)
578
83.3k
                          : 0;
579
83.3k
      size_t c_in = c;
580
83.3k
      if (frame_header.color_transform == ColorTransform::kXYB) {
581
28.0k
        factor = dec_state->shared->matrices.DCQuants()[c];
582
        // XYB is encoded as YX(B-Y)
583
28.0k
        if (c < 2) c_in = 1 - c;
584
55.2k
      } else if (rgb_from_gray) {
585
467
        c_in = 0;
586
467
      }
587
83.3k
      JXL_ENSURE(c_in < gi.channel.size());
588
83.3k
      Channel& ch_in = gi.channel[c_in];
589
      // TODO(eustas): could we detect it on earlier stage?
590
83.3k
      if (ch_in.w == 0 || ch_in.h == 0) {
591
0
        return JXL_FAILURE("Empty image");
592
0
      }
593
83.3k
      JXL_ENSURE(ch_in.hshift <= 3 && ch_in.vshift <= 3);
594
83.3k
      Rect r = render_pipeline_input.GetBuffer(c).second;
595
83.3k
      Rect mr(modular_rect.x0() >> ch_in.hshift,
596
83.3k
              modular_rect.y0() >> ch_in.vshift,
597
83.3k
              DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
598
83.3k
              DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
599
83.3k
      mr = mr.Crop(ch_in.plane);
600
83.3k
      size_t xsize_shifted = r.xsize();
601
83.3k
      size_t ysize_shifted = r.ysize();
602
83.3k
      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
83.3k
      if (frame_header.color_transform == ColorTransform::kXYB && c == 2) {
610
9.35k
        JXL_ENSURE(!fp);
611
9.35k
        const auto process_row = [&](const uint32_t task,
612
399k
                                     size_t /* thread */) -> Status {
613
399k
          const size_t y = task;
614
399k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
615
399k
          const pixel_type* const JXL_RESTRICT row_in_Y =
616
399k
              mr.Row(&gi.channel[0].plane, y);
617
399k
          float* const JXL_RESTRICT row_out = get_row(c, y);
618
399k
          HWY_DYNAMIC_DISPATCH(MultiplySum)
619
399k
          (xsize_shifted, row_in, row_in_Y, factor, row_out);
620
399k
          return true;
621
399k
        };
622
9.35k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
623
9.35k
                                      ThreadPool::NoInit, process_row,
624
9.35k
                                      "ModularIntToFloat"));
625
73.9k
      } else if (fp) {
626
14.4k
        int bits = metadata->m.bit_depth.bits_per_sample;
627
14.4k
        int exp_bits = metadata->m.bit_depth.exponent_bits_per_sample;
628
14.4k
        const auto process_row = [&](const uint32_t task,
629
116k
                                     size_t /* thread */) -> Status {
630
116k
          const size_t y = task;
631
116k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
632
116k
          if (rgb_from_gray) {
633
5.17k
            for (size_t cc = 0; cc < 3; cc++) {
634
3.87k
              float* const JXL_RESTRICT row_out = get_row(cc, y);
635
3.87k
              JXL_RETURN_IF_ERROR(
636
3.87k
                  int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
637
3.87k
            }
638
115k
          } else {
639
115k
            float* const JXL_RESTRICT row_out = get_row(c, y);
640
115k
            JXL_RETURN_IF_ERROR(
641
115k
                int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
642
115k
          }
643
116k
          return true;
644
116k
        };
645
14.4k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
646
14.4k
                                      ThreadPool::NoInit, process_row,
647
14.4k
                                      "ModularIntToFloat_losslessfloat"));
648
59.4k
      } else {
649
59.4k
        const auto process_row = [&](const uint32_t task,
650
2.80M
                                     size_t /* thread */) -> Status {
651
2.80M
          const size_t y = task;
652
2.80M
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
653
2.80M
          if (rgb_from_gray) {
654
29.4k
            if (full_image.bitdepth < 23) {
655
29.4k
              HWY_DYNAMIC_DISPATCH(RgbFromSingle)
656
29.4k
              (xsize_shifted, row_in, factor, get_row(0, y), get_row(1, y),
657
29.4k
               get_row(2, y));
658
29.4k
            } 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
2.77M
          } else {
667
2.77M
            float* const JXL_RESTRICT row_out = get_row(c, y);
668
2.77M
            if (full_image.bitdepth < 23) {
669
2.77M
              HWY_DYNAMIC_DISPATCH(SingleFromSingle)
670
2.77M
              (xsize_shifted, row_in, factor, row_out);
671
2.77M
            } else {
672
944
              SingleFromSingleAccurate(xsize_shifted, row_in, factor, row_out);
673
944
            }
674
2.77M
          }
675
2.80M
          return true;
676
2.80M
        };
677
59.4k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
678
59.4k
                                      ThreadPool::NoInit, process_row,
679
59.4k
                                      "ModularIntToFloat"));
680
59.4k
      }
681
83.3k
      if (rgb_from_gray) {
682
467
        break;
683
467
      }
684
83.3k
    }
685
28.0k
    if (rgb_from_gray) {
686
467
      c = 1;
687
467
    }
688
28.0k
  }
689
28.0k
  size_t num_extra_channels = metadata->m.num_extra_channels;
690
30.3k
  for (size_t ec = 0; ec < num_extra_channels; ec++, c++) {
691
2.31k
    const ExtraChannelInfo& eci = metadata->m.extra_channel_info[ec];
692
2.31k
    int bits = eci.bit_depth.bits_per_sample;
693
2.31k
    int exp_bits = eci.bit_depth.exponent_bits_per_sample;
694
2.31k
    bool fp = eci.bit_depth.floating_point_sample;
695
2.31k
    JXL_ENSURE(fp || bits < 32);
696
2.31k
    const double factor = fp ? 0 : (1.0 / ((1u << bits) - 1));
697
2.31k
    JXL_ENSURE(c < gi.channel.size());
698
2.31k
    Channel& ch_in = gi.channel[c];
699
2.31k
    const auto& buffer = render_pipeline_input.GetBuffer(3 + ec);
700
2.31k
    Rect r = buffer.second;
701
2.31k
    Rect mr(modular_rect.x0() >> ch_in.hshift,
702
2.31k
            modular_rect.y0() >> ch_in.vshift,
703
2.31k
            DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
704
2.31k
            DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
705
2.31k
    mr = mr.Crop(ch_in.plane);
706
2.31k
    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
55.7k
    for (size_t y = 0; y < r.ysize(); ++y) {
714
53.4k
      float* const JXL_RESTRICT row_out = r.Row(buffer.first, y);
715
53.4k
      const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
716
53.4k
      if (fp) {
717
3.19k
        JXL_RETURN_IF_ERROR(
718
3.19k
            int_to_float(row_in, row_out, r.xsize(), bits, exp_bits));
719
50.2k
      } else {
720
50.2k
        if (full_image.bitdepth < 23) {
721
50.2k
          HWY_DYNAMIC_DISPATCH(SingleFromSingle)
722
50.2k
          (r.xsize(), row_in, factor, row_out);
723
50.2k
        } else {
724
59
          SingleFromSingleAccurate(r.xsize(), row_in, factor, row_out);
725
59
        }
726
50.2k
      }
727
53.4k
    }
728
2.31k
  }
729
28.0k
  return true;
730
28.0k
}
731
732
Status ModularFrameDecoder::FinalizeDecoding(const FrameHeader& frame_header,
733
                                             PassesDecoderState* dec_state,
734
                                             jxl::ThreadPool* pool,
735
27.8k
                                             bool inplace) {
736
27.8k
  if (!use_full_image) return true;
737
27.1k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
738
27.1k
  Image gi{memory_manager};
739
27.1k
  if (inplace) {
740
27.1k
    gi = std::move(full_image);
741
27.1k
  } else {
742
0
    JXL_ASSIGN_OR_RETURN(gi, Image::Clone(full_image));
743
0
  }
744
27.1k
  size_t xsize = gi.w;
745
27.1k
  size_t ysize = gi.h;
746
747
27.1k
  JXL_DEBUG_V(3, "Finalizing decoding for modular image: %s",
748
27.1k
              gi.DebugString().c_str());
749
750
  // Don't use threads if total image size is smaller than a group
751
27.1k
  if (xsize * ysize < frame_dim.group_dim * frame_dim.group_dim) pool = nullptr;
752
753
  // Undo the global transforms
754
27.1k
  gi.undo_transforms(global_header.wp_header, pool);
755
27.1k
  JXL_ENSURE(global_transform.empty());
756
27.1k
  if (gi.error) return JXL_FAILURE("Undoing transforms failed");
757
758
54.5k
  for (size_t i = 0; i < dec_state->shared->frame_dim.num_groups; i++) {
759
27.4k
    dec_state->render_pipeline->ClearDone(i);
760
27.4k
  }
761
762
27.1k
  const auto init = [&](size_t num_threads) -> Status {
763
27.1k
    bool use_group_ids = (frame_header.encoding == FrameEncoding::kVarDCT ||
764
27.1k
                          (frame_header.flags & FrameHeader::kNoise));
765
27.1k
    JXL_RETURN_IF_ERROR(dec_state->render_pipeline->PrepareForThreads(
766
27.1k
        num_threads, use_group_ids));
767
27.1k
    return true;
768
27.1k
  };
769
27.1k
  const auto process_group = [&](const uint32_t group,
770
27.4k
                                 size_t thread_id) -> Status {
771
27.4k
    RenderPipelineInput input =
772
27.4k
        dec_state->render_pipeline->GetInputBuffers(group, thread_id);
773
27.4k
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
774
27.4k
        frame_header, gi, dec_state, nullptr, input,
775
27.4k
        dec_state->shared->frame_dim.GroupRect(group)));
776
27.4k
    JXL_RETURN_IF_ERROR(input.Done());
777
27.4k
    return true;
778
27.4k
  };
779
27.1k
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0,
780
27.1k
                                dec_state->shared->frame_dim.num_groups, init,
781
27.1k
                                process_group, "ModularToRect"));
782
27.1k
  return true;
783
27.1k
}
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
52
    ModularFrameDecoder* modular_frame_decoder) {
791
52
  JXL_RETURN_IF_ERROR(F16Coder::Read(br, &encoding->qraw.qtable_den));
792
49
  if (encoding->qraw.qtable_den < kAlmostZero) {
793
    // qtable[] values are already checked for <= 0 so the denominator may not
794
    // be negative.
795
3
    return JXL_FAILURE("Invalid qtable_den: value too small");
796
3
  }
797
92
  JXL_ASSIGN_OR_RETURN(
798
92
      Image image,
799
92
      Image::Create(memory_manager, required_size_x, required_size_y, 8, 3));
800
92
  ModularOptions options;
801
92
  if (modular_frame_decoder) {
802
46
    JXL_ASSIGN_OR_RETURN(ModularStreamId qt, ModularStreamId::QuantTable(idx));
803
46
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(
804
46
        br, image, /*header=*/nullptr, qt.ID(modular_frame_decoder->frame_dim),
805
46
        &options, /*undo_transforms=*/true, &modular_frame_decoder->tree,
806
46
        &modular_frame_decoder->code, &modular_frame_decoder->context_map));
807
46
  } else {
808
0
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(br, image, /*header=*/nullptr,
809
0
                                                 0, &options,
810
0
                                                 /*undo_transforms=*/true));
811
0
  }
812
31
  if (!encoding->qraw.qtable) {
813
31
    encoding->qraw.qtable =
814
31
        new std::vector<int>(required_size_x * required_size_y * 3);
815
31
  } else {
816
0
    JXL_ENSURE(encoding->qraw.qtable->size() ==
817
0
               required_size_x * required_size_y * 3);
818
0
  }
819
31
  int* qtable = encoding->qraw.qtable->data();
820
67
  for (size_t c = 0; c < 3; c++) {
821
840
    for (size_t y = 0; y < required_size_y; y++) {
822
804
      int32_t* JXL_RESTRICT row = image.channel[c].Row(y);
823
55.4k
      for (size_t x = 0; x < required_size_x; x++) {
824
54.6k
        qtable[c * required_size_x * required_size_y + y * required_size_x +
825
54.6k
               x] = row[x];
826
54.6k
        if (row[x] <= 0) {
827
22
          return JXL_FAILURE("Invalid raw quantization table");
828
22
        }
829
54.6k
      }
830
804
    }
831
58
  }
832
9
  return true;
833
31
}
834
835
}  // namespace jxl
836
#endif  // HWY_ONCE