Coverage Report

Created: 2026-04-01 07:24

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
6.09k
                               size_t num_passes, size_t used_acs) {
52
12.1k
  for (size_t i = 0; i < num_passes; i++) {
53
6.09k
    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
5.85k
      JXL_ASSIGN_OR_RETURN(num_nzeroes[i],
59
5.85k
                           Image3I::Create(memory_manager, kGroupDimInBlocks,
60
5.85k
                                           kGroupDimInBlocks));
61
5.85k
    }
62
6.09k
  }
63
6.09k
  size_t max_block_area = 0;
64
65
170k
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
66
164k
    AcStrategy acs = AcStrategy::FromRawStrategy(o);
67
164k
    if ((used_acs & (1 << o)) == 0) continue;
68
15.7k
    size_t area =
69
15.7k
        acs.covered_blocks_x() * acs.covered_blocks_y() * kDCTBlockSize;
70
15.7k
    max_block_area = std::max(area, max_block_area);
71
15.7k
  }
72
73
6.09k
  if (max_block_area > max_block_area_) {
74
5.84k
    max_block_area_ = max_block_area;
75
    // We need 3x float blocks for dequantized coefficients and 1x for scratch
76
    // space for transforms.
77
5.84k
    JXL_ASSIGN_OR_RETURN(
78
5.84k
        float_memory_,
79
5.84k
        AlignedMemory::Create(memory_manager,
80
5.84k
                              max_block_area_ * 7 * sizeof(float)));
81
    // We need 3x int32 or int16 blocks for quantized coefficients.
82
5.84k
    JXL_ASSIGN_OR_RETURN(
83
5.84k
        int32_memory_,
84
5.84k
        AlignedMemory::Create(memory_manager,
85
5.84k
                              max_block_area_ * 3 * sizeof(int32_t)));
86
5.84k
    JXL_ASSIGN_OR_RETURN(
87
5.84k
        int16_memory_,
88
5.84k
        AlignedMemory::Create(memory_manager,
89
5.84k
                              max_block_area_ * 3 * sizeof(int16_t)));
90
5.84k
  }
91
92
6.09k
  dec_group_block = float_memory_.address<float>();
93
6.09k
  scratch_space = dec_group_block + max_block_area_ * 3;
94
6.09k
  dec_group_qblock = int32_memory_.address<int32_t>();
95
6.09k
  dec_group_qblock16 = int16_memory_.address<int16_t>();
96
6.09k
  return true;
97
6.09k
}
98
99
// Initialize the decoder state after all of DC is decoded.
100
13.3k
Status PassesDecoderState::InitForAC(size_t num_passes, ThreadPool* pool) {
101
13.3k
  shared_storage.coeff_order_size = 0;
102
373k
  for (uint8_t o = 0; o < AcStrategy::kNumValidStrategies; ++o) {
103
359k
    if (((1 << o) & used_acs) == 0) continue;
104
14.4k
    uint8_t ord = kStrategyOrder[o];
105
14.4k
    shared_storage.coeff_order_size =
106
14.4k
        std::max(kCoeffOrderOffset[3 * (ord + 1)] * kDCTBlockSize,
107
14.4k
                 shared_storage.coeff_order_size);
108
14.4k
  }
109
13.3k
  size_t sz = num_passes * shared_storage.coeff_order_size;
110
13.3k
  if (sz > shared_storage.coeff_orders.size()) {
111
53
    shared_storage.coeff_orders.resize(sz);
112
53
  }
113
13.3k
  return true;
114
13.3k
}
115
116
Status PassesDecoderState::PreparePipeline(const FrameHeader& frame_header,
117
                                           const ImageMetadata* metadata,
118
                                           ImageBundle* decoded,
119
13.3k
                                           PipelineOptions options) {
120
13.3k
  JxlMemoryManager* memory_manager = this->memory_manager();
121
13.3k
  size_t num_c = 3 + frame_header.nonserialized_metadata->m.num_extra_channels;
122
13.3k
  size_t num_tmp_c = options.render_noise ? 3 : 0;
123
124
13.3k
  if (frame_header.CanBeReferenced()) {
125
    // Necessary so that SetInputSizes() can allocate output buffers as needed.
126
10.5k
    frame_storage_for_referencing = ImageBundle(memory_manager, metadata);
127
10.5k
  }
128
129
13.3k
  RenderPipeline::Builder builder(memory_manager, num_c + num_tmp_c);
130
131
13.3k
  if (options.use_slow_render_pipeline) {
132
0
    builder.UseSimpleImplementation();
133
0
  }
134
135
13.3k
  if (!frame_header.chroma_subsampling.Is444()) {
136
10.2k
    for (size_t c = 0; c < 3; c++) {
137
7.68k
      if (frame_header.chroma_subsampling.HShift(c) != 0) {
138
3.93k
        JXL_RETURN_IF_ERROR(
139
3.93k
            builder.AddStage(GetChromaUpsamplingStage(c, /*horizontal=*/true)));
140
3.93k
      }
141
7.68k
      if (frame_header.chroma_subsampling.VShift(c) != 0) {
142
1.59k
        JXL_RETURN_IF_ERROR(builder.AddStage(
143
1.59k
            GetChromaUpsamplingStage(c, /*horizontal=*/false)));
144
1.59k
      }
145
7.68k
    }
146
2.56k
  }
147
148
13.3k
  if (frame_header.loop_filter.gab) {
149
1.72k
    JXL_RETURN_IF_ERROR(
150
1.72k
        builder.AddStage(GetGaborishStage(frame_header.loop_filter)));
151
1.72k
  }
152
153
13.3k
  {
154
13.3k
    const LoopFilter& lf = frame_header.loop_filter;
155
13.3k
    if (lf.epf_iters >= 3) {
156
737
      JXL_RETURN_IF_ERROR(
157
737
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::Zero)));
158
737
    }
