Coverage Report

Created: 2026-05-24 07:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/dec_cache.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_cache.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <cstddef>
12
#include <cstdint>
13
#include <utility>
14
15
#include "lib/jxl/ac_strategy.h"
16
#include "lib/jxl/base/bits.h"
17
#include "lib/jxl/base/data_parallel.h"
18
#include "lib/jxl/base/status.h"
19
#include "lib/jxl/blending.h"
20
#include "lib/jxl/coeff_order.h"
21
#include "lib/jxl/color_encoding_internal.h"
22
#include "lib/jxl/common.h"  // JXL_HIGH_PRECISION
23
#include "lib/jxl/frame_dimensions.h"
24
#include "lib/jxl/frame_header.h"
25
#include "lib/jxl/image.h"
26
#include "lib/jxl/image_bundle.h"
27
#include "lib/jxl/image_metadata.h"
28
#include "lib/jxl/loop_filter.h"
29
#include "lib/jxl/memory_manager_internal.h"
30
#include "lib/jxl/render_pipeline/render_pipeline.h"
31
#include "lib/jxl/render_pipeline/stage_blending.h"
32
#include "lib/jxl/render_pipeline/stage_chroma_upsampling.h"
33
#include "lib/jxl/render_pipeline/stage_cms.h"
34
#include "lib/jxl/render_pipeline/stage_epf.h"
35
#include "lib/jxl/render_pipeline/stage_from_linear.h"
36
#include "lib/jxl/render_pipeline/stage_gaborish.h"
37
#include "lib/jxl/render_pipeline/stage_noise.h"
38
#include "lib/jxl/render_pipeline/stage_patches.h"
39
#include "lib/jxl/render_pipeline/stage_splines.h"
40
#include "lib/jxl/render_pipeline/stage_spot.h"
41
#include "lib/jxl/render_pipeline/stage_to_linear.h"
42
#include "lib/jxl/render_pipeline/stage_tone_mapping.h"
43
#include "lib/jxl/render_pipeline/stage_upsampling.h"
44
#include "lib/jxl/render_pipeline/stage_write.h"
45
#include "lib/jxl/render_pipeline/stage_xyb.h"
46
#include "lib/jxl/render_pipeline/stage_ycbcr.h"
47
48
namespace jxl {
49
50
Status GroupDecCache::InitOnce(JxlMemoryManager* memory_manager,
51
44.4k
                               size_t num_passes, size_t used_acs) {
52
61.1k
  for (size_t i = 0; i < num_passes; i++) {
53
16.7k
    if (num_nzeroes[i].xsize() == 0) {
54
      // Allocate enough for a whole group - partial groups on the
55
      // right/bottom border just use a subset. The valid size is passed via
56
      // Rect.
57
58
9.19k
      JXL_ASSIGN_OR_RETURN(num_nzeroes[i],
59
9.19k
                           Image3I::Create(memory_manager, kGroupDimInBlocks,
60
9.19k
                                           kGroupDimInBlocks));
61
9.19k
    }
62
16.7k
  }
63
44.4k
  size_t max_block_area = 0;
64
65
1.24M
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
66
1.19M
    AcStrategy acs = AcStrategy::FromRawStrategy(o);
67
1.19M
    if ((used_acs & (1 << o)) == 0) continue;
68
827k
    size_t area =
69
827k
        acs.covered_blocks_x() * acs.covered_blocks_y() * kDCTBlockSize;
70
827k
    max_block_area = std::max(area, max_block_area);
71
827k
  }
72
73
44.4k
  if (max_block_area > max_block_area_) {
74
20.8k
    max_block_area_ = max_block_area;
75
    // We need 3x float blocks for dequantized coefficients and 1x for scratch
76
    // space for transforms.
77
20.8k
    JXL_ASSIGN_OR_RETURN(
78
20.8k
        float_memory_,
79
20.8k
        AlignedMemory::Create(memory_manager,
80
20.8k
                              max_block_area_ * 7 * sizeof(float)));
81
    // We need 3x int32 or int16 blocks for quantized coefficients.
82
20.8k
    JXL_ASSIGN_OR_RETURN(
83
20.8k
        int32_memory_,
84
20.8k
        AlignedMemory::Create(memory_manager,
85
20.8k
                              max_block_area_ * 3 * sizeof(int32_t)));
86
20.8k
    JXL_ASSIGN_OR_RETURN(
87
20.8k
        int16_memory_,
88
20.8k
        AlignedMemory::Create(memory_manager,
89
20.8k
                              max_block_area_ * 3 * sizeof(int16_t)));
90
20.8k
  }
91
92
44.4k
  dec_group_block = float_memory_.address<float>();
93
44.4k
  scratch_space = dec_group_block + max_block_area_ * 3;
94
44.4k
  dec_group_qblock = int32_memory_.address<int32_t>();
95
44.4k
  dec_group_qblock16 = int16_memory_.address<int16_t>();
96
44.4k
  return true;
97
44.4k
}
98
99
// Initialize the decoder state after all of DC is decoded.
100
82.7k
Status PassesDecoderState::InitForAC(size_t num_passes, ThreadPool* pool) {
101
82.7k
  shared_storage.coeff_order_size = 0;
102
2.31M
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
103
2.23M
    if (((1 << o) & used_acs) == 0) continue;
104
56.0k
    uint8_t ord = kStrategyOrder[o];
105
56.0k
    shared_storage.coeff_order_size =
106
56.0k
        std::max(kCoeffOrderOffset[3 * (ord + 1)] * kDCTBlockSize,
107
56.0k
                 shared_storage.coeff_order_size);
108
56.0k
  }
