Coverage Report

Created: 2026-05-16 07:22

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
26.2k
                               size_t num_passes, size_t used_acs) {
52
31.1k
  for (size_t i = 0; i < num_passes; i++) {
53
4.90k
    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
4.30k
      JXL_ASSIGN_OR_RETURN(num_nzeroes[i],
59
4.30k
                           Image3I::Create(memory_manager, kGroupDimInBlocks,
60
4.30k
                                           kGroupDimInBlocks));
61
4.30k
    }
62
4.90k
  }
63
26.2k
  size_t max_block_area = 0;
64
65
736k
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
66
709k
    AcStrategy acs = AcStrategy::FromRawStrategy(o);
67
709k
    if ((used_acs & (1 << o)) == 0) continue;
68
587k
    size_t area =
69
587k
        acs.covered_blocks_x() * acs.covered_blocks_y() * kDCTBlockSize;
70
587k
    max_block_area = std::max(area, max_block_area);
71
587k
  }
72
73
26.2k
  if (max_block_area > max_block_area_) {
74
12.1k
    max_block_area_ = max_block_area;
75
    // We need 3x float blocks for dequantized coefficients and 1x for scratch
76
    // space for transforms.
77
12.1k
    JXL_ASSIGN_OR_RETURN(
78
12.1k
        float_memory_,
79
12.1k
        AlignedMemory::Create(memory_manager,
80
12.1k
                              max_block_area_ * 7 * sizeof(float)));
81
    // We need 3x int32 or int16 blocks for quantized coefficients.
82
12.1k
    JXL_ASSIGN_OR_RETURN(
83
12.1k
        int32_memory_,
84
12.1k
        AlignedMemory::Create(memory_manager,
85
12.1k
                              max_block_area_ * 3 * sizeof(int32_t)));
86
12.1k
    JXL_ASSIGN_OR_RETURN(
87
12.1k
        int16_memory_,
88
12.1k
        AlignedMemory::Create(memory_manager,
89
12.1k
                              max_block_area_ * 3 * sizeof(int16_t)));
90
12.1k
  }
91
92
26.2k
  dec_group_block = float_memory_.address<float>();
93
26.2k
  scratch_space = dec_group_block + max_block_area_ * 3;
94
26.2k
  dec_group_qblock = int32_memory_.address<int32_t>();
95
26.2k
  dec_group_qblock16 = int16_memory_.address<int16_t>();
96
26.2k
  return true;
97
26.2k
}
98
99
// Initialize the decoder state after all of DC is decoded.
100
32.7k
Status PassesDecoderState::InitForAC(size_t num_passes, ThreadPool* pool) {
101
32.7k
  shared_storage.coeff_order_size = 0;
102
916k
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
103
883k
    if (((1 << o) & used_acs) == 0) continue;
104
6.98k
    uint8_t ord = kStrategyOrder[o];
105
6.98k
    shared_storage.coeff_order_size =
106
6.98k
        std::max(kCoeffOrderOffset[3 * (ord + 1)] * kDCTBlockSize,
107
6.98k
                 shared_storage.coeff_order_size);
108
6.98k
  }
109
32.7k
  size_t sz = num_passes * shared_storage.coeff_order_size;
110
32.7k
  if (sz > shared_storage.coeff_orders.size()) {
111
1.25k
    shared_storage.coeff_orders.resize(sz);
112
1.25k
  }
113
32.7k
  return true;
114
32.7k
}
115
116
Status PassesDecoderState::PreparePipeline(const FrameHeader& frame_header,
117
                                           const ImageMetadata* metadata,
118
                                           ImageBundle* decoded,
119
40.6k
                                           PipelineOptions options) {
120
40.6k
  JxlMemoryManager* memory_manager = this->memory_manager();
121
40.6k
  size_t num_c = 3 + frame_header.nonserialized_metadata->m.num_extra_channels;
122
40.6k
  size_t num_tmp_c = options.render_noise ? 3 : 0;
123
124
40.6k
  if (frame_header.CanBeReferenced()) {
125
    // Necessary so that SetInputSizes() can allocate output buffers as needed.
126
19.5k
    frame_storage_for_referencing = ImageBundle(memory_manager, metadata);
127
19.5k
  }
128
129
40.6k
  RenderPipeline::Builder builder(memory_manager, num_c + num_tmp_c);
130
131
40.6k
  if (options.use_slow_render_pipeline) {
132
0
    builder.UseSimpleImplementation();
133
0
  }
134
135
40.6k
  if (!frame_header.chroma_subsampling.Is444()) {
136
21.8k
    for (size_t c = 0; c < 3; c++) {
137
16.4k
      if (frame_header.chroma_subsampling.HShift(c) != 0) {
138
6.16k
        JXL_RETURN_IF_ERROR(
139
6.16k
            builder.AddStage(GetChromaUpsamplingStage(c, /*horizontal=*/true)));
140
6.16k
      }
141
16.4k
      if (frame_header.chroma_subsampling.VShift(c) != 0) {
142
5.86k
        JXL_RETURN_IF_ERROR(builder.AddStage(
143
5.86k
            GetChromaUpsamplingStage(c, /*horizontal=*/false)));
144
5.86k
      }
145
16.4k
    }
146
5.46k
  }
147
148
40.6k
  if (frame_header.loop_filter.gab) {
149
20.5k
    JXL_RETURN_IF_ERROR(
150
20.5k
        builder.AddStage(GetGaborishStage(frame_header.loop_filter)));
151
20.5k
  }
152
153
40.6k
  {
154
40.6k
    const LoopFilter& lf = frame_header.loop_filter;
155
40.6k
    if (lf.epf_iters >= 3) {
156
504
      JXL_RETURN_IF_ERROR(
157
504
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::Zero)));
158
504
    }
