Coverage Report

Created: 2026-10-27 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/dec_frame.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/dec_frame.h"
7
8
#include <jxl/decode.h>
9
#include <jxl/memory_manager.h>
10
#include <jxl/types.h>
11
12
#include <algorithm>
13
#include <cstddef>
14
#include <cstdint>
15
#include <cstdlib>
16
#include <memory>
17
#include <utility>
18
#include <vector>
19
20
#include "lib/jxl/ac_context.h"
21
#include "lib/jxl/ac_strategy.h"
22
#include "lib/jxl/base/bits.h"
23
#include "lib/jxl/base/common.h"
24
#include "lib/jxl/base/compiler_specific.h"
25
#include "lib/jxl/base/data_parallel.h"
26
#include "lib/jxl/base/printf_macros.h"
27
#include "lib/jxl/base/rect.h"
28
#include "lib/jxl/base/span.h"
29
#include "lib/jxl/base/status.h"
30
#include "lib/jxl/chroma_from_luma.h"
31
#include "lib/jxl/coeff_order.h"
32
#include "lib/jxl/coeff_order_fwd.h"
33
#include "lib/jxl/common.h"  // kMaxNumPasses
34
#include "lib/jxl/compressed_dc.h"
35
#include "lib/jxl/dct_util.h"
36
#include "lib/jxl/dec_ans.h"
37
#include "lib/jxl/dec_bit_reader.h"
38
#include "lib/jxl/dec_cache.h"
39
#include "lib/jxl/dec_group.h"
40
#include "lib/jxl/dec_modular.h"
41
#include "lib/jxl/dec_noise.h"
42
#include "lib/jxl/dec_patch_dictionary.h"
43
#include "lib/jxl/entropy_coder.h"
44
#include "lib/jxl/epf.h"
45
#include "lib/jxl/fields.h"
46
#include "lib/jxl/frame_dimensions.h"
47
#include "lib/jxl/frame_header.h"
48
#include "lib/jxl/image_bundle.h"
49
#include "lib/jxl/image_metadata.h"
50
#include "lib/jxl/image_ops.h"
51
#include "lib/jxl/jpeg/jpeg_data.h"
52
#include "lib/jxl/loop_filter.h"
53
#include "lib/jxl/passes_state.h"
54
#include "lib/jxl/quant_weights.h"
55
#include "lib/jxl/quantizer.h"
56
#include "lib/jxl/render_pipeline/render_pipeline.h"
57
#include "lib/jxl/splines.h"
58
#include "lib/jxl/toc.h"
59
60
namespace jxl {
61
62
namespace {
63
Status DecodeGlobalDCInfo(BitReader* reader, bool is_jpeg,
64
6.23k
                          PassesDecoderState* state, ThreadPool* pool) {
65
6.23k
  JXL_RETURN_IF_ERROR(state->shared_storage.quantizer.Decode(reader));
66
67
6.23k
  JXL_RETURN_IF_ERROR(DecodeBlockCtxMap(state->memory_manager(), reader,
68
6.23k
                                        &state->shared_storage.block_ctx_map));
69
70
6.23k
  JXL_RETURN_IF_ERROR(state->shared_storage.cmap.DecodeDC(reader));
71
72
  // Pre-compute info for decoding a group.
73
6.23k
  if (is_jpeg) {
74
0
    state->shared_storage.quantizer.ClearDCMul();  // Don't dequant DC
75
0
  }
76
77
6.23k
  state->shared_storage.ac_strategy.FillInvalid();
78
6.23k
  return true;
79
6.23k
}
80
}  // namespace
81
82
Status DecodeFrame(PassesDecoderState* dec_state, ThreadPool* JXL_RESTRICT pool,
83
                   const uint8_t* next_in, size_t avail_in,
84
                   FrameHeader* frame_header, ImageBundle* decoded,
85
                   const CodecMetadata& metadata,
86
0
                   bool use_slow_rendering_pipeline) {
87
0
  FrameDecoder frame_decoder(dec_state, metadata, pool,
88
0
                             use_slow_rendering_pipeline);
89
90
0
  BitReader reader(Bytes(next_in, avail_in));
91
0
  JXL_RETURN_IF_ERROR(frame_decoder.InitFrame(&reader, decoded,
92
0
                                              /*is_preview=*/false));
93
0
  JXL_RETURN_IF_ERROR(frame_decoder.InitFrameOutput());
94
0
  if (frame_header) {
95
0
    *frame_header = frame_decoder.GetFrameHeader();
96
0
  }
97
98
0
  JXL_RETURN_IF_ERROR(reader.AllReadsWithinBounds());
99
0
  size_t header_bytes = reader.TotalBitsConsumed() / kBitsPerByte;
100
0
  JXL_RETURN_IF_ERROR(reader.Close());
101
102
0
  size_t processed_bytes = header_bytes;
103
0
  Status close_ok = true;
104
0
  std::vector<std::unique_ptr<BitReader>> section_readers;
105
0
  {
106
0
    std::vector<std::unique_ptr<BitReaderScopedCloser>> section_closers;
107
0
    std::vector<FrameDecoder::SectionInfo> section_info;
108
0
    std::vector<FrameDecoder::SectionStatus> section_status;
109
0
    size_t pos = header_bytes;
110
0
    size_t index = 0;
111
0
    for (auto toc_entry : frame_decoder.Toc()) {
112
0
      JXL_RETURN_IF_ERROR(pos + toc_entry.size <= avail_in);
113
0
      auto br = make_unique<BitReader>(Bytes(next_in + pos, toc_entry.size));
114
0
      section_info.emplace_back(
115
0
          FrameDecoder::SectionInfo{br.get(), toc_entry.id, index++});
116
0
      section_closers.emplace_back(
117
0
          make_unique<BitReaderScopedCloser>(*br, close_ok));
118
0
      section_readers.emplace_back(std::move(br));
119
0
      pos += toc_entry.size;
120
0
    }
121
0
    section_status.resize(section_info.size());
122
0
    JXL_RETURN_IF_ERROR(frame_decoder.ProcessSections(
123
0
        section_info.data(), section_info.size(), section_status.data()));
124
0
    for (size_t i = 0; i < section_status.size(); i++) {
125
0
      JXL_RETURN_IF_ERROR(section_status[i] == FrameDecoder::kDone);
126
0
      processed_bytes += frame_decoder.Toc()[i].size;
127
0
    }
128
0
  }
129
0
  JXL_RETURN_IF_ERROR(close_ok);
130
0
  JXL_RETURN_IF_ERROR(frame_decoder.FinalizeFrame());
131
0
  decoded->SetDecodedBytes(processed_bytes);
132
0
  return true;
133
0
}
134
135
Status FrameDecoder::InitFrame(BitReader* JXL_RESTRICT br, ImageBundle* decoded,
136
81.9k
                               bool is_preview) {
137
81.9k
  decoded_ = decoded;
138
81.9k
  JXL_ENSURE(is_finalized_);
139
81.9k
  JxlMemoryManager* memory_manager = decoded_->memory_manager();
140
141
  // Reset the dequantization matrices to their default values.
142
81.9k
  dec_state_->shared_storage.matrices = DequantMatrices();
143
144
81.9k
  frame_header_.nonserialized_is_preview = is_preview;
145
81.9k
  JXL_ENSURE(frame_header_.nonserialized_metadata != nullptr);
146
81.9k
  JXL_RETURN_IF_ERROR(ReadFrameHeader(br, &frame_header_));
147
81.8k
  frame_dim_ = frame_header_.ToFrameDimensions();
148
81.8k
  JXL_DEBUG_V(2, "FrameHeader: %s", frame_header_.DebugString().c_str());
149
150
81.8k
  const size_t num_passes = frame_header_.passes.num_passes;
151
81.8k
  const size_t num_groups = frame_dim_.num_groups;
152
153
  // If the previous frame was not a kRegularFrame, `decoded` may have different
154
  // dimensions; must reset to avoid errors.
155
81.8k
  decoded->RemoveColor();
156
81.8k
  decoded->ClearExtraChannels();
157
158
81.8k
  decoded->duration = frame_header_.animation_frame.duration;
159
160
81.8k
  if (!frame_header_.nonserialized_is_preview &&
161
81.8k
      (frame_header_.is_last || frame_header_.animation_frame.duration > 0) &&
162
3.58k
      (frame_header_.frame_type == kRegularFrame ||
163
3.58k
       frame_header_.frame_type == kSkipProgressive)) {
164
3.58k
    ++dec_state_->visible_frame_index;
165
3.58k
    dec_state_->nonvisible_frame_index = 0;
166
78.2k
  } else {
167
78.2k
    ++dec_state_->nonvisible_frame_index;
168
78.2k
  }
169
170
  // Read TOC.
171
81.8k
  const size_t toc_entries =
172
81.8k
      NumTocEntries(num_groups, frame_dim_.num_dc_groups, num_passes);
173
81.8k
  std::vector<uint32_t> sizes;
174
81.8k
  std::vector<coeff_order_t> permutation;
175
81.8k
  JXL_RETURN_IF_ERROR(
176
81.8k
      ReadToc(memory_manager, toc_entries, br, &sizes, &permutation));
177
81.8k
  bool have_permutation = !permutation.empty();
178
81.8k
  toc_.resize(toc_entries);
179
81.8k
  section_sizes_sum_ = 0;
180
753k
  for (size_t i = 0; i < toc_entries; ++i) {
181
671k
    toc_[i].size = sizes[i];
182
671k
    size_t index = have_permutation ? permutation[i] : i;
183
671k
    toc_[index].id = i;
184
671k
    if (section_sizes_sum_ + toc_[i].size < section_sizes_sum_) {
185
0
      return JXL_FAILURE("group offset overflow");
186
0
    }
187
671k
    section_sizes_sum_ += toc_[i].size;
188
671k
  }
189
190
81.8k
  if (JXL_DEBUG_V_LEVEL >= 3) {
191
0
    for (size_t i = 0; i < toc_entries; ++i) {
192
0
      JXL_DEBUG_V(3, "TOC entry %" PRIuS " size %" PRIuS " id %" PRIuS "", i,
193
0
                  toc_[i].size, toc_[i].id);
194
0
    }
195
0
  }
196
197
81.8k
  JXL_ENSURE((br->TotalBitsConsumed() % kBitsPerByte) == 0);
198
81.8k
  const size_t group_codes_begin = br->TotalBitsConsumed() / kBitsPerByte;
199
81.8k
  JXL_ENSURE(!toc_.empty());
200
201
  // Overflow check.
202
81.8k
  if (group_codes_begin + section_sizes_sum_ < group_codes_begin) {
203
0
    return JXL_FAILURE("Invalid group codes");
204
0
  }
205
81.8k
  return true;
206
81.8k
}
207
208
16.6k
Status FrameDecoder::InitFrameOutput() {
209
16.6k
  JXL_RETURN_IF_ERROR(
210
16.6k
      InitializePassesSharedState(frame_header_, &dec_state_->shared_storage));
211
16.6k
  JXL_RETURN_IF_ERROR(dec_state_->Init(frame_header_));
212
16.6k
  modular_frame_decoder_.Init(frame_dim_);
213
214
16.6k
  if (decoded_->IsJPEG()) {
215
0
    if (frame_header_.encoding == FrameEncoding::kModular) {
216
0
      return JXL_FAILURE("Cannot output JPEG from Modular");
217
0
    }
218
0
    jpeg::JPEGData* jpeg_data = decoded_->jpeg_data.get();
219
0
    size_t num_components = jpeg_data->components.size();
220
0
    if (num_components != 1 && num_components != 3) {
221
0
      return JXL_FAILURE("Invalid number of components");
222
0
    }
223
0
    if (frame_header_.nonserialized_metadata->m.xyb_encoded) {
224
0
      return JXL_FAILURE("Cannot decode to JPEG an XYB image");
225
0
    }
226
0
    auto jpeg_c_map = JpegOrder(ColorTransform::kYCbCr, num_components == 1);
227
0
    decoded_->jpeg_data->width = frame_dim_.xsize;
228
0
    decoded_->jpeg_data->height = frame_dim_.ysize;
229
0
    for (size_t c = 0; c < num_components; c++) {
230
0
      auto& component = jpeg_data->components[jpeg_c_map[c]];
231
0
      component.width_in_blocks =
232
0
          frame_dim_.xsize_blocks >> frame_header_.chroma_subsampling.HShift(c);
233
0
      component.height_in_blocks =
234
0
          frame_dim_.ysize_blocks >> frame_header_.chroma_subsampling.VShift(c);
235
0
      component.h_samp_factor =
236
0
          1 << frame_header_.chroma_subsampling.RawHShift(c);
237
0
      component.v_samp_factor =
238
0
          1 << frame_header_.chroma_subsampling.RawVShift(c);
239
0
      size_t num_blocks = static_cast<size_t>(component.width_in_blocks) *
240
0
                          component.height_in_blocks;
241
0
      component.coeffs.resize(num_blocks * jxl::kDCTBlockSize);
242
0
    }
243
0
  }
244
245
  // Clear the state.
246
16.6k
  decoded_dc_global_ = false;
247
16.6k
  decoded_ac_global_ = false;
248
16.6k
  is_finalized_ = false;
249
16.6k
  finalized_dc_ = false;
250
16.6k
  num_sections_done_ = 0;
251
16.6k
  decoded_dc_groups_.clear();
252
16.6k
  decoded_dc_groups_.resize(frame_dim_.num_dc_groups);
253
16.6k
  decoded_passes_per_ac_group_.clear();
254
16.6k
  decoded_passes_per_ac_group_.resize(frame_dim_.num_groups, 0);
255
16.6k
  processed_section_.clear();
256
16.6k
  processed_section_.resize(toc_.size());
257
16.6k
  allocated_ = false;
258
16.6k
  return true;
259
16.6k
}
260
261
16.6k
Status FrameDecoder::ProcessDCGlobal(BitReader* br) {
262
16.6k
  PassesSharedState& shared = dec_state_->shared_storage;
263
16.6k
  JxlMemoryManager* memory_manager = shared.memory_manager;
264
16.6k
  if (frame_header_.flags & FrameHeader::kPatches) {
265
1.33k
    bool uses_extra_channels;
266
1.33k
    JXL_RETURN_IF_ERROR(shared.image_features.patches.Decode(
267
1.33k
        memory_manager, br, frame_dim_.xsize_padded, frame_dim_.ysize_padded,
268
1.33k
        shared.metadata->m.num_extra_channels, &uses_extra_channels));
269
1.32k
    if (frame_header_.upsampling != 1) {
270
996
      for (size_t ecups : frame_header_.extra_channel_upsampling) {
271
0
        if (ecups != frame_header_.upsampling) {
272
0
          return JXL_FAILURE(
273
0
              "Cannot use extra channels in patches if color channels are "
274
0
              "subsampled differently from extra channels");
275
0
        }
276
0
      }
277
996
    }
278
15.2k
  } else {
279
15.2k
    shared.image_features.patches.Clear();
280
15.2k
  }
281
16.6k
  shared.image_features.splines.Clear();
282
16.6k
  if (frame_header_.flags & FrameHeader::kSplines) {
283
1.02k
    JXL_RETURN_IF_ERROR(shared.image_features.splines.Decode(
284
1.02k
        br, frame_dim_.xsize * frame_dim_.ysize));
285
1.02k
  }
286
16.6k
  if (frame_header_.flags & FrameHeader::kNoise) {
287
4.98k
    JXL_RETURN_IF_ERROR(DecodeNoise(br, &shared.image_features.noise_params));
288
4.98k
  }
289
16.6k
  JXL_RETURN_IF_ERROR(dec_state_->shared_storage.matrices.DecodeDC(br));
290
291
16.5k
  if (frame_header_.encoding == FrameEncoding::kVarDCT) {
292
6.23k
    JXL_RETURN_IF_ERROR(
293
6.23k
        jxl::DecodeGlobalDCInfo(br, decoded_->IsJPEG(), dec_state_, pool_));
294
6.23k
  }
295
  // Splines' draw cache uses the color correlation map.
296
16.5k
  if (frame_header_.flags & FrameHeader::kSplines) {
297
1.02k
    JXL_RETURN_IF_ERROR(shared.image_features.splines.InitializeDrawCache(
298
1.02k
        frame_dim_.xsize_upsampled, frame_dim_.ysize_upsampled,
299
1.02k
        dec_state_->shared->cmap.base()));
300
1.02k
  }
301
16.5k
  Status dec_status = modular_frame_decoder_.DecodeGlobalInfo(
302
16.5k
      br, frame_header_, /*allow_truncated_group=*/false);
303
16.5k
  if (dec_status.IsFatalError()) return dec_status;
304
16.5k
  if (dec_status) {
305
16.5k
    decoded_dc_global_ = true;
306
16.5k
  }
307
16.5k
  return dec_status;
308
16.5k
}
309
310
18.3k
Status FrameDecoder::ProcessDCGroup(size_t dc_group_id, BitReader* br) {
311
18.3k
  const size_t gx = dc_group_id % frame_dim_.xsize_dc_groups;
312
18.3k
  const size_t gy = dc_group_id / frame_dim_.xsize_dc_groups;
313
18.3k
  const LoopFilter& lf = frame_header_.loop_filter;
314
18.3k
  if (frame_header_.encoding == FrameEncoding::kVarDCT &&
315
6.41k
      !(frame_header_.flags & FrameHeader::kUseDcFrame)) {
316
6.41k
    JXL_RETURN_IF_ERROR(modular_frame_decoder_.DecodeVarDCTDC(
317
6.41k
        frame_header_, dc_group_id, br, dec_state_));
318
6.41k
  }
319
18.2k
  const Rect mrect(gx * frame_dim_.dc_group_dim, gy * frame_dim_.dc_group_dim,
320
18.2k
                   frame_dim_.dc_group_dim, frame_dim_.dc_group_dim);
321
18.2k
  JXL_RETURN_IF_ERROR(modular_frame_decoder_.DecodeGroup(
322
18.2k
      frame_header_, mrect, br, 3, 1000,
323
18.2k
      ModularStreamId::ModularDC(dc_group_id),
324
18.2k
      /*zerofill=*/false, nullptr, nullptr,
325
18.2k
      /*allow_truncated=*/false));
326
18.2k
  if (frame_header_.encoding == FrameEncoding::kVarDCT) {
327
6.39k
    JXL_RETURN_IF_ERROR(modular_frame_decoder_.DecodeAcMetadata(
328
6.39k
        frame_header_, dc_group_id, br, dec_state_));
329
11.8k
  } else if (lf.epf_iters > 0) {
330
2.18k
    FillImage(kInvSigmaNum / lf.epf_sigma_for_modular, &dec_state_->sigma);
331
2.18k
  }
332
18.2k
  decoded_dc_groups_[dc_group_id] = JXL_TRUE;
333
18.2k
  return true;
334
18.2k
}
335
336
16.5k
Status FrameDecoder::FinalizeDC() {
337
  // Do Adaptive DC smoothing if enabled. This *must* happen between all the
338
  // ProcessDCGroup and ProcessACGroup.
339
16.5k
  JxlMemoryManager* memory_manager = dec_state_->memory_manager();
340
16.5k
  if (frame_header_.encoding == FrameEncoding::kVarDCT &&
341
6.20k
      !(frame_header_.flags & FrameHeader::kSkipAdaptiveDCSmoothing) &&
342
5.77k
      !(frame_header_.flags & FrameHeader::kUseDcFrame) &&
343
      // Skip smoothing when reconstructing to JPEG.
344
5.77k
      !decoded_->IsJPEG()) {
345
5.77k
    JXL_RETURN_IF_ERROR(AdaptiveDCSmoothing(
346
5.77k
        memory_manager, dec_state_->shared->quantizer.MulDC(),
347
5.77k
        &dec_state_->shared_storage.dc_storage,
348
5.77k
        frame_header_.chroma_subsampling, pool_));
349
5.77k
  }
350
351
16.5k
  finalized_dc_ = true;
352
16.5k
  return true;
353
16.5k
}
354
355
16.5k
Status FrameDecoder::AllocateOutput() {
356
16.5k
  if (allocated_) return true;
357
16.5k
  modular_frame_decoder_.MaybeDropFullImage();
358
16.5k
  decoded_->origin = frame_header_.frame_origin;
359
16.5k
  JXL_RETURN_IF_ERROR(
360
16.5k
      dec_state_->InitForAC(frame_header_.passes.num_passes, nullptr));
361
16.5k
  allocated_ = true;
362
16.5k
  return true;
363
16.5k
}
364
365
16.4k
Status FrameDecoder::ProcessACGlobal(BitReader* br) {
366
16.4k
  JXL_ENSURE(finalized_dc_);
367
16.4k
  JxlMemoryManager* memory_manager = dec_state_->memory_manager();
368
369
  // Decode AC group.
370
16.4k
  if (frame_header_.encoding == FrameEncoding::kVarDCT) {
371
6.20k
    JXL_RETURN_IF_ERROR(dec_state_->shared_storage.matrices.Decode(
372
6.20k
        memory_manager, br, &modular_frame_decoder_));
373
6.19k
    JXL_RETURN_IF_ERROR(dec_state_->shared_storage.matrices.EnsureComputed(
374
6.19k
        memory_manager, dec_state_->used_acs));
375
376
6.19k
    size_t num_histo_bits =
377
6.19k
        CeilLog2Nonzero(dec_state_->shared->frame_dim.num_groups);
378
6.19k
    dec_state_->shared_storage.num_histograms =
379
6.19k
        1 + br->ReadBits(num_histo_bits);
380
381
6.19k
    JXL_DEBUG_V(3,
382
6.19k
                "Processing AC global with %d passes and %" PRIuS
383
6.19k
                " sets of histograms",
384
6.19k
                frame_header_.passes.num_passes,
385
6.19k
                dec_state_->shared_storage.num_histograms);
386
387
6.19k
    dec_state_->code.resize(kMaxNumPasses);
388
6.19k
    dec_state_->context_map.resize(kMaxNumPasses);
389
    // Read coefficient orders and histograms.
390
6.19k
    size_t max_num_bits_ac = 0;
391
12.4k
    for (size_t i = 0; i < frame_header_.passes.num_passes; i++) {
392
6.24k
      uint16_t used_orders = U32Coder::Read(kOrderEnc, br);
393
6.24k
      JXL_RETURN_IF_ERROR(DecodeCoeffOrders(
394
6.24k
          memory_manager, used_orders, dec_state_->used_acs,
395
6.24k
          &dec_state_->shared_storage
396
6.24k
               .coeff_orders[i * dec_state_->shared_storage.coeff_order_size],
397
6.24k
          br));
398
6.24k
      size_t num_contexts =
399
6.24k
          dec_state_->shared->num_histograms *
400
6.24k
          dec_state_->shared_storage.block_ctx_map.NumACContexts();
401
6.24k
      JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br, num_contexts,
402
6.24k
                                           &dec_state_->code[i],
403
6.24k
                                           &dec_state_->context_map[i]));
404
      // Add extra values to enable the cheat in hot loop of DecodeACVarBlock.
405
6.23k
      dec_state_->context_map[i].resize(
406
6.23k
          num_contexts + kZeroDensityContextLimit - kZeroDensityContextCount);
407
6.23k
      max_num_bits_ac =
408
6.23k
          std::max(max_num_bits_ac, dec_state_->code[i].max_num_bits);
409
6.23k
    }
410
6.19k
    max_num_bits_ac += CeilLog2Nonzero(frame_header_.passes.num_passes);
411
    // 16-bit buffer for decoding to JPEG are not implemented.
412
    // TODO(veluca): figure out the exact limit - 16 should still work with
413
    // 16-bit buffers, but we are excluding it for safety.
414
6.19k
    bool use_16_bit = max_num_bits_ac < 16 && !decoded_->IsJPEG();
415
6.19k
    bool store = frame_header_.passes.num_passes > 1;
416
6.19k
    size_t xs = store ? kGroupDim * kGroupDim : 0;
417
6.19k
    size_t ys = store ? frame_dim_.num_groups : 0;
418
6.19k
    if (use_16_bit) {
419
5.44k
      JXL_ASSIGN_OR_RETURN(dec_state_->coefficients,
420
5.44k
                           ACImageT<int16_t>::Make(memory_manager, xs, ys));
421
5.44k
    } else {
422
749
      JXL_ASSIGN_OR_RETURN(dec_state_->coefficients,
423
749
                           ACImageT<int32_t>::Make(memory_manager, xs, ys));
424
749
    }
425
6.19k
    if (store) {
426
4
      dec_state_->coefficients->ZeroFill();
427
4
    }
428
6.19k
  }