109
82.7k
  size_t sz = num_passes * shared_storage.coeff_order_size;
110
82.7k
  if (sz > shared_storage.coeff_orders.size()) {
111
31.0k
    shared_storage.coeff_orders.resize(sz);
112
31.0k
  }
113
82.7k
  return true;
114
82.7k
}
115
116
Status PassesDecoderState::PreparePipeline(const FrameHeader& frame_header,
117
                                           const ImageMetadata* metadata,
118
                                           ImageBundle* decoded,
119
94.6k
                                           PipelineOptions options) {
120
94.6k
  JxlMemoryManager* memory_manager = this->memory_manager();
121
94.6k
  size_t num_c = 3 + frame_header.nonserialized_metadata->m.num_extra_channels;
122
94.6k
  size_t num_tmp_c = options.render_noise ? 3 : 0;
123
124
94.6k
  if (frame_header.CanBeReferenced()) {
125
    // Necessary so that SetInputSizes() can allocate output buffers as needed.
126
34.9k
    frame_storage_for_referencing = ImageBundle(memory_manager, metadata);
127
34.9k
  }
128
129
94.6k
  RenderPipeline::Builder builder(memory_manager, num_c + num_tmp_c);
130
131
94.6k
  if (options.use_slow_render_pipeline) {
132
0
    builder.UseSimpleImplementation();
133
0
  }
134
135
94.6k
  if (!frame_header.chroma_subsampling.Is444()) {
136
26.6k
    for (size_t c = 0; c < 3; c++) {
137
20.0k
      if (frame_header.chroma_subsampling.HShift(c) != 0) {
138
9.53k
        JXL_RETURN_IF_ERROR(
139
9.53k
            builder.AddStage(GetChromaUpsamplingStage(c, /*horizontal=*/true)));
140
9.53k
      }
141
20.0k
      if (frame_header.chroma_subsampling.VShift(c) != 0) {
142
5.71k
        JXL_RETURN_IF_ERROR(builder.AddStage(
143
5.71k
            GetChromaUpsamplingStage(c, /*horizontal=*/false)));
144
5.71k
      }
145
20.0k
    }
146
6.67k
  }
147
148
94.6k
  if (frame_header.loop_filter.gab) {
149
65.9k
    JXL_RETURN_IF_ERROR(
150
65.9k
        builder.AddStage(GetGaborishStage(frame_header.loop_filter)));
151
65.9k
  }
152
153
94.6k
  {
154
94.6k
    const LoopFilter& lf = frame_header.loop_filter;
155
94.6k
    if (lf.epf_iters >= 3) {
156
1.71k
      JXL_RETURN_IF_ERROR(
157
1.71k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::Zero)));
158
1.71k
    }
