Coverage Report

Created: 2026-10-14 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/encode.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 <brotli/encode.h>
7
#include <jxl/cms.h>
8
#include <jxl/cms_interface.h>
9
#include <jxl/codestream_header.h>
10
#include <jxl/color_encoding.h>
11
#include <jxl/encode.h>
12
#include <jxl/jxl_export.h>
13
#include <jxl/memory_manager.h>
14
#include <jxl/parallel_runner.h>
15
#include <jxl/stats.h>
16
#include <jxl/types.h>
17
#include <jxl/version.h>
18
19
#include <algorithm>
20
#include <atomic>
21
#include <cstddef>
22
#include <cstdint>
23
#include <cstring>
24
#include <memory>
25
#include <string>
26
#include <utility>
27
#include <vector>
28
29
#include "lib/jxl/base/byte_order.h"
30
#include "lib/jxl/base/common.h"
31
#include "lib/jxl/base/compiler_specific.h"
32
#include "lib/jxl/base/data_parallel.h"
33
#include "lib/jxl/base/exif.h"
34
#include "lib/jxl/base/override.h"
35
#include "lib/jxl/base/printf_macros.h"
36
#include "lib/jxl/base/sanitizers.h"
37
#include "lib/jxl/base/span.h"
38
#include "lib/jxl/base/status.h"
39
#include "lib/jxl/cms/color_encoding_cms.h"
40
#include "lib/jxl/color_encoding_internal.h"
41
#include "lib/jxl/enc_aux_out.h"
42
#include "lib/jxl/enc_bit_writer.h"
43
#include "lib/jxl/enc_cache.h"
44
#include "lib/jxl/enc_fast_lossless.h"
45
#include "lib/jxl/enc_fields.h"
46
#include "lib/jxl/enc_frame.h"
47
#include "lib/jxl/enc_icc_codec.h"
48
#include "lib/jxl/enc_params.h"
49
#include "lib/jxl/encode_internal.h"
50
#include "lib/jxl/frame_header.h"
51
#include "lib/jxl/image_metadata.h"
52
#include "lib/jxl/jpeg/enc_jpeg_data.h"
53
#include "lib/jxl/jpeg/jpeg_data.h"
54
#include "lib/jxl/luminance.h"
55
#include "lib/jxl/memory_manager_internal.h"
56
#include "lib/jxl/modular/options.h"
57
#include "lib/jxl/padded_bytes.h"
58
59
struct JxlErrorOrStatus {
60
  // NOLINTNEXTLINE(google-explicit-constructor)
61
0
  operator jxl::Status() const {
62
0
    switch (error_) {
63
0
      case JXL_ENC_SUCCESS:
64
0
        return jxl::OkStatus();
65
0
      case JXL_ENC_NEED_MORE_OUTPUT:
66
0
        return jxl::StatusCode::kNotEnoughBytes;
67
0
      default:
68
0
        return jxl::StatusCode::kGenericError;
69
0
    }
70
0
  }
71
  // NOLINTNEXTLINE(google-explicit-constructor)
72
0
  operator JxlEncoderStatus() const { return error_; }
73
74
0
  static JxlErrorOrStatus Success() {
75
0
    return JxlErrorOrStatus(JXL_ENC_SUCCESS);
76
0
  }
77
78
0
  static JxlErrorOrStatus MoreOutput() {
79
0
    return JxlErrorOrStatus(JXL_ENC_NEED_MORE_OUTPUT);
80
0
  }
81
82
0
  static JxlErrorOrStatus Error() { return JxlErrorOrStatus(JXL_ENC_ERROR); }
83
84
 private:
85
0
  explicit JxlErrorOrStatus(JxlEncoderStatus error) : error_(error) {}
86
  JxlEncoderStatus error_;
87
};
88
89
// Debug-printing failure macro similar to JXL_FAILURE, but for the status code
90
// JXL_ENC_ERROR
91
#if (JXL_CRASH_ON_ERROR)
92
#define JXL_API_ERROR(enc, error_code, format, ...)                          \
93
  (enc->error = error_code,                                                  \
94
   ::jxl::Debug(("%s:%d: " format "\n"), __FILE__, __LINE__, ##__VA_ARGS__), \
95
   ::jxl::Abort(), JxlErrorOrStatus::Error())
96
#define JXL_API_ERROR_NOSET(format, ...)                                     \
97
  (::jxl::Debug(("%s:%d: " format "\n"), __FILE__, __LINE__, ##__VA_ARGS__), \
98
   ::jxl::Abort(), JxlErrorOrStatus::Error())
99
#else  // JXL_CRASH_ON_ERROR
100
#define JXL_API_ERROR(enc, error_code, format, ...)                            \
101
0
  (enc->error = error_code,                                                    \
102
0
   ((JXL_IS_DEBUG_BUILD) &&                                                    \
103
0
    ::jxl::Debug(("%s:%d: " format "\n"), __FILE__, __LINE__, ##__VA_ARGS__)), \
104
0
   JxlErrorOrStatus::Error())
105
#define JXL_API_ERROR_NOSET(format, ...)                                     \
106
0
  (::jxl::Debug(("%s:%d: " format "\n"), __FILE__, __LINE__, ##__VA_ARGS__), \
107
0
   JxlErrorOrStatus::Error())
108
#endif  // JXL_CRASH_ON_ERROR
109
110
jxl::StatusOr<JxlOutputProcessorBuffer>
111
JxlEncoderOutputProcessorWrapper::GetBuffer(size_t min_size,
112
0
                                            size_t requested_size) {
113
0
  JXL_ENSURE(min_size > 0);
114
0
  JXL_ENSURE(!has_buffer_);
115
0
  if (stop_requested_) return jxl::StatusCode::kNotEnoughBytes;
116
0
  requested_size = std::max(min_size, requested_size);
117
118
  // If we support seeking, output_position_ == position_.
119
0
  if (external_output_processor_ && external_output_processor_->seek) {
120
0
    JXL_ENSURE(output_position_ == position_);
121
0
  }
122
  // Otherwise, output_position_ <= position_.
123
0
  JXL_ENSURE(output_position_ <= position_);
124
0
  size_t additional_size = position_ - output_position_;
125
0
  JXL_ENSURE(memory_manager_ != nullptr);
126
127
0
  if (external_output_processor_) {
128
    // TODO(veluca): here, we cannot just ask for a larger buffer, as it will be
129
    // released with a prefix of the buffer that has not been written yet.
130
    // Figure out if there is a good way to do this more efficiently.
131
0
    if (additional_size == 0) {
132
0
      size_t size = requested_size;
133
0
      uint8_t* user_buffer =
134
0
          static_cast<uint8_t*>(external_output_processor_->get_buffer(
135
0
              external_output_processor_->opaque, &size));
136
0
      if (size == 0 || user_buffer == nullptr) {
137
0
        stop_requested_ = true;
138
0
        return jxl::StatusCode::kNotEnoughBytes;
139
0
      }
140
0
      if (size < min_size) {
141
0
        external_output_processor_->release_buffer(
142
0
            external_output_processor_->opaque, 0);
143
0
      } else {
144
0
        internal_buffers_.emplace(position_, InternalBuffer(memory_manager_));
145
0
        has_buffer_ = true;
146
0
        return JxlOutputProcessorBuffer(user_buffer, size, 0, this);
147
0
      }
148
0
    }
149
0
  } else if (avail_out_ != nullptr) {
150
0
    if (min_size + additional_size < *avail_out_) {
151
0
      internal_buffers_.emplace(position_, InternalBuffer(memory_manager_));
152
0
      has_buffer_ = true;
153
0
      return JxlOutputProcessorBuffer(*next_out_ + additional_size,
154
0
                                      *avail_out_ - additional_size, 0, this);
155
0
    }
156
0
  }
157
158
  // Otherwise, we need to allocate our own buffer.
159
0
  auto it =
160
0
      internal_buffers_.emplace(position_, InternalBuffer(memory_manager_))
161
0
          .first;
162
0
  InternalBuffer& buffer = it->second;
163
0
  size_t alloc_size = requested_size;
164
0
  it++;
165
0
  if (it != internal_buffers_.end()) {
166
0
    alloc_size = std::min(alloc_size, it->first - position_);
167
0
    JXL_ENSURE(alloc_size >= min_size);
168
0
  }
169
0
  JXL_RETURN_IF_ERROR(buffer.owned_data.resize(alloc_size));
170
0
  has_buffer_ = true;
171
0
  return JxlOutputProcessorBuffer(buffer.owned_data.data(), alloc_size, 0,
172
0
                                  this);
173
0
}
174
175
0
jxl::Status JxlEncoderOutputProcessorWrapper::Seek(size_t pos) {
176
0
  JXL_ENSURE(!has_buffer_);
177
0
  if (external_output_processor_ && external_output_processor_->seek) {
178
0
    external_output_processor_->seek(external_output_processor_->opaque, pos);
179
0
    output_position_ = pos;
180
0
  }
181
0
  JXL_ENSURE(pos >= finalized_position_);
182
0
  position_ = pos;
183
0
  return true;
184
0
}
185
186
0
jxl::Status JxlEncoderOutputProcessorWrapper::SetFinalizedPosition() {
187
0
  JXL_ENSURE(!has_buffer_);
188
0
  if (external_output_processor_ && external_output_processor_->seek) {
189
0
    external_output_processor_->set_finalized_position(
190
0
        external_output_processor_->opaque, position_);
191
0
  }
192
0
  finalized_position_ = position_;
193
0
  JXL_RETURN_IF_ERROR(FlushOutput(next_out_, avail_out_));
194
0
  return true;
195
0
}
196
197
jxl::Status JxlEncoderOutputProcessorWrapper::SetAvailOut(uint8_t** next_out,
198
0
                                                          size_t* avail_out) {
199
0
  JXL_ENSURE(!external_output_processor_);
200
0
  avail_out_ = avail_out;
201
0
  next_out_ = next_out;
202
0
  JXL_RETURN_IF_ERROR(FlushOutput(next_out_, avail_out_));
203
0
  return true;
204
0
}
205
206
jxl::Status JxlEncoderOutputProcessorWrapper::CopyOutput(
207
0
    std::vector<uint8_t>& output) {
208
0
  output.resize(64);
209
0
  size_t avail_out = output.size();
210
0
  uint8_t* next_out = output.data();
211
0
  while (HasOutputToWrite()) {
212
0
    JXL_RETURN_IF_ERROR(FlushOutput(&next_out, &avail_out));
213
0
    if (avail_out == 0) {
214
0
      size_t offset = next_out - output.data();
215
0
      output.resize(output.size() * 2);
216
0
      next_out = output.data() + offset;
217
0
      avail_out = output.size() - offset;
218
0
    }
219
0
  }
220
0
  output.resize(output.size() - avail_out);
221
0
  return true;
222
0
}
223
224
0
jxl::Status JxlEncoderOutputProcessorWrapper::ReleaseBuffer(size_t bytes_used) {
225
0
  JXL_ENSURE(has_buffer_);
226
0
  has_buffer_ = false;
227
0
  auto it = internal_buffers_.find(position_);
228
0
  JXL_ENSURE(it != internal_buffers_.end());
229
0
  if (bytes_used == 0) {
230
0
    if (external_output_processor_) {
231
0
      external_output_processor_->release_buffer(
232
0
          external_output_processor_->opaque, bytes_used);
233
0
    }
234
0
    internal_buffers_.erase(it);
235
0
    return true;
236
0
  }
237
0
  it->second.written_bytes = bytes_used;
238
0
  position_ += bytes_used;
239
240
0
  auto it_to_next = it;
241
0
  it_to_next++;
242
0
  if (it_to_next != internal_buffers_.end()) {
243
0
    JXL_ENSURE(it_to_next->first >= position_);
244
0
  }
245
246
0
  if (external_output_processor_) {
247
    // If the buffer was given by the user, tell the user it is not needed
248
    // anymore.
249
0
    if (it->second.owned_data.empty()) {
250
0
      external_output_processor_->release_buffer(
251
0
          external_output_processor_->opaque, bytes_used);
252
      // If we don't support seeking, this implies we will never modify again
253
      // the bytes that were written so far. Advance the finalized position and
254
      // flush the output to clean up the internal buffers.
255
0
      if (!external_output_processor_->seek) {
256
0
        JXL_RETURN_IF_ERROR(SetFinalizedPosition());
257
0
        JXL_ENSURE(output_position_ == finalized_position_);
258
0
        JXL_ENSURE(output_position_ == position_);
259
0
      } else {
260
        // Otherwise, advance the output position accordingly.
261
0
        output_position_ += bytes_used;
262
0
        JXL_ENSURE(output_position_ >= finalized_position_);
263
0
        JXL_ENSURE(output_position_ == position_);
264
0
      }
265
0
    } else if (external_output_processor_->seek) {
266
      // If we had buffered the data internally, flush it out to the external
267
      // processor if we can.
268
0
      external_output_processor_->seek(external_output_processor_->opaque,
269
0
                                       position_ - bytes_used);
270
0
      output_position_ = position_ - bytes_used;
271
0
      while (output_position_ < position_) {
272
0
        size_t num_to_write = position_ - output_position_;
273
0
        if (!AppendBufferToExternalProcessor(it->second.owned_data.data() +
274
0
                                                 output_position_ - position_ +
275
0
                                                 bytes_used,
276
0
                                             num_to_write)) {
277
0
          return true;
278
0
        }
279
0
      }
280
0
      it->second.owned_data.clear();
281
0
    }
282
0
  }
283
0
  return true;
284
0
}
285
286
// Tries to write all the bytes up to the finalized position.
287
jxl::Status JxlEncoderOutputProcessorWrapper::FlushOutput(uint8_t** next_out,
288
0
                                                          size_t* avail_out) {
289
0
  JXL_ENSURE(!has_buffer_);
290
0
  if (!external_output_processor_ && !avail_out) {
291
0
    return true;
292
0
  }
293
0
  while (output_position_ < finalized_position_ &&
294
0
         (avail_out == nullptr || *avail_out > 0)) {
295
0
    JXL_ENSURE(!internal_buffers_.empty());
296
0
    auto it = internal_buffers_.begin();
297
    // If this fails, we are trying to move the finalized position past data
298
    // that was not written yet. This is a library programming error.
299
0
    JXL_ENSURE(output_position_ >= it->first);
300
0
    JXL_ENSURE(it->second.written_bytes != 0);
301
0
    size_t buffer_last_byte = it->first + it->second.written_bytes;
302
0
    if (!it->second.owned_data.empty()) {
303
0
      size_t start_in_buffer = output_position_ - it->first;
304
      // Guaranteed by the invariant on `internal_buffers_`.
305
0
      JXL_ENSURE(buffer_last_byte > output_position_);
306
0
      size_t num_to_write =
307
0
          std::min(buffer_last_byte, finalized_position_) - output_position_;
308
0
      if (avail_out != nullptr) {
309
0
        size_t n = std::min(num_to_write, *avail_out);
310
0
        memcpy(*next_out, it->second.owned_data.data() + start_in_buffer, n);
311
0
        *avail_out -= n;
312
0
        *next_out += n;
313
0
        output_position_ += n;
314
0
      } else {
315
0
        JXL_ENSURE(external_output_processor_);
316
0
        if (!AppendBufferToExternalProcessor(
317
0
                it->second.owned_data.data() + start_in_buffer, num_to_write)) {
318
0
          return true;
319
0
        }
320
0
      }
321
0
    } else {
322
0
      size_t advance =
323
0
          std::min(buffer_last_byte, finalized_position_) - output_position_;
324
0
      output_position_ += advance;
325
0
      if (avail_out != nullptr) {
326
0
        *next_out += advance;
327
0
        *avail_out -= advance;
328
0
      }
329
0
    }
330
0
    if (buffer_last_byte == output_position_) {
331
0
      internal_buffers_.erase(it);
332
0
    }
333
0
    if (external_output_processor_ && !external_output_processor_->seek) {
334
0
      external_output_processor_->set_finalized_position(
335
0
          external_output_processor_->opaque, output_position_);
336
0
    }
337
0
  }
338
0
  return true;
339
0
}
340
341
bool JxlEncoderOutputProcessorWrapper::AppendBufferToExternalProcessor(
342
0
    void* data, size_t count) {
343
0
  JXL_DASSERT(external_output_processor_);
344
0
  size_t n = count;
345
0
  void* user_buffer = external_output_processor_->get_buffer(
346
0
      external_output_processor_->opaque, &n);
347
0
  if (user_buffer == nullptr || n == 0) {
348
0
    stop_requested_ = true;
349
0
    return false;
350
0
  }
351
0
  n = std::min(n, count);
352
0
  memcpy(user_buffer, data, n);
353
0
  external_output_processor_->release_buffer(external_output_processor_->opaque,
354
0
                                             n);
355
0
  output_position_ += n;
356
0
  return true;
357
0
}
358
359
namespace jxl {
360
361
size_t WriteBoxHeader(const jxl::BoxType& type, size_t size, bool unbounded,
362
0
                      bool force_large_box, uint8_t* output) {
363
0
  uint64_t box_size = 0;
364
0
  bool large_size = false;
365
0
  if (!unbounded) {
366
0
    if (box_size >= kLargeBoxContentSizeThreshold || force_large_box) {
367
0
      large_size = true;
368
      // TODO(firsching): send a separate CL for this (+ test),
369
      // quick fix in the old code: box_size += 8
370
0
      box_size = size + kLargeBoxHeaderSize;
371
0
    } else {
372
0
      box_size = size + kSmallBoxHeaderSize;
373
0
    }
374
0
  }
375
376
0
  size_t idx = 0;
377
0
  {
378
0
    const uint64_t store = large_size ? 1 : box_size;
379
0
    for (size_t i = 0; i < 4; i++) {
380
0
      output[idx++] = store >> (8 * (3 - i)) & 0xff;
381
0
    }
382
0
  }
383
0
  for (size_t i = 0; i < 4; i++) {
384
0
    output[idx++] = type[i];
385
0
  }
386
387
0
  if (large_size) {
388
0
    for (size_t i = 0; i < 8; i++) {
389
0
      output[idx++] = box_size >> (8 * (7 - i)) & 0xff;
390
0
    }
391
0
  }
392
0
  return idx;
393
0
}
394
}  // namespace jxl
395
396
template <typename WriteBox>
397
jxl::Status JxlEncoder::AppendBox(const jxl::BoxType& type, bool unbounded,
398
                                  size_t box_max_size,
399
0
                                  const WriteBox& write_box) {
400
0
  size_t current_position = output_processor.CurrentPosition();
401
0
  bool large_box = false;
402
0
  size_t box_header_size = 0;
403
0
  if (box_max_size >= jxl::kLargeBoxContentSizeThreshold && !unbounded) {
404
0
    box_header_size = jxl::kLargeBoxHeaderSize;
405
0
    large_box = true;
406
0
  } else {
407
0
    box_header_size = jxl::kSmallBoxHeaderSize;
408
0
  }
409
0
  JXL_RETURN_IF_ERROR(
410
0
      output_processor.Seek(current_position + box_header_size));
411
0
  size_t box_contents_start = output_processor.CurrentPosition();
412
0
  JXL_RETURN_IF_ERROR(write_box());
413
0
  size_t box_contents_end = output_processor.CurrentPosition();
414
0
  JXL_RETURN_IF_ERROR(output_processor.Seek(current_position));
415
0
  JXL_ENSURE(box_contents_end >= box_contents_start);
416
0
  if (box_contents_end - box_contents_start > box_max_size) {
417
0
    return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
418
0
                         "Internal error: upper bound on box size was "
419
0
                         "violated, upper bound: %" PRIuS ", actual: %" PRIuS,
420
0
                         box_max_size, box_contents_end - box_contents_start);
421
0
  }
422
  // We need to release the buffer before Seek.
423
0
  {
424
0
    JXL_ASSIGN_OR_RETURN(
425
0
        auto buffer,
426
0
        output_processor.GetBuffer(box_contents_start - current_position));
427
0
    const size_t n =
428
0
        jxl::WriteBoxHeader(type, box_contents_end - box_contents_start,
429
0
                            unbounded, large_box, buffer.data());
430
0
    JXL_ENSURE(n == box_header_size);
431
0
    JXL_RETURN_IF_ERROR(buffer.advance(n));
432
0
  }
433
0
  JXL_RETURN_IF_ERROR(output_processor.Seek(box_contents_end));
434
0
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
435
0
  return jxl::OkStatus();
436
0
}
Unexecuted instantiation: encode.cc:jxl::Status JxlEncoder::AppendBox<JxlEncoder::ProcessOneEnqueuedInput()::$_2>(std::__1::array<unsigned char, 4ul> const&, bool, unsigned long, JxlEncoder::ProcessOneEnqueuedInput()::$_2 const&)
Unexecuted instantiation: jxl::Status JxlEncoder::AppendBox<JxlEncoder::AppendBoxWithContents<std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > >(std::__1::array<unsigned char, 4ul> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&)::{lambda()#1}>(std::__1::array<unsigned char, 4ul> const&, bool, unsigned long, JxlEncoder::AppendBoxWithContents<std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > >(std::__1::array<unsigned char, 4ul> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&)::{lambda()#1} const&)
Unexecuted instantiation: jxl::Status JxlEncoder::AppendBox<JxlEncoder::AppendBoxWithContents<jxl::Span<unsigned char const> >(std::__1::array<unsigned char, 4ul> const&, jxl::Span<unsigned char const> const&)::{lambda()#1}>(std::__1::array<unsigned char, 4ul> const&, bool, unsigned long, JxlEncoder::AppendBoxWithContents<jxl::Span<unsigned char const> >(std::__1::array<unsigned char, 4ul> const&, jxl::Span<unsigned char const> const&)::{lambda()#1} const&)
Unexecuted instantiation: jxl::Status JxlEncoder::AppendBox<JxlEncoder::AppendBoxWithContents<jxl::PaddedBytes>(std::__1::array<unsigned char, 4ul> const&, jxl::PaddedBytes const&)::{lambda()#1}>(std::__1::array<unsigned char, 4ul> const&, bool, unsigned long, JxlEncoder::AppendBoxWithContents<jxl::PaddedBytes>(std::__1::array<unsigned char, 4ul> const&, jxl::PaddedBytes const&)::{lambda()#1} const&)
437
438
template <typename BoxContents>
439
jxl::Status JxlEncoder::AppendBoxWithContents(const jxl::BoxType& type,
440
0
                                              const BoxContents& contents) {
441
0
  size_t size = std::end(contents) - std::begin(contents);
442
0
  return AppendBox(type, /*unbounded=*/false, size,
443
0
                   [&]() { return AppendData(output_processor, contents); });
Unexecuted instantiation: JxlEncoder::AppendBoxWithContents<std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > >(std::__1::array<unsigned char, 4ul> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&)::{lambda()#1}::operator()() const
Unexecuted instantiation: JxlEncoder::AppendBoxWithContents<jxl::Span<unsigned char const> >(std::__1::array<unsigned char, 4ul> const&, jxl::Span<unsigned char const> const&)::{lambda()#1}::operator()() const
Unexecuted instantiation: JxlEncoder::AppendBoxWithContents<jxl::PaddedBytes>(std::__1::array<unsigned char, 4ul> const&, jxl::PaddedBytes const&)::{lambda()#1}::operator()() const
444
0
}
Unexecuted instantiation: jxl::Status JxlEncoder::AppendBoxWithContents<std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > >(std::__1::array<unsigned char, 4ul> const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&)
Unexecuted instantiation: jxl::Status JxlEncoder::AppendBoxWithContents<jxl::Span<unsigned char const> >(std::__1::array<unsigned char, 4ul> const&, jxl::Span<unsigned char const> const&)
Unexecuted instantiation: jxl::Status JxlEncoder::AppendBoxWithContents<jxl::PaddedBytes>(std::__1::array<unsigned char, 4ul> const&, jxl::PaddedBytes const&)
445
446
0
uint32_t JxlEncoderVersion(void) {
447
0
  return JPEGXL_MAJOR_VERSION * 1000000 + JPEGXL_MINOR_VERSION * 1000 +
448
0
         JPEGXL_PATCH_VERSION;
449
0
}
450
451
namespace {
452
453
constexpr int kStripAlphaAuto = -1;
454
constexpr int kStripAlphaForce = 1;
455
constexpr int kStripAlphaIfOpaque = 2;
456
457
0
void WriteJxlpBoxCounter(uint32_t counter, bool last, uint8_t* buffer) {
458
0
  if (last) counter |= 0x80000000;
459
0
  for (size_t i = 0; i < 4; i++) {
460
0
    buffer[i] = counter >> (8 * (3 - i)) & 0xff;
461
0
  }
462
0
}
463
464
jxl::Status WriteJxlpBoxCounter(uint32_t counter, bool last,
465
0
                                JxlOutputProcessorBuffer& buffer) {
466
0
  uint8_t buf[4];
467
0
  WriteJxlpBoxCounter(counter, last, buf);
468
0
  JXL_RETURN_IF_ERROR(buffer.append(buf, 4));
469
0
  return true;
470
0
}
471
472
void QueueFrame(
473
    const JxlEncoderFrameSettings* frame_settings,
474
0
    jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedFrame>& frame) {
475
0
  if (frame_settings->values.lossless) {
476
0
    frame->option_values.cparams.SetLossless();
477
0
  }
478
479
0
  jxl::JxlEncoderQueuedInput queued_input(frame_settings->enc->memory_manager);
480
0
  int om = frame->option_values.cparams.output_mode;
481
0
  if (om < 0) om = (frame->option_values.cparams.buffering == 3 ? 1 : 0);
482
0
  queued_input.output_mode = om;
483
0
  queued_input.frame = std::move(frame);
484
0
  frame_settings->enc->input_queue.emplace_back(std::move(queued_input));
485
0
  frame_settings->enc->num_queued_frames++;
486
0
}
487
488
void QueueFastLosslessFrame(const JxlEncoderFrameSettings* frame_settings,
489
0
                            JxlFastLosslessFrameState* fast_lossless_frame) {
490
0
  jxl::JxlEncoderQueuedInput queued_input(frame_settings->enc->memory_manager);
491
0
  queued_input.fast_lossless_frame.reset(fast_lossless_frame);
492
0
  int om = frame_settings->values.cparams.output_mode;
493
0
  if (om < 0) om = (frame_settings->values.cparams.buffering == 3 ? 1 : 0);
494
0
  if (om == 2) om = 1;  // OOO streaming not implemented for fast_lossless
495
0
  queued_input.output_mode = om;
496
0
  frame_settings->enc->input_queue.emplace_back(std::move(queued_input));
497
0
  frame_settings->enc->num_queued_frames++;
498
0
}
499
500
void QueueBox(JxlEncoder* enc,
501
0
              jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedBox>& box) {
502
0
  jxl::JxlEncoderQueuedInput queued_input(enc->memory_manager);
503
0
  queued_input.box = std::move(box);
504
0
  enc->input_queue.emplace_back(std::move(queued_input));
505
0
  enc->num_queued_boxes++;
506
0
}
507
508
// TODO(lode): share this code and the Brotli compression code in enc_jpeg_data
509
JxlEncoderStatus BrotliCompress(int quality, const uint8_t* in, size_t in_size,
510
0
                                jxl::PaddedBytes* out) {
511
0
  JxlMemoryManager* memory_manager = out->memory_manager();
512
0
  std::unique_ptr<BrotliEncoderState, decltype(BrotliEncoderDestroyInstance)*>
513
0
      enc(BrotliEncoderCreateInstance(nullptr, nullptr, nullptr),
514
0
          BrotliEncoderDestroyInstance);
515
0
  if (!enc) return JXL_API_ERROR_NOSET("BrotliEncoderCreateInstance failed");
516
517
0
  BrotliEncoderSetParameter(enc.get(), BROTLI_PARAM_QUALITY, quality);
518
0
  BrotliEncoderSetParameter(enc.get(), BROTLI_PARAM_SIZE_HINT, in_size);
519
520
0
  constexpr size_t kBufferSize = 128 * 1024;
521
0
#define QUIT(message) return JXL_API_ERROR_NOSET(message)
522
0
  JXL_ASSIGN_OR_QUIT(
523
0
      jxl::PaddedBytes temp_buffer,
524
0
      jxl::PaddedBytes::WithInitialSpace(memory_manager, kBufferSize),
525
0
      "Initialization of PaddedBytes failed");
526
0
#undef QUIT
527
528
0
  size_t avail_in = in_size;
529
0
  const uint8_t* next_in = in;
530
531
0
  size_t total_out = 0;
532
533
0
  for (;;) {
534
0
    size_t avail_out = kBufferSize;
535
0
    uint8_t* next_out = temp_buffer.data();
536
0
    jxl::msan::MemoryIsInitialized(next_in, avail_in);
537
0
    if (!BrotliEncoderCompressStream(enc.get(), BROTLI_OPERATION_FINISH,
538
0
                                     &avail_in, &next_in, &avail_out, &next_out,
539
0
                                     &total_out)) {
540
0
      return JXL_API_ERROR_NOSET("Brotli compression failed");
541
0
    }
542
0
    size_t out_size = next_out - temp_buffer.data();
543
0
    jxl::msan::UnpoisonMemory(next_out - out_size, out_size);
544
0
    if (!out->resize(out->size() + out_size)) {
545
0
      return JXL_API_ERROR_NOSET("resizing of PaddedBytes failed");
546
0
    }
547
548
0
    memcpy(out->data() + out->size() - out_size, temp_buffer.data(), out_size);
549
0
    if (BrotliEncoderIsFinished(enc.get())) break;
550
0
  }
551
552
0
  return JxlErrorOrStatus::Success();
553
0
}
554
555
// The JXL codestream can have level 5 or level 10. Levels have certain
556
// restrictions such as max allowed image dimensions. This function checks the
557
// level required to support the current encoder settings. The debug_string is
558
// intended to be used for developer API error messages, and may be set to
559
// nullptr.
560
0
int VerifyLevelSettings(const JxlEncoder* enc, std::string* debug_string) {
561
0
  const auto& m = enc->metadata.m;
562
563
0
  uint64_t xsize = enc->metadata.size.xsize();
564
0
  uint64_t ysize = enc->metadata.size.ysize();
565
  // The uncompressed ICC size, if it is used.
566
0
  size_t icc_size = 0;
567
0
  if (m.color_encoding.WantICC()) {
568
0
    icc_size = m.color_encoding.ICC().size();
569
0
  }
570
571
  // Level 10 checks
572
573
0
  if (xsize > (1ull << 30ull) || ysize > (1ull << 30ull) ||
574
0
      xsize * ysize > (1ull << 40ull)) {
575
0
    if (debug_string) *debug_string = "Too large image dimensions";
576
0
    return -1;
577
0
  }
578
0
  if (icc_size > (1ull << 28)) {
579
0
    if (debug_string) *debug_string = "Too large ICC profile size";
580
0
    return -1;
581
0
  }
582
0
  if (m.num_extra_channels > 256) {
583
0
    if (debug_string) *debug_string = "Too many extra channels";
584
0
    return -1;
585
0
  }
586
587
  // Level 5 checks
588
589
0
  if (!m.modular_16_bit_buffer_sufficient) {
590
0
    if (debug_string) *debug_string = "Too high modular bit depth";
591
0
    return 10;
592
0
  }
593
0
  if (xsize > (1ull << 18ull) || ysize > (1ull << 18ull) ||
594
0
      xsize * ysize > (1ull << 28ull)) {
595
0
    if (debug_string) *debug_string = "Too large image dimensions";
596
0
    return 10;
597
0
  }
598
0
  if (icc_size > (1ull << 22)) {
599
0
    if (debug_string) *debug_string = "Too large ICC profile";
600
0
    return 10;
601
0
  }
602
0
  if (m.num_extra_channels > 4) {
603
0
    if (debug_string) *debug_string = "Too many extra channels";
604
0
    return 10;
605
0
  }
606
0
  for (const auto& eci : m.extra_channel_info) {
607
0
    if (eci.type == jxl::ExtraChannel::kBlack) {
608
0
      if (debug_string) *debug_string = "CMYK channel not allowed";
609
0
      return 10;
610
0
    }
611
0
  }
612
613
  // TODO(lode): also need to check if consecutive composite-still frames total
614
  // pixel amount doesn't exceed 2**28 in the case of level 5. This should be
615
  // done when adding frame and requires ability to add composite still frames
616
  // to be added first.
617
618
  // TODO(lode): also need to check animation duration of a frame. This should
619
  // be done when adding frame, but first requires implementing setting the
620
  // JxlFrameHeader for a frame.
621
622
  // TODO(lode): also need to check properties such as num_splines, num_patches,
623
  // modular_16bit_buffers and multiple properties of modular trees. However
624
  // these are not user-set properties so cannot be checked here, but decisions
625
  // the C++ encoder should be able to make based on the level.
626
627
  // All level 5 checks passes, so can return the more compatible level 5
628
0
  return 5;
629
0
}
630
631
JxlEncoderStatus CheckValidBitdepth(uint32_t bits_per_sample,
632
0
                                    uint32_t exponent_bits_per_sample) {
633
0
  if (!exponent_bits_per_sample) {
634
    // The spec allows up to 31 for bits_per_sample here, but
635
    // the code does not (yet) support it.
636
0
    if (!(bits_per_sample > 0 && bits_per_sample <= 24)) {
637
0
      return JXL_API_ERROR_NOSET("Invalid value for bits_per_sample");
638
0
    }
639
0
  } else if ((exponent_bits_per_sample > 8) ||
640
0
             (bits_per_sample > 24 + exponent_bits_per_sample) ||
641
0
             (bits_per_sample < 3 + exponent_bits_per_sample)) {
642
0
    return JXL_API_ERROR_NOSET(
643
0
        "Invalid float description: bits per sample = %u, exp bits = %u",
644
0
        bits_per_sample, exponent_bits_per_sample);
645
0
  }
646
0
  return JxlErrorOrStatus::Success();
647
0
}
648
649
JxlEncoderStatus VerifyInputBitDepth(JxlBitDepth bit_depth,
650
0
                                     JxlPixelFormat format) {
651
0
  return JxlErrorOrStatus::Success();
652
0
}
653
654
inline bool EncodeVarInt(uint64_t value, size_t output_size, size_t* output_pos,
655
0
                         uint8_t* output) {
656
  // While more than 7 bits of data are left,
657
  // store 7 bits and set the next byte flag
658
0
  while (value > 127) {
659
    // TODO(eustas): should it be `>=` ?
660
0
    if (*output_pos > output_size) return false;
661
    // |128: Set the next byte flag
662
0
    output[(*output_pos)++] = (static_cast<uint8_t>(value & 127)) | 128;
663
    // Remove the seven bits we just wrote
664
0
    value >>= 7;
665
0
  }
666
  // TODO(eustas): should it be `>=` ?
667
0
  if (*output_pos > output_size) return false;
668
0
  output[(*output_pos)++] = static_cast<uint8_t>(value & 127);
669
0
  return true;
670
0
}
671
672
bool EncodeFrameIndexBox(const jxl::JxlEncoderFrameIndexBox& frame_index_box,
673
0
                         std::vector<uint8_t>& buffer_vec) {
674
0
  bool ok = true;
675
0
  int NF = 0;
676
0
  for (size_t i = 0; i < frame_index_box.entries.size(); ++i) {
677
0
    if (i == 0 || frame_index_box.entries[i].to_be_indexed) {
678
0
      ++NF;
679
0
    }
680
0
  }
681
  // Frame index box contents varint + 8 bytes
682
  // continue with NF * 3 * varint
683
  // varint max length is 10 for 64 bit numbers, and these numbers
684
  // are limited to 63 bits.
685
0
  static const int kVarintMaxLength = 10;
686
0
  static const int kFrameIndexBoxHeaderLength = kVarintMaxLength + 8;
687
0
  static const int kFrameIndexBoxElementLength = 3 * kVarintMaxLength;
688
0
  const int buffer_size =
689
0
      kFrameIndexBoxHeaderLength + NF * kFrameIndexBoxElementLength;
690
0
  buffer_vec.resize(buffer_size);
691
0
  uint8_t* buffer = buffer_vec.data();
692
0
  size_t output_pos = 0;
693
0
  ok &= EncodeVarInt(NF, buffer_vec.size(), &output_pos, buffer);
694
0
  StoreBE32(frame_index_box.TNUM, &buffer[output_pos]);
695
0
  output_pos += 4;
696
0
  StoreBE32(frame_index_box.TDEN, &buffer[output_pos]);
697
0
  output_pos += 4;
698
  // When we record a frame in the index, the record needs to know
699
  // how many frames until the next indexed frame. That is why
700
  // we store the 'prev' record. That 'prev' record needs to store
701
  // the offset byte position to previously recorded indexed frame,
702
  // that's why we also trace previous to the previous frame.
703
0
  int prev_prev_ix = -1;  // For position offset (OFFi) delta coding.
704
0
  int prev_ix = 0;
705
0
  int T_prev = 0;
706
0
  int T = 0;
707
0
  for (size_t i = 1; i < frame_index_box.entries.size(); ++i) {
708
0
    if (frame_index_box.entries[i].to_be_indexed) {
709
      // Now we can record the previous entry, since we need to store
710
      // there how many frames until the next one.
711
0
      int64_t OFFi = frame_index_box.entries[prev_ix].OFFi;
712
0
      if (prev_prev_ix != -1) {
713
        // Offi needs to be offset of start byte of this frame compared to start
714
        // byte of previous frame from this index in the JPEG XL codestream. For
715
        // the first frame, this is the offset from the first byte of the JPEG
716
        // XL codestream.
717
0
        OFFi -= frame_index_box.entries[prev_prev_ix].OFFi;
718
0
      }
719
0
      int32_t Ti = T_prev;
720
0
      int32_t Fi = i - prev_ix;
721
0
      ok &= EncodeVarInt(OFFi, buffer_vec.size(), &output_pos, buffer);
722
0
      ok &= EncodeVarInt(Ti, buffer_vec.size(), &output_pos, buffer);
723
0
      ok &= EncodeVarInt(Fi, buffer_vec.size(), &output_pos, buffer);
724
0
      prev_prev_ix = prev_ix;
725
0
      prev_ix = i;
726
0
      T_prev = T;
727
0
      T += frame_index_box.entries[i].duration;
728
0
    }
729
0
  }
730
0
  {
731
    // Last frame.
732
0
    size_t i = frame_index_box.entries.size();
733
0
    int64_t OFFi = frame_index_box.entries[prev_ix].OFFi;
734
0
    if (prev_prev_ix != -1) {
735
0
      OFFi -= frame_index_box.entries[prev_prev_ix].OFFi;
736
0
    }
737
0
    int32_t Ti = T_prev;
738
0
    int32_t Fi = i - prev_ix;
739
0
    ok &= EncodeVarInt(OFFi, buffer_vec.size(), &output_pos, buffer);
740
0
    ok &= EncodeVarInt(Ti, buffer_vec.size(), &output_pos, buffer);
741
0
    ok &= EncodeVarInt(Fi, buffer_vec.size(), &output_pos, buffer);
742
0
  }
743
0
  if (ok) buffer_vec.resize(output_pos);
744
0
  return ok;
745
0
}
746
747
struct RunnerTicket {
748
0
  explicit RunnerTicket(jxl::ThreadPool* pool) : pool(pool) {}
749
  jxl::ThreadPool* pool;
750
  std::atomic<uint32_t> has_error{0};
751
};
752
753
void FastLosslessRunnerAdapter(void* void_ticket, void* opaque,
754
0
                               void fun(void*, size_t), size_t count) {
755
0
  auto* ticket = reinterpret_cast<RunnerTicket*>(void_ticket);
756
0
  if (!jxl::RunOnPool(
757
0
          ticket->pool, 0, count, jxl::ThreadPool::NoInit,
758
0
          [&](size_t i, size_t) -> jxl::Status {
759
0
            fun(opaque, i);
760
0
            return true;
761
0
          },
762
0
          "Encode fast lossless")) {
763
0
    ticket->has_error = 1;
764
0
  }
765
0
}
766
767
bool IsAlphaBufferOpaque(const void* buffer, const JxlPixelFormat& format,
768
                         size_t xsize, size_t ysize, size_t row_offset,
769
0
                         size_t alpha_c, size_t alpha_bits) {
770
0
  if (!buffer || format.num_channels <= alpha_c) return false;
771
0
  size_t bytes_per_pixel = jxl::BytesPerPixel(format);
772
0
  if (bytes_per_pixel == 0) return false;
773
0
  const uint8_t* p = reinterpret_cast<const uint8_t*>(buffer);
774
775
0
  if (format.data_type == JXL_TYPE_UINT8) {
776
0
    size_t offset = alpha_c;
777
0
    uint8_t expected =
778
0
        (alpha_bits > 0 && alpha_bits <= 8) ? ((1u << alpha_bits) - 1) : 255;
779
0
    for (size_t y = 0; y < ysize; ++y) {
780
0
      const uint8_t* row = p + y * row_offset;
781
0
      for (size_t x = 0; x < xsize; ++x) {
782
0
        if (row[x * bytes_per_pixel + offset] != expected) {
783
0
          return false;
784
0
        }
785
0
      }
786
0
    }
787
0
    return true;
788
0
  } else if (format.data_type == JXL_TYPE_UINT16) {
789
0
    size_t offset = alpha_c * 2;
790
0
    bool swap = SwapEndianness(format.endianness);
791
0
    uint16_t expected =
792
0
        (alpha_bits > 0 && alpha_bits <= 16) ? ((1u << alpha_bits) - 1) : 65535;
793
0
    for (size_t y = 0; y < ysize; ++y) {
794
0
      const uint8_t* row = p + y * row_offset;
795
0
      for (size_t x = 0; x < xsize; ++x) {
796
0
        uint16_t val;
797
0
        memcpy(&val, row + x * bytes_per_pixel + offset, 2);
798
0
        if (swap) val = JXL_BSWAP16(val);
799
0
        if (val != expected) {
800
0
          return false;
801
0
        }
802
0
      }
803
0
    }
804
0
    return true;
805
0
  } else if (format.data_type == JXL_TYPE_FLOAT) {
806
0
    size_t offset = alpha_c * 4;
807
0
    bool swap = SwapEndianness(format.endianness);
808
0
    for (size_t y = 0; y < ysize; ++y) {
809
0
      const uint8_t* row = p + y * row_offset;
810
0
      for (size_t x = 0; x < xsize; ++x) {
811
0
        uint32_t bits;
812
0
        memcpy(&bits, row + x * bytes_per_pixel + offset, 4);
813
0
        if (swap) bits = JXL_BSWAP32(bits);
814
0
        if (bits != 0x3F800000) {
815
0
          return false;
816
0
        }
817
0
      }
818
0
    }
819
0
    return true;
820
0
  } else if (format.data_type == JXL_TYPE_FLOAT16) {
821
0
    size_t offset = alpha_c * 2;
822
0
    bool swap = SwapEndianness(format.endianness);
823
0
    for (size_t y = 0; y < ysize; ++y) {
824
0
      const uint8_t* row = p + y * row_offset;
825
0
      for (size_t x = 0; x < xsize; ++x) {
826
0
        uint16_t bits;
827
0
        memcpy(&bits, row + x * bytes_per_pixel + offset, 2);
828
0
        if (swap) bits = JXL_BSWAP16(bits);
829
0
        if (bits != 0x3C00) {
830
0
          return false;
831
0
        }
832
0
      }
833
0
    }
834
0
    return true;
835
0
  }
836
0
  return false;
837
0
}
838
839
}  // namespace
840
841
0
jxl::Status JxlEncoder::ProcessOneEnqueuedInput() {
842
0
  jxl::PaddedBytes header_bytes{&memory_manager};
843
844
0
  jxl::JxlEncoderQueuedInput& input = input_queue[0];
845
846
0
  const int output_mode = input.output_mode;  // resolved at queue time
847
848
  // Mode 2 requires that the container was started with ftyp version 1.
849
0
  if (output_mode == 2 && wrote_bytes && container_ftyp_version != 1) {
850
0
    return JXL_API_ERROR(this, JXL_ENC_ERR_API_USAGE,
851
0
                         "output mode 2 requires ftyp version 1, but the "
852
0
                         "container header was already written without it");
853
0
  }
854
855
  // TODO(lode): split this into 3 functions: for adding the signature and other
856
  // initial headers (jbrd, ...), one for adding frame, and one for adding user
857
  // box.
858
859
0
  if (!wrote_bytes) {
860
0
    jxl::JxlEncoderQueuedFrame* first_frame = nullptr;
861
0
    for (auto& qi : input_queue) {
862
0
      if (qi.frame) {
863
0
        first_frame = qi.frame.get();
864
0
        break;
865
0
      }
866
0
    }
867
868
0
    if (metadata.m.HasAlpha()) {
869
0
      const size_t alpha_ec_idx = metadata.m.Find(jxl::ExtraChannel::kAlpha) -
870
0
                                  metadata.m.extra_channel_info.data();
871
0
      const size_t alpha_bits =
872
0
          metadata.m.extra_channel_info[alpha_ec_idx].bit_depth.bits_per_sample;
873
0
      const int strip_alpha = first_frame
874
0
                                  ? first_frame->option_values.strip_alpha
875
0
                                  : kStripAlphaAuto;
876
0
      const bool is_lossless =
877
0
          first_frame && first_frame->option_values.lossless;
878
879
      // Only auto-strip alpha for single-frame images with exactly one extra
880
      // channel.
881
0
      const bool is_multiframe_or_animation =
882
0
          metadata.m.have_animation || !frames_closed ||
883
0
          num_queued_frames != 1 || metadata.m.num_extra_channels != 1;
884
885
0
      bool should_strip = (strip_alpha == kStripAlphaForce &&
886
0
                           metadata.m.num_extra_channels == 1);
887
888
      // Check if alpha can be stripped because it is fully opaque.
889
0
      if (!should_strip && !is_multiframe_or_animation && first_frame &&
890
0
          alpha_ec_idx < first_frame->ec_initialized.size() &&
891
0
          first_frame->ec_initialized[alpha_ec_idx] &&
892
0
          (strip_alpha == kStripAlphaIfOpaque ||
893
0
           (strip_alpha == kStripAlphaAuto && !is_lossless))) {
894
0
        JxlChunkedFrameInputSource src =
895
0
            first_frame->frame_data.GetInputSource();
896
0
        if (src.get_color_channels_pixel_format &&
897
0
            src.get_color_channel_data_at && src.release_buffer) {
898
0
          JxlPixelFormat color_fmt;
899
0
          src.get_color_channels_pixel_format(src.opaque, &color_fmt);
900
0
          const bool has_interleaved =
901
0
              color_fmt.num_channels == 2 || color_fmt.num_channels == 4;
902
0
          const bool has_extra_channel = !has_interleaved &&
903
0
                                         src.get_extra_channel_pixel_format &&
904
0
                                         src.get_extra_channel_data_at;
905
906
0
          if (has_interleaved || has_extra_channel) {
907
0
            JxlPixelFormat ec_fmt;
908
0
            if (has_extra_channel) {
909
0
              src.get_extra_channel_pixel_format(src.opaque, alpha_ec_idx,
910
0
                                                 &ec_fmt);
911
0
            }
912
0
            const JxlPixelFormat& fmt = has_interleaved ? color_fmt : ec_fmt;
913
0
            const size_t alpha_c =
914
0
                has_interleaved ? (color_fmt.num_channels - 1) : 0;
915
916
0
            auto is_chunk_opaque = [&](size_t x, size_t y, size_t xs,
917
0
                                       size_t ys) -> bool {
918
0
              size_t row_offset = 0;
919
0
              if (has_interleaved) {
920
0
                auto buf = jxl::GetColorBuffer(src, x, y, xs, ys, &row_offset);
921
0
                return buf &&
922
0
                       IsAlphaBufferOpaque(buf.get(), fmt, xs, ys, row_offset,
923
0
                                           alpha_c, alpha_bits);
924
0
              } else {
925
0
                auto buf = jxl::GetExtraChannelBuffer(src, alpha_ec_idx, x, y,
926
0
                                                      xs, ys, &row_offset);
927
0
                return buf &&
928
0
                       IsAlphaBufferOpaque(buf.get(), fmt, xs, ys, row_offset,
929
0
                                           alpha_c, alpha_bits);
930
0
              }
931
0
            };
932
933
0
            constexpr size_t kChunkDimY = 256;
934
0
            constexpr size_t kChunkDimX = 2048;
935
0
            const size_t xsize = metadata.xsize();
936
0
            const size_t ysize = metadata.ysize();
937
0
            bool all_opaque = true;
938
939
0
            for (size_t y = 0; y < ysize && all_opaque; y += kChunkDimY) {
940
0
              const size_t chunk_ysize = std::min(kChunkDimY, ysize - y);
941
0
              for (size_t x = 0; x < xsize; x += kChunkDimX) {
942
0
                const size_t chunk_xsize = std::min(kChunkDimX, xsize - x);
943
0
                if (!is_chunk_opaque(x, y, chunk_xsize, chunk_ysize)) {
944
0
                  all_opaque = false;
945
0
                  break;
946
0
                }
947
0
              }
948
0
            }
949
0
            should_strip = all_opaque;
950
0
          }
951
0
        }
952
0
      }
953
954
0
      if (should_strip) {
955
0
        metadata.m.extra_channel_info.erase(
956
0
            metadata.m.extra_channel_info.begin() + alpha_ec_idx);
957
0
        metadata.m.num_extra_channels--;
958
0
        basic_info.num_extra_channels = metadata.m.num_extra_channels;
959
0
        basic_info.alpha_bits = 0;
960
0
        basic_info.alpha_exponent_bits = 0;
961
0
        basic_info.alpha_premultiplied = JXL_FALSE;
962
963
0
        for (auto& qi : input_queue) {
964
0
          if (qi.frame) {
965
0
            if (alpha_ec_idx < qi.frame->ec_initialized.size()) {
966
0
              qi.frame->ec_initialized.erase(qi.frame->ec_initialized.begin() +
967
0
                                             alpha_ec_idx);
968
0
            }
969
0
            if (alpha_ec_idx <
970
0
                qi.frame->option_values.extra_channel_blend_info.size()) {
971
0
              qi.frame->option_values.extra_channel_blend_info.erase(
972
0
                  qi.frame->option_values.extra_channel_blend_info.begin() +
973
0
                  alpha_ec_idx);
974
0
            }
975
0
            if (alpha_ec_idx <
976
0
                qi.frame->option_values.cparams.ec_distance.size()) {
977
0
              qi.frame->option_values.cparams.ec_distance.erase(
978
0
                  qi.frame->option_values.cparams.ec_distance.begin() +
979
0
                  alpha_ec_idx);
980
0
            }
981
0
          }
982
0
        }
983
0
      }
984
0
    }
985
986
    // First time encoding any data, verify the level 5 vs level 10 settings
987
0
    std::string level_message;
988
0
    int required_level = VerifyLevelSettings(this, &level_message);
989
    // Only level 5 and 10 are defined, and the function can return -1 to
990
    // indicate full incompatibility.
991
0
    JXL_ENSURE(required_level == -1 || required_level == 5 ||
992
0
               required_level == 10);
993
    // codestream_level == -1 means auto-set to the required level
994
0
    if (codestream_level == -1) codestream_level = required_level;
995
0
    if (codestream_level == 5 && required_level != 5) {
996
      // If the required level is 10, return error rather than automatically
997
      // setting the level to 10, to avoid inadvertently creating a level 10
998
      // JXL file while intending to target a level 5 decoder.
999
0
      return JXL_API_ERROR(
1000
0
          this, JXL_ENC_ERR_API_USAGE, "%s",
1001
0
          ("Codestream level verification for level 5 failed: " + level_message)
1002
0
              .c_str());
1003
0
    }
1004
0
    if (required_level == -1) {
1005
0
      return JXL_API_ERROR(
1006
0
          this, JXL_ENC_ERR_API_USAGE, "%s",
1007
0
          ("Codestream level verification for level 10 failed: " +
1008
0
           level_message)
1009
0
              .c_str());
1010
0
    }
1011
0
    jxl::AuxOut* aux_out =
1012
0
        first_frame ? first_frame->option_values.aux_out : nullptr;
1013
0
    jxl::BitWriter writer{&memory_manager};
1014
0
    if (!WriteCodestreamHeaders(&metadata, &writer, aux_out)) {
1015
0
      return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
1016
0
                           "Failed to write codestream header");
1017
0
    }
1018
    // Only send ICC (at least several hundred bytes) if fields aren't enough.
1019
0
    if (metadata.m.color_encoding.WantICC()) {
1020
0
      if (!jxl::WriteICC(jxl::Bytes(metadata.m.color_encoding.ICC()), &writer,
1021
0
                         jxl::LayerType::Header, aux_out)) {
1022
0
        return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
1023
0
                             "Failed to write ICC profile");
1024
0
      }
1025
0
    }
1026
    // TODO(lode): preview should be added here if a preview image is added
1027
1028
0
    JXL_RETURN_IF_ERROR(
1029
0
        writer.WithMaxBits(8, jxl::LayerType::Header, aux_out, [&] {
1030
0
          writer.ZeroPadToByte();
1031
0
          return true;
1032
0
        }));
1033
1034
0
    header_bytes = std::move(writer).TakeBytes();
1035
1036
    // Not actually the end of frame, but the end of metadata/ICC, but helps
1037
    // the next frame to start here for indexing purposes.
1038
0
    codestream_bytes_written_end_of_frame += header_bytes.size();
1039
1040
0
    if (MustUseContainer(output_mode)) {
1041
      // If any queued input uses output mode 2, ftyp version 1 is needed.
1042
0
      int ftyp_version = (output_mode == 2) ? 1 : 0;
1043
0
      for (const auto& qi : input_queue) {
1044
0
        if (qi.output_mode == 2) {
1045
0
          ftyp_version = 1;
1046
0
          break;
1047
0
        }
1048
0
      }
1049
0
      container_ftyp_version = ftyp_version;
1050
      // Add "JXL " and ftyp box.
1051
0
      JXL_RETURN_IF_ERROR(
1052
0
          AppendData(output_processor, jxl::MakeContainerHeader(ftyp_version)));
1053
1054
0
      if (codestream_level != 5) {
1055
        // Add jxll box directly after the ftyp box to indicate the codestream
1056
        // level.
1057
0
        const uint8_t level = static_cast<uint8_t>(codestream_level);
1058
0
        std::vector<uint8_t> jxll_box;
1059
0
        jxl::AppendBoxHeader(jxl::MakeBoxType("jxll"), 1,
1060
0
                             /*unbounded=*/false, &jxll_box);
1061
0
        jxll_box.push_back(level);
1062
0
        JXL_RETURN_IF_ERROR(AppendData(output_processor, jxll_box));
1063
0
      }
1064
1065
      // Whether to write the basic info and color profile header of the
1066
      // codestream into an early separate jxlp box, so that it comes before
1067
      // metadata or jpeg reconstruction boxes. In theory this could simply
1068
      // always be done, but there's no reason to add an extra box with box
1069
      // header overhead if the codestream will already come immediately after
1070
      // the signature and level boxes.
1071
0
      bool partial_header =
1072
0
          store_jpeg_metadata ||
1073
0
          (use_boxes && (!input.frame && !input.fast_lossless_frame));
1074
1075
0
      if (partial_header) {
1076
0
        auto write_box = [&]() -> jxl::Status {
1077
0
          JXL_ASSIGN_OR_RETURN(
1078
0
              auto buffer, output_processor.GetBuffer(header_bytes.size() + 4));
1079
0
          JXL_RETURN_IF_ERROR(
1080
0
              WriteJxlpBoxCounter(jxlp_counter++, /*last=*/false, buffer));
1081
0
          JXL_RETURN_IF_ERROR(buffer.append(header_bytes));
1082
0
          return jxl::OkStatus();
1083
0
        };
1084
0
        JXL_RETURN_IF_ERROR(AppendBox(jxl::MakeBoxType("jxlp"),
1085
0
                                      /*unbounded=*/false,
1086
0
                                      header_bytes.size() + 4, write_box));
1087
0
        header_bytes.clear();
1088
0
      }
1089
1090
0
      if (store_jpeg_metadata && !jpeg_metadata.empty()) {
1091
0
        JXL_RETURN_IF_ERROR(
1092
0
            AppendBoxWithContents(jxl::MakeBoxType("jbrd"), jpeg_metadata));
1093
0
      }
1094
0
    }
1095
0
    wrote_bytes = true;
1096
0
  }
1097
1098
0
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
1099
1100
  // Choose frame or box processing: exactly one of the two unique pointers (box
1101
  // or frame) in the input queue item is non-null.
1102
0
  if (input.frame || input.fast_lossless_frame) {
1103
0
    jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedFrame> input_frame =
1104
0
        std::move(input.frame);
1105
0
    jxl::FJXLFrameUniquePtr fast_lossless_frame =
1106
0
        std::move(input.fast_lossless_frame);
1107
0
    input_queue.erase(input_queue.begin());
1108
0
    num_queued_frames--;
1109
0
    if (input_frame) {
1110
0
      for (unsigned idx = 0; idx < input_frame->ec_initialized.size(); idx++) {
1111
0
        if (!input_frame->ec_initialized[idx]) {
1112
0
          return JXL_API_ERROR(this, JXL_ENC_ERR_API_USAGE,
1113
0
                               "Extra channel %u is not initialized", idx);
1114
0
        }
1115
0
      }
1116
1117
      // TODO(zond): If the input queue is empty and the frames_closed is true,
1118
      // then mark this frame as the last.
1119
1120
      // TODO(zond): Handle progressive mode like EncodeFile does it.
1121
      // TODO(zond): Handle animation like EncodeFile does it, by checking if
1122
      //             JxlEncoderCloseFrames has been called and if the frame
1123
      //             queue is empty (to see if it's the last animation frame).
1124
1125
0
      if (metadata.m.xyb_encoded) {
1126
0
        input_frame->option_values.cparams.color_transform =
1127
0
            jxl::ColorTransform::kXYB;
1128
0
      } else {
1129
        // TODO(zond): Figure out when to use kYCbCr instead.
1130
0
        input_frame->option_values.cparams.color_transform =
1131
0
            jxl::ColorTransform::kNone;
1132
0
      }
1133
0
    }
1134
1135
0
    uint32_t duration;
1136
0
    uint32_t timecode;
1137
0
    if (input_frame && metadata.m.have_animation) {
1138
0
      duration = input_frame->option_values.header.duration;
1139
0
      timecode = input_frame->option_values.header.timecode;
1140
0
    } else {
1141
      // If have_animation is false, the encoder should ignore the duration and
1142
      // timecode values. However, assigning them to ib will cause the encoder
1143
      // to write an invalid frame header that can't be decoded so ensure
1144
      // they're the default value of 0 here.
1145
0
      duration = 0;
1146
0
      timecode = 0;
1147
0
    }
1148
1149
0
    const bool last_frame = frames_closed && (num_queued_frames == 0);
1150
1151
0
    uint32_t max_bits_per_sample = metadata.m.bit_depth.bits_per_sample;
1152
0
    for (const auto& info : metadata.m.extra_channel_info) {
1153
0
      max_bits_per_sample =
1154
0
          std::max(max_bits_per_sample, info.bit_depth.bits_per_sample);
1155
0
    }
1156
    // Heuristic upper bound on how many bits a single pixel in a single channel
1157
    // can use.
1158
0
    uint32_t bits_per_channels_estimate =
1159
0
        std::max(24u, max_bits_per_sample + 3);
1160
0
    size_t upper_bound_on_compressed_size_bits =
1161
0
        metadata.xsize() * metadata.ysize() *
1162
0
        (metadata.m.color_encoding.Channels() + metadata.m.num_extra_channels) *
1163
0
        bits_per_channels_estimate;
1164
    // Add a 1MB = 0x100000 for an heuristic upper bound on small sizes.
1165
0
    size_t upper_bound_on_compressed_size_bytes =
1166
0
        0x100000 + (upper_bound_on_compressed_size_bits >> 3);
1167
0
    bool use_large_box = upper_bound_on_compressed_size_bytes >=
1168
0
                         jxl::kLargeBoxContentSizeThreshold;
1169
0
    size_t box_header_size =
1170
0
        use_large_box ? jxl::kLargeBoxHeaderSize : jxl::kSmallBoxHeaderSize;
1171
1172
0
    size_t frame_start_pos = output_processor.CurrentPosition();
1173
0
    const size_t n0 = jxlp_counter;
1174
1175
0
    if (MustUseContainer(output_mode) && output_mode != 2) {
1176
0
      if (!last_frame || jxlp_counter > 0) {
1177
        // If this is the last frame and no jxlp boxes were used yet, it's
1178
        // slightly more efficient to write a jxlc box since it has 4 bytes
1179
        // less overhead.
1180
0
        box_header_size += 4;  // jxlp_counter field
1181
0
      }
1182
0
      JXL_RETURN_IF_ERROR(
1183
0
          output_processor.Seek(frame_start_pos + box_header_size));
1184
0
    }
1185
0
    const size_t content_start = output_processor.CurrentPosition();
1186
1187
0
    if (!header_bytes.empty()) {
1188
0
      if (output_mode == 2) {
1189
0
        uint8_t hdr[jxl::kLargeBoxHeaderSize + 4];
1190
0
        const size_t hdr_size = jxl::WriteBoxHeader(
1191
0
            jxl::MakeBoxType("jxlp"), 4 + header_bytes.size(),
1192
0
            /*unbounded=*/false, /*force_large_box=*/false, hdr);
1193
0
        WriteJxlpBoxCounter(static_cast<uint32_t>(jxlp_counter++),
1194
0
                            /*last=*/false, hdr + hdr_size);
1195
0
        JXL_RETURN_IF_ERROR(AppendData(
1196
0
            output_processor, jxl::Span<const uint8_t>(hdr, hdr_size + 4)));
1197
0
      }
1198
0
      JXL_RETURN_IF_ERROR(AppendData(output_processor, header_bytes));
1199
0
    }
1200
1201
    // For mode 2: frame_start_pos points to where EncodeFrame may leave a
1202
    // 12-byte gap on one-shot fallback; we detect and fill it via n1 below.
1203
0
    if (output_mode == 2) {
1204
0
      frame_start_pos = output_processor.CurrentPosition();
1205
0
      box_header_size = 12;
1206
0
    }
1207
0
    const uint32_t n1 = jxlp_counter;
1208
1209
0
    if (input_frame) {
1210
0
      frame_index_box.AddFrame(codestream_bytes_written_end_of_frame, duration,
1211
0
                               input_frame->option_values.frame_index_box);
1212
1213
0
      size_t save_as_reference =
1214
0
          input_frame->option_values.header.layer_info.save_as_reference;
1215
0
      if (save_as_reference >= 3) {
1216
0
        return JXL_API_ERROR(
1217
0
            this, JXL_ENC_ERR_API_USAGE,
1218
0
            "Cannot use save_as_reference values >=3 (found: %d)",
1219
0
            static_cast<int>(save_as_reference));
1220
0
      }
1221
1222
0
      jxl::FrameInfo frame_info;
1223
0
      frame_info.is_last = last_frame;
1224
0
      frame_info.save_as_reference = save_as_reference;
1225
0
      frame_info.source =
1226
0
          input_frame->option_values.header.layer_info.blend_info.source;
1227
0
      frame_info.clamp = FROM_JXL_BOOL(
1228
0
          input_frame->option_values.header.layer_info.blend_info.clamp);
1229
0
      frame_info.alpha_channel =
1230
0
          input_frame->option_values.header.layer_info.blend_info.alpha;
1231
0
      frame_info.extra_channel_blending_info.resize(
1232
0
          metadata.m.num_extra_channels);
1233
      // If extra channel blend info has not been set, use the blend mode from
1234
      // the layer_info.
1235
0
      JxlBlendInfo default_blend_info =
1236
0
          input_frame->option_values.header.layer_info.blend_info;
1237
0
      for (size_t i = 0; i < metadata.m.num_extra_channels; ++i) {
1238
0
        auto& to = frame_info.extra_channel_blending_info[i];
1239
0
        const auto& from =
1240
0
            i < input_frame->option_values.extra_channel_blend_info.size()
1241
0
                ? input_frame->option_values.extra_channel_blend_info[i]
1242
0
                : default_blend_info;
1243
0
        to.mode = static_cast<jxl::BlendMode>(from.blendmode);
1244
0
        to.source = from.source;
1245
0
        to.alpha_channel = from.alpha;
1246
0
        to.clamp = (from.clamp != 0);
1247
0
      }
1248
0
      frame_info.origin.x0 =
1249
0
          input_frame->option_values.header.layer_info.crop_x0;
1250
0
      frame_info.origin.y0 =
1251
0
          input_frame->option_values.header.layer_info.crop_y0;
1252
0
      frame_info.blendmode = static_cast<jxl::BlendMode>(
1253
0
          input_frame->option_values.header.layer_info.blend_info.blendmode);
1254
0
      frame_info.blend =
1255
0
          input_frame->option_values.header.layer_info.blend_info.blendmode !=
1256
0
          JXL_BLEND_REPLACE;
1257
0
      frame_info.image_bit_depth = input_frame->option_values.image_bit_depth;
1258
0
      frame_info.duration = duration;
1259
0
      frame_info.timecode = timecode;
1260
0
      frame_info.name = input_frame->option_values.frame_name;
1261
0
      jxl::CompressParams frame_cparams = input_frame->option_values.cparams;
1262
0
      frame_cparams.output_mode = output_mode;
1263
0
      uint32_t jxlp_ctr = static_cast<uint32_t>(jxlp_counter);
1264
0
      if (!jxl::EncodeFrame(&memory_manager, frame_cparams, frame_info,
1265
0
                            &metadata, input_frame->frame_data, cms,
1266
0
                            thread_pool.get(), &output_processor,
1267
0
                            input_frame->option_values.aux_out, &jxlp_ctr)) {
1268
0
        return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
1269
0
                             "Failed to encode frame");
1270
0
      }
1271
0
      jxlp_counter = jxlp_ctr;
1272
0
      last_used_cparams = input_frame->option_values.cparams;
1273
0
    } else {
1274
0
      JXL_ENSURE(fast_lossless_frame);
1275
0
      RunnerTicket ticket{thread_pool.get()};
1276
0
      bool ok = JxlFastLosslessProcessFrame(
1277
0
          fast_lossless_frame.get(), last_frame, &ticket,
1278
0
          &FastLosslessRunnerAdapter, &output_processor);
1279
0
      if (!ok || ticket.has_error) {
1280
0
        return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
1281
0
                             "Internal: JxlFastLosslessProcessFrame failed");
1282
0
      }
1283
0
    }
1284
1285
0
    const size_t content_size =
1286
0
        output_processor.CurrentPosition() - content_start;
1287
1288
0
    codestream_bytes_written_end_of_frame +=
1289
0
        content_size - header_bytes.size() - (jxlp_counter - n0) * 12;
1290
1291
0
    if (MustUseContainer(output_mode) &&
1292
0
        (output_mode != 2 || jxlp_counter == n1)) {
1293
0
      JXL_RETURN_IF_ERROR(output_processor.Seek(frame_start_pos));
1294
0
      std::vector<uint8_t> box_header(box_header_size);
1295
      // For mode 2 fallback the box wraps only the frame data (not
1296
      // header_bytes).
1297
0
      const size_t frame_content_size =
1298
0
          output_mode == 2
1299
0
              ? content_size - (frame_start_pos - content_start) - 12
1300
0
              : content_size;
1301
0
      if (!use_large_box &&
1302
0
          frame_content_size >= jxl::kLargeBoxContentSizeThreshold) {
1303
        // Assuming our upper bound estimate is correct, this should never
1304
        // happen.
1305
0
        return JXL_API_ERROR(
1306
0
            this, JXL_ENC_ERR_GENERIC,
1307
0
            "Box size was estimated to be small, but turned out to be large. "
1308
0
            "Please file this error in size estimation as a bug.");
1309
0
      }
1310
0
      if (last_frame && jxlp_counter == 0) {
1311
0
        size_t n = jxl::WriteBoxHeader(
1312
0
            jxl::MakeBoxType("jxlc"), frame_content_size,
1313
0
            /*unbounded=*/false, use_large_box, box_header.data());
1314
0
        JXL_ENSURE(n == box_header_size);
1315
0
      } else {
1316
0
        size_t n = jxl::WriteBoxHeader(
1317
0
            jxl::MakeBoxType("jxlp"), frame_content_size + 4,
1318
0
            /*unbounded=*/false, use_large_box, box_header.data());
1319
0
        JXL_ENSURE(n == box_header_size - 4);
1320
0
        WriteJxlpBoxCounter(jxlp_counter++, last_frame,
1321
0
                            &box_header[box_header_size - 4]);
1322
0
      }
1323
0
      JXL_RETURN_IF_ERROR(AppendData(output_processor, box_header));
1324
0
      JXL_ENSURE(output_processor.CurrentPosition() ==
1325
0
                 frame_start_pos + box_header_size);
1326
0
      JXL_RETURN_IF_ERROR(output_processor.Seek(content_start + content_size));
1327
0
    }
1328
0
    JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
1329
0
    if (last_frame && frame_index_box.StoreFrameIndexBox()) {
1330
0
      std::vector<uint8_t> index_box_content;
1331
      // Enough buffer has been allocated, this function should never fail in
1332
      // writing.
1333
0
      JXL_ENSURE(EncodeFrameIndexBox(frame_index_box, index_box_content));
1334
0
      JXL_RETURN_IF_ERROR(AppendBoxWithContents(jxl::MakeBoxType("jxli"),
1335
0
                                                jxl::Bytes(index_box_content)));
1336
0
    }
1337
0
  } else {
1338
    // Not a frame, so is a box instead
1339
0
    jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedBox> box =
1340
0
        std::move(input.box);
1341
0
    input_queue.erase(input_queue.begin());
1342
0
    num_queued_boxes--;
1343
1344
0
    if (box->compress_box) {
1345
0
      jxl::PaddedBytes compressed(&memory_manager);
1346
      // Prepend the original box type in the brob box contents
1347
0
      JXL_RETURN_IF_ERROR(compressed.append(box->type));
1348
0
      if (JXL_ENC_SUCCESS !=
1349
0
          BrotliCompress((brotli_effort >= 0 ? brotli_effort : 4),
1350
0
                         box->contents.data(), box->contents.size(),
1351
0
                         &compressed)) {
1352
0
        return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
1353
0
                             "Brotli compression for brob box failed");
1354
0
      }
1355
1356
0
      JXL_RETURN_IF_ERROR(
1357
0
          AppendBoxWithContents(jxl::MakeBoxType("brob"), compressed));
1358
0
    } else {
1359
0
      JXL_RETURN_IF_ERROR(AppendBoxWithContents(box->type, box->contents));
1360
0
    }
1361
0
  }
1362
1363
0
  return jxl::OkStatus();
1364
0
}
1365
1366
JxlEncoderStatus JxlEncoderSetColorEncoding(JxlEncoder* enc,
1367
0
                                            const JxlColorEncoding* color) {
1368
0
  if (!enc->basic_info_set) {
1369
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Basic info not yet set");
1370
0
  }
1371
0
  if (enc->color_encoding_set) {
1372
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1373
0
                         "Color encoding is already set");
1374
0
  }
1375
0
  if (!enc->metadata.m.color_encoding.FromExternal(*color)) {
1376
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_GENERIC, "Error in color conversion");
1377
0
  }
1378
0
  if (enc->metadata.m.color_encoding.GetColorSpace() ==
1379
0
      jxl::ColorSpace::kGray) {
1380
0
    if (enc->basic_info.num_color_channels != 1) {
1381
0
      return JXL_API_ERROR(
1382
0
          enc, JXL_ENC_ERR_API_USAGE,
1383
0
          "Cannot use grayscale color encoding with num_color_channels != 1");
1384
0
    }
1385
0
  } else {
1386
0
    if (enc->basic_info.num_color_channels != 3) {
1387
0
      return JXL_API_ERROR(
1388
0
          enc, JXL_ENC_ERR_API_USAGE,
1389
0
          "Cannot use RGB color encoding with num_color_channels != 3");
1390
0
    }
1391
0
  }
1392
0
  enc->color_encoding_set = true;
1393
0
  if (!enc->intensity_target_set) {
1394
0
    jxl::SetIntensityTarget(&enc->metadata.m);
1395
0
  }
1396
0
  return JxlErrorOrStatus::Success();
1397
0
}
1398
1399
JxlEncoderStatus JxlEncoderSetICCProfile(JxlEncoder* enc,
1400
                                         const uint8_t* icc_profile,
1401
0
                                         size_t size) {
1402
0
  if (!enc->basic_info_set) {
1403
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Basic info not yet set");
1404
0
  }
1405
0
  if (enc->color_encoding_set) {
1406
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1407
0
                         "ICC profile is already set");
1408
0
  }
1409
0
  if (size == 0) {
1410
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_BAD_INPUT, "Empty ICC profile");
1411
0
  }
1412
0
  jxl::IccBytes icc;
1413
0
  icc.assign(icc_profile, icc_profile + size);
1414
0
  if (enc->cms_set) {
1415
0
    if (!enc->metadata.m.color_encoding.SetICC(std::move(icc), &enc->cms)) {
1416
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_BAD_INPUT,
1417
0
                           "ICC profile could not be set");
1418
0
    }
1419
0
  } else {
1420
0
    enc->metadata.m.color_encoding.SetICCRaw(std::move(icc));
1421
0
  }
1422
0
  if (enc->metadata.m.color_encoding.GetColorSpace() ==
1423
0
      jxl::ColorSpace::kGray) {
1424
0
    if (enc->basic_info.num_color_channels != 1) {
1425
0
      return JXL_API_ERROR(
1426
0
          enc, JXL_ENC_ERR_BAD_INPUT,
1427
0
          "Cannot use grayscale ICC profile with num_color_channels != 1");
1428
0
    }
1429
0
  } else {
1430
0
    if (enc->basic_info.num_color_channels != 3) {
1431
0
      return JXL_API_ERROR(
1432
0
          enc, JXL_ENC_ERR_BAD_INPUT,
1433
0
          "Cannot use RGB ICC profile with num_color_channels != 3");
1434
0
    }
1435
    // TODO(jon): also check that a kBlack extra channel is provided in the CMYK
1436
    // case
1437
0
  }
1438
0
  enc->color_encoding_set = true;
1439
0
  if (!enc->intensity_target_set) {
1440
0
    jxl::SetIntensityTarget(&enc->metadata.m);
1441
0
  }
1442
1443
0
  if (!enc->basic_info.uses_original_profile && enc->cms_set) {
1444
0
    enc->metadata.m.color_encoding.DecideIfWantICC(enc->cms);
1445
0
  }
1446
1447
0
  return JxlErrorOrStatus::Success();
1448
0
}
1449
1450
0
void JxlEncoderInitBasicInfo(JxlBasicInfo* info) {
1451
0
  info->have_container = JXL_FALSE;
1452
0
  info->xsize = 0;
1453
0
  info->ysize = 0;
1454
0
  info->bits_per_sample = 8;
1455
0
  info->exponent_bits_per_sample = 0;
1456
0
  info->intensity_target = 0.f;
1457
0
  info->min_nits = 0.f;
1458
0
  info->relative_to_max_display = JXL_FALSE;
1459
0
  info->linear_below = 0.f;
1460
0
  info->uses_original_profile = JXL_FALSE;
1461
0
  info->have_preview = JXL_FALSE;
1462
0
  info->have_animation = JXL_FALSE;
1463
0
  info->orientation = JXL_ORIENT_IDENTITY;
1464
0
  info->num_color_channels = 3;
1465
0
  info->num_extra_channels = 0;
1466
0
  info->alpha_bits = 0;
1467
0
  info->alpha_exponent_bits = 0;
1468
0
  info->alpha_premultiplied = JXL_FALSE;
1469
0
  info->preview.xsize = 0;
1470
0
  info->preview.ysize = 0;
1471
0
  info->intrinsic_xsize = 0;
1472
0
  info->intrinsic_ysize = 0;
1473
0
  info->animation.tps_numerator = 10;
1474
0
  info->animation.tps_denominator = 1;
1475
0
  info->animation.num_loops = 0;
1476
0
  info->animation.have_timecodes = JXL_FALSE;
1477
0
}
1478
1479
0
void JxlEncoderInitFrameHeader(JxlFrameHeader* frame_header) {
1480
  // For each field, the default value of the specification is used. Depending
1481
  // on whether an animation frame, or a composite still blending frame,
1482
  // is used, different fields have to be set up by the user after initing
1483
  // the frame header.
1484
0
  frame_header->duration = 0;
1485
0
  frame_header->timecode = 0;
1486
0
  frame_header->name_length = 0;
1487
  // In the specification, the default value of is_last is !frame_type, and the
1488
  // default frame_type is kRegularFrame which has value 0, so is_last is true
1489
  // by default. However, the encoder does not use this value (the field exists
1490
  // for the decoder to set) since last frame is determined by usage of
1491
  // JxlEncoderCloseFrames instead.
1492
0
  frame_header->is_last = JXL_TRUE;
1493
0
  frame_header->layer_info.have_crop = JXL_FALSE;
1494
0
  frame_header->layer_info.crop_x0 = 0;
1495
0
  frame_header->layer_info.crop_y0 = 0;
1496
  // These must be set if have_crop is enabled, but the default value has
1497
  // have_crop false, and these dimensions 0. The user must set these to the
1498
  // desired size after enabling have_crop (which is not yet implemented).
1499
0
  frame_header->layer_info.xsize = 0;
1500
0
  frame_header->layer_info.ysize = 0;
1501
0
  JxlEncoderInitBlendInfo(&frame_header->layer_info.blend_info);
1502
0
  frame_header->layer_info.save_as_reference = 0;
1503
0
}
1504
1505
0
void JxlEncoderInitBlendInfo(JxlBlendInfo* blend_info) {
1506
  // Default blend mode in the specification is 0. Note that combining
1507
  // blend mode of replace with a duration is not useful, but the user has to
1508
  // manually set duration in case of animation, or manually change the blend
1509
  // mode in case of composite stills, so initing to a combination that is not
1510
  // useful on its own is not an issue.
1511
0
  blend_info->blendmode = JXL_BLEND_REPLACE;
1512
0
  blend_info->source = 0;
1513
0
  blend_info->alpha = 0;
1514
0
  blend_info->clamp = 0;
1515
0
}
1516
1517
JxlEncoderStatus JxlEncoderSetBasicInfo(JxlEncoder* enc,
1518
0
                                        const JxlBasicInfo* info) {
1519
0
  if (!enc->metadata.size.Set(info->xsize, info->ysize)) {
1520
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid dimensions");
1521
0
  }
1522
0
  if (JXL_ENC_SUCCESS != CheckValidBitdepth(info->bits_per_sample,
1523
0
                                            info->exponent_bits_per_sample)) {
1524
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid bit depth");
1525
0
  }
1526
1527
0
  enc->metadata.m.bit_depth.bits_per_sample = info->bits_per_sample;
1528
0
  enc->metadata.m.bit_depth.exponent_bits_per_sample =
1529
0
      info->exponent_bits_per_sample;
1530
0
  enc->metadata.m.bit_depth.floating_point_sample =
1531
0
      (info->exponent_bits_per_sample != 0u);
1532
0
  enc->metadata.m.modular_16_bit_buffer_sufficient =
1533
0
      (!FROM_JXL_BOOL(info->uses_original_profile) ||
1534
0
       info->bits_per_sample <= 12) &&
1535
0
      info->alpha_bits <= 12;
1536
0
  if ((info->intrinsic_xsize > 0 || info->intrinsic_ysize > 0) &&
1537
0
      (info->intrinsic_xsize != info->xsize ||
1538
0
       info->intrinsic_ysize != info->ysize)) {
1539
0
    if (info->intrinsic_xsize > (1ull << 30ull) ||
1540
0
        info->intrinsic_ysize > (1ull << 30ull) ||
1541
0
        !enc->metadata.m.intrinsic_size.Set(info->intrinsic_xsize,
1542
0
                                            info->intrinsic_ysize)) {
1543
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1544
0
                           "Invalid intrinsic dimensions");
1545
0
    }
1546
0
    enc->metadata.m.have_intrinsic_size = true;
1547
0
  }
