Coverage Report

Created: 2024-09-08 07:14

/src/libjxl/lib/extras/enc/jxl.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/extras/enc/jxl.h"
7
8
#include <jxl/codestream_header.h>
9
#include <jxl/encode.h>
10
#include <jxl/encode_cxx.h>
11
#include <jxl/types.h>
12
13
#include <algorithm>
14
#include <cstddef>
15
#include <cstdint>
16
#include <cstdio>
17
#include <vector>
18
19
#include "lib/extras/packed_image.h"
20
#include "lib/jxl/base/exif.h"
21
22
namespace jxl {
23
namespace extras {
24
25
JxlEncoderStatus SetOption(const JXLOption& opt,
26
0
                           JxlEncoderFrameSettings* settings) {
27
0
  return opt.is_float
28
0
             ? JxlEncoderFrameSettingsSetFloatOption(settings, opt.id, opt.fval)
29
0
             : JxlEncoderFrameSettingsSetOption(settings, opt.id, opt.ival);
30
0
}
31
32
bool SetFrameOptions(const std::vector<JXLOption>& options, size_t frame_index,
33
0
                     size_t* option_idx, JxlEncoderFrameSettings* settings) {
34
0
  while (*option_idx < options.size()) {
35
0
    const auto& opt = options[*option_idx];
36
0
    if (opt.frame_index > frame_index) {
37
0
      break;
38
0
    }
39
0
    if (JXL_ENC_SUCCESS != SetOption(opt, settings)) {
40
0
      fprintf(stderr, "Setting option id %d failed.\n", opt.id);
41
0
      return false;
42
0
    }
43
0
    (*option_idx)++;
44
0
  }
45
0
  return true;
46
0
}
47
48
bool SetupFrame(JxlEncoder* enc, JxlEncoderFrameSettings* settings,
49
                const JxlFrameHeader& frame_header,
50
                const JXLCompressParams& params, const PackedPixelFile& ppf,
51
                size_t frame_index, size_t num_alpha_channels,
52
0
                size_t num_interleaved_alpha, size_t& option_idx) {
53
0
  if (JXL_ENC_SUCCESS != JxlEncoderSetFrameHeader(settings, &frame_header)) {
54
0
    fprintf(stderr, "JxlEncoderSetFrameHeader() failed.\n");
55
0
    return false;
56
0
  }
57
0
  if (!SetFrameOptions(params.options, frame_index, &option_idx, settings)) {
58
0
    return false;
59
0
  }
60
0
  if (num_alpha_channels > 0) {
61
0
    JxlExtraChannelInfo extra_channel_info;
62
0
    JxlEncoderInitExtraChannelInfo(JXL_CHANNEL_ALPHA, &extra_channel_info);
63
0
    extra_channel_info.bits_per_sample = ppf.info.alpha_bits;
64
0
    extra_channel_info.exponent_bits_per_sample = ppf.info.alpha_exponent_bits;
65
0
    if (params.premultiply != -1) {
66
0
      if (params.premultiply != 0 && params.premultiply != 1) {
67
0
        fprintf(stderr, "premultiply must be one of: -1, 0, 1.\n");
68
0
        return false;
69
0
      }
70
0
      extra_channel_info.alpha_premultiplied = params.premultiply;
71
0
    }
72
0
    if (JXL_ENC_SUCCESS !=
73
0
        JxlEncoderSetExtraChannelInfo(enc, 0, &extra_channel_info)) {
74
0
      fprintf(stderr, "JxlEncoderSetExtraChannelInfo() failed.\n");
75
0
      return false;
76
0
    }
77
    // We take the extra channel blend info frame_info, but don't do
78
    // clamping.
79
0
    JxlBlendInfo extra_channel_blend_info = frame_header.layer_info.blend_info;
80
0
    extra_channel_blend_info.clamp = JXL_FALSE;
81
0
    JxlEncoderSetExtraChannelBlendInfo(settings, 0, &extra_channel_blend_info);
82
0
  }
83
  // Add extra channel info for the rest of the extra channels.
84
0
  for (size_t i = 0; i < ppf.info.num_extra_channels; ++i) {
85
0
    if (i < ppf.extra_channels_info.size()) {
86
0
      const auto& ec_info = ppf.extra_channels_info[i].ec_info;
87
0
      if (JXL_ENC_SUCCESS != JxlEncoderSetExtraChannelInfo(
88
0
                                 enc, num_interleaved_alpha + i, &ec_info)) {
89
0
        fprintf(stderr, "JxlEncoderSetExtraChannelInfo() failed.\n");
90
0
        return false;
91
0
      }
92
0
    }
93
0
  }
94
0
  return true;
95
0
}
96
97
0
bool ReadCompressedOutput(JxlEncoder* enc, std::vector<uint8_t>* compressed) {
98
0
  compressed->clear();
99
0
  compressed->resize(4096);
100
0
  uint8_t* next_out = compressed->data();
101
0
  size_t avail_out = compressed->size() - (next_out - compressed->data());
102
0
  JxlEncoderStatus result = JXL_ENC_NEED_MORE_OUTPUT;
103
0
  while (result == JXL_ENC_NEED_MORE_OUTPUT) {
104
0
    result = JxlEncoderProcessOutput(enc, &next_out, &avail_out);
105
0
    if (result == JXL_ENC_NEED_MORE_OUTPUT) {
106
0
      size_t offset = next_out - compressed->data();
107
0
      compressed->resize(compressed->size() * 2);
108
0
      next_out = compressed->data() + offset;
109
0
      avail_out = compressed->size() - offset;
110
0
    }
111
0
  }
112
0
  compressed->resize(next_out - compressed->data());
113
0
  if (result != JXL_ENC_SUCCESS) {
114
0
    fprintf(stderr, "JxlEncoderProcessOutput failed.\n");
115
0
    return false;
116
0
  }
117
0
  return true;
118
0
}
119
120
bool EncodeImageJXL(const JXLCompressParams& params, const PackedPixelFile& ppf,
121
                    const std::vector<uint8_t>* jpeg_bytes,
122
0
                    std::vector<uint8_t>* compressed) {
123
0
  auto encoder = JxlEncoderMake(params.memory_manager);
124
0
  JxlEncoder* enc = encoder.get();
125
126
0
  if (params.allow_expert_options) {
127
0
    JxlEncoderAllowExpertOptions(enc);
128
0
  }
129
130
0
  if (params.runner_opaque != nullptr &&
131
0
      JXL_ENC_SUCCESS != JxlEncoderSetParallelRunner(enc, params.runner,
132
0
                                                     params.runner_opaque)) {
133
0
    fprintf(stderr, "JxlEncoderSetParallelRunner failed\n");
134
0
    return false;
135
0
  }
136
137
0
  if (params.HasOutputProcessor() &&
138
0
      JXL_ENC_SUCCESS !=
139
0
          JxlEncoderSetOutputProcessor(enc, params.output_processor)) {
140
0
    fprintf(stderr, "JxlEncoderSetOutputProcessorfailed\n");
141
0
    return false;
142
0
  }
143
144
0
  auto* settings = JxlEncoderFrameSettingsCreate(enc, nullptr);
145
0
  size_t option_idx = 0;
146
0
  if (!SetFrameOptions(params.options, 0, &option_idx, settings)) {
147
0
    return false;
148
0
  }
149
0
  if (JXL_ENC_SUCCESS !=
150
0
      JxlEncoderSetFrameDistance(settings, params.distance)) {
151
0
    fprintf(stderr, "Setting frame distance failed.\n");
152
0
    return false;
153
0
  }
154
0
  if (params.debug_image) {
155
0
    JxlEncoderSetDebugImageCallback(settings, params.debug_image,
156
0
                                    params.debug_image_opaque);
157
0
  }
158
0
  if (params.stats) {
159
0
    JxlEncoderCollectStats(settings, params.stats);
160
0
  }
161
162
0
  bool has_jpeg_bytes = (jpeg_bytes != nullptr);
163
0
  bool use_boxes = !ppf.metadata.exif.empty() || !ppf.metadata.xmp.empty() ||
164
0
                   !ppf.metadata.jhgm.empty() || !ppf.metadata.jumbf.empty() ||
165
0
                   !ppf.metadata.iptc.empty();
166
0
  bool use_container = params.use_container || use_boxes ||
167
0
                       (has_jpeg_bytes && params.jpeg_store_metadata);
168
169
0
  if (JXL_ENC_SUCCESS !=
170
0
      JxlEncoderUseContainer(enc, static_cast<int>(use_container))) {
171
0
    fprintf(stderr, "JxlEncoderUseContainer failed.\n");
172
0
    return false;
173
0
  }
174
175
0
  if (has_jpeg_bytes) {
176
0
    if (params.jpeg_store_metadata &&
177
0
        JXL_ENC_SUCCESS != JxlEncoderStoreJPEGMetadata(enc, JXL_TRUE)) {
178
0
      fprintf(stderr, "Storing JPEG metadata failed.\n");
179
0
      return false;
180
0
    }
181
0
    if (params.jpeg_store_metadata && params.jpeg_strip_exif) {
182
0
      fprintf(stderr,
183
0
              "Cannot store metadata and strip exif at the same time.\n");
184
0
      return false;
185
0
    }
186
0
    if (params.jpeg_store_metadata && params.jpeg_strip_xmp) {
187
0
      fprintf(stderr,
188
0
              "Cannot store metadata and strip xmp at the same time.\n");
189
0
      return false;
190
0
    }
191
0
    if (!params.jpeg_store_metadata && params.jpeg_strip_exif) {
192
0
      JxlEncoderFrameSettingsSetOption(settings,
193
0
                                       JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF, 0);
194
0
    }
195
0
    if (!params.jpeg_store_metadata && params.jpeg_strip_xmp) {
196
0
      JxlEncoderFrameSettingsSetOption(settings,
197
0
                                       JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP, 0);
198
0
    }
199
0
    if (params.jpeg_strip_jumbf) {
200
0
      JxlEncoderFrameSettingsSetOption(
201
0
          settings, JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF, 0);
202
0
    }
203
0
    if (JXL_ENC_SUCCESS != JxlEncoderAddJPEGFrame(settings, jpeg_bytes->data(),
204
0
                                                  jpeg_bytes->size())) {
205
0
      JxlEncoderError error = JxlEncoderGetError(enc);
206
0
      if (error == JXL_ENC_ERR_BAD_INPUT) {
207
0
        fprintf(stderr,
208
0
                "Error while decoding the JPEG image. It may be corrupt (e.g. "
209
0
                "truncated) or of an unsupported type (e.g. CMYK).\n");
210
0
      } else if (error == JXL_ENC_ERR_JBRD) {
211
0
        fprintf(stderr,
212
0
                "JPEG bitstream reconstruction data could not be created. "
213
0
                "Possibly there is too much tail data.\n"
214
0
                "Try using --allow_jpeg_reconstruction 0, to losslessly "
215
0
                "recompress the JPEG image data without bitstream "
216
0
                "reconstruction data.\n");
217
0
      } else {
218
0
        fprintf(stderr, "JxlEncoderAddJPEGFrame() failed.\n");
219
0
      }
220
0
      return false;
221
0
    }
222
0
  } else {
223
0
    size_t num_alpha_channels = 0;  // Adjusted below.
224
0
    JxlBasicInfo basic_info = ppf.info;
225
0
    basic_info.xsize *= params.already_downsampled;
226
0
    basic_info.ysize *= params.already_downsampled;
227
0
    if (basic_info.alpha_bits > 0) num_alpha_channels = 1;
228
0
    if (params.intensity_target > 0) {
229
0
      basic_info.intensity_target = params.intensity_target;
230
0
    }
231
0
    basic_info.num_extra_channels =
232
0
        std::max<uint32_t>(num_alpha_channels, ppf.info.num_extra_channels);
233
0
    basic_info.num_color_channels = ppf.info.num_color_channels;
234
0
    const bool lossless = (params.distance == 0);
235
0
    auto non_perceptual_option = std::find_if(
236
0
        params.options.begin(), params.options.end(), [](JXLOption option) {
237
0
          return option.id ==
238
0
                 JXL_ENC_FRAME_SETTING_DISABLE_PERCEPTUAL_HEURISTICS;
239
0
        });
240
0
    const bool non_perceptual = non_perceptual_option != params.options.end() &&
241
0
                                non_perceptual_option->ival == 1;
242
0
    basic_info.uses_original_profile = TO_JXL_BOOL(lossless || non_perceptual);
243
0
    if (params.override_bitdepth != 0) {
244
0
      basic_info.bits_per_sample = params.override_bitdepth;
245
0
      basic_info.exponent_bits_per_sample =
246
0
          params.override_bitdepth == 32 ? 8 : 0;
247
0
    }
248
0
    if (JXL_ENC_SUCCESS !=
249
0
        JxlEncoderSetCodestreamLevel(enc, params.codestream_level)) {
250
0
      fprintf(stderr, "Setting --codestream_level failed.\n");
251
0
      return false;
252
0
    }
253
0
    if (JXL_ENC_SUCCESS != JxlEncoderSetBasicInfo(enc, &basic_info)) {
254
0
      fprintf(stderr, "JxlEncoderSetBasicInfo() failed.\n");
255
0
      return false;
256
0
    }
257
0
    if (JXL_ENC_SUCCESS !=
258
0
        JxlEncoderSetUpsamplingMode(enc, params.already_downsampled,
259
0
                                    params.upsampling_mode)) {
260
0
      fprintf(stderr, "JxlEncoderSetUpsamplingMode() failed.\n");
261
0
      return false;
262
0
    }
263
0
    if (JXL_ENC_SUCCESS !=
264
0
        JxlEncoderSetFrameBitDepth(settings, &ppf.input_bitdepth)) {
265
0
      fprintf(stderr, "JxlEncoderSetFrameBitDepth() failed.\n");
266
0
      return false;
267
0
    }
268
0
    if (num_alpha_channels != 0 &&
269
0
        JXL_ENC_SUCCESS != JxlEncoderSetExtraChannelDistance(
270
0
                               settings, 0, params.alpha_distance)) {
271
0
      fprintf(stderr, "Setting alpha distance failed.\n");
272
0
      return false;
273
0
    }
274
0
    if (lossless &&
275
0
        JXL_ENC_SUCCESS != JxlEncoderSetFrameLossless(settings, JXL_TRUE)) {
276
0
      fprintf(stderr, "JxlEncoderSetFrameLossless() failed.\n");
277
0
      return false;
278
0
    }
279
0
    if (ppf.primary_color_representation == PackedPixelFile::kIccIsPrimary) {
280
0
      if (JXL_ENC_SUCCESS !=
281
0
          JxlEncoderSetICCProfile(enc, ppf.icc.data(), ppf.icc.size())) {
282
0
        fprintf(stderr, "JxlEncoderSetICCProfile() failed.\n");
283
0
        return false;
284
0
      }
285
0
    } else {
286
0
      if (JXL_ENC_SUCCESS !=
287
0
          JxlEncoderSetColorEncoding(enc, &ppf.color_encoding)) {
288
0
        fprintf(stderr, "JxlEncoderSetColorEncoding() failed.\n");
289
0
        return false;
290
0
      }
291
0
    }
292
293
0
    if (use_boxes) {
294
0
      if (JXL_ENC_SUCCESS != JxlEncoderUseBoxes(enc)) {
295
0
        fprintf(stderr, "JxlEncoderUseBoxes() failed.\n");
296
0
        return false;
297
0
      }
298
      // Prepend 4 zero bytes to exif for tiff header offset
299
0
      std::vector<uint8_t> exif_with_offset;
300
0
      bool bigendian;
301
0
      if (IsExif(ppf.metadata.exif, &bigendian)) {
302
0
        exif_with_offset.resize(ppf.metadata.exif.size() + 4);
303
0
        memcpy(exif_with_offset.data() + 4, ppf.metadata.exif.data(),
304
0
               ppf.metadata.exif.size());
305
0
      }
306
0
      const struct BoxInfo {
307
0
        const char* type;
308
0
        const std::vector<uint8_t>& bytes;
309
0
      } boxes[] = {
310
0
          {"Exif", exif_with_offset},   {"xml ", ppf.metadata.xmp},
311
0
          {"jumb", ppf.metadata.jumbf}, {"xml ", ppf.metadata.iptc},
312
0
          {"jhgm", ppf.metadata.jhgm},
313
0
      };
314
0
      for (auto box : boxes) {
315
0
        if (!box.bytes.empty()) {
316
0
          if (JXL_ENC_SUCCESS !=
317
0
              JxlEncoderAddBox(enc, box.type, box.bytes.data(),
318
0
                               box.bytes.size(),
319
0
                               TO_JXL_BOOL(params.compress_boxes))) {
320
0
            fprintf(stderr, "JxlEncoderAddBox() failed (%s).\n", box.type);
321
0
            return false;
322
0
          }
323
0
        }
324
0
      }
325
0
      JxlEncoderCloseBoxes(enc);
326
0
    }
327
328
0
    for (size_t num_frame = 0; num_frame < ppf.frames.size(); ++num_frame) {
329
0
      const jxl::extras::PackedFrame& pframe = ppf.frames[num_frame];
330
0
      const jxl::extras::PackedImage& pimage = pframe.color;
331
0
      JxlPixelFormat ppixelformat = pimage.format;
332
0
      size_t num_interleaved_alpha =
333
0
          (ppixelformat.num_channels - ppf.info.num_color_channels);
334
0
      if (!SetupFrame(enc, settings, pframe.frame_info, params, ppf, num_frame,
335
0
                      num_alpha_channels, num_interleaved_alpha, option_idx)) {
336
0
        return false;
337
0
      }
338
0
      if (JXL_ENC_SUCCESS != JxlEncoderAddImageFrame(settings, &ppixelformat,
339
0
                                                     pimage.pixels(),
340
0
                                                     pimage.pixels_size)) {
341
0
        fprintf(stderr, "JxlEncoderAddImageFrame() failed.\n");
342
0
        return false;
343
0
      }
344
      // Only set extra channel buffer if it is provided non-interleaved.
345
0
      for (size_t i = 0; i < pframe.extra_channels.size(); ++i) {
346
0
        if (JXL_ENC_SUCCESS !=
347
0
            JxlEncoderSetExtraChannelBuffer(settings, &ppixelformat,
348
0
                                            pframe.extra_channels[i].pixels(),
349
0
                                            pframe.extra_channels[i].stride *
350
0
                                                pframe.extra_channels[i].ysize,
351
0
                                            num_interleaved_alpha + i)) {
352
0
          fprintf(stderr, "JxlEncoderSetExtraChannelBuffer() failed.\n");
353
0
          return false;
354
0
        }
355
0
      }
356
0
    }
357
0
    for (size_t fi = 0; fi < ppf.chunked_frames.size(); ++fi) {
358
0
      ChunkedPackedFrame& chunked_frame = ppf.chunked_frames[fi];
359
0
      size_t num_interleaved_alpha =
360
0
          (chunked_frame.format.num_channels - ppf.info.num_color_channels);
361
0
      if (!SetupFrame(enc, settings, chunked_frame.frame_info, params, ppf, fi,
362
0
                      num_alpha_channels, num_interleaved_alpha, option_idx)) {
363
0
        return false;
364
0
      }
365
0
      const bool last_frame = fi + 1 == ppf.chunked_frames.size();
366
0
      if (JXL_ENC_SUCCESS !=
367
0
          JxlEncoderAddChunkedFrame(settings, TO_JXL_BOOL(last_frame),
368
0
                                    chunked_frame.GetInputSource())) {
369
0
        fprintf(stderr, "JxlEncoderAddChunkedFrame() failed.\n");
370
0
        return false;
371
0
      }
372
0
    }
373
0
  }
374
0
  JxlEncoderCloseInput(enc);
375
0
  if (params.HasOutputProcessor()) {
376
0
    if (JXL_ENC_SUCCESS != JxlEncoderFlushInput(enc)) {
377
0
      fprintf(stderr, "JxlEncoderAddChunkedFrame() failed.\n");
378
0
      return false;
379
0
    }
380
0
  } else if (!ReadCompressedOutput(enc, compressed)) {
381
0
    return false;
382
0
  }
383
0
  return true;
384
0
}
385
386
}  // namespace extras
387
}  // namespace jxl