159
13.3k
    if (lf.epf_iters >= 1) {
160
8.13k
      JXL_RETURN_IF_ERROR(
161
8.13k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::One)));
162
8.13k
    }
163
13.3k
    if (lf.epf_iters >= 2) {
164
8.12k
      JXL_RETURN_IF_ERROR(
165
8.12k
          builder.AddStage(GetEPFStage(lf, sigma, EpfStage::Two)));
166
8.12k
    }
167
13.3k
  }
168
169
13.3k
  bool late_ec_upsample = frame_header.upsampling != 1;
170
13.3k
  for (auto ecups : frame_header.extra_channel_upsampling) {
171
2.00k
    if (ecups != frame_header.upsampling) {
172
      // If patches are applied, either frame_header.upsampling == 1 or
173
      // late_ec_upsample is true.
174
176
      late_ec_upsample = false;
175
176
    }
176
2.00k
  }
177
178
13.3k
  if (!late_ec_upsample) {
179
4.43k
    for (size_t ec = 0; ec < frame_header.extra_channel_upsampling.size();
180
3.16k
         ec++) {
181
1.27k
      if (frame_header.extra_channel_upsampling[ec] != 1) {
182
176
        JXL_RETURN_IF_ERROR(builder.AddStage(GetUpsamplingStage(
183
176
            memory_manager, frame_header.nonserialized_metadata->transform_data,
184
176
            3 + ec,
185
176
            CeilLog2Nonzero(frame_header.extra_channel_upsampling[ec]))));
186
176
      }
187
1.27k
    }
188
3.16k
  }
189
190
13.3k
  if ((frame_header.flags & FrameHeader::kPatches) != 0) {
191
958
    JXL_RETURN_IF_ERROR(builder.AddStage(GetPatchesStage(
192
958
        &shared->image_features.patches,
193
958
        &frame_header.nonserialized_metadata->m.extra_channel_info)));
194
958
  }
195
13.3k
  if ((frame_header.flags & FrameHeader::kSplines) != 0) {
196
440
    JXL_RETURN_IF_ERROR(
197
440
        builder.AddStage(GetSplineStage(&shared->image_features.splines)));
198
440
  }
199
200
13.3k
  if (frame_header.upsampling != 1) {
201
10.1k
    size_t nb_channels =
202
10.1k
        3 +
203
10.1k
        (late_ec_upsample ? frame_header.extra_channel_upsampling.size() : 0);
204
41.4k
    for (size_t c = 0; c < nb_channels; c++) {
205
31.2k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetUpsamplingStage(
206
31.2k
          memory_manager, frame_header.nonserialized_metadata->transform_data,
207
31.2k
          c, CeilLog2Nonzero(frame_header.upsampling))));