1548
1549
  // The number of extra channels includes the alpha channel, so for example and
1550
  // RGBA with no other extra channels, has exactly num_extra_channels == 1
1551
0
  enc->metadata.m.num_extra_channels = info->num_extra_channels;
1552
0
  enc->metadata.m.extra_channel_info.resize(enc->metadata.m.num_extra_channels);
1553
0
  if (info->num_extra_channels == 0 && info->alpha_bits) {
1554
0
    return JXL_API_ERROR(
1555
0
        enc, JXL_ENC_ERR_API_USAGE,
1556
0
        "when alpha_bits is non-zero, the number of channels must be at least "
1557
0
        "1");
1558
0
  }
1559
  // If the user provides non-zero alpha_bits, we make the channel info at index
1560
  // zero the appropriate alpha channel.
1561
0
  if (info->alpha_bits) {
1562
0
    JxlExtraChannelInfo channel_info;
1563
0
    JxlEncoderInitExtraChannelInfo(JXL_CHANNEL_ALPHA, &channel_info);
1564
0
    channel_info.bits_per_sample = info->alpha_bits;
1565
0
    channel_info.exponent_bits_per_sample = info->alpha_exponent_bits;
1566
0
    channel_info.alpha_premultiplied = info->alpha_premultiplied;
1567
0
    if (JxlEncoderSetExtraChannelInfo(enc, 0, &channel_info)) {
1568
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1569
0
                           "Problem setting extra channel info for alpha");
1570
0
    }