429
430
  // Set JPEG decoding data.
431
16.4k
  if (decoded_->IsJPEG()) {
432
0
    decoded_->color_transform = frame_header_.color_transform;
433
0
    decoded_->chroma_subsampling = frame_header_.chroma_subsampling;
434
0
    const std::vector<QuantEncoding>& qe =
435
0
        dec_state_->shared_storage.matrices.encodings();
436
0
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
437
0
        std::abs(qe[0].qraw.qtable_den - 1.f / (8 * 255)) > 1e-8f) {
438
0
      return JXL_FAILURE(
439
0
          "Quantization table is not a JPEG quantization table.");
440
0
    }
441
0
    jpeg::JPEGData* jpeg_data = decoded_->jpeg_data.get();
442
0
    size_t num_components = jpeg_data->components.size();
443
0
    bool is_gray = (num_components == 1);
444
0
    JXL_ENSURE(frame_header_.color_transform != ColorTransform::kXYB);
445
0
    auto jpeg_c_map = JpegOrder(frame_header_.color_transform, is_gray);
446
0
    size_t qt_set = 0;
447
0
    JXL_ENSURE(num_components <= 3);
448
0
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
449
0
    int* qtable = qe[0].qraw.qtable->data();
450
0
    for (size_t c = 0; c < num_components; c++) {
451
      // TODO(eustas): why 1-st quant table for gray?
452
0
      size_t quant_c = is_gray ? 1 : c;
453
0
      size_t qpos = jpeg_data->components[jpeg_c_map[c]].quant_idx;
454
0
      JXL_ENSURE(qpos != jpeg_data->quant.size());
455
0
      qt_set |= 1 << qpos;
456
0
      for (size_t x = 0; x < 8; x++) {
457
0
        for (size_t y = 0; y < 8; y++) {
458
0
          jpeg_data->quant[qpos].values[x * 8 + y] =
459
0
              qtable[quant_c * 64 + y * 8 + x];
460
0
        }
461
0
      }
462
0
    }