159
94.6k
    if (lf.epf_iters >= 1) {
160
64.1k
      JXL_RETURN_IF_ERROR(
161
64.1k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::One)));
162
64.1k
    }
163
94.6k
    if (lf.epf_iters >= 2) {
164
61.4k
      JXL_RETURN_IF_ERROR(
165
61.4k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::Two)));
166
61.4k
    }
167
94.6k
  }
168
169
94.6k
  bool late_ec_upsample = frame_header.upsampling != 1;
170
94.6k
  for (auto ecups : frame_header.extra_channel_upsampling) {
171
17.8k
    if (ecups != frame_header.upsampling) {
172
      // If patches are applied, either frame_header.upsampling == 1 or
173
      // late_ec_upsample is true.
174
6.71k
      late_ec_upsample = false;
175
6.71k
    }
176
17.8k
  }
177
178
94.6k
  if (!late_ec_upsample) {
179
75.9k
    for (size_t ec = 0; ec < frame_header.extra_channel_upsampling.size();
180
59.4k
         ec++) {
181
16.5k
      if (frame_header.extra_channel_upsampling[ec] != 1) {
182
6.72k
        JXL_RETURN_IF_ERROR(builder.AddStage(GetUpsamplingStage(
183
6.72k
            memory_manager, frame_header.nonserialized_metadata->transform_data,
184
6.72k
            3 + ec,
185
6.72k
            CeilLog2Nonzero(frame_header.extra_channel_upsampling[ec]))));
186
6.72k
      }
187
16.5k
    }
188
59.4k
  }
189
190
94.6k
  if ((frame_header.flags & FrameHeader::kPatches) != 0) {
191
6.84k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetPatchesStage(
192
6.84k
        &shared->image_features.patches,
193
6.84k
        &frame_header.nonserialized_metadata->m.extra_channel_info)));
194
6.84k
  }
195
94.6k
  if ((frame_header.flags & FrameHeader::kSplines) != 0) {
196
1.88k
    JXL_RETURN_IF_ERROR(
197
1.88k
        builder.AddStage(GetSplineStage(&shared->image_features.splines)));
198
1.88k
  }
199
200
94.6k
  if (frame_header.upsampling != 1) {
201
35.5k
    size_t nb_channels =
202
35.5k
        3 +
203
35.5k
        (late_ec_upsample ? frame_header.extra_channel_upsampling.size() : 0);
204
143k
    for (size_t c = 0; c < nb_channels; c++) {
205
107k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetUpsamplingStage(
206
107k
          memory_manager, frame_header.nonserialized_metadata->transform_data,
207
107k
          c, CeilLog2Nonzero(frame_header.upsampling))));
208
107k
    }
209
35.5k
  }
210
  // Starting from this line all the stages considered to have zero xextra.
211
  // Upsampling does not have xextra as well (even if it happens before
212
  // splines/patches for EC).
213
94.6k
  if (options.render_noise) {
214
7.83k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetConvolveNoiseStage(num_c)));
215
7.83k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetAddNoiseStage(
216
7.83k
        shared->image_features.noise_params, shared->cmap.base(), num_c)));
217
7.83k
  }
218
94.6k
  if (frame_header.dc_level != 0) {
219
9.52k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImage3FStage(
220
9.52k
        memory_manager, &shared_storage.dc_frames[frame_header.dc_level - 1])));