1571
0
  }
1572
1573
0
  enc->metadata.m.xyb_encoded = !FROM_JXL_BOOL(info->uses_original_profile);
1574
0
  if (info->orientation > 0 && info->orientation <= 8) {
1575
0
    enc->metadata.m.orientation = info->orientation;
1576
0
  } else {
1577
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1578
0
                         "Invalid value for orientation field");
1579
0
  }
1580
0
  if (info->num_color_channels != 1 && info->num_color_channels != 3) {
1581
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1582
0
                         "Invalid number of color channels");
1583
0
  }
1584
0
  if (info->intensity_target != 0) {
1585
0
    enc->metadata.m.SetIntensityTarget(info->intensity_target);
1586
0
    enc->intensity_target_set = true;
1587
0
  } else if (enc->color_encoding_set) {
1588
    // If this is false, JxlEncoderSetColorEncoding will be called later and we
1589
    // will get one more chance to call jxl::SetIntensityTarget, after the color
1590
    // encoding is indeed set.
1591
0
    jxl::SetIntensityTarget(&enc->metadata.m);
1592
0
    enc->intensity_target_set = true;
1593
0
  }
1594
0
  enc->metadata.m.tone_mapping.min_nits = info->min_nits;
1595
0
  enc->metadata.m.tone_mapping.relative_to_max_display =