463
0
    for (size_t i = 0; i < jpeg_data->quant.size(); i++) {
464
0
      if (qt_set & (1 << i)) continue;
465
0
      if (i == 0) return JXL_FAILURE("First quant table unused.");
466
      // Unused quant table is set to copy of previous quant table
467
0
      for (size_t j = 0; j < 64; j++) {
468
0
        jpeg_data->quant[i].values[j] = jpeg_data->quant[i - 1].values[j];
469
0
      }
470
0
    }
471
0
  }
472
16.4k
  decoded_ac_global_ = true;
473
16.4k
  return true;
474
16.4k
}
475
476
Status FrameDecoder::ProcessACGroup(size_t ac_group_id, PassesReaders& br,
477
                                    size_t num_passes, size_t thread,
478
25.7k
                                    bool force_draw, bool dc_only) {
479
25.7k
  size_t group_dim = frame_dim_.group_dim;
480
25.7k
  const size_t gx = ac_group_id % frame_dim_.xsize_groups;
481
25.7k
  const size_t gy = ac_group_id / frame_dim_.xsize_groups;
482
25.7k
  const size_t x = gx * group_dim;
483
25.7k
  const size_t y = gy * group_dim;
484
25.7k
  JxlMemoryManager* memory_manager = dec_state_->memory_manager();
485
25.7k
  JXL_DEBUG_V(3,
486
25.7k
              "Processing AC group %" PRIuS "(%" PRIuS ",%" PRIuS
487
25.7k
              ") group_dim: %" PRIuS " decoded passes: %u new passes: %" PRIuS,
488
25.7k
              ac_group_id, gx, gy, group_dim,
489
25.7k
              decoded_passes_per_ac_group_[ac_group_id], num_passes);
490
491
25.7k
  RenderPipelineInput render_pipeline_input =
492
25.7k
      dec_state_->render_pipeline->GetInputBuffers(ac_group_id, thread);
493
494
25.7k
  bool should_run_pipeline = true;
495
496
25.7k
  if (frame_header_.encoding == FrameEncoding::kVarDCT) {
497
10.0k
    JXL_RETURN_IF_ERROR(group_dec_caches_[thread].InitOnce(
498
10.0k
        memory_manager, frame_header_.passes.num_passes, dec_state_->used_acs));
499
10.0k
    JXL_RETURN_IF_ERROR(DecodeGroup(
500
10.0k
        frame_header_, br.data(), num_passes, ac_group_id, dec_state_,
501
10.0k
        &group_dec_caches_[thread], thread, render_pipeline_input,
502
10.0k
        decoded_->jpeg_data.get(), decoded_passes_per_ac_group_[ac_group_id],
503
10.0k
        force_draw, dc_only, &should_run_pipeline));
504
10.0k
  }
505
506
  // don't limit to image dimensions here (is done in DecodeGroup)
507
25.7k
  const Rect mrect(x, y, group_dim, group_dim);
508
25.7k
  bool modular_ready = false;
509
25.7k
  size_t pass0 = decoded_passes_per_ac_group_[ac_group_id];
510
25.7k
  size_t pass1 =
511
25.7k
      force_draw ? frame_header_.passes.num_passes : pass0 + num_passes;
512
51.3k
  for (size_t i = pass0; i < pass1; ++i) {
513
25.7k
    int minShift;
514
25.7k
    int maxShift;
515
25.7k
    frame_header_.passes.GetDownsamplingBracket(i, minShift, maxShift);
516
25.7k
    bool modular_pass_ready = true;
517
25.7k
    JXL_DEBUG_V(2, "Decoding modular in group %d pass %d",
518
25.7k
                static_cast<int>(ac_group_id), static_cast<int>(i));
519
25.7k
    if (i < pass0 + num_passes) {  // i.e. i - pass0 < num_passes
520
25.7k
      BitReader* r = br[i - pass0];
521
25.7k
      JXL_ENSURE(r);
522
25.7k
      JXL_DEBUG_V(2, "Bit reader position: %" PRIuS " / %" PRIuS,
523
25.7k
                  r->TotalBitsConsumed(), r->TotalBytes() * kBitsPerByte);
524
25.7k
      JXL_RETURN_IF_ERROR(modular_frame_decoder_.DecodeGroup(
525
25.7k
          frame_header_, mrect, r, minShift, maxShift,
526
25.7k
          ModularStreamId::ModularAC(ac_group_id, i),
527
25.7k
          /*zerofill=*/false, dec_state_, &render_pipeline_input,
528
25.7k
          /*allow_truncated=*/false, &modular_pass_ready));
529
18.4E
    } else {
530
18.4E
      JXL_RETURN_IF_ERROR(modular_frame_decoder_.DecodeGroup(
531
18.4E
          frame_header_, mrect, nullptr, minShift, maxShift,
532
18.4E
          ModularStreamId::ModularAC(ac_group_id, i), /*zerofill=*/true,
533
18.4E
          dec_state_, &render_pipeline_input,
534
18.4E
          /*allow_truncated=*/false, &modular_pass_ready));
535
18.4E
    }
536
25.5k
    if (modular_pass_ready) modular_ready = true;
537
25.5k
  }
538
25.6k
  decoded_passes_per_ac_group_[ac_group_id] += num_passes;
539
540
25.6k
  if ((frame_header_.flags & FrameHeader::kNoise) != 0) {
541
6.15k
    PrepareNoiseInput(*dec_state_, frame_dim_, frame_header_, ac_group_id,
542
6.15k
                      thread);
543
6.15k
  }
544
545
25.6k
  if (!modular_frame_decoder_.UsesFullImage() && !decoded_->IsJPEG()) {
546
14.6k
    if (should_run_pipeline && modular_ready) {
547
14.5k
      JXL_RETURN_IF_ERROR(render_pipeline_input.Done());
548
14.5k
    } else if (force_draw) {
549
0
      return JXL_FAILURE("Modular group decoding failed.");
550
0
    }
551
14.6k
  }
552
25.6k
  return true;
553
25.6k
}
554
555
void FrameDecoder::MarkSections(const SectionInfo* sections, size_t num,
556
16.4k
                                const SectionStatus* section_status) {
557
16.4k
  num_sections_done_ += num;
558
98.5k
  for (size_t i = 0; i < num; i++) {
559
82.0k
    if (section_status[i] != SectionStatus::kDone) {
560
52.5k
      processed_section_[sections[i].id] = JXL_FALSE;
561
52.5k
      num_sections_done_--;
562
52.5k
    }
563
82.0k
  }
564
16.4k
}
565
566
Status FrameDecoder::ProcessSections(const SectionInfo* sections, size_t num,
567
16.6k
                                     SectionStatus* section_status) {
568
16.6k
  if (num == 0) return true;  // Nothing to process
569
16.6k
  std::fill(section_status, section_status + num, SectionStatus::kSkipped);
570
16.6k
  size_t dc_global_sec = num;
571
16.6k
  size_t ac_global_sec = num;
572
16.6k
  std::vector<size_t> dc_group_sec(frame_dim_.num_dc_groups, num);
573
16.6k
  std::vector<std::vector<size_t>> ac_group_sec(
574
16.6k
      frame_dim_.num_groups,
575
16.6k
      std::vector<size_t>(frame_header_.passes.num_passes, num));
576
  // This keeps track of the number of ac passes we want to process during this
577
  // call of ProcessSections.
578
16.6k
  std::vector<size_t> desired_num_ac_passes(frame_dim_.num_groups);
579
16.6k
  bool single_section =
580
16.6k
      frame_dim_.num_groups == 1 && frame_header_.passes.num_passes == 1;
581
16.6k
  if (single_section) {
582
14.9k
    JXL_ENSURE(num == 1);
583
14.9k
    JXL_ENSURE(sections[0].id == 0);
584
14.9k
    if (processed_section_[0] == JXL_FALSE) {
585
14.9k
      processed_section_[0] = JXL_TRUE;
586
14.9k
      ac_group_sec[0].resize(1);
587
14.9k
      dc_global_sec = ac_global_sec = dc_group_sec[0] = ac_group_sec[0][0] = 0;
588
14.9k
      desired_num_ac_passes[0] = 1;
589
14.9k
    } else {
590
0
      section_status[0] = SectionStatus::kDuplicate;
591
0
    }
592
14.9k
  } else {
593
1.67k
    size_t ac_global_index = frame_dim_.num_dc_groups + 1;
594
102k
    for (size_t i = 0; i < num; i++) {
595
100k
      JXL_ENSURE(sections[i].id < processed_section_.size());
596
100k
      if (processed_section_[sections[i].id]) {
597
0
        section_status[i] = SectionStatus::kDuplicate;
598
0
        continue;
599
0
      }
600
100k
      if (sections[i].id == 0) {
601
1.67k
        dc_global_sec = i;
602
98.9k
      } else if (sections[i].id < ac_global_index) {
603
10.5k
        dc_group_sec[sections[i].id - 1] = i;
604
88.4k
      } else if (sections[i].id == ac_global_index) {
605
1.64k
        ac_global_sec = i;
606
86.7k
      } else {
607
86.7k
        size_t ac_idx = sections[i].id - ac_global_index - 1;
608
86.7k
        size_t acg = ac_idx % frame_dim_.num_groups;
609
86.7k
        size_t acp = ac_idx / frame_dim_.num_groups;
610
86.7k
        if (acp >= frame_header_.passes.num_passes) {
611
0
          return JXL_FAILURE("Invalid section ID");
612
0
        }
613
86.7k
        ac_group_sec[acg][acp] = i;
614
86.7k
      }
615
100k
      processed_section_[sections[i].id] = JXL_TRUE;
616
100k
    }
617
    // Count number of new passes per group.
618
238k
    for (size_t g = 0; g < ac_group_sec.size(); g++) {
619
236k
      size_t j = 0;
620
323k
      for (; j + decoded_passes_per_ac_group_[g] <
621
323k
             frame_header_.passes.num_passes;
622
243k
           j++) {
623
243k
        if (ac_group_sec[g][j + decoded_passes_per_ac_group_[g]] == num) {
624
156k
          break;
625
156k
        }
626
243k
      }
627
236k
      desired_num_ac_passes[g] = j;
628
236k
    }
629
1.67k
  }
630
16.6k
  if (dc_global_sec != num) {
631
16.6k
    Status dc_global_status = ProcessDCGlobal(sections[dc_global_sec].br);
632
16.6k
    if (dc_global_status.IsFatalError()) return dc_global_status;
633
16.5k
    if (dc_global_status) {
634
16.5k
      section_status[dc_global_sec] = SectionStatus::kDone;
635
16.5k
    } else {
636
4
      section_status[dc_global_sec] = SectionStatus::kPartial;
637
4
    }
638
16.5k
  }
639
640
16.5k
  if (decoded_dc_global_) {
641
16.5k
    const auto process_section = [this, &dc_group_sec, &num, &sections,
642
16.5k
                                  &section_status](size_t i,
643
20.0k
                                                   size_t thread) -> Status {
644
20.0k
      if (dc_group_sec[i] != num) {
645
18.3k
        JXL_RETURN_IF_ERROR(ProcessDCGroup(i, sections[dc_group_sec[i]].br));
646
18.2k
        section_status[dc_group_sec[i]] = SectionStatus::kDone;
647
18.2k
      }
648
20.0k
      return true;
649
20.0k
    };
650
16.5k
    JXL_RETURN_IF_ERROR(RunOnPool(pool_, 0, dc_group_sec.size(),
651
16.5k
                                  ThreadPool::NoInit, process_section,
652
16.5k
                                  "DecodeDCGroup"));
653
16.5k
  }
654
655
16.5k
  if (!HasDcGroupToDecode() && !finalized_dc_) {
656
16.5k
    PassesDecoderState::PipelineOptions pipeline_options;
657
16.5k
    pipeline_options.use_slow_render_pipeline = use_slow_rendering_pipeline_;
658
16.5k
    pipeline_options.coalescing = coalescing_;
659
16.5k
    pipeline_options.render_spotcolors = render_spotcolors_;
660
16.5k
    pipeline_options.render_noise = true;
661
16.5k
    JXL_RETURN_IF_ERROR(dec_state_->PreparePipeline(
662
16.5k
        frame_header_, &frame_header_.nonserialized_metadata->m, decoded_,
663
16.5k
        pipeline_options));
664
16.5k
    JXL_RETURN_IF_ERROR(FinalizeDC());
665
16.5k
    JXL_RETURN_IF_ERROR(AllocateOutput());
666
16.5k
    if (progressive_detail_ >= JxlProgressiveDetail::kDC) {
667
0
      MarkSections(sections, num, section_status);
668
0
      return true;
669
0
    }
670
16.5k
  }
671
672
16.5k
  if (finalized_dc_ && ac_global_sec != num && !decoded_ac_global_) {
673
16.4k
    JXL_RETURN_IF_ERROR(ProcessACGlobal(sections[ac_global_sec].br));
674
16.4k
    section_status[ac_global_sec] = SectionStatus::kDone;
675
16.4k
  }
676
677
16.5k
  if (progressive_detail_ >= JxlProgressiveDetail::kLastPasses) {
678
    // Mark that we only want the next progression pass.
679
0
    size_t target_complete_passes = NextNumPassesToPause();
680
0
    for (size_t i = 0; i < ac_group_sec.size(); i++) {
681
0
      desired_num_ac_passes[i] =
682
0
          std::min(desired_num_ac_passes[i],
683
0
                   target_complete_passes - decoded_passes_per_ac_group_[i]);
684
0
    }
685
0
  }
686
687
16.5k
  if (decoded_ac_global_) {
688
    // Mark all the AC groups that we received as not complete yet.
689
52.5k
    for (size_t i = 0; i < ac_group_sec.size(); i++) {
690
36.0k
      if (desired_num_ac_passes[i] != 0) {
691
26.2k
        dec_state_->render_pipeline->ClearDone(i);
692
26.2k
      }
693
36.0k
    }
694
695
16.4k
    const auto prepare_storage = [this](size_t num_threads) -> Status {
696
16.4k
      JXL_RETURN_IF_ERROR(
697
16.4k
          PrepareStorage(num_threads, decoded_passes_per_ac_group_.size()));
698
16.4k
      return true;
699
16.4k
    };
700
16.4k
    const auto process_group = [this, &ac_group_sec, &desired_num_ac_passes,
701
16.4k
                                &num, &sections, &section_status](
702
31.9k
                                   size_t g, size_t thread) -> Status {
703
31.9k
      if (desired_num_ac_passes[g] == 0) {
704
        // no new AC pass, nothing to do
705
6.25k
        return true;
706
6.25k
      }
707
25.7k
      size_t first_pass = decoded_passes_per_ac_group_[g];
708
25.7k
      PassesReaders readers = {};
709
51.4k
      for (size_t i = 0; i < desired_num_ac_passes[g]; i++) {
710
25.7k
        JXL_ENSURE(ac_group_sec[g][first_pass + i] != num);
711
25.7k
        readers[i] = sections[ac_group_sec[g][first_pass + i]].br;
712
25.7k
      }
713
25.7k
      JXL_RETURN_IF_ERROR(ProcessACGroup(
714
25.7k
          g, readers, desired_num_ac_passes[g], GetStorageLocation(thread, g),
715
25.7k
          /*force_draw=*/false, /*dc_only=*/false));
716
51.1k
      for (size_t i = 0; i < desired_num_ac_passes[g]; i++) {
717
25.6k
        section_status[ac_group_sec[g][first_pass + i]] = SectionStatus::kDone;
718
25.6k
      }
719
25.5k
      return true;
720
25.7k
    };
721
16.4k
    JXL_RETURN_IF_ERROR(RunOnPool(pool_, 0, ac_group_sec.size(),
722
16.4k
                                  prepare_storage, process_group,
723
16.4k
                                  "DecodeGroup"));
724
16.4k
  }
725
726
16.4k
  MarkSections(sections, num, section_status);
727
16.4k
  return true;
728
16.5k
}
729
730
0
Status FrameDecoder::Flush() {
731
0
  bool has_blending = frame_header_.blending_info.mode != BlendMode::kReplace ||
732
0
                      frame_header_.custom_size_or_origin;
733
0
  for (const auto& blending_info_ec :
734
0
       frame_header_.extra_channel_blending_info) {
735
0
    if (blending_info_ec.mode != BlendMode::kReplace) has_blending = true;
736
0
  }
737
  // No early Flush() if blending is enabled.
738
0
  if (has_blending && !is_finalized_) {
739
0
    return false;
740
0
  }
741
  // No early Flush() - nothing to do - if the frame is a kSkipProgressive
742
  // frame.
743
0
  if (frame_header_.frame_type == FrameType::kSkipProgressive &&
744
0
      !is_finalized_) {
745
0
    return true;
746
0
  }
747
0
  if (decoded_->IsJPEG()) {
748
    // Nothing to do.
749
0
    return true;
750
0
  }
751
0
  JXL_RETURN_IF_ERROR(AllocateOutput());
752
753
0
  uint32_t completely_decoded_ac_pass = *std::min_element(
754
0
      decoded_passes_per_ac_group_.begin(), decoded_passes_per_ac_group_.end());
755
0
  if (completely_decoded_ac_pass < frame_header_.passes.num_passes) {
756
    // We don't have all AC yet: force a draw of all the missing areas.
757
    // Mark all sections as not complete.
758
0
    for (size_t i = 0; i < decoded_passes_per_ac_group_.size(); i++) {
759
0
      if (decoded_passes_per_ac_group_[i] < frame_header_.passes.num_passes) {
760
0
        dec_state_->render_pipeline->ClearDone(i);
761
0
      }
762
0
    }
763
0
    const auto prepare_storage = [this](const size_t num_threads) -> Status {
764
0
      JXL_RETURN_IF_ERROR(
765
0
          PrepareStorage(num_threads, decoded_passes_per_ac_group_.size()));
766
0
      return true;
767
0
    };
768
0
    const auto process_group = [this](const uint32_t g,
769
0
                                      size_t thread) -> Status {
770
0
      if (decoded_passes_per_ac_group_[g] == frame_header_.passes.num_passes) {
771
        // This group was drawn already, nothing to do.
772
0
        return true;
773
0
      }
774
0
      PassesReaders readers = {};
775
0
      JXL_RETURN_IF_ERROR(ProcessACGroup(
776
0
          g, readers, /*num_passes=*/0, GetStorageLocation(thread, g),
777
0
          /*force_draw=*/true, /*dc_only=*/!decoded_ac_global_));
778
0
      return true;
779
0
    };
780
0
    JXL_RETURN_IF_ERROR(RunOnPool(pool_, 0, decoded_passes_per_ac_group_.size(),
781
0
                                  prepare_storage, process_group,
782
0
                                  "ForceDrawGroup"));
783
0
  }
784
785
  // undo global modular transforms and copy int pixel buffers to float ones
786
0
  JXL_RETURN_IF_ERROR(modular_frame_decoder_.FinalizeDecoding(
787
0
      frame_header_, dec_state_, pool_, is_finalized_));
788
789
0
  return true;
790
0
}
791
792
81.8k
int FrameDecoder::SavedAs(const FrameHeader& header) {
793
81.8k
  if (header.frame_type == FrameType::kDCFrame) {
794
    // bits 16, 32, 64, 128 for DC level
795
3.31k
    return 16 << (header.dc_level - 1);
796
78.4k
  } else if (header.CanBeReferenced()) {
797
    // bits 1, 2, 4 and 8 for the references
798
75.1k
    return 1 << header.save_as_reference;
799
75.1k
  }
800
801
3.33k
  return 0;
802
81.8k
}
803
804
16.3k
bool FrameDecoder::HasEverything() const {
805
16.3k
  if (!decoded_dc_global_) return false;
806
16.3k
  if (!decoded_ac_global_) return false;
807
16.3k
  if (HasDcGroupToDecode()) return false;
808
21.4k
  for (const auto& nb_passes : decoded_passes_per_ac_group_) {
809
21.4k
    if (nb_passes < frame_header_.passes.num_passes) return false;
810
21.4k
  }
811
16.3k
  return true;
812
16.3k
}
813
814
16.3k
int FrameDecoder::References() const {
815
16.3k
  if (is_finalized_) {
816
0
    return 0;
817
0
  }
818
16.3k
  if (!HasEverything()) return 0;
819
820
16.3k
  int result = 0;
821
822
  // Blending
823
16.3k
  if (frame_header_.frame_type == FrameType::kRegularFrame ||
824
12.9k
      frame_header_.frame_type == FrameType::kSkipProgressive) {
825
12.9k
    bool cropped = frame_header_.custom_size_or_origin;
826
12.9k
    if (cropped || frame_header_.blending_info.mode != BlendMode::kReplace) {
827
3.22k
      result |= (1 << frame_header_.blending_info.source);
828
3.22k
    }
829
12.9k
    const auto& extra = frame_header_.extra_channel_blending_info;
830
12.9k
    for (const auto& ecbi : extra) {
831
1.79k
      if (cropped || ecbi.mode != BlendMode::kReplace) {
832
496
        result |= (1 << ecbi.source);
833
496
      }
834
1.79k
    }
835
12.9k
  }
836
837
  // Patches
838
16.3k
  if (frame_header_.flags & FrameHeader::kPatches) {
839
1.30k
    result |= dec_state_->shared->image_features.patches.GetReferences();
840
1.30k
  }
841
842
  // DC Level
843
16.3k
  if (frame_header_.flags & FrameHeader::kUseDcFrame) {
844
    // Reads from the next dc level
845
0
    int dc_level = frame_header_.dc_level + 1;
846
    // bits 16, 32, 64, 128 for DC level
847
0
    result |= (16 << (dc_level - 1));
848
0
  }
849
850
16.3k
  return result;
851
16.3k
}
852
853
16.3k
Status FrameDecoder::FinalizeFrame() {
854
16.3k
  if (is_finalized_) {
855
0
    return JXL_FAILURE("FinalizeFrame called multiple times");
856
0
  }
857
16.3k
  is_finalized_ = true;
858
16.3k
  if (decoded_->IsJPEG()) {
859
    // Nothing to do.
860
0
    return true;
861
0
  }
862
863
  // undo global modular transforms and copy int pixel buffers to float ones
864
16.3k
  JXL_RETURN_IF_ERROR(
865
16.3k
      modular_frame_decoder_.FinalizeDecoding(frame_header_, dec_state_, pool_,
866
16.3k
                                              /*inplace=*/true));
867
868
16.3k
  if (frame_header_.CanBeReferenced()) {
869
11.5k
    auto& info = dec_state_->shared_storage
870
11.5k
                     .reference_frames[frame_header_.save_as_reference];
871
11.5k
    *info.frame = std::move(dec_state_->frame_storage_for_referencing);
872
11.5k
    info.ib_is_in_xyb = frame_header_.save_before_color_transform;
873
11.5k
  }
874
16.3k
  return true;
875
16.3k
}
876
877
}  // namespace jxl