159
40.6k
    if (lf.epf_iters >= 1) {
160
20.2k
      JXL_RETURN_IF_ERROR(
161
20.2k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::One)));
162
20.2k
    }
163
40.6k
    if (lf.epf_iters >= 2) {
164
11.9k
      JXL_RETURN_IF_ERROR(
165
11.9k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::Two)));
166
11.9k
    }
167
40.6k
  }
168
169
40.6k
  bool late_ec_upsample = frame_header.upsampling != 1;
170
40.6k
  for (auto ecups : frame_header.extra_channel_upsampling) {
171
14.3k
    if (ecups != frame_header.upsampling) {
172
      // If patches are applied, either frame_header.upsampling == 1 or
173
      // late_ec_upsample is true.
174
5.84k
      late_ec_upsample = false;
175
5.84k
    }
176
14.3k
  }
177
178
40.6k
  if (!late_ec_upsample) {
179
33.5k
    for (size_t ec = 0; ec < frame_header.extra_channel_upsampling.size();
180
21.0k
         ec++) {
181
12.5k
      if (frame_header.extra_channel_upsampling[ec] != 1) {
182
5.93k
        JXL_RETURN_IF_ERROR(builder.AddStage(GetUpsamplingStage(
183
5.93k
            memory_manager, frame_header.nonserialized_metadata->transform_data,
184
5.93k
            3 + ec,
185
5.93k
            CeilLog2Nonzero(frame_header.extra_channel_upsampling[ec]))));
186
5.93k
      }
187
12.5k
    }
188
21.0k
  }
189
190
40.6k
  if ((frame_header.flags & FrameHeader::kPatches) != 0) {
191
3.41k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetPatchesStage(
192
3.41k
        &shared->image_features.patches,
193
3.41k
        &frame_header.nonserialized_metadata->m.extra_channel_info)));
194
3.41k
  }
195
40.6k
  if ((frame_header.flags & FrameHeader::kSplines) != 0) {
196
3.65k
    JXL_RETURN_IF_ERROR(
197
3.65k
        builder.AddStage(GetSplineStage(&shared->image_features.splines)));
198
3.65k
  }
199
200
40.6k
  if (frame_header.upsampling != 1) {
201
20.4k
    size_t nb_channels =
202
20.4k
        3 +
203
20.4k
        (late_ec_upsample ? frame_header.extra_channel_upsampling.size() : 0);
204
83.4k
    for (size_t c = 0; c < nb_channels; c++) {
205
63.0k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetUpsamplingStage(
206
63.0k
          memory_manager, frame_header.nonserialized_metadata->transform_data,
207
63.0k
          c, CeilLog2Nonzero(frame_header.upsampling))));
208
63.0k
    }
209
20.4k
  }
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
40.6k
  if (options.render_noise) {
214
2.70k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetConvolveNoiseStage(num_c)));
215
2.70k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetAddNoiseStage(
216
2.70k
        shared->image_features.noise_params, shared->cmap.base(), num_c)));
217
2.70k
  }
218
40.6k
  if (frame_header.dc_level != 0) {
219
9.34k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImage3FStage(
220
9.34k
        memory_manager, &shared_storage.dc_frames[frame_header.dc_level - 1])));
221
9.34k
  }
222
223
40.6k
  if (frame_header.CanBeReferenced() &&
224
19.5k
      frame_header.save_before_color_transform) {
225
3.36k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImageBundleStage(
226
3.36k
        &frame_storage_for_referencing, output_encoding_info)));