1596
0
      FROM_JXL_BOOL(info->relative_to_max_display);
1597
0
  enc->metadata.m.tone_mapping.linear_below = info->linear_below;
1598
0
  enc->basic_info = *info;
1599
0
  enc->basic_info_set = true;
1600
1601
0
  enc->metadata.m.have_animation = FROM_JXL_BOOL(info->have_animation);
1602
0
  if (info->have_animation) {
1603
0
    if (info->animation.tps_denominator < 1) {
1604
0
      return JXL_API_ERROR(
1605
0
          enc, JXL_ENC_ERR_API_USAGE,
1606
0
          "If animation is used, tps_denominator must be >= 1");
1607
0
    }
1608
0
    if (info->animation.tps_numerator < 1) {
1609
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1610
0
                           "If animation is used, tps_numerator must be >= 1");
1611
0
    }
1612
0
    enc->metadata.m.animation.tps_numerator = info->animation.tps_numerator;
1613
0
    enc->metadata.m.animation.tps_denominator = info->animation.tps_denominator;
1614
0
    enc->metadata.m.animation.num_loops = info->animation.num_loops;
1615
0
    enc->metadata.m.animation.have_timecodes =
1616
0
        FROM_JXL_BOOL(info->animation.have_timecodes);
1617
0
  }
