Coverage Report

Created: 2025-09-08 07:52

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