208
31.2k
    }
209
10.1k
  }
210
13.3k
  if (options.render_noise) {
211
1.80k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetConvolveNoiseStage(num_c)));
212
1.80k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetAddNoiseStage(
213
1.80k
        shared->image_features.noise_params, shared->cmap.base(), num_c)));
214
1.80k
  }
215
13.3k
  if (frame_header.dc_level != 0) {
216
1.69k
    JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImage3FStage(
217
1.69k
        memory_manager, &shared_storage.dc_frames[frame_header.dc_level - 1])));
218
1.69k
  }
219
220
13.3k
  if (frame_header.CanBeReferenced() &&
221
10.5k
      frame_header.save_before_color_transform) {
222
723
    JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImageBundleStage(
223
723
        &frame_storage_for_referencing, output_encoding_info)));
224
723
  }
225
226
13.3k
  bool has_alpha = false;
227
13.3k
  size_t alpha_c = 0;
228
14.0k
  for (size_t i = 0; i < metadata->extra_channel_info.size(); i++) {
229
1.49k
    if (metadata->extra_channel_info[i].type == ExtraChannel::kAlpha) {
230
759
      has_alpha = true;
231
759
      alpha_c = 3 + i;
232
759
      break;
233
759
    }
234
1.49k
  }
235
236
13.3k
  if (fast_xyb_srgb8_conversion) {
237
#if !JXL_HIGH_PRECISION
238
    JXL_ENSURE(!NeedsBlending(frame_header));
239
    JXL_ENSURE(!frame_header.CanBeReferenced() ||
240
               frame_header.save_before_color_transform);
241
    JXL_ENSURE(!options.render_spotcolors ||
242
               !metadata->Find(ExtraChannel::kSpotColor));
243
    bool is_rgba = (main_output.format.num_channels == 4);
244
    uint8_t* rgb_output = reinterpret_cast<uint8_t*>(main_output.buffer);
245
    JXL_RETURN_IF_ERROR(builder.AddStage(
246
        GetFastXYBTosRGB8Stage(rgb_output, main_output.stride, width, height,
247
                               is_rgba, has_alpha, alpha_c)));
248
#endif
249
13.3k
  } else {
250
13.3k
    bool linear = false;
251
13.3k
    if (frame_header.color_transform == ColorTransform::kYCbCr) {
252
2.60k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetYCbCrStage()));
253
10.7k
    } else if (frame_header.color_transform == ColorTransform::kXYB) {
254
2.57k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetXYBStage(output_encoding_info)));
255
2.57k
      if (output_encoding_info.color_encoding.GetColorSpace() !=
256
2.57k
          ColorSpace::kXYB) {
257
2.57k
        linear = true;
258
2.57k
      }
259
2.57k
    }  // Nothing to do for kNone.
260
261
13.3k
    if (options.coalescing && NeedsBlending(frame_header)) {
262
2.64k
      if (linear) {
263
1.13k
        JXL_RETURN_IF_ERROR(
264
1.13k
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
265
1.13k
        linear = false;
266
1.13k
      }
267
2.64k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetBlendingStage(
268
2.64k
          frame_header, this, output_encoding_info.color_encoding)));
269
2.64k
    }
270
271
13.3k
    if (options.coalescing && frame_header.CanBeReferenced() &&
272
10.5k
        !frame_header.save_before_color_transform) {
273
9.78k
      if (linear) {
274
706
        JXL_RETURN_IF_ERROR(
275
706
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
276
706
        linear = false;
277
706
      }
278
9.78k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToImageBundleStage(
279
9.78k
          &frame_storage_for_referencing, output_encoding_info)));
280
9.78k
    }
281
282
13.3k
    if (options.render_spotcolors &&
283
13.3k
        frame_header.nonserialized_metadata->m.Find(ExtraChannel::kSpotColor)) {
284
384
      for (size_t i = 0; i < metadata->extra_channel_info.size(); i++) {
285
        // Don't use Find() because there may be multiple spot color channels.
286
195
        const ExtraChannelInfo& eci = metadata->extra_channel_info[i];
287
195
        if (eci.type == ExtraChannel::kSpotColor) {
288
189
          JXL_RETURN_IF_ERROR(
289
189
              builder.AddStage(GetSpotColorStage(i, eci.spot_color)));
290
189
        }
291
195
      }
292
189
    }