1618
0
  std::string level_message;
1619
0
  int required_level = VerifyLevelSettings(enc, &level_message);
1620
0
  int verified_level = (required_level == -1) ? 10 : enc->codestream_level;
1621
0
  if (required_level == -1 ||
1622
0
      (static_cast<int>(enc->codestream_level) < required_level &&
1623
0
       enc->codestream_level != -1)) {
1624
0
    return JXL_API_ERROR(
1625
0
        enc, JXL_ENC_ERR_API_USAGE, "%s",
1626
0
        ("Codestream level verification for level " +
1627
0
         std::to_string(verified_level) + " failed: " + level_message)
1628
0
            .c_str());
1629
0
  }
1630
0
  return JxlErrorOrStatus::Success();
1631
0
}
1632
1633
void JxlEncoderInitExtraChannelInfo(JxlExtraChannelType type,
1634
0
                                    JxlExtraChannelInfo* info) {
1635
0
  info->type = type;
1636
0
  info->bits_per_sample = 8;
1637
0
  info->exponent_bits_per_sample = 0;
1638
0
  info->dim_shift = 0;
1639
0
  info->name_length = 0;
1640
0
  info->alpha_premultiplied = JXL_FALSE;
1641
0
  info->spot_color[0] = 0;
1642
0
  info->spot_color[1] = 0;
1643
0
  info->spot_color[2] = 0;
1644
0
  info->spot_color[3] = 0;
1645
0
  info->cfa_channel = 0;
1646
0
}
1647
1648
JXL_EXPORT JxlEncoderStatus JxlEncoderSetUpsamplingMode(JxlEncoder* enc,
1649
                                                        const int64_t factor,
1650
0
                                                        const int64_t mode) {
1651
  // for convenience, allow calling this with factor 1 and just make it a no-op
1652
0
  if (factor == 1) return JxlErrorOrStatus::Success();
1653
0
  if (factor != 2 && factor != 4 && factor != 8) {
1654
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1655
0
                         "Invalid upsampling factor");
1656
0
  }
1657
0
  if (mode < -1)
1658
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid upsampling mode");
1659
0
  if (mode > 1) {
1660
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_NOT_SUPPORTED,
1661
0
                         "Unsupported upsampling mode");
1662
0
  }
1663
1664
0
  const size_t count = (factor == 2 ? 15 : (factor == 4 ? 55 : 210));
1665
0
  auto& td = enc->metadata.transform_data;
1666
0
  float* weights = (factor == 2 ? td.upsampling2_weights
1667
0
                                : (factor == 4 ? td.upsampling4_weights
1668
0
                                               : td.upsampling8_weights));
1669
0
  if (mode == -1) {
1670
    // Default fancy upsampling: don't signal custom weights
1671
0
    enc->metadata.transform_data.custom_weights_mask &= ~(factor >> 1);
1672
0
  } else if (mode == 0) {
1673
    // Nearest neighbor upsampling
1674
0
    enc->metadata.transform_data.custom_weights_mask |= (factor >> 1);
1675
0
    memset(weights, 0, sizeof(float) * count);
1676
0
    if (factor == 2) {
1677
0
      weights[9] = 1.f;
1678
0
    } else if (factor == 4) {
1679
0
      for (int i : {19, 24, 49}) weights[i] = 1.f;
1680
0
    } else if (factor == 8) {
1681
0
      for (int i : {39, 44, 49, 54, 119, 124, 129, 174, 179, 204}) {
1682
0
        weights[i] = 1.f;
1683
0
      }
1684
0
    }
1685
0
  } else if (mode == 1) {
1686
    // 'Pixel dots' upsampling (nearest-neighbor with cut corners)
1687
0
    JxlEncoderSetUpsamplingMode(enc, factor, 0);
1688
0
    if (factor == 4) {
1689
0
      weights[19] = 0.f;
1690
0
      weights[24] = 0.5f;
1691
0
    } else if (factor == 8) {
1692
0
      for (int i : {39, 44, 49, 119}) weights[i] = 0.f;
1693
0
      for (int i : {54, 124}) weights[i] = 0.5f;
1694
0
    }
1695
0
  }
1696
0
  return JxlErrorOrStatus::Success();
1697
0
}
1698
1699
JXL_EXPORT JxlEncoderStatus JxlEncoderSetExtraChannelInfo(
1700
0
    JxlEncoder* enc, size_t index, const JxlExtraChannelInfo* info) {
1701
0
  if (index >= enc->metadata.m.num_extra_channels) {
1702
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1703
0
                         "Invalid value for the index of extra channel");
1704
0
  }
1705
0
  if (JXL_ENC_SUCCESS != CheckValidBitdepth(info->bits_per_sample,
1706
0
                                            info->exponent_bits_per_sample)) {
1707
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid bit depth");
1708
0
  }
1709
1710
0
  jxl::ExtraChannelInfo& channel = enc->metadata.m.extra_channel_info[index];
1711
0
  channel.type = static_cast<jxl::ExtraChannel>(info->type);
1712
0
  channel.bit_depth.bits_per_sample = info->bits_per_sample;
1713
0
  enc->metadata.m.modular_16_bit_buffer_sufficient &=
1714
0
      info->bits_per_sample <= 12;
1715
0
  channel.bit_depth.exponent_bits_per_sample = info->exponent_bits_per_sample;
1716
0
  channel.bit_depth.floating_point_sample = info->exponent_bits_per_sample != 0;
1717
0
  channel.dim_shift = info->dim_shift;
1718
0
  channel.name = "";
1719
0
  channel.alpha_associated = (info->alpha_premultiplied != 0);
1720
0
  channel.cfa_channel = info->cfa_channel;
1721
0
  channel.spot_color[0] = info->spot_color[0];
1722
0
  channel.spot_color[1] = info->spot_color[1];
1723
0
  channel.spot_color[2] = info->spot_color[2];
1724
0
  channel.spot_color[3] = info->spot_color[3];
1725
0
  std::string level_message;
1726
0
  int required_level = VerifyLevelSettings(enc, &level_message);
1727
0
  int verified_level = (required_level == -1) ? 10 : enc->codestream_level;
1728
0
  if (required_level == -1 ||
1729
0
      (static_cast<int>(enc->codestream_level) < required_level &&
1730
0
       enc->codestream_level != -1)) {
1731
0
    return JXL_API_ERROR(
1732
0
        enc, JXL_ENC_ERR_API_USAGE, "%s",
1733
0
        ("Codestream level verification for level " +
1734
0
         std::to_string(verified_level) + " failed: " + level_message)
1735
0
            .c_str());
1736
0
  }
1737
0
  return JxlErrorOrStatus::Success();
1738
0
}
1739
1740
JXL_EXPORT JxlEncoderStatus JxlEncoderSetExtraChannelName(JxlEncoder* enc,
1741
                                                          size_t index,
1742
                                                          const char* name,
1743
0
                                                          size_t size) {
1744
0
  if (index >= enc->metadata.m.num_extra_channels) {
1745
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1746
0
                         "Invalid value for the index of extra channel");
1747
0
  }
1748
0
  enc->metadata.m.extra_channel_info[index].name =
1749
0
      std::string(name, name + size);
1750
0
  return JxlErrorOrStatus::Success();
1751
0
}
1752
1753
JxlEncoderFrameSettings* JxlEncoderFrameSettingsCreate(
1754
0
    JxlEncoder* enc, const JxlEncoderFrameSettings* source) {
1755
0
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(opts, JxlEncoderFrameSettings,
1756
0
                                           (&enc->memory_manager), nullptr);
1757
0
  opts->enc = enc;
1758
0
  if (source != nullptr) {
1759
0
    opts->values = source->values;
1760
0
  } else {
1761
0
    opts->values.lossless = false;
1762
0
  }
1763
0
  opts->values.cparams.level = enc->codestream_level;
1764
0
  opts->values.cparams.ec_distance.resize(enc->metadata.m.num_extra_channels,
1765
0
                                          0);
1766
1767
0
  JxlEncoderFrameSettings* ret = opts.get();
1768
0
  enc->encoder_options.emplace_back(std::move(opts));
1769
0
  return ret;
1770
0
}
1771
1772
JxlEncoderStatus JxlEncoderSetFrameLossless(
1773
0
    JxlEncoderFrameSettings* frame_settings, const JXL_BOOL lossless) {
1774
0
  if (lossless && frame_settings->enc->basic_info_set &&
1775
0
      frame_settings->enc->metadata.m.xyb_encoded) {
1776
0
    return JXL_API_ERROR(
1777
0
        frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1778
0
        "Set uses_original_profile=true for lossless encoding");
1779
0
  }
1780
0
  frame_settings->values.lossless = FROM_JXL_BOOL(lossless);
1781
0
  return JxlErrorOrStatus::Success();
1782
0
}
1783
1784
JxlEncoderStatus JxlEncoderSetFrameDistance(
1785
0
    JxlEncoderFrameSettings* frame_settings, float distance) {
1786
0
  if (distance < 0.f || distance > 25.f) {
1787
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1788
0
                         "Distance has to be in [0.0..25.0] (corresponding to "
1789
0
                         "quality in [0.0..100.0])");
1790
0
  }
1791
0
  if (distance > 0.f && distance < jxl::kMinButteraugliDistance) {
1792
0
    distance = jxl::kMinButteraugliDistance;
1793
0
  }
1794
0
  frame_settings->values.cparams.butteraugli_distance = distance;
1795
0
  if (distance == 0.f) {
1796
0
    return JxlEncoderSetFrameLossless(frame_settings, JXL_TRUE);
1797
0
  }
1798
0
  return JxlErrorOrStatus::Success();
1799
0
}
1800
1801
JxlEncoderStatus JxlEncoderSetExtraChannelDistance(
1802
0
    JxlEncoderFrameSettings* frame_settings, size_t index, float distance) {
1803
0
  if (index >= frame_settings->enc->metadata.m.num_extra_channels) {
1804
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1805
0
                         "Invalid value for the index of extra channel");
1806
0
  }
1807
0
  if (distance != -1.f && (distance < 0.f || distance > 25.f)) {
1808
0
    return JXL_API_ERROR(
1809
0
        frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1810
0
        "Distance has to be -1 or in [0.0..25.0] (corresponding to "
1811
0
        "quality in [0.0..100.0])");
1812
0
  }
1813
0
  if (distance > 0.f && distance < 0.01f) {
1814
0
    distance = 0.01f;
1815
0
  }
1816
1817
0
  if (index >= frame_settings->values.cparams.ec_distance.size()) {
1818
    // This can only happen if JxlEncoderFrameSettingsCreate() was called before
1819
    // JxlEncoderSetBasicInfo().
1820
0
    frame_settings->values.cparams.ec_distance.resize(
1821
0
        frame_settings->enc->metadata.m.num_extra_channels, 0);
1822
0
  }
1823
1824
0
  frame_settings->values.cparams.ec_distance[index] = distance;
1825
0
  return JxlErrorOrStatus::Success();
1826
0
}
1827
1828
0
float JxlEncoderDistanceFromQuality(float quality) {
1829
0
  return quality >= 100.0 ? 0.0
1830
0
         : quality >= 30
1831
0
             ? 0.1 + (100 - quality) * 0.09
1832
0
             : 53.0 / 3000.0 * quality * quality - 23.0 / 20.0 * quality + 25.0;
1833
0
}
1834
1835
JxlEncoderStatus JxlEncoderFrameSettingsSetOption(
1836
    JxlEncoderFrameSettings* frame_settings, JxlEncoderFrameSettingId option,
1837
0
    int64_t value) {
1838
  // Tri-state to bool convertors.
1839
0
  const auto default_to_true = [](int64_t v) { return v != 0; };
1840
0
  const auto default_to_false = [](int64_t v) { return v == 1; };
1841
1842
  // check if value is -1, 0 or 1 for Override-type options
1843
0
  switch (option) {
1844
0
    case JXL_ENC_FRAME_SETTING_NOISE:
1845
0
    case JXL_ENC_FRAME_SETTING_DOTS:
1846
0
    case JXL_ENC_FRAME_SETTING_PATCHES:
1847
0
    case JXL_ENC_FRAME_SETTING_GABORISH:
1848
0
    case JXL_ENC_FRAME_SETTING_MODULAR:
1849
0
    case JXL_ENC_FRAME_SETTING_KEEP_INVISIBLE:
1850
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER:
1851
0
    case JXL_ENC_FRAME_SETTING_RESPONSIVE:
1852
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_AC:
1853
0
    case JXL_ENC_FRAME_SETTING_QPROGRESSIVE_AC:
1854
0
    case JXL_ENC_FRAME_SETTING_LOSSY_PALETTE:
1855
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_CFL:
1856
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_LFS:
1857
0
    case JXL_ENC_FRAME_SETTING_JPEG_COMPRESS_BOXES:
1858
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF:
1859
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP:
1860
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF:
1861
0
      if (value < -1 || value > 1) {
1862
0
        return JXL_API_ERROR(
1863
0
            frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1864
0
            "Option value has to be -1 (default), 0 (off) or 1 (on)");
1865
0
      }
1866
0
      break;
1867
0
    default:
1868
0
      break;
1869
0
  }
1870
1871
0
  switch (option) {
1872
0
    case JXL_ENC_FRAME_SETTING_EFFORT:
1873
0
      if (frame_settings->enc->allow_expert_options) {
1874
0
        if (value < 1 || value > 11) {
1875
0
          return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
1876
0
                               "Encode effort has to be in [1..11]");
1877
0
        }
1878
0
      } else {
1879
0
        if (value < 1 || value > 10) {
1880
0
          return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
1881
0
                               "Encode effort has to be in [1..10]");
1882
0
        }
1883
0
      }
1884
0
      frame_settings->values.cparams.speed_tier =
1885
0
          static_cast<jxl::SpeedTier>(10 - value);
1886
0
      break;
1887
0
    case JXL_ENC_FRAME_SETTING_BROTLI_EFFORT:
1888
0
      if (value < -1 || value > 11) {
1889
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1890
0
                             "Brotli effort has to be in [-1..11]");
1891
0
      }
1892
      // set cparams for brotli use in JPEG frames
1893
0
      frame_settings->values.cparams.brotli_effort = value;
1894
      // set enc option for brotli use in brob boxes
1895
0
      frame_settings->enc->brotli_effort = value;
1896
0
      break;
1897
0
    case JXL_ENC_FRAME_SETTING_DECODING_SPEED:
1898
0
      if (value < 0 || value > 4) {
1899
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
1900
0
                             "Decoding speed has to be in [0..4]");
1901
0
      }
1902
0
      frame_settings->values.cparams.decoding_speed_tier = value;
1903
0
      break;
1904
0
    case JXL_ENC_FRAME_SETTING_RESAMPLING:
1905
0
      if (value != -1 && value != 1 && value != 2 && value != 4 && value != 8) {
1906
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1907
0
                             "Resampling factor has to be 1, 2, 4 or 8");
1908
0
      }
1909
0
      frame_settings->values.cparams.resampling = value;
1910
0
      break;
1911
0
    case JXL_ENC_FRAME_SETTING_EXTRA_CHANNEL_RESAMPLING:
1912
      // TODO(lode): the jxl codestream allows choosing a different resampling
1913
      // factor for each extra channel, independently per frame. Move this
1914
      // option to a JxlEncoderFrameSettings-option that can be set per extra
1915
      // channel, so needs its own function rather than
1916
      // JxlEncoderFrameSettingsSetOption due to the extra channel index
1917
      // argument required.
1918
0
      if (value != -1 && value != 1 && value != 2 && value != 4 && value != 8) {
1919
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1920
0
                             "Resampling factor has to be 1, 2, 4 or 8");
1921
0
      }
1922
0
      frame_settings->values.cparams.ec_resampling = value;
1923
0
      break;
1924
0
    case JXL_ENC_FRAME_SETTING_ALREADY_DOWNSAMPLED:
1925
0
      if (value < 0 || value > 1) {
1926
0
        return JxlErrorOrStatus::Error();
1927
0
      }
1928
0
      frame_settings->values.cparams.already_downsampled = (value == 1);
1929
0
      break;
1930
0
    case JXL_ENC_FRAME_SETTING_NOISE:
1931
0
      frame_settings->values.cparams.noise = static_cast<jxl::Override>(value);
1932
0
      break;
1933
0
    case JXL_ENC_FRAME_SETTING_DOTS:
1934
0
      frame_settings->values.cparams.dots = static_cast<jxl::Override>(value);
1935
0
      break;
1936
0
    case JXL_ENC_FRAME_SETTING_PATCHES:
1937
0
      frame_settings->values.cparams.patches =