227
3.36k
  }
228
229
40.6k
  bool has_alpha = false;
230
40.6k
  size_t alpha_c = 0;
231
41.9k
  for (size_t i = 0; i < metadata->extra_channel_info.size(); i++) {
232
8.89k
    if (metadata->extra_channel_info[i].type == ExtraChannel::kAlpha) {
233
7.59k
      has_alpha = true;
234
7.59k
      alpha_c = 3 + i;
235
7.59k
      break;
236
7.59k
    }
237
8.89k
  }
238
239
40.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
40.6k
  } else {
253
40.6k
    bool linear = false;
254
40.6k
    if (frame_header.color_transform == ColorTransform::kYCbCr) {
255
5.53k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetYCbCrStage()));
256
35.1k
    } else if (frame_header.color_transform == ColorTransform::kXYB) {
257
18.5k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetXYBStage(output_encoding_info)));
258
18.5k
      if (output_encoding_info.color_encoding.GetColorSpace() !=
259
18.5k
          ColorSpace::kXYB) {
260
18.5k
        linear = true;
261
18.5k
      }
262
18.5k
    }  // Nothing to do for kNone.
263
264
40.6k
    if (options.coalescing && NeedsBlending(frame_header)) {
265
9.97k
      if (linear) {
266
4.75k
        JXL_RETURN_IF_ERROR(
267
4.75k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
268
4.75k
        linear = false;
269
4.75k
      }
270
9.97k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetBlendingStage(
271
9.97k
          frame_header, this, output_encoding_info.color_encoding)));
272
9.97k
    }
273
274
40.6k
    if (options.coalescing && frame_header.CanBeReferenced() &&
275
19.5k
        !frame_header.save_before_color_transform) {
276
16.1k
      if (linear) {
277
3.77k
        JXL_RETURN_IF_ERROR(
278
3.77k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
279
3.77k
        linear = false;
280
3.77k
      }
281
16.1k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImageBundleStage(
282
16.1k
          &frame_storage_for_referencing, output_encoding_info)));
283
16.1k
    }
284
285
40.6k
    if (options.render_spotcolors &&
286
32.7k
        frame_header.nonserialized_metadata->m.Find(ExtraChannel::kSpotColor)) {
287
2.10k
      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
1.80k
        const ExtraChannelInfo& eci = metadata->extra_channel_info[i];
290
1.80k
        if (eci.type == ExtraChannel::kSpotColor) {
291
532
          JXL_RETURN_IF_ERROR(
292
532
              builder.AddStage(GetSpotColorStage(i, eci.spot_color)));
293
532
        }
294
1.80k
      }
295
300
    }
296
297
40.6k
    auto tone_mapping_stage = GetToneMappingStage(output_encoding_info);
298
40.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
40.6k
    if (linear) {
318
10.0k
      const size_t channels_src =
319
10.0k
          (output_encoding_info.orig_color_encoding.IsCMYK()
320
10.0k
               ? 4
321
10.0k
               : output_encoding_info.orig_color_encoding.Channels());
322
10.0k
      const size_t channels_dst =
323
10.0k
          output_encoding_info.color_encoding.Channels();
324
10.0k
      bool mixing_color_and_grey = (channels_dst != channels_src);
325
10.0k
      if ((output_encoding_info.color_encoding_is_original) ||
326
10.0k
          (!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
10.0k
        JXL_RETURN_IF_ERROR(
337
10.0k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
338
10.0k
      } 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
10.0k
      linear = false;
348
30.6k
    } else {
349
30.6k
      auto cms_stage = GetCmsStage(output_encoding_info, false);
350
30.6k
      if (cms_stage) {
351
0
        JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
352
0
      }
353
30.6k
    }
354
40.6k
    (void)linear;
355
356
40.6k
    if (main_output.callback.IsPresent() || main_output.buffer) {
357
4.04k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToOutputStage(
358
4.04k
          main_output, width, height, has_alpha, unpremul_alpha, alpha_c,
359
4.04k
          undo_orientation, extra_output, memory_manager)));
360
36.6k
    } else {
361
36.6k
      JXL_RETURN_IF_ERROR(builder.AddStage(
362
36.6k
          GetWriteToImageBundleStage(decoded, output_encoding_info)));
363
36.6k
    }
364
40.6k
  }
365
40.6k
  JXL_ASSIGN_OR_RETURN(render_pipeline,
366
40.6k
                       std::move(builder).Finalize(shared->frame_dim));
367
40.6k
  return render_pipeline->IsInitialized();
368
40.6k
}
369
370
}  // namespace jxl