293
294
13.3k
    auto tone_mapping_stage = GetToneMappingStage(output_encoding_info);
295
13.3k
    if (tone_mapping_stage) {
296
0
      if (!linear) {
297
0
        auto to_linear_stage = GetToLinearStage(output_encoding_info);
298
0
        if (!to_linear_stage) {
299
0
          if (!output_encoding_info.cms_set) {
300
0
            return JXL_FAILURE("Cannot tonemap this colorspace without a CMS");
301
0
          }
302
0
          auto cms_stage = GetCmsStage(output_encoding_info);
303
0
          if (cms_stage) {
304
0
            JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
305
0
          }
306
0
        } else {
307
0
          JXL_RETURN_IF_ERROR(builder.AddStage(std::move(to_linear_stage)));
308
0
        }
309
0
        linear = true;
310
0
      }
311
0
      JXL_RETURN_IF_ERROR(builder.AddStage(std::move(tone_mapping_stage)));
312
0
    }
313
314
13.3k
    if (linear) {
315
741
      const size_t channels_src =
316
741
          (output_encoding_info.orig_color_encoding.IsCMYK()
317
741
               ? 4
318
741
               : output_encoding_info.orig_color_encoding.Channels());
319
741
      const size_t channels_dst =
320
741
          output_encoding_info.color_encoding.Channels();
321
741
      bool mixing_color_and_grey = (channels_dst != channels_src);
322
741
      if ((output_encoding_info.color_encoding_is_original) ||
323
397
          (!output_encoding_info.cms_set) || mixing_color_and_grey) {
324
        // in those cases we only need a linear stage in other cases we attempt
325
        // to obtain a cms stage: the cases are
326
        // - output_encoding_info.color_encoding_is_original: no cms stage
327
        // needed because it would be a no-op
328
        // - !output_encoding_info.cms_set: can't use the cms, so no point in
329
        // trying to add a cms stage
330
        // - mixing_color_and_grey: cms stage can't handle that
331
        // TODO(firsching): remove "mixing_color_and_grey" condition after
332
        // adding support for greyscale to cms stage.
333
344
        JXL_RETURN_IF_ERROR(
334
344
            builder.AddStage(GetFromLinearStage(output_encoding_info)));
335
397
      } else {
336
397
        if (!output_encoding_info.linear_color_encoding.CreateICC()) {
337
0
          return JXL_FAILURE("Failed to create ICC");
338
0
        }
339
397
        auto cms_stage = GetCmsStage(output_encoding_info);
340
397
        if (cms_stage) {
341
397
          JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
342
397
        }
343
397
      }
344
741
      linear = false;
345
12.5k
    } else {
346
12.5k
      auto cms_stage = GetCmsStage(output_encoding_info, false);
347
12.5k
      if (cms_stage) {
348
391
        JXL_RETURN_IF_ERROR(builder.AddStage(std::move(cms_stage)));
349
391
      }
350
12.5k
    }
351
13.3k
    (void)linear;
352
353
13.3k
    if (main_output.callback.IsPresent() || main_output.buffer) {
354
1.13k
      JXL_RETURN_IF_ERROR(builder.AddStage(GetWriteToOutputStage(
355
1.13k
          main_output, width, height, has_alpha, unpremul_alpha, alpha_c,
356
1.13k
          undo_orientation, extra_output, memory_manager)));
357
12.1k
    } else {
358
12.1k
      JXL_RETURN_IF_ERROR(builder.AddStage(
359
12.1k
          GetWriteToImageBundleStage(decoded, output_encoding_info)));
360
12.1k
    }
361
13.3k
  }
362
13.3k
  JXL_ASSIGN_OR_RETURN(render_pipeline,
363
13.3k
                       std::move(builder).Finalize(shared->frame_dim));
364
13.3k
  return render_pipeline->IsInitialized();
365
13.3k
}
366
367
}  // namespace jxl