1938
0
          static_cast<jxl::Override>(value);
1939
0
      break;
1940
0
    case JXL_ENC_FRAME_SETTING_EPF:
1941
0
      if (value < -1 || value > 3) {
1942
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1943
0
                             "EPF value has to be in [-1..3]");
1944
0
      }
1945
0
      frame_settings->values.cparams.epf = static_cast<int>(value);
1946
0
      break;
1947
0
    case JXL_ENC_FRAME_SETTING_GABORISH:
1948
0
      frame_settings->values.cparams.gaborish =
1949
0
          static_cast<jxl::Override>(value);
1950
0
      break;
1951
0
    case JXL_ENC_FRAME_SETTING_MODULAR:
1952
0
      frame_settings->values.cparams.modular_mode = (value == 1);
1953
0
      break;
1954
0
    case JXL_ENC_FRAME_SETTING_KEEP_INVISIBLE:
1955
0
      frame_settings->values.cparams.keep_invisible =
1956
0
          static_cast<jxl::Override>(value);
1957
0
      break;
1958
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER:
1959
0
      frame_settings->values.cparams.centerfirst = (value == 1);
1960
0
      break;
1961
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_X:
1962
0
      if (value < -1) {
1963
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1964
0
                             "Center x coordinate has to be -1 or positive");
1965
0
      }
1966
0
      frame_settings->values.cparams.center_x = static_cast<size_t>(value);
1967
0
      break;
1968
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_Y:
1969
0
      if (value < -1) {
1970
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1971
0
                             "Center y coordinate has to be -1 or positive");
1972
0
      }
1973
0
      frame_settings->values.cparams.center_y = static_cast<size_t>(value);
1974
0
      break;
1975
0
    case JXL_ENC_FRAME_SETTING_RESPONSIVE:
1976
0
      frame_settings->values.cparams.responsive = value;
1977
0
      break;
1978
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_AC:
1979
0
      frame_settings->values.cparams.progressive_mode =
1980
0
          static_cast<jxl::Override>(value);
1981
0
      break;
1982
0
    case JXL_ENC_FRAME_SETTING_QPROGRESSIVE_AC:
1983
0
      frame_settings->values.cparams.qprogressive_mode =
1984
0
          static_cast<jxl::Override>(value);
1985
0
      break;
1986
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_DC:
1987
0
      if (value < -1 || value > 2) {
1988
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1989
0
                             "Progressive DC has to be in [-1..2]");
1990
0
      }
1991
0
      frame_settings->values.cparams.progressive_dc = value;
1992
0
      break;
1993
0
    case JXL_ENC_FRAME_SETTING_PALETTE_COLORS:
1994
0
      if (value < -1 || value > 70913) {
1995
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1996
0
                             "Option value has to be in [-1..70913]");
1997
0
      }
1998
0
      if (value == -1) {
1999
0
        frame_settings->values.cparams.palette_colors = 1 << 10;
2000
0
      } else {
2001
0
        frame_settings->values.cparams.palette_colors = value;
2002
0
      }
2003
0
      break;
2004
0
    case JXL_ENC_FRAME_SETTING_LOSSY_PALETTE:
2005
      // TODO(lode): the defaults of some palette settings depend on others.
2006
      // See the logic in cjxl. Similar for other settings. This should be
2007
      // handled in the encoder during JxlEncoderProcessOutput (or,
2008
      // alternatively, in the cjxl binary like now)
2009
0
      frame_settings->values.cparams.lossy_palette = default_to_false(value);
2010
0
      break;
2011
0
    case JXL_ENC_FRAME_SETTING_COLOR_TRANSFORM:
2012
0
      if (value < -1 || value > 2) {
2013
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2014
0
                             "Option value has to be in [-1..2]");
2015
0
      }
2016
0
      if (value == -1) {
2017
0
        frame_settings->values.cparams.color_transform =
2018
0
            jxl::ColorTransform::kXYB;
2019
0
      } else {
2020
0
        frame_settings->values.cparams.color_transform =
2021
0
            static_cast<jxl::ColorTransform>(value);
2022
0
      }
2023
0
      break;
2024
0
    case JXL_ENC_FRAME_SETTING_MODULAR_COLOR_SPACE:
2025
0
      if (value < -1 || value > 41) {
2026
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2027
0
                             "Option value has to be in [-1..41]");
2028
0
      }
2029
0
      frame_settings->values.cparams.colorspace = value;
2030
0
      break;
2031
0
    case JXL_ENC_FRAME_SETTING_MODULAR_GROUP_SIZE:
2032
0
      if (value < -1 || value > 3) {
2033
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2034
0
                             "Option value has to be in [-1..3]");
2035
0
      }
2036
0
      frame_settings->values.cparams.modular_group_size_shift = value;
2037
0
      break;
2038
0
    case JXL_ENC_FRAME_SETTING_MODULAR_PREDICTOR:
2039
0
      if (value < -1 || value > 15) {
2040
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2041
0
                             "Option value has to be in [-1..15]");
2042
0
      }
2043
0
      frame_settings->values.cparams.options.predictor =
2044
0
          static_cast<jxl::Predictor>(value);
2045
0
      break;
2046
0
    case JXL_ENC_FRAME_SETTING_MODULAR_NB_PREV_CHANNELS:
2047
      // The max allowed value can in theory be higher. However, it depends on
2048
      // the effort setting. 11 is the highest safe value that doesn't cause
2049
      // tree_samples to be >= 64 in the encoder. The specification may allow
2050
      // more than this. With more fine tuning higher values could be allowed.
2051
      // For N-channel images, the largest useful value is N-1.
2052
0
      if (value < -1 || value > 11) {
2053
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2054
0
                             "Option value has to be in [-1..11]");
2055
0
      }
2056
0
      if (value == -1) {
2057
0
        frame_settings->values.cparams.options.max_properties = 0;
2058
0
      } else {
2059
0
        frame_settings->values.cparams.options.max_properties = value;
2060
0
      }
2061
0
      break;
2062
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_CFL:
2063
0
      frame_settings->values.cparams.force_cfl_jpeg_recompression =
2064
0
          default_to_true(value);
2065
0
      break;
2066
0
    case JXL_ENC_FRAME_INDEX_BOX:
2067
0
      if (value < 0 || value > 1) {
2068
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2069
0
                             "Option value has to be 0 or 1");
2070
0
      }
2071
0
      frame_settings->values.frame_index_box = true;
2072
0
      break;
2073
0
    case JXL_ENC_FRAME_SETTING_PHOTON_NOISE:
2074
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2075
0
                           "Float option, try setting it with "
2076
0
                           "JxlEncoderFrameSettingsSetFloatOption");
2077
0
    case JXL_ENC_FRAME_SETTING_JPEG_COMPRESS_BOXES:
2078
0
      frame_settings->values.cparams.jpeg_compress_boxes =
2079
0
          default_to_true(value);
2080
0
      break;
2081
0
    case JXL_ENC_FRAME_SETTING_BUFFERING:
2082
0
      if (value < -1 || value > 3) {
2083
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2084
0
                             "Buffering has to be in [-1..3]");
2085
0
      }
2086
0
      frame_settings->values.cparams.buffering = value;
2087
0
      break;
2088
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF:
2089
0
      frame_settings->values.cparams.jpeg_keep_exif = default_to_true(value);
2090
0
      break;
2091
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP:
2092
0
      frame_settings->values.cparams.jpeg_keep_xmp = default_to_true(value);
2093
0
      break;
2094
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF:
2095
0
      frame_settings->values.cparams.jpeg_keep_jumbf = default_to_true(value);
2096
0
      break;
2097
0
    case JXL_ENC_FRAME_SETTING_USE_FULL_IMAGE_HEURISTICS:
2098
0
      if (value < 0 || value > 1) {
2099
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2100
0
                             "Option value has to be 0 or 1");
2101
0
      }
2102
0
      frame_settings->values.cparams.use_full_image_heuristics =
2103
0
          default_to_false(value);
2104
0
      break;
2105
0
    case JXL_ENC_FRAME_SETTING_DISABLE_PERCEPTUAL_HEURISTICS:
2106
0
      if (value < 0 || value > 1) {
2107
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2108
0
                             "Option value has to be 0 or 1");
2109
0
      }
2110
0
      frame_settings->values.cparams.disable_perceptual_optimizations =
2111
0
          default_to_false(value);
2112
0
      if (frame_settings->values.cparams.disable_perceptual_optimizations &&
2113
0
          frame_settings->enc->basic_info_set &&
2114
0
          frame_settings->enc->metadata.m.xyb_encoded) {
2115
0
        return JXL_API_ERROR(
2116
0
            frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2117
0
            "Set uses_original_profile=true for non-perceptual encoding");
2118
0
      }
2119
0
      break;
2120
0
    case JXL_ENC_FRAME_SETTING_OUTPUT_MODE:
2121
0
      if (value < -1 || value > 2) {
2122
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2123
0
                             "Output mode has to be in [-1..2]");
2124
0
      }
2125
0
      frame_settings->values.cparams.output_mode = value;
2126
0
      break;
2127
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_LFS:
2128
0
      frame_settings->values.cparams.force_lfs_jpeg_recompression = value;
2129
0
      break;
2130
0
    case JXL_ENC_FRAME_SETTING_STRIP_ALPHA:
2131
0
      if (value < -1 || value > 2) {
2132
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2133
0
                             "Strip alpha has to be in [-1..2]");
2134
0
      }
2135
0
      frame_settings->values.strip_alpha = static_cast<int>(value);
2136
0
      break;
2137
2138
0
    default:
2139
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2140
0
                           "Unknown option");
2141
0
  }
2142
0
  return JxlErrorOrStatus::Success();
2143
0
}
2144
2145
JxlEncoderStatus JxlEncoderFrameSettingsSetFloatOption(
2146
    JxlEncoderFrameSettings* frame_settings, JxlEncoderFrameSettingId option,
2147
0
    float value) {
2148
0
  switch (option) {
2149
0
    case JXL_ENC_FRAME_SETTING_PHOTON_NOISE:
2150
0
      if (value < 0) return JXL_ENC_ERROR;
2151
      // TODO(lode): add encoder setting to set the 8 floating point values of
2152
      // the noise synthesis parameters per frame for more fine grained control.
2153
0
      frame_settings->values.cparams.photon_noise_iso = value;
2154
0
      return JxlErrorOrStatus::Success();
2155
0
    case JXL_ENC_FRAME_SETTING_MODULAR_MA_TREE_LEARNING_PERCENT:
2156
0
      if (value < -1.f || value > 100.f) {
2157
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2158
0
                             "Option value has to be smaller than 100");
2159
0
      }
2160
      // This value is called "iterations" or "nb_repeats" in cjxl, but is in
2161
      // fact a fraction in range 0.0-1.0, with the default value 0.5.
2162
      // Convert from floating point percentage to floating point fraction here.
2163
0
      if (value < -.5f) {
2164
        // TODO(lode): for this and many other settings (also in
2165
        // JxlEncoderFrameSettingsSetOption), avoid duplicating the default
2166
        // values here and in enc_params.h and options.h, have one location
2167
        // where the defaults are specified.
2168
0
        frame_settings->values.cparams.options.nb_repeats = 0.5f;
2169
0
      } else {
2170
0
        frame_settings->values.cparams.options.nb_repeats = value * 0.01f;
2171
0
      }
2172
0
      return JxlErrorOrStatus::Success();
2173
0
    case JXL_ENC_FRAME_SETTING_CHANNEL_COLORS_GLOBAL_PERCENT:
2174
0
      if (value < -1.f || value > 100.f) {
2175
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2176
0
                             "Option value has to be in [-1..100]");
2177
0
      }
2178
0
      if (value < -.5f) {
2179
0
        frame_settings->values.cparams.channel_colors_pre_transform_percent =
2180
0
            95.0f;
2181
0
      } else {
2182
0
        frame_settings->values.cparams.channel_colors_pre_transform_percent =
2183
0
            value;
2184
0
      }
2185
0
      return JxlErrorOrStatus::Success();
2186
0
    case JXL_ENC_FRAME_SETTING_CHANNEL_COLORS_GROUP_PERCENT:
2187
0
      if (value < -1.f || value > 100.f) {
2188
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2189
0
                             "Option value has to be in [-1..100]");
2190
0
      }
2191
0
      if (value < -.5f) {
2192
0
        frame_settings->values.cparams.channel_colors_percent = 80.0f;
2193
0
      } else {
2194
0
        frame_settings->values.cparams.channel_colors_percent = value;
2195
0
      }
2196
0
      return JxlErrorOrStatus::Success();
2197
0
    case JXL_ENC_FRAME_SETTING_EFFORT:
2198
0
    case JXL_ENC_FRAME_SETTING_DECODING_SPEED:
2199
0
    case JXL_ENC_FRAME_SETTING_RESAMPLING:
2200
0
    case JXL_ENC_FRAME_SETTING_EXTRA_CHANNEL_RESAMPLING:
2201
0
    case JXL_ENC_FRAME_SETTING_ALREADY_DOWNSAMPLED:
2202
0
    case JXL_ENC_FRAME_SETTING_NOISE:
2203
0
    case JXL_ENC_FRAME_SETTING_DOTS:
2204
0
    case JXL_ENC_FRAME_SETTING_PATCHES:
2205
0
    case JXL_ENC_FRAME_SETTING_EPF:
2206
0
    case JXL_ENC_FRAME_SETTING_GABORISH:
2207
0
    case JXL_ENC_FRAME_SETTING_MODULAR:
2208
0
    case JXL_ENC_FRAME_SETTING_KEEP_INVISIBLE:
2209
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER:
2210
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_X:
2211
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_Y:
2212
0
    case JXL_ENC_FRAME_SETTING_RESPONSIVE:
2213
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_AC:
2214
0
    case JXL_ENC_FRAME_SETTING_QPROGRESSIVE_AC:
2215
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_DC:
2216
0
    case JXL_ENC_FRAME_SETTING_PALETTE_COLORS:
2217
0
    case JXL_ENC_FRAME_SETTING_LOSSY_PALETTE:
2218
0
    case JXL_ENC_FRAME_SETTING_COLOR_TRANSFORM:
2219
0
    case JXL_ENC_FRAME_SETTING_MODULAR_COLOR_SPACE:
2220
0
    case JXL_ENC_FRAME_SETTING_MODULAR_GROUP_SIZE:
2221
0
    case JXL_ENC_FRAME_SETTING_MODULAR_PREDICTOR:
2222
0
    case JXL_ENC_FRAME_SETTING_MODULAR_NB_PREV_CHANNELS:
2223
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_CFL:
2224
0
    case JXL_ENC_FRAME_INDEX_BOX:
2225
0
    case JXL_ENC_FRAME_SETTING_BROTLI_EFFORT:
2226
0
    case JXL_ENC_FRAME_SETTING_FILL_ENUM:
2227
0
    case JXL_ENC_FRAME_SETTING_JPEG_COMPRESS_BOXES:
2228
0
    case JXL_ENC_FRAME_SETTING_BUFFERING:
2229
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF:
2230
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP:
2231
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF:
2232
0
    case JXL_ENC_FRAME_SETTING_USE_FULL_IMAGE_HEURISTICS:
2233
0
    case JXL_ENC_FRAME_SETTING_STRIP_ALPHA:
2234
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2235
0
                           "Int option, try setting it with "
2236
0
                           "JxlEncoderFrameSettingsSetOption");
2237
0
    default:
2238
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2239
0
                           "Unknown option");
2240
0
  }
2241
0
}
2242
0
JxlEncoder* JxlEncoderCreate(const JxlMemoryManager* memory_manager) {
2243
0
  JxlMemoryManager local_memory_manager;
2244
0
  if (!jxl::MemoryManagerInit(&local_memory_manager, memory_manager)) {
2245
0
    return nullptr;
2246
0
  }
2247
2248
0
  void* alloc =
2249
0
      jxl::MemoryManagerAlloc(&local_memory_manager, sizeof(JxlEncoder));
2250
0
  if (!alloc) return nullptr;
2251
0
  JxlEncoder* enc = new (alloc) JxlEncoder();
2252
0
  enc->memory_manager = local_memory_manager;
2253
  // TODO(sboukortt): add an API function to set this.
2254
0
  enc->cms = *JxlGetDefaultCms();
2255
0
  enc->cms_set = true;
2256
2257
  // Initialize all the field values.
2258
0
  JxlEncoderReset(enc);
2259
2260
0
  return enc;
2261
0
}
2262
2263
0
void JxlEncoderReset(JxlEncoder* enc) {
2264
0
  enc->thread_pool.reset();
2265
0
  enc->input_queue.clear();
2266
0
  enc->num_queued_frames = 0;
2267
0
  enc->num_queued_boxes = 0;
2268
0
  enc->encoder_options.clear();
2269
0
  enc->codestream_bytes_written_end_of_frame = 0;
2270
0
  enc->wrote_bytes = false;
2271
0
  enc->jxlp_counter = 0;
2272
0
  enc->metadata = jxl::CodecMetadata();
2273
0
  enc->last_used_cparams = jxl::CompressParams();
2274
0
  enc->frames_closed = false;
2275
0
  enc->boxes_closed = false;
2276
0
  enc->basic_info_set = false;
2277
0
  enc->color_encoding_set = false;
2278
0
  enc->intensity_target_set = false;
2279
0
  enc->use_container = false;
2280
0
  enc->use_boxes = false;
2281
0
  enc->container_ftyp_version = -1;
2282
0
  enc->store_jpeg_metadata = false;
2283
0
  enc->codestream_level = -1;
2284
0
  enc->output_processor =
2285
0
      JxlEncoderOutputProcessorWrapper(&enc->memory_manager);
2286
0
  JxlEncoderInitBasicInfo(&enc->basic_info);
2287
2288
  // jxl::JxlEncoderFrameIndexBox frame_index_box;
2289
  // JxlEncoderError error = JxlEncoderError::JXL_ENC_ERR_OK;
2290
  // bool allow_expert_options = false;
2291
  // int brotli_effort = -1;
2292
0
}
2293
2294
0
void JxlEncoderDestroy(JxlEncoder* enc) {
2295
0
  if (enc) {
2296
0
    JxlMemoryManager local_memory_manager = enc->memory_manager;
2297
    // Call destructor directly since custom free function is used.
2298
0
    enc->~JxlEncoder();
2299
0
    jxl::MemoryManagerFree(&local_memory_manager, enc);
2300
0
  }
2301
0
}
2302
2303
0
JxlEncoderError JxlEncoderGetError(JxlEncoder* enc) { return enc->error; }
2304
2305
JxlEncoderStatus JxlEncoderUseContainer(JxlEncoder* enc,
2306
0
                                        JXL_BOOL use_container) {
2307
0
  if (enc->wrote_bytes) {
2308
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2309
0
                         "this setting can only be set at the beginning");
2310
0
  }
2311
0
  enc->use_container = FROM_JXL_BOOL(use_container);
2312
0
  return JxlErrorOrStatus::Success();
2313
0
}
2314
2315
JxlEncoderStatus JxlEncoderStoreJPEGMetadata(JxlEncoder* enc,
2316
0
                                             JXL_BOOL store_jpeg_metadata) {
2317
0
  if (enc->wrote_bytes) {
2318
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2319
0
                         "this setting can only be set at the beginning");
2320
0
  }
2321
0
  enc->store_jpeg_metadata = FROM_JXL_BOOL(store_jpeg_metadata);
2322
0
  return JxlErrorOrStatus::Success();
2323
0
}
2324
2325
0
JxlEncoderStatus JxlEncoderSetCodestreamLevel(JxlEncoder* enc, int level) {
2326
0
  if (level != -1 && level != 5 && level != 10) {
2327
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_NOT_SUPPORTED, "invalid level");
2328
0
  }
2329
0
  if (enc->wrote_bytes) {
2330
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2331
0
                         "this setting can only be set at the beginning");
2332
0
  }
2333
0
  enc->codestream_level = level;
2334
0
  return JxlErrorOrStatus::Success();
