summaryrefslogtreecommitdiffstats
path: root/third_party/jpeg-xl/lib/extras/enc/jxl.cc
blob: 633c6f2adee60b98365600cac4e2b9f8d524ede0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "lib/extras/enc/jxl.h"

#include <jxl/encode_cxx.h>

#include "lib/jxl/exif.h"

namespace jxl {
namespace extras {

JxlEncoderStatus SetOption(const JXLOption& opt,
                           JxlEncoderFrameSettings* settings) {
  return opt.is_float
             ? JxlEncoderFrameSettingsSetFloatOption(settings, opt.id, opt.fval)
             : JxlEncoderFrameSettingsSetOption(settings, opt.id, opt.ival);
}

bool SetFrameOptions(const std::vector<JXLOption>& options, size_t frame_index,
                     size_t* option_idx, JxlEncoderFrameSettings* settings) {
  while (*option_idx < options.size()) {
    const auto& opt = options[*option_idx];
    if (opt.frame_index > frame_index) {
      break;
    }
    if (JXL_ENC_SUCCESS != SetOption(opt, settings)) {
      fprintf(stderr, "Setting option id %d failed.\n", opt.id);
      return false;
    }
    (*option_idx)++;
  }
  return true;
}

bool EncodeImageJXL(const JXLCompressParams& params, const PackedPixelFile& ppf,
                    const std::vector<uint8_t>* jpeg_bytes,
                    std::vector<uint8_t>* compressed) {
  auto encoder = JxlEncoderMake(/*memory_manager=*/nullptr);
  JxlEncoder* enc = encoder.get();

  if (params.allow_expert_options) {
    JxlEncoderAllowExpertOptions(enc);
  }

  if (params.runner_opaque != nullptr &&
      JXL_ENC_SUCCESS != JxlEncoderSetParallelRunner(enc, params.runner,
                                                     params.runner_opaque)) {
    fprintf(stderr, "JxlEncoderSetParallelRunner failed\n");
    return false;
  }

  auto settings = JxlEncoderFrameSettingsCreate(enc, nullptr);
  size_t option_idx = 0;
  if (!SetFrameOptions(params.options, 0, &option_idx, settings)) {
    return false;
  }
  if (JXL_ENC_SUCCESS !=
      JxlEncoderSetFrameDistance(settings, params.distance)) {
    fprintf(stderr, "Setting frame distance failed.\n");
    return false;
  }

  bool use_boxes = !ppf.metadata.exif.empty() || !ppf.metadata.xmp.empty() ||
                   !ppf.metadata.jumbf.empty() || !ppf.metadata.iptc.empty();
  bool use_container = params.use_container || use_boxes ||
                       (jpeg_bytes && params.jpeg_store_metadata);

  if (JXL_ENC_SUCCESS !=
      JxlEncoderUseContainer(enc, static_cast<int>(use_container))) {
    fprintf(stderr, "JxlEncoderUseContainer failed.\n");
    return false;
  }

  if (jpeg_bytes) {
    if (params.jpeg_store_metadata &&
        JXL_ENC_SUCCESS != JxlEncoderStoreJPEGMetadata(enc, JXL_TRUE)) {
      fprintf(stderr, "Storing JPEG metadata failed.\n");
      return false;
    }
    if (JXL_ENC_SUCCESS != JxlEncoderAddJPEGFrame(settings, jpeg_bytes->data(),
                                                  jpeg_bytes->size())) {
      fprintf(stderr, "JxlEncoderAddJPEGFrame() failed.\n");
      return false;
    }
  } else {
    size_t num_alpha_channels = 0;  // Adjusted below.
    JxlBasicInfo basic_info = ppf.info;
    if (basic_info.alpha_bits > 0) num_alpha_channels = 1;
    if (params.intensity_target > 0) {
      basic_info.intensity_target = params.intensity_target;
    }
    basic_info.num_extra_channels =
        std::max<uint32_t>(num_alpha_channels, ppf.info.num_extra_channels);
    basic_info.num_color_channels = ppf.info.num_color_channels;
    const bool lossless = params.distance == 0;
    basic_info.uses_original_profile = lossless;
    if (params.override_bitdepth != 0) {
      basic_info.bits_per_sample = params.override_bitdepth;
      basic_info.exponent_bits_per_sample =
          params.override_bitdepth == 32 ? 8 : 0;
    }
    if (JXL_ENC_SUCCESS !=
        JxlEncoderSetCodestreamLevel(enc, params.codestream_level)) {
      fprintf(stderr, "Setting --codestream_level failed.\n");
      return false;
    }
    if (JXL_ENC_SUCCESS != JxlEncoderSetBasicInfo(enc, &basic_info)) {
      fprintf(stderr, "JxlEncoderSetBasicInfo() failed.\n");
      return false;
    }
    if (JXL_ENC_SUCCESS !=
        JxlEncoderSetFrameBitDepth(settings, &params.input_bitdepth)) {
      fprintf(stderr, "JxlEncoderSetFrameBitDepth() failed.\n");
      return false;
    }
    if (num_alpha_channels != 0 &&
        JXL_ENC_SUCCESS != JxlEncoderSetExtraChannelDistance(
                               settings, 0, params.alpha_distance)) {
      fprintf(stderr, "Setting alpha distance failed.\n");
      return false;
    }
    if (lossless &&
        JXL_ENC_SUCCESS != JxlEncoderSetFrameLossless(settings, JXL_TRUE)) {
      fprintf(stderr, "JxlEncoderSetFrameLossless() failed.\n");
      return false;
    }
    if (!ppf.icc.empty()) {
      if (JXL_ENC_SUCCESS !=
          JxlEncoderSetICCProfile(enc, ppf.icc.data(), ppf.icc.size())) {
        fprintf(stderr, "JxlEncoderSetICCProfile() failed.\n");
        return false;
      }
    } else {
      if (JXL_ENC_SUCCESS !=
          JxlEncoderSetColorEncoding(enc, &ppf.color_encoding)) {
        fprintf(stderr, "JxlEncoderSetColorEncoding() failed.\n");
        return false;
      }
    }

    if (use_boxes) {
      if (JXL_ENC_SUCCESS != JxlEncoderUseBoxes(enc)) {
        fprintf(stderr, "JxlEncoderUseBoxes() failed.\n");
        return false;
      }
      // Prepend 4 zero bytes to exif for tiff header offset
      std::vector<uint8_t> exif_with_offset;
      bool bigendian;
      if (IsExif(ppf.metadata.exif, &bigendian)) {
        exif_with_offset.resize(ppf.metadata.exif.size() + 4);
        memcpy(exif_with_offset.data() + 4, ppf.metadata.exif.data(),
               ppf.metadata.exif.size());
      }
      const struct BoxInfo {
        const char* type;
        const std::vector<uint8_t>& bytes;
      } boxes[] = {
          {"Exif", exif_with_offset},
          {"xml ", ppf.metadata.xmp},
          {"jumb", ppf.metadata.jumbf},
          {"xml ", ppf.metadata.iptc},
      };
      for (size_t i = 0; i < sizeof boxes / sizeof *boxes; ++i) {
        const BoxInfo& box = boxes[i];
        if (!box.bytes.empty() &&
            JXL_ENC_SUCCESS != JxlEncoderAddBox(enc, box.type, box.bytes.data(),
                                                box.bytes.size(),
                                                params.compress_boxes)) {
          fprintf(stderr, "JxlEncoderAddBox() failed (%s).\n", box.type);
          return false;
        }
      }
      JxlEncoderCloseBoxes(enc);
    }

    for (size_t num_frame = 0; num_frame < ppf.frames.size(); ++num_frame) {
      const jxl::extras::PackedFrame& pframe = ppf.frames[num_frame];
      const jxl::extras::PackedImage& pimage = pframe.color;
      JxlPixelFormat ppixelformat = pimage.format;
      if (JXL_ENC_SUCCESS !=
          JxlEncoderSetFrameHeader(settings, &pframe.frame_info)) {
        fprintf(stderr, "JxlEncoderSetFrameHeader() failed.\n");
        return false;
      }
      if (!SetFrameOptions(params.options, num_frame, &option_idx, settings)) {
        return false;
      }
      if (num_alpha_channels > 0) {
        JxlExtraChannelInfo extra_channel_info;
        JxlEncoderInitExtraChannelInfo(JXL_CHANNEL_ALPHA, &extra_channel_info);
        extra_channel_info.bits_per_sample = ppf.info.alpha_bits;
        extra_channel_info.exponent_bits_per_sample =
            ppf.info.alpha_exponent_bits;
        if (params.premultiply != -1) {
          if (params.premultiply != 0 && params.premultiply != 1) {
            fprintf(stderr, "premultiply must be one of: -1, 0, 1.\n");
            return false;
          }
          extra_channel_info.alpha_premultiplied = params.premultiply;
        }
        if (JXL_ENC_SUCCESS !=
            JxlEncoderSetExtraChannelInfo(enc, 0, &extra_channel_info)) {
          fprintf(stderr, "JxlEncoderSetExtraChannelInfo() failed.\n");
          return false;
        }
        // We take the extra channel blend info frame_info, but don't do
        // clamping.
        JxlBlendInfo extra_channel_blend_info =
            pframe.frame_info.layer_info.blend_info;
        extra_channel_blend_info.clamp = JXL_FALSE;
        JxlEncoderSetExtraChannelBlendInfo(settings, 0,
                                           &extra_channel_blend_info);
      }
      size_t num_interleaved_alpha =
          (ppixelformat.num_channels - ppf.info.num_color_channels);
      // Add extra channel info for the rest of the extra channels.
      for (size_t i = 0; i < ppf.info.num_extra_channels; ++i) {
        if (i < ppf.extra_channels_info.size()) {
          const auto& ec_info = ppf.extra_channels_info[i].ec_info;
          if (JXL_ENC_SUCCESS !=
              JxlEncoderSetExtraChannelInfo(enc, num_interleaved_alpha + i,
                                            &ec_info)) {
            fprintf(stderr, "JxlEncoderSetExtraChannelInfo() failed.\n");
            return false;
          }
        }
      }
      if (JXL_ENC_SUCCESS != JxlEncoderAddImageFrame(settings, &ppixelformat,
                                                     pimage.pixels(),
                                                     pimage.pixels_size)) {
        fprintf(stderr, "JxlEncoderAddImageFrame() failed.\n");
        return false;
      }
      // Only set extra channel buffer if it is provided non-interleaved.
      for (size_t i = 0; i < pframe.extra_channels.size(); ++i) {
        if (JXL_ENC_SUCCESS !=
            JxlEncoderSetExtraChannelBuffer(settings, &ppixelformat,
                                            pframe.extra_channels[i].pixels(),
                                            pframe.extra_channels[i].stride *
                                                pframe.extra_channels[i].ysize,
                                            num_interleaved_alpha + i)) {
          fprintf(stderr, "JxlEncoderSetExtraChannelBuffer() failed.\n");
          return false;
        }
      }
    }
  }
  JxlEncoderCloseInput(enc);
  // Reading compressed output
  compressed->clear();
  compressed->resize(4096);
  uint8_t* next_out = compressed->data();
  size_t avail_out = compressed->size() - (next_out - compressed->data());
  JxlEncoderStatus result = JXL_ENC_NEED_MORE_OUTPUT;
  while (result == JXL_ENC_NEED_MORE_OUTPUT) {
    result = JxlEncoderProcessOutput(enc, &next_out, &avail_out);
    if (result == JXL_ENC_NEED_MORE_OUTPUT) {
      size_t offset = next_out - compressed->data();
      compressed->resize(compressed->size() * 2);
      next_out = compressed->data() + offset;
      avail_out = compressed->size() - offset;
    }
  }
  compressed->resize(next_out - compressed->data());
  if (result != JXL_ENC_SUCCESS) {
    fprintf(stderr, "JxlEncoderProcessOutput failed.\n");
    return false;
  }
  return true;
}

}  // namespace extras
}  // namespace jxl