221
9.52k
  }
222
223
94.6k
  if (frame_header.CanBeReferenced() &&
224
34.9k
      frame_header.save_before_color_transform) {
225
12.7k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImageBundleStage(
226
12.7k
        &frame_storage_for_referencing, output_encoding_info)));
227
12.7k
  }
228
229
94.6k
  bool has_alpha = false;
230
94.6k
  size_t alpha_c = 0;
231
105k
  for (size_t i = 0; i < metadata->extra_channel_info.size(); i++) {
232
14.2k
    if (metadata->extra_channel_info[i].type == ExtraChannel::kAlpha) {
233
3.56k
      has_alpha = true;
234
3.56k
      alpha_c = 3 + i;
235
3.56k
      break;
236
3.56k
    }
237
14.2k
  }
238
239
94.6k
  if (fast_xyb_srgb8_conversion) {
240
#if !JXL_HIGH_PRECISION
241
    JXL_ENSURE(!NeedsBlending(frame_header));
242
    JXL_ENSURE(!frame_header.CanBeReferenced() ||
243
               frame_header.save_before_color_transform);
244
    JXL_ENSURE(!options.render_spotcolors ||
245
               !metadata->Find(ExtraChannel::kSpotColor));
246
    bool is_rgba = (main_output.format.num_channels == 4);
247
    uint8_t* rgb_output = reinterpret_cast<uint8_t*>(main_output.buffer);
248
    JXL_RETURN_IF_ERROR(builder.AddStage(
249
        GetFastXYBTosRGB8Stage(rgb_output, main_output.stride, width, height,
250
                               is_rgba, has_alpha, alpha_c)));
251
#endif
252
94.6k
  } else {
253
94.6k
    bool linear = false;
254
94.6k
    if (frame_header.color_transform == ColorTransform::kYCbCr) {
255
6.77k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetYCbCrStage()));
256
87.9k
    } else if (frame_header.color_transform == ColorTransform::kXYB) {
257
52.0k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetXYBStage(output_encoding_info)));
258
52.0k
      if (output_encoding_info.color_encoding.GetColorSpace() !=
259
52.0k
          ColorSpace::kXYB) {
260
52.0k
        linear = true;
261
52.0k
      }
262
52.0k
    }  // Nothing to do for kNone.
263
264
94.6k
    if (options.coalescing && NeedsBlending(frame_header)) {
265
20.7k
      if (linear) {
266
9.64k
        JXL_RETURN_IF_ERROR(
267
9.64k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
268
9.64k
        linear = false;
269
9.64k
      }
270
20.7k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetBlendingStage(
271
20.7k
          frame_header, this, output_encoding_info.color_encoding)));
272
20.7k
    }
273
274
94.6k
    if (options.coalescing && frame_header.CanBeReferenced() &&
275
34.9k
        !frame_header.save_before_color_transform) {
276
22.1k
      if (linear) {
277
2.02k
        JXL_RETURN_IF_ERROR(
278
2.02k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
279
2.02k
        linear = false;
280
2.02k
      }
281
22.1k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImageBundleStage(
282
22.1k
          &frame_storage_for_referencing, output_encoding_info)));
283
22.1k
    }
284
285
94.6k
    if (options.render_spotcolors &&
286
82.8k
        frame_header.nonserialized_metadata->m.Find(ExtraChannel::kSpotColor)) {
287
11.6k
      for (size_t i = 0; i < metadata->extra_channel_info.size(); i++) {
288
        // Don't use Find() because there may be multiple spot color channels.
289
9.21k
        const ExtraChannelInfo& eci = metadata->extra_channel_info[i];
290
9.21k
        if (eci.type == ExtraChannel::kSpotColor) {
291
2.39k
          JXL_RETURN_IF_ERROR(
292
2.39k
              builder.AddStage(GetSpotColorStage(i, eci.spot_color)));
293
2.39k
        }
294
9.21k
      }
295
2.38k
    }