2335
0
}
2336
2337
0
int JxlEncoderGetRequiredCodestreamLevel(const JxlEncoder* enc) {
2338
0
  return VerifyLevelSettings(enc, nullptr);
2339
0
}
2340
2341
0
void JxlEncoderSetCms(JxlEncoder* enc, JxlCmsInterface cms) {
2342
0
  jxl::msan::MemoryIsInitialized(&cms, sizeof(cms));
2343
0
  enc->cms = cms;
2344
0
  enc->cms_set = true;
2345
0
}
2346
2347
JxlEncoderStatus JxlEncoderSetParallelRunner(JxlEncoder* enc,
2348
                                             JxlParallelRunner parallel_runner,
2349
0
                                             void* parallel_runner_opaque) {
2350
0
  if (enc->thread_pool) {
2351
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2352
0
                         "parallel runner already set");
2353
0
  }
2354
0
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2355
0
      thread_pool, jxl::ThreadPool,
2356
0
      (&enc->memory_manager, parallel_runner, parallel_runner_opaque),
2357
0
      JXL_API_ERROR(enc, JXL_ENC_ERR_OOM, "can not allocate thread pool"));
2358
0
  enc->thread_pool = std::move(thread_pool);
2359
0
  return JxlErrorOrStatus::Success();
2360
0
}
2361
2362
namespace {
2363
JxlEncoderStatus GetCurrentDimensions(
2364
    const JxlEncoderFrameSettings* frame_settings, size_t& xsize,
2365
0
    size_t& ysize) {
2366
0
  xsize = frame_settings->enc->metadata.xsize();
2367
0
  ysize = frame_settings->enc->metadata.ysize();
2368
0
  if (frame_settings->values.header.layer_info.have_crop) {
2369
0
    xsize = frame_settings->values.header.layer_info.xsize;
2370
0
    ysize = frame_settings->values.header.layer_info.ysize;
2371
0
  }
2372
0
  if (frame_settings->values.cparams.already_downsampled) {
2373
0
    size_t factor = frame_settings->values.cparams.resampling;
2374
0
    xsize = jxl::DivCeil(xsize, factor);
2375
0
    ysize = jxl::DivCeil(ysize, factor);
2376
0
  }
2377
0
  if (xsize == 0 || ysize == 0) {
2378
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2379
0
                         "zero-sized frame is not allowed");
2380
0
  }
2381
0
  return JxlErrorOrStatus::Success();
2382
0
}
2383
}  // namespace
2384
2385
JxlEncoderStatus JxlEncoderAddJPEGFrame(
2386
    const JxlEncoderFrameSettings* frame_settings, const uint8_t* buffer,
2387
0
    size_t size) {
2388
0
  JxlMemoryManager* memory_manager = &frame_settings->enc->memory_manager;
2389
0
  if (frame_settings->enc->frames_closed) {
2390
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2391
0
                         "Frame input is already closed");
2392
0
  }
2393
2394
0
  std::unique_ptr<jxl::jpeg::JPEGData> jpeg_data;
2395
0
  auto decode_jpg = [&]() -> jxl::Status {
2396
0
    JXL_ASSIGN_OR_RETURN(
2397
0
        jpeg_data,
2398
0
        jxl::jpeg::ParseJPG(memory_manager, jxl::Bytes(buffer, size)));
2399
0
    return true;
2400
0
  };
2401
0
  jxl::Status status = decode_jpg();
2402
0
  if (!status) {
2403
0
    if (status.code() == jxl::StatusCode::kUnsupported) {
2404
0
      return JXL_API_ERROR(
2405
0
          frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2406
0
          "Unsupported JPEG feature (CMYK, arithmetic coding, etc.)");
2407
0
    } else {
2408
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_BAD_INPUT,
2409
0
                           "Error during decode of input JPEG");
2410
0
    }
2411
0
  }
2412
2413
0
  if (!frame_settings->enc->color_encoding_set) {
2414
0
    if (!SetColorEncodingFromJpegData(
2415
0
            *jpeg_data, &frame_settings->enc->metadata.m.color_encoding)) {
2416
0
      return JXL_API_ERROR(
2417
0
          frame_settings->enc, JXL_ENC_ERR_BAD_INPUT,
2418
0
          "Error decoding the ICC profile embedded in the input JPEG");
2419
0
    }
2420
0
    frame_settings->enc->color_encoding_set = true;
2421
0
  }
2422
2423
0
  if (!frame_settings->enc->basic_info_set) {
2424
0
    JxlBasicInfo basic_info;
2425
0
    JxlEncoderInitBasicInfo(&basic_info);
2426
0
    basic_info.xsize = jpeg_data->width;
2427
0
    basic_info.ysize = jpeg_data->height;
2428
0
    basic_info.uses_original_profile = JXL_TRUE;
2429
0
    if (JxlEncoderSetBasicInfo(frame_settings->enc, &basic_info) !=
2430
0
        JXL_ENC_SUCCESS) {
2431
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2432
0
                           "Error setting basic info");
2433
0
    }
2434
0
  }
2435
2436
0
  size_t xsize;
2437
0
  size_t ysize;
2438
0
  if (GetCurrentDimensions(frame_settings, xsize, ysize) != JXL_ENC_SUCCESS) {
2439
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2440
0
                         "bad dimensions");
2441
0
  }
2442
0
  if (xsize != static_cast<size_t>(jpeg_data->width) ||
2443
0
      ysize != static_cast<size_t>(jpeg_data->height)) {
2444
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2445
0
                         "JPEG dimensions don't match frame dimensions");
2446
0
  }
2447
2448
0
  if (frame_settings->enc->metadata.m.xyb_encoded) {
2449
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2450
0
                         "Can't XYB encode a lossless JPEG");
2451
0
  }
2452
2453
0
  jxl::jpeg::Blobs blobs;
2454
0
  if (!SetBlobsFromJpegData(*jpeg_data, &blobs)) {
2455
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_BAD_INPUT,
2456
0
                         "Error during parsing of input JPEG blobs");
2457
0
  }
2458
2459
0
  if (!blobs.exif.empty()) {
2460
0
    JxlOrientation orientation = static_cast<JxlOrientation>(
2461
0
        frame_settings->enc->metadata.m.orientation);
2462
0
    jxl::InterpretExif(blobs.exif, &orientation);
2463
0
    frame_settings->enc->metadata.m.orientation = orientation;
2464
0
  }
2465
0
  if (!blobs.exif.empty() && frame_settings->values.cparams.jpeg_keep_exif) {
2466
0
    size_t exif_size = blobs.exif.size();
2467
    // Exif data in JPEG is limited to 64k
2468
0
    if (exif_size > 0xFFFF) {
2469
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2470
0
                           "Exif larger than possible in JPEG?");
2471
0
    }
2472
0
    exif_size += 4;  // prefix 4 zero bytes for tiff offset
2473
0
    std::vector<uint8_t> exif(exif_size);
2474
0
    memcpy(exif.data() + 4, blobs.exif.data(), blobs.exif.size());
2475
0
    JxlEncoderUseBoxes(frame_settings->enc);
2476
0
    JxlEncoderAddBox(
2477
0
        frame_settings->enc, "Exif", exif.data(), exif_size,
2478
0
        TO_JXL_BOOL(frame_settings->values.cparams.jpeg_compress_boxes));
2479
0
  }
2480
0
  if (!blobs.xmp.empty() && frame_settings->values.cparams.jpeg_keep_xmp) {
2481
0
    JxlEncoderUseBoxes(frame_settings->enc);
2482
0
    JxlEncoderAddBox(
2483
0
        frame_settings->enc, "xml ", blobs.xmp.data(), blobs.xmp.size(),
2484
0
        TO_JXL_BOOL(frame_settings->values.cparams.jpeg_compress_boxes));
2485
0
  }
2486
0
  if (!blobs.jumbf.empty() && frame_settings->values.cparams.jpeg_keep_jumbf) {
2487
0
    JxlEncoderUseBoxes(frame_settings->enc);
2488
0
    JxlEncoderAddBox(
2489
0
        frame_settings->enc, "jumb", blobs.jumbf.data(), blobs.jumbf.size(),
2490
0
        TO_JXL_BOOL(frame_settings->values.cparams.jpeg_compress_boxes));
2491
0
  }
2492
0
  if (frame_settings->enc->store_jpeg_metadata) {
2493
0
    if (!frame_settings->values.cparams.jpeg_keep_exif ||
2494
0
        !frame_settings->values.cparams.jpeg_keep_xmp) {
2495
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2496
0
                           "Need to preserve EXIF and XMP to allow JPEG "
2497
0
                           "bitstream reconstruction");
2498
0
    }
2499
0
    std::vector<uint8_t> jpeg_metadata;
2500
0
    if (!jxl::jpeg::EncodeJPEGData(&frame_settings->enc->memory_manager,
2501
0
                                   *jpeg_data, &jpeg_metadata,
2502
0
                                   frame_settings->values.cparams)) {
2503
0
      return JXL_API_ERROR(
2504
0
          frame_settings->enc, JXL_ENC_ERR_JBRD,
2505
0
          "JPEG bitstream reconstruction data cannot be encoded");
2506
0
    }
2507
0
    frame_settings->enc->jpeg_metadata = jpeg_metadata;
2508
0
  }
2509
2510
0
  jxl::JxlEncoderChunkedFrameAdapter frame_data(
2511
0
      xsize, ysize, frame_settings->enc->metadata.m.num_extra_channels);
2512
0
  frame_data.SetJPEGData(std::move(jpeg_data));
2513
2514
  // JxlEncoderQueuedFrame is a struct with no constructors, so we use the
2515
  // default move constructor there.
2516
0
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2517
0
      queued_frame, jxl::JxlEncoderQueuedFrame,
2518
0
      (&frame_settings->enc->memory_manager,
2519
0
       jxl::JxlEncoderQueuedFrame{
2520
0
           frame_settings->values, std::move(frame_data), {}}),
2521
0
      JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_OOM,
2522
0
                    "can not allocate queued frame"));
2523
0
  queued_frame->ec_initialized.resize(
2524
0
      frame_settings->enc->metadata.m.num_extra_channels);
2525
2526
0
  QueueFrame(frame_settings, queued_frame);
2527
0
  return JxlErrorOrStatus::Success();
2528
0
}
2529
2530
static bool CanDoFastLossless(const JxlEncoderFrameSettings* frame_settings,
2531
                              const JxlPixelFormat* pixel_format,
2532
0
                              bool has_alpha) {
2533
0
  if (!frame_settings->values.lossless) {
2534
0
    return false;
2535
0
  }
2536
0
  if (has_alpha && frame_settings->values.strip_alpha > 0) {
2537
0
    return false;
2538
0
  }
2539
  // TODO(veluca): many of the following options could be made to work, but are
2540
  // just not implemented in FJXL's frame header handling yet.
2541
0
  if (frame_settings->values.frame_index_box) {
2542
0
    return false;
2543
0
  }
2544
0
  if (frame_settings->values.header.layer_info.have_crop) {
2545
0
    return false;
2546
0
  }
2547
0
  if (frame_settings->enc->metadata.m.have_animation) {
2548
0
    return false;
2549
0
  }
2550
0
  if (frame_settings->values.cparams.speed_tier != jxl::SpeedTier::kLightning) {
2551
0
    return false;
2552
0
  }
2553
0
  if (frame_settings->values.image_bit_depth.type ==
2554
0
          JxlBitDepthType::JXL_BIT_DEPTH_CUSTOM &&
2555
0
      frame_settings->values.image_bit_depth.bits_per_sample !=
2556
0
          frame_settings->enc->metadata.m.bit_depth.bits_per_sample) {
2557
0
    return false;
2558
0
  }
2559
  // TODO(veluca): implement support for LSB-padded input in fast_lossless.
2560
0
  if (frame_settings->values.image_bit_depth.type ==
2561
0
          JxlBitDepthType::JXL_BIT_DEPTH_FROM_PIXEL_FORMAT &&
2562
0
      frame_settings->enc->metadata.m.bit_depth.bits_per_sample % 8 != 0) {
2563
0
    return false;
2564
0
  }
2565
0
  if (!frame_settings->values.frame_name.empty()) {
2566
0
    return false;
2567
0
  }
2568
  // No extra channels other than alpha.
2569
0
  if (!(has_alpha && frame_settings->enc->metadata.m.num_extra_channels == 1) &&
2570
0
      frame_settings->enc->metadata.m.num_extra_channels != 0) {
2571
0
    return false;
2572
0
  }
2573
0
  if (frame_settings->enc->metadata.m.bit_depth.bits_per_sample > 16) {
2574
0
    return false;
2575
0
  }
2576
0
  if (pixel_format->data_type != JxlDataType::JXL_TYPE_FLOAT16 &&
2577
0
      pixel_format->data_type != JxlDataType::JXL_TYPE_UINT16 &&
2578
0
      pixel_format->data_type != JxlDataType::JXL_TYPE_UINT8) {
2579
0
    return false;
2580
0
  }
2581
0
  if ((frame_settings->enc->metadata.m.bit_depth.bits_per_sample > 8) !=
2582
0
      (pixel_format->data_type == JxlDataType::JXL_TYPE_UINT16 ||
2583
0
       pixel_format->data_type == JxlDataType::JXL_TYPE_FLOAT16)) {
2584
0
    return false;
2585
0
  }
2586
0
  if (!((pixel_format->num_channels == 1 || pixel_format->num_channels == 3) &&
2587
0
        !has_alpha) &&
2588
0
      !((pixel_format->num_channels == 2 || pixel_format->num_channels == 4) &&
2589
0
        has_alpha)) {
2590
0
    return false;
2591
0
  }
2592
2593
0
  return true;
2594
0
}
2595
2596
namespace {
2597
JxlEncoderStatus JxlEncoderAddImageFrameInternal(
2598
    const JxlEncoderFrameSettings* frame_settings, size_t xsize, size_t ysize,
2599
0
    bool streaming, jxl::JxlEncoderChunkedFrameAdapter&& frame_data) {
2600
0
  JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
2601
0
  {
2602
0
    JxlChunkedFrameInputSource input = frame_data.GetInputSource();
2603
0
    input.get_color_channels_pixel_format(input.opaque, &pixel_format);
2604
0
  }
2605
0
  uint32_t num_channels = pixel_format.num_channels;
2606
0
  size_t has_interleaved_alpha =
2607
0
      static_cast<size_t>(num_channels == 2 || num_channels == 4);
2608
2609
0
  if (!frame_settings->enc->basic_info_set) {
2610
    // Basic Info must be set. Otherwise, this is an API misuse.
2611
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2612
0
                         "Basic info or color encoding not set yet");
2613
0
  }
2614
0
  if (frame_settings->enc->frames_closed) {
2615
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2616
0
                         "Frame input already closed");
2617
0
  }
2618
0
  if (num_channels < 3) {
2619
0
    if (frame_settings->enc->basic_info.num_color_channels != 1) {
2620
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2621
0
                           "Grayscale pixel format input for an RGB image");
2622
0
    }
2623
0
  } else {
2624
0
    if (frame_settings->enc->basic_info.num_color_channels != 3) {
2625
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2626
0
                           "RGB pixel format input for a grayscale image");
2627
0
    }
2628
0
  }
2629
0
  if (frame_settings->values.lossless &&
2630
0
      frame_settings->enc->metadata.m.xyb_encoded) {
2631
0
    return JXL_API_ERROR(
2632
0
        frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2633
0
        "Set uses_original_profile=true for lossless encoding");
2634
0
  }
2635
0
  if (frame_settings->values.cparams.disable_perceptual_optimizations &&
2636
0
      frame_settings->enc->metadata.m.xyb_encoded) {
2637
0
    return JXL_API_ERROR(
2638
0
        frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2639
0
        "Set uses_original_profile=true for non-perceptual encoding");
2640
0
  }
2641
0
  if (JXL_ENC_SUCCESS !=
2642
0
      VerifyInputBitDepth(frame_settings->values.image_bit_depth,
2643
0
                          pixel_format)) {
2644
0
    return JXL_API_ERROR_NOSET("Invalid input bit depth");
2645
0
  }
2646
0
  if (has_interleaved_alpha >
2647
0
      frame_settings->enc->metadata.m.num_extra_channels) {
2648
0
    if (frame_settings->values.strip_alpha == kStripAlphaForce) {
2649
0
      has_interleaved_alpha = 0;
2650
0
    } else {
2651
0
      return JXL_API_ERROR(
2652
0
          frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2653
0
          "number of extra channels mismatch (need 1 extra channel for alpha)");
2654
0
    }
2655
0
  }
2656
2657
0
  bool has_alpha = frame_settings->enc->metadata.m.HasAlpha();
2658
2659
  // All required conditions to do fast-lossless.
2660
0
  if (CanDoFastLossless(frame_settings, &pixel_format, has_alpha)) {
2661
0
    const bool big_endian =
2662
0
        pixel_format.endianness == JXL_BIG_ENDIAN ||
2663
0
        (pixel_format.endianness == JXL_NATIVE_ENDIAN && !IsLittleEndian());
2664
2665
0
    RunnerTicket ticket{frame_settings->enc->thread_pool.get()};
2666
0
    JXL_BOOL oneshot = TO_JXL_BOOL(!frame_data.StreamingInput());
2667
0
    auto* frame_state = JxlFastLosslessPrepareFrame(
2668
0
        frame_data.GetInputSource(), xsize, ysize, num_channels,
2669
0
        frame_settings->enc->metadata.m.bit_depth.bits_per_sample, big_endian,
2670
0
        /*effort=*/2, oneshot);
2671
0
    if (!frame_state) {
2672
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2673
0
                           "Internal: JxlFastLosslessPrepareFrame failed");
2674
0
    }
2675
0
    if (!streaming) {
2676
0
      bool ok =
2677
0
          JxlFastLosslessProcessFrame(frame_state, /*is_last=*/false, &ticket,
2678
0
                                      &FastLosslessRunnerAdapter, nullptr);
2679
0
      if (!ok || ticket.has_error) {
2680
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2681
0
                             "Internal: JxlFastLosslessProcessFrame failed");
2682
0
      }
2683
0
    }
2684
0
    QueueFastLosslessFrame(frame_settings, frame_state);
2685
0
    return JxlErrorOrStatus::Success();
2686
0
  }
2687
2688
0
  if (!streaming) {
2689
    // The input callbacks are only guaranteed to be available during frame
2690
    // encoding when both the input and the output is streaming. In all other
2691
    // cases we need to create an internal copy of the frame data.
2692
0
    if (!frame_data.CopyBuffers()) {
2693
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2694
0
                           "Invalid chunked frame input source");
2695
0
    }
2696
0
  }
2697
2698
0
  if (!frame_settings->enc->color_encoding_set) {
2699
0
    jxl::ColorEncoding c_current;
2700
0
    if ((pixel_format.data_type == JXL_TYPE_FLOAT) ||
2701
0
        (pixel_format.data_type == JXL_TYPE_FLOAT16)) {
2702
0
      c_current = jxl::ColorEncoding::LinearSRGB(num_channels < 3);
2703
0
    } else {
2704
0
      c_current = jxl::ColorEncoding::SRGB(num_channels < 3);
2705
0
    }
2706
0
    frame_settings->enc->metadata.m.color_encoding = c_current;
2707
0
  }
2708
  // JxlEncoderQueuedFrame is a struct with no constructors, so we use the
2709
  // default move constructor there.
2710
0
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2711
0
      queued_frame, jxl::JxlEncoderQueuedFrame,
2712
0
      (&frame_settings->enc->memory_manager,
2713
0
       jxl::JxlEncoderQueuedFrame{
2714
0
           frame_settings->values, std::move(frame_data), {}}),
2715
0
      JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_OOM,
2716
0
                    "can not allocate queued frame"));
2717
2718
0
  for (auto& ec_info : frame_settings->enc->metadata.m.extra_channel_info) {
2719
0
    if (has_interleaved_alpha && ec_info.type == jxl::ExtraChannel::kAlpha) {
2720
0
      queued_frame->ec_initialized.push_back(1);
2721
0
      has_interleaved_alpha = 0;  // only first Alpha is initialized
2722
0
    } else {
2723
0
      queued_frame->ec_initialized.push_back(0);
2724
0
    }
2725
0
  }
2726
0
  queued_frame->option_values.cparams.level =
2727
0
      frame_settings->enc->codestream_level;
2728
2729
0
  QueueFrame(frame_settings, queued_frame);
2730
0
  return JxlErrorOrStatus::Success();
2731
0
}
2732
}  // namespace
2733
2734
JxlEncoderStatus JxlEncoderAddImageFrame(
2735
    const JxlEncoderFrameSettings* frame_settings,
2736
0
    const JxlPixelFormat* pixel_format, const void* buffer, size_t size) {
2737
0
  size_t xsize;
2738
0
  size_t ysize;
2739
0
  if (GetCurrentDimensions(frame_settings, xsize, ysize) != JXL_ENC_SUCCESS) {
2740
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2741
0
                         "bad dimensions");
2742
0
  }
2743
0
  jxl::JxlEncoderChunkedFrameAdapter frame_data(
2744
0
      xsize, ysize, frame_settings->enc->metadata.m.num_extra_channels);
2745
0
  if (!frame_data.SetFromBuffer(0, reinterpret_cast<const uint8_t*>(buffer),
2746
0
                                size, *pixel_format)) {
2747
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2748
0
                         "provided image buffer too small");
2749
0
  }
2750
0
  return JxlEncoderAddImageFrameInternal(frame_settings, xsize, ysize,
2751
0
                                         /*streaming=*/false,
2752
0
                                         std::move(frame_data));
2753
0
}
2754
2755
JxlEncoderStatus JxlEncoderAddChunkedFrame(
2756
    const JxlEncoderFrameSettings* frame_settings, JXL_BOOL is_last_frame,
2757
0
    JxlChunkedFrameInputSource chunked_frame_input) {
2758
0
  size_t xsize;
2759
0
  size_t ysize;
2760
0
  if (GetCurrentDimensions(frame_settings, xsize, ysize) != JXL_ENC_SUCCESS) {
2761
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2762
0
                         "bad dimensions");
2763
0
  }
2764
0
  bool streaming = frame_settings->enc->output_processor.OutputProcessorSet();
2765
0
  jxl::JxlEncoderChunkedFrameAdapter frame_data(
2766
0
      xsize, ysize, frame_settings->enc->metadata.m.num_extra_channels);
2767
0
  frame_data.SetInputSource(chunked_frame_input);
2768
0
  auto status = JxlEncoderAddImageFrameInternal(
2769
0
      frame_settings, xsize, ysize, streaming, std::move(frame_data));
2770
0
  if (status != JXL_ENC_SUCCESS) return status;
2771
2772
0
  auto& queued_frame = frame_settings->enc->input_queue.back();
2773
0
  if (queued_frame.frame) {
2774
0
    for (auto& val : queued_frame.frame->ec_initialized) val = 1;
2775
0
  }
2776
2777
0
  if (is_last_frame) {
2778
0
    JxlEncoderCloseFrames(frame_settings->enc);
2779
0
  }
2780
0
  if (streaming) {
2781
0
    return JxlEncoderFlushInput(frame_settings->enc);
2782
0
  }
2783
0
  return JxlErrorOrStatus::Success();
2784
0
}
2785
2786
0
JxlEncoderStatus JxlEncoderUseBoxes(JxlEncoder* enc) {
2787
0
  if (enc->wrote_bytes) {
2788
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2789
0
                         "this setting can only be set at the beginning");
2790
0
  }
2791
0
  enc->use_boxes = true;
2792
0
  return JxlErrorOrStatus::Success();
2793
0
}
2794
2795
JxlEncoderStatus JxlEncoderAddBox(JxlEncoder* enc, const JxlBoxType type,
2796
                                  const uint8_t* contents, size_t size,
2797
0
                                  JXL_BOOL compress_box) {
2798
0
  if (!enc->use_boxes) {
2799
0
    return JXL_API_ERROR(
2800
0
        enc, JXL_ENC_ERR_API_USAGE,
2801
0
        "must set JxlEncoderUseBoxes at the beginning to add boxes");
2802
0
  }
2803
0
  if (enc->boxes_closed) {
2804
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2805
0
                         "Box input already closed");
2806
0
  }
2807
0
  if (compress_box) {
2808
0
    if (memcmp("jxl", type, 3) == 0) {
2809
0
      return JXL_API_ERROR(
2810
0
          enc, JXL_ENC_ERR_API_USAGE,
2811
0
          "brob box may not contain a type starting with \"jxl\"");
2812
0
    }
2813
0
    if (memcmp("jbrd", type, 4) == 0) {
2814
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2815
0
                           "jbrd box may not be brob compressed");
2816
0
    }
2817
0
    if (memcmp("brob", type, 4) == 0) {
2818
      // The compress_box will compress an existing non-brob box into a brob
2819
      // box. If already giving a valid brotli-compressed brob box, set
2820
      // compress_box to false since it is already compressed.
2821
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2822
0
                           "a brob box cannot contain another brob box");
2823
0
    }
2824
0
  }
2825
2826
0
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2827
0
      box, jxl::JxlEncoderQueuedBox, (&enc->memory_manager),
2828
0
      JXL_API_ERROR(enc, JXL_ENC_ERR_OOM, "can not allocate queued box"));
2829
2830
0
  box->type = jxl::MakeBoxType(type);
2831
0
  box->contents.assign(contents, contents + size);
2832
0
  box->compress_box = FROM_JXL_BOOL(compress_box);
2833
0
  QueueBox(enc, box);
2834
0
  return JxlErrorOrStatus::Success();
2835
0
}
2836
2837
JXL_EXPORT JxlEncoderStatus JxlEncoderSetExtraChannelBuffer(
2838
    const JxlEncoderFrameSettings* frame_settings,
2839
    const JxlPixelFormat* pixel_format, const void* buffer, size_t size,
2840
0
    uint32_t index) {
2841
0
  if (index >= frame_settings->enc->metadata.m.num_extra_channels) {
2842
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2843
0
                         "Invalid value for the index of extra channel");
2844
0
  }
2845
0
  if (!frame_settings->enc->basic_info_set ||
2846
0
      !frame_settings->enc->color_encoding_set) {
2847
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2848
0
                         "Basic info has to be set first");
2849
0
  }
2850
0
  if (frame_settings->enc->input_queue.empty()) {
2851
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2852
0
                         "First add image frame, then extra channels");
2853
0
  }
2854
0
  if (frame_settings->enc->frames_closed) {
2855
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2856
0
                         "Frame input already closed");
2857
0
  }
2858
0
  JxlPixelFormat ec_format = *pixel_format;
2859
0
  ec_format.num_channels = 1;
2860
0
  if (JXL_ENC_SUCCESS !=
2861
0
      VerifyInputBitDepth(frame_settings->values.image_bit_depth, ec_format)) {
2862
0
    return JXL_API_ERROR_NOSET("Invalid input bit depth");
2863
0
  }
2864
0
  const uint8_t* uint8_buffer = reinterpret_cast<const uint8_t*>(buffer);
2865
0
  auto* queued_frame = frame_settings->enc->input_queue.back().frame.get();
2866
0
  if (!queued_frame->frame_data.SetFromBuffer(1 + index, uint8_buffer, size,
2867
0
                                              ec_format)) {
2868
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2869
0
                         "provided image buffer too small");
2870
0
  }
2871
0
  queued_frame->ec_initialized[index] = 1;
2872
2873
0
  return JxlErrorOrStatus::Success();
2874
0
}
2875
2876
0
void JxlEncoderCloseFrames(JxlEncoder* enc) { enc->frames_closed = true; }
2877
2878
0
void JxlEncoderCloseBoxes(JxlEncoder* enc) { enc->boxes_closed = true; }
2879
2880
0
void JxlEncoderCloseInput(JxlEncoder* enc) {
2881
0
  JxlEncoderCloseFrames(enc);
2882
0
  JxlEncoderCloseBoxes(enc);
2883
0
}
2884
2885
0
JXL_EXPORT JxlEncoderStatus JxlEncoderFlushInput(JxlEncoder* enc) {
2886
0
  if (!enc->output_processor.OutputProcessorSet()) {
2887
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2888
0
                         "Cannot flush input without setting output "
2889
0
                         "processor with JxlEncoderSetOutputProcessor");
2890
0
  }
2891
0
  while (!enc->input_queue.empty()) {
2892
0
    if (!enc->ProcessOneEnqueuedInput()) {
2893
0
      return JxlErrorOrStatus::Error();
2894
0
    }
2895
0
  }
2896
0
  return JxlErrorOrStatus::Success();
2897
0
}
2898
2899
JXL_EXPORT JxlEncoderStatus JxlEncoderSetOutputProcessor(
2900
0
    JxlEncoder* enc, JxlEncoderOutputProcessor output_processor) {
2901
0
  if (enc->output_processor.HasAvailOut()) {
2902
0
    return JXL_API_ERROR(
2903
0
        enc, JXL_ENC_ERR_API_USAGE,
2904
0
        "Cannot set an output processor when some output was already produced");
2905
0
  }
2906
0
  if (!output_processor.set_finalized_position ||
2907
0
      !output_processor.get_buffer || !output_processor.release_buffer) {
2908
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2909
0
                         "Missing output processor functions");
2910
0
  }
2911
0
  enc->output_processor =
2912
0
      JxlEncoderOutputProcessorWrapper(&enc->memory_manager, output_processor);
2913
0
  return JxlErrorOrStatus::Success();
2914
0
}
2915
2916
JxlEncoderStatus JxlEncoderProcessOutput(JxlEncoder* enc, uint8_t** next_out,
2917
0
                                         size_t* avail_out) {
2918
0
  if (enc->output_processor.OutputProcessorSet()) {
2919
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2920
0
                         "Cannot call JxlEncoderProcessOutput after calling "
2921
0
                         "JxlEncoderSetOutputProcessor");
2922
0
  }
2923
0
  if (!enc->output_processor.SetAvailOut(next_out, avail_out)) {
2924
0
    return JxlErrorOrStatus::Error();
2925
0
  }
2926
0
  while (*avail_out != 0 && !enc->input_queue.empty()) {
2927
0
    if (!enc->ProcessOneEnqueuedInput()) {
2928
0
      return JxlErrorOrStatus::Error();
2929
0
    }
2930
0
  }
2931
2932
0
  if (!enc->input_queue.empty() || enc->output_processor.HasOutputToWrite()) {
2933
0
    return JxlErrorOrStatus::MoreOutput();
2934
0
  }
2935
0
  return JxlErrorOrStatus::Success();
2936
0
}
2937
2938
JxlEncoderStatus JxlEncoderSetFrameHeader(
2939
    JxlEncoderFrameSettings* frame_settings,
2940
0
    const JxlFrameHeader* frame_header) {
2941
0
  if (frame_header->layer_info.blend_info.source > 3) {
2942
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2943
0
                         "invalid blending source index");
2944
0
  }
2945
  // If there are no extra channels, it's ok for the value to be 0.
2946
0
  if (frame_header->layer_info.blend_info.alpha != 0 &&
2947
0
      frame_header->layer_info.blend_info.alpha >=
2948
0
          frame_settings->enc->metadata.m.extra_channel_info.size()) {
2949
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2950
0
                         "alpha blend channel index out of bounds");
2951
0
  }
2952
2953
0
  frame_settings->values.header = *frame_header;
2954
  // Setting the frame header resets the frame name, it must be set again with
2955
  // JxlEncoderSetFrameName if desired.
2956
0
  frame_settings->values.frame_name = "";
2957
2958
0
  return JxlErrorOrStatus::Success();
2959
0
}
2960
2961
JxlEncoderStatus JxlEncoderSetExtraChannelBlendInfo(
2962
    JxlEncoderFrameSettings* frame_settings, size_t index,
2963
0
    const JxlBlendInfo* blend_info) {
2964
0
  if (index >= frame_settings->enc->metadata.m.num_extra_channels) {
2965
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2966
0
                         "Invalid value for the index of extra channel");
2967
0
  }
2968
2969
0
  if (frame_settings->values.extra_channel_blend_info.size() !=
2970
0
      frame_settings->enc->metadata.m.num_extra_channels) {
2971
0
    JxlBlendInfo default_blend_info;
2972
0
    JxlEncoderInitBlendInfo(&default_blend_info);
2973
0
    frame_settings->values.extra_channel_blend_info.resize(
2974
0
        frame_settings->enc->metadata.m.num_extra_channels, default_blend_info);
2975
0
  }
2976
0
  frame_settings->values.extra_channel_blend_info[index] = *blend_info;
2977
0
  return JxlErrorOrStatus::Success();
2978
0
}
2979
2980
JxlEncoderStatus JxlEncoderSetFrameName(JxlEncoderFrameSettings* frame_settings,
2981
0
                                        const char* frame_name) {
2982
0
  std::string str = frame_name ? frame_name : "";
2983
0
  if (str.size() > 1071) {
2984
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2985
0
                         "frame name can be max 1071 bytes long");
2986
0
  }
2987
0
  frame_settings->values.frame_name = str;
2988
0
  frame_settings->values.header.name_length = str.size();
2989
0
  return JxlErrorOrStatus::Success();
2990
0
}
2991
2992
JxlEncoderStatus JxlEncoderSetFrameBitDepth(
2993
0
    JxlEncoderFrameSettings* frame_settings, const JxlBitDepth* bit_depth) {
2994
0
  if (bit_depth->type != JXL_BIT_DEPTH_FROM_PIXEL_FORMAT &&
2995
0
      bit_depth->type != JXL_BIT_DEPTH_FROM_CODESTREAM) {
2996
0
    return JXL_API_ERROR_NOSET(
2997
0
        "Only JXL_BIT_DEPTH_FROM_PIXEL_FORMAT and "
2998
0
        "JXL_BIT_DEPTH_FROM_CODESTREAM is implemented "
2999
0
        "for input buffers.");
3000
0
  }
3001
0
  frame_settings->values.image_bit_depth = *bit_depth;
3002
0
  return JxlErrorOrStatus::Success();
3003
0
}
3004
3005
void JxlColorEncodingSetToSRGB(JxlColorEncoding* color_encoding,
3006
500
                               JXL_BOOL is_gray) {
3007
500
  *color_encoding =
3008
500
      jxl::ColorEncoding::SRGB(FROM_JXL_BOOL(is_gray)).ToExternal();
3009
500
}
3010
3011
void JxlColorEncodingSetToLinearSRGB(JxlColorEncoding* color_encoding,
3012
0
                                     JXL_BOOL is_gray) {
3013
0
  *color_encoding =
3014
0
      jxl::ColorEncoding::LinearSRGB(FROM_JXL_BOOL(is_gray)).ToExternal();
3015
0
}
3016
3017
0
void JxlEncoderAllowExpertOptions(JxlEncoder* enc) {
3018
0
  enc->allow_expert_options = true;
3019
0
}
3020
3021
JXL_EXPORT void JxlEncoderSetDebugImageCallback(
3022
    JxlEncoderFrameSettings* frame_settings, JxlDebugImageCallback callback,
3023
0
    void* opaque) {
3024
0
  frame_settings->values.cparams.debug_image = callback;
3025
0
  frame_settings->values.cparams.debug_image_opaque = opaque;
3026
0
}
3027
3028
0
JXL_EXPORT JxlEncoderStats* JxlEncoderStatsCreate() {
3029
0
  JxlEncoderStats* result = new JxlEncoderStats();
3030
0
  result->aux_out = jxl::make_unique<jxl::AuxOut>();
3031
0
  return result;
3032
0
}
3033
3034
0
JXL_EXPORT void JxlEncoderStatsDestroy(JxlEncoderStats* stats) { delete stats; }
3035
3036
JXL_EXPORT void JxlEncoderCollectStats(JxlEncoderFrameSettings* frame_settings,
3037
0
                                       JxlEncoderStats* stats) {
3038
0
  if (!stats) return;
3039
0
  frame_settings->values.aux_out = stats->aux_out.get();
3040
0
}
3041
3042
JXL_EXPORT size_t JxlEncoderStatsGet(const JxlEncoderStats* stats,
3043
0
                                     JxlEncoderStatsKey key) {
3044
0
  if (!stats) return 0;
3045
0
  const jxl::AuxOut& aux_out = *stats->aux_out;
3046
0
  switch (key) {
3047
0
    case JXL_ENC_STAT_HEADER_BITS:
3048
0
      return aux_out.layer(jxl::LayerType::Header).total_bits;
3049
0
    case JXL_ENC_STAT_TOC_BITS:
3050
0
      return aux_out.layer(jxl::LayerType::Toc).total_bits;
3051
0
    case JXL_ENC_STAT_DICTIONARY_BITS:
3052
0
      return aux_out.layer(jxl::LayerType::Dictionary).total_bits;
3053
0
    case JXL_ENC_STAT_SPLINES_BITS:
3054
0
      return aux_out.layer(jxl::LayerType::Splines).total_bits;
3055
0
    case JXL_ENC_STAT_NOISE_BITS:
3056
0
      return aux_out.layer(jxl::LayerType::Noise).total_bits;
3057
0
    case JXL_ENC_STAT_QUANT_BITS:
3058
0
      return aux_out.layer(jxl::LayerType::Quant).total_bits;
3059
0
    case JXL_ENC_STAT_MODULAR_TREE_BITS:
3060
0
      return aux_out.layer(jxl::LayerType::ModularTree).total_bits;
3061
0
    case JXL_ENC_STAT_MODULAR_GLOBAL_BITS:
3062
0
      return aux_out.layer(jxl::LayerType::ModularGlobal).total_bits;
3063
0
    case JXL_ENC_STAT_DC_BITS:
3064
0
      return aux_out.layer(jxl::LayerType::Dc).total_bits;
3065
0
    case JXL_ENC_STAT_MODULAR_DC_GROUP_BITS:
3066
0
      return aux_out.layer(jxl::LayerType::ModularDcGroup).total_bits;
3067
0
    case JXL_ENC_STAT_CONTROL_FIELDS_BITS:
3068
0
      return aux_out.layer(jxl::LayerType::ControlFields).total_bits;
3069
0
    case JXL_ENC_STAT_COEF_ORDER_BITS:
3070
0
      return aux_out.layer(jxl::LayerType::Order).total_bits;
3071
0
    case JXL_ENC_STAT_AC_HISTOGRAM_BITS:
3072
0
      return aux_out.layer(jxl::LayerType::Ac).total_bits;
3073
0
    case JXL_ENC_STAT_AC_BITS:
3074
0
      return aux_out.layer(jxl::LayerType::AcTokens).total_bits;
3075
0
    case JXL_ENC_STAT_MODULAR_AC_GROUP_BITS:
3076
0
      return aux_out.layer(jxl::LayerType::ModularAcGroup).total_bits;
3077
0
    case JXL_ENC_STAT_NUM_SMALL_BLOCKS:
3078
0
      return aux_out.num_small_blocks;
3079
0
    case JXL_ENC_STAT_NUM_DCT4X8_BLOCKS:
3080
0
      return aux_out.num_dct4x8_blocks;
3081
0
    case JXL_ENC_STAT_NUM_AFV_BLOCKS:
3082
0
      return aux_out.num_afv_blocks;
3083
0
    case JXL_ENC_STAT_NUM_DCT8_BLOCKS:
3084
0
      return aux_out.num_dct8_blocks;
3085
0
    case JXL_ENC_STAT_NUM_DCT8X32_BLOCKS:
3086
0
      return aux_out.num_dct16_blocks;
3087
0
    case JXL_ENC_STAT_NUM_DCT16_BLOCKS:
3088
0
      return aux_out.num_dct16x32_blocks;
3089
0
    case JXL_ENC_STAT_NUM_DCT16X32_BLOCKS:
3090
0
      return aux_out.num_dct32_blocks;
3091
0
    case JXL_ENC_STAT_NUM_DCT32_BLOCKS:
3092
0
      return aux_out.num_dct32x64_blocks;
3093
0
    case JXL_ENC_STAT_NUM_DCT32X64_BLOCKS:
3094
0
      return aux_out.num_dct32x64_blocks;
3095
0
    case JXL_ENC_STAT_NUM_DCT64_BLOCKS:
3096
0
      return aux_out.num_dct64_blocks;
3097
0
    case JXL_ENC_STAT_NUM_BUTTERAUGLI_ITERS:
3098
0
      return aux_out.num_butteraugli_iters;
3099
0
    default:
3100
0
      return 0;
3101
0
  }
3102
0
}
3103
3104
JXL_EXPORT void JxlEncoderStatsMerge(JxlEncoderStats* stats,
3105
0
                                     const JxlEncoderStats* other) {
3106
0
  if (!stats || !other) return;
3107
0
  stats->aux_out->Assimilate(*other->aux_out);
3108
0
}