296
297
94.6k
    auto tone_mapping_stage = GetToneMappingStage(output_encoding_info);
298
94.6k
    if (tone_mapping_stage) {
299
0
      if (!linear) {
300
0
        auto to_linear_stage = GetToLinearStage(output_encoding_info);
301
0
        if (!to_linear_stage) {
302
0
          if (!output_encoding_info.cms_set) {
303
0
            return JXL_FAILURE("Cannot tonemap this colorspace without a CMS");
304
0
          }
305
0
          auto cms_stage = GetCmsStage(output_encoding_info);
306
0
          if (cms_stage) {
307
0
            JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
308
0
          }
309
0
        } else {
310
0
          JXL_RETURN_IF_ERROR(builder.AddStage(std::move(to_linear_stage)));
311
0
        }
312
0
        linear = true;
313
0
      }
314
0
      JXL_RETURN_IF_ERROR(builder.AddStage(std::move(tone_mapping_stage)));
315
0
    }
316
317
94.6k
    if (linear) {
318
40.3k
      const size_t channels_src =
319
40.3k
          (output_encoding_info.orig_color_encoding.IsCMYK()
320
40.3k
               ? 4
321
40.3k
               : output_encoding_info.orig_color_encoding.Channels());
322
40.3k
      const size_t channels_dst =
323
40.3k
          output_encoding_info.color_encoding.Channels();
324
40.3k
      bool mixing_color_and_grey = (channels_dst != channels_src);
325
40.3k
      if ((output_encoding_info.color_encoding_is_original) ||
326
40.3k
          (!output_encoding_info.cms_set) || mixing_color_and_grey) {
327
        // in those cases we only need a linear stage in other cases we attempt
328
        // to obtain a cms stage: the cases are
329
        // - output_encoding_info.color_encoding_is_original: no cms stage
330
        // needed because it would be a no-op
331
        // - !output_encoding_info.cms_set: can't use the cms, so no point in
332
        // trying to add a cms stage
333
        // - mixing_color_and_grey: cms stage can't handle that
334
        // TODO(firsching): remove "mixing_color_and_grey" condition after
335
        // adding support for greyscale to cms stage.
336
40.3k
        JXL_RETURN_IF_ERROR(
337
40.3k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
338
40.3k
      } else {
339
0
        if (!output_encoding_info.linear_color_encoding.CreateICC()) {
340
0
          return JXL_FAILURE("Failed to create ICC");
341
0
        }
342
0
        auto cms_stage = GetCmsStage(output_encoding_info);
343
0
        if (cms_stage) {
344
0
          JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
345
0
        }
346
0
      }
347
40.3k
      linear = false;
348
54.3k
    } else {
349
54.3k
      auto cms_stage = GetCmsStage(output_encoding_info, false);
350
54.3k
      if (cms_stage) {
351
0
        JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
352
0
      }
353
54.3k
    }
354
94.6k
    (void)linear;
355
356
94.6k
    if (main_output.callback.IsPresent() || main_output.buffer) {
357
38.3k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToOutputStage(
358
38.3k
          main_output, width, height, has_alpha, unpremul_alpha, alpha_c,
359
38.3k
          undo_orientation, extra_output, memory_manager)));
360
56.3k
    } else {
361
56.3k
      JXL_RETURN_IF_ERROR(builder.AddStage(
362
56.3k
          GetWriteToImageBundleStage(decoded, output_encoding_info)));
363
56.3k
    }
364
94.6k
  }
365
94.6k
  JXL_ASSIGN_OR_RETURN(render_pipeline,
366
94.6k
                       std::move(builder).Finalize(shared->frame_dim));
367
94.6k
  return render_pipeline->IsInitialized();
368
94.6k
}
369
370
}  // namespace jxl