Coverage Report

Created: 2026-09-28 06:47

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
102
  operator jxl::Status() const {
62
102
    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
102
      default:
68
102
        return jxl::StatusCode::kGenericError;
69
102
    }
70
102
  }
71
  // NOLINTNEXTLINE(google-explicit-constructor)
72
25.4k
  operator JxlEncoderStatus() const { return error_; }
73
74
25.2k
  static JxlErrorOrStatus Success() {
75
25.2k
    return JxlErrorOrStatus(JXL_ENC_SUCCESS);
76
25.2k
  }
77
78
2
  static JxlErrorOrStatus MoreOutput() {
79
2
    return JxlErrorOrStatus(JXL_ENC_NEED_MORE_OUTPUT);
80
2
  }
81
82
277
  static JxlErrorOrStatus Error() { return JxlErrorOrStatus(JXL_ENC_ERROR); }
83
84
 private:
85
25.5k
  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
175
  (enc->error = error_code,                                                    \
102
175
   ((JXL_IS_DEBUG_BUILD) &&                                                    \
103
175
    ::jxl::Debug(("%s:%d: " format "\n"), __FILE__, __LINE__, ##__VA_ARGS__)), \
104
175
   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
11.8k
                                            size_t requested_size) {
113
11.8k
  JXL_ENSURE(min_size > 0);
114
11.8k
  JXL_ENSURE(!has_buffer_);
115
11.8k
  if (stop_requested_) return jxl::StatusCode::kNotEnoughBytes;
116
11.8k
  requested_size = std::max(min_size, requested_size);
117
118
  // If we support seeking, output_position_ == position_.
119
11.8k
  if (external_output_processor_ && external_output_processor_->seek) {
120
0
    JXL_ENSURE(output_position_ == position_);
121
0
  }
122
  // Otherwise, output_position_ <= position_.
123
11.8k
  JXL_ENSURE(output_position_ <= position_);
124
11.8k
  size_t additional_size = position_ - output_position_;
125
11.8k
  JXL_ENSURE(memory_manager_ != nullptr);
126
127
11.8k
  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
11.8k
  } else if (avail_out_ != nullptr) {
150
10.9k
    if (min_size + additional_size < *avail_out_) {
151
10.9k
      internal_buffers_.emplace(position_, InternalBuffer(memory_manager_));
152
10.9k
      has_buffer_ = true;
153
10.9k
      return JxlOutputProcessorBuffer(*next_out_ + additional_size,
154
10.9k
                                      *avail_out_ - additional_size, 0, this);
155
10.9k
    }
156
10.9k
  }
157
158
  // Otherwise, we need to allocate our own buffer.
159
895
  auto it =
160
895
      internal_buffers_.emplace(position_, InternalBuffer(memory_manager_))
161
895
          .first;
162
895
  InternalBuffer& buffer = it->second;
163
895
  size_t alloc_size = requested_size;
164
895
  it++;
165
895
  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
895
  JXL_RETURN_IF_ERROR(buffer.owned_data.resize(alloc_size));
170
895
  has_buffer_ = true;
171
895
  return JxlOutputProcessorBuffer(buffer.owned_data.data(), alloc_size, 0,
172
895
                                  this);
173
895
}
174
175
2.57k
jxl::Status JxlEncoderOutputProcessorWrapper::Seek(size_t pos) {
176
2.57k
  JXL_ENSURE(!has_buffer_);
177
2.57k
  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
2.57k
  JXL_ENSURE(pos >= finalized_position_);
182
2.57k
  position_ = pos;
183
2.57k
  return true;
184
2.57k
}
185
186
6.72k
jxl::Status JxlEncoderOutputProcessorWrapper::SetFinalizedPosition() {
187
6.72k
  JXL_ENSURE(!has_buffer_);
188
6.72k
  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
6.72k
  finalized_position_ = position_;
193
6.72k
  JXL_RETURN_IF_ERROR(FlushOutput(next_out_, avail_out_));
194
6.72k
  return true;
195
6.72k
}
196
197
jxl::Status JxlEncoderOutputProcessorWrapper::SetAvailOut(uint8_t** next_out,
198
2.90k
                                                          size_t* avail_out) {
199
2.90k
  JXL_ENSURE(!external_output_processor_);
200
2.90k
  avail_out_ = avail_out;
201
2.90k
  next_out_ = next_out;
202
2.90k
  JXL_RETURN_IF_ERROR(FlushOutput(next_out_, avail_out_));
203
2.90k
  return true;
204
2.90k
}
205
206
jxl::Status JxlEncoderOutputProcessorWrapper::CopyOutput(
207
893
    std::vector<uint8_t>& output) {
208
893
  output.resize(64);
209
893
  size_t avail_out = output.size();
210
893
  uint8_t* next_out = output.data();
211
6.77k
  while (HasOutputToWrite()) {
212
5.88k
    JXL_RETURN_IF_ERROR(FlushOutput(&next_out, &avail_out));
213
5.88k
    if (avail_out == 0) {
214
4.98k
      size_t offset = next_out - output.data();
215
4.98k
      output.resize(output.size() * 2);
216
4.98k
      next_out = output.data() + offset;
217
4.98k
      avail_out = output.size() - offset;
218
4.98k
    }
219
5.88k
  }
220
893
  output.resize(output.size() - avail_out);
221
893
  return true;
222
893
}
223
224
11.8k
jxl::Status JxlEncoderOutputProcessorWrapper::ReleaseBuffer(size_t bytes_used) {
225
11.8k
  JXL_ENSURE(has_buffer_);
226
11.8k
  has_buffer_ = false;
227
11.8k
  auto it = internal_buffers_.find(position_);
228
11.8k
  JXL_ENSURE(it != internal_buffers_.end());
229
11.8k
  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
11.8k
  it->second.written_bytes = bytes_used;
238
11.8k
  position_ += bytes_used;
239
240
11.8k
  auto it_to_next = it;
241
11.8k
  it_to_next++;
242
11.8k
  if (it_to_next != internal_buffers_.end()) {
243
832
    JXL_ENSURE(it_to_next->first >= position_);
244
832
  }
245
246
11.8k
  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
11.8k
  return true;
284
11.8k
}
285
286
// Tries to write all the bytes up to the finalized position.
287
jxl::Status JxlEncoderOutputProcessorWrapper::FlushOutput(uint8_t** next_out,
288
15.5k
                                                          size_t* avail_out) {
289
15.5k
  JXL_ENSURE(!has_buffer_);
290
15.5k
  if (!external_output_processor_ && !avail_out) {
291
893
    return true;
292
893
  }
293
31.3k
  while (output_position_ < finalized_position_ &&
294
21.7k
         (avail_out == nullptr || *avail_out > 0)) {
295
16.7k
    JXL_ENSURE(!internal_buffers_.empty());
296
16.7k
    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
16.7k
    JXL_ENSURE(output_position_ >= it->first);
300
16.7k
    JXL_ENSURE(it->second.written_bytes != 0);
301
16.7k
    size_t buffer_last_byte = it->first + it->second.written_bytes;
302
16.7k
    if (!it->second.owned_data.empty()) {
303
5.88k
      size_t start_in_buffer = output_position_ - it->first;
304
      // Guaranteed by the invariant on `internal_buffers_`.
305
5.88k
      JXL_ENSURE(buffer_last_byte > output_position_);
306
5.88k
      size_t num_to_write =
307
5.88k
          std::min(buffer_last_byte, finalized_position_) - output_position_;
308
5.88k
      if (avail_out != nullptr) {
309
5.88k
        size_t n = std::min(num_to_write, *avail_out);
310
5.88k
        memcpy(*next_out, it->second.owned_data.data() + start_in_buffer, n);
311
5.88k
        *avail_out -= n;
312
5.88k
        *next_out += n;
313
5.88k
        output_position_ += n;
314
5.88k
      } 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
10.8k
    } else {
322
10.8k
      size_t advance =
323
10.8k
          std::min(buffer_last_byte, finalized_position_) - output_position_;
324
10.8k
      output_position_ += advance;
325
10.8k
      if (avail_out != nullptr) {
326
10.8k
        *next_out += advance;
327
10.8k
        *avail_out -= advance;
328
10.8k
      }
329
10.8k
    }
330
16.7k
    if (buffer_last_byte == output_position_) {
331
11.7k
      internal_buffers_.erase(it);
332
11.7k
    }
333
16.7k
    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
16.7k
  }
338
14.6k
  return true;
339
14.6k
}
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
2.45k
                      bool force_large_box, uint8_t* output) {
363
2.45k
  uint64_t box_size = 0;
364
2.45k
  bool large_size = false;
365
2.45k
  if (!unbounded) {
366
2.45k
    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
2.45k
    } else {
372
2.45k
      box_size = size + kSmallBoxHeaderSize;
373
2.45k
    }
374
2.45k
  }
375
376
2.45k
  size_t idx = 0;
377
2.45k
  {
378
2.45k
    const uint64_t store = large_size ? 1 : box_size;
379
12.2k
    for (size_t i = 0; i < 4; i++) {
380
9.81k
      output[idx++] = store >> (8 * (3 - i)) & 0xff;
381
9.81k
    }
382
2.45k
  }
383
12.2k
  for (size_t i = 0; i < 4; i++) {
384
9.81k
    output[idx++] = type[i];
385
9.81k
  }
386
387
2.45k
  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
2.45k
  return idx;
393
2.45k
}
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
82
                                  const WriteBox& write_box) {
400
82
  size_t current_position = output_processor.CurrentPosition();
401
82
  bool large_box = false;
402
82
  size_t box_header_size = 0;
403
82
  if (box_max_size >= jxl::kLargeBoxContentSizeThreshold && !unbounded) {
404
0
    box_header_size = jxl::kLargeBoxHeaderSize;
405
0
    large_box = true;
406
82
  } else {
407
82
    box_header_size = jxl::kSmallBoxHeaderSize;
408
82
  }
409
82
  JXL_RETURN_IF_ERROR(
410
82
      output_processor.Seek(current_position + box_header_size));
411
82
  size_t box_contents_start = output_processor.CurrentPosition();
412
82
  JXL_RETURN_IF_ERROR(write_box());
413
82
  size_t box_contents_end = output_processor.CurrentPosition();
414
82
  JXL_RETURN_IF_ERROR(output_processor.Seek(current_position));
415
82
  JXL_ENSURE(box_contents_end >= box_contents_start);
416
82
  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
82
  {
424
82
    JXL_ASSIGN_OR_RETURN(
425
82
        auto buffer,
426
82
        output_processor.GetBuffer(box_contents_start - current_position));
427
82
    const size_t n =
428
82
        jxl::WriteBoxHeader(type, box_contents_end - box_contents_start,
429
82
                            unbounded, large_box, buffer.data());
430
82
    JXL_ENSURE(n == box_header_size);
431
82
    JXL_RETURN_IF_ERROR(buffer.advance(n));
432
82
  }
433
82
  JXL_RETURN_IF_ERROR(output_processor.Seek(box_contents_end));
434
82
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
435
82
  return jxl::OkStatus();
436
82
}
encode.cc:jxl::Status JxlEncoder::AppendBox<JxlEncoder::ProcessOneEnqueuedInput()::$_2>(std::__1::array<unsigned char, 4ul> const&, bool, unsigned long, JxlEncoder::ProcessOneEnqueuedInput()::$_2 const&)
Line
Count
Source
399
41
                                  const WriteBox& write_box) {
400
41
  size_t current_position = output_processor.CurrentPosition();
401
41
  bool large_box = false;
402
41
  size_t box_header_size = 0;
403
41
  if (box_max_size >= jxl::kLargeBoxContentSizeThreshold && !unbounded) {
404
0
    box_header_size = jxl::kLargeBoxHeaderSize;
405
0
    large_box = true;
406
41
  } else {
407
41
    box_header_size = jxl::kSmallBoxHeaderSize;
408
41
  }
409
41
  JXL_RETURN_IF_ERROR(
410
41
      output_processor.Seek(current_position + box_header_size));
411
41
  size_t box_contents_start = output_processor.CurrentPosition();
412
41
  JXL_RETURN_IF_ERROR(write_box());
413
41
  size_t box_contents_end = output_processor.CurrentPosition();
414
41
  JXL_RETURN_IF_ERROR(output_processor.Seek(current_position));
415
41
  JXL_ENSURE(box_contents_end >= box_contents_start);
416
41
  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
41
  {
424
41
    JXL_ASSIGN_OR_RETURN(
425
41
        auto buffer,
426
41
        output_processor.GetBuffer(box_contents_start - current_position));
427
41
    const size_t n =
428
41
        jxl::WriteBoxHeader(type, box_contents_end - box_contents_start,
429
41
                            unbounded, large_box, buffer.data());
430
41
    JXL_ENSURE(n == box_header_size);
431
41
    JXL_RETURN_IF_ERROR(buffer.advance(n));
432
41
  }
433
41
  JXL_RETURN_IF_ERROR(output_processor.Seek(box_contents_end));
434
41
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
435
41
  return jxl::OkStatus();
436
41
}
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&)
Line
Count
Source
399
41
                                  const WriteBox& write_box) {
400
41
  size_t current_position = output_processor.CurrentPosition();
401
41
  bool large_box = false;
402
41
  size_t box_header_size = 0;
403
41
  if (box_max_size >= jxl::kLargeBoxContentSizeThreshold && !unbounded) {
404
0
    box_header_size = jxl::kLargeBoxHeaderSize;
405
0
    large_box = true;
406
41
  } else {
407
41
    box_header_size = jxl::kSmallBoxHeaderSize;
408
41
  }
409
41
  JXL_RETURN_IF_ERROR(
410
41
      output_processor.Seek(current_position + box_header_size));
411
41
  size_t box_contents_start = output_processor.CurrentPosition();
412
41
  JXL_RETURN_IF_ERROR(write_box());
413
41
  size_t box_contents_end = output_processor.CurrentPosition();
414
41
  JXL_RETURN_IF_ERROR(output_processor.Seek(current_position));
415
41
  JXL_ENSURE(box_contents_end >= box_contents_start);
416
41
  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
41
  {
424
41
    JXL_ASSIGN_OR_RETURN(
425
41
        auto buffer,
426
41
        output_processor.GetBuffer(box_contents_start - current_position));
427
41
    const size_t n =
428
41
        jxl::WriteBoxHeader(type, box_contents_end - box_contents_start,
429
41
                            unbounded, large_box, buffer.data());
430
41
    JXL_ENSURE(n == box_header_size);
431
41
    JXL_RETURN_IF_ERROR(buffer.advance(n));
432
41
  }
433
41
  JXL_RETURN_IF_ERROR(output_processor.Seek(box_contents_end));
434
41
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
435
41
  return jxl::OkStatus();
436
41
}
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
41
                                              const BoxContents& contents) {
441
41
  size_t size = std::end(contents) - std::begin(contents);
442
41
  return AppendBox(type, /*unbounded=*/false, size,
443
41
                   [&]() { return AppendData(output_processor, contents); });
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
Line
Count
Source
443
41
                   [&]() { return AppendData(output_processor, contents); });
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
41
}
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&)
Line
Count
Source
440
41
                                              const BoxContents& contents) {
441
41
  size_t size = std::end(contents) - std::begin(contents);
442
41
  return AppendBox(type, /*unbounded=*/false, size,
443
41
                   [&]() { return AppendData(output_processor, contents); });
444
41
}
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
82
void WriteJxlpBoxCounter(uint32_t counter, bool last, uint8_t* buffer) {
458
82
  if (last) counter |= 0x80000000;
459
410
  for (size_t i = 0; i < 4; i++) {
460
328
    buffer[i] = counter >> (8 * (3 - i)) & 0xff;
461
328
  }
462
82
}
463
464
jxl::Status WriteJxlpBoxCounter(uint32_t counter, bool last,
465
41
                                JxlOutputProcessorBuffer& buffer) {
466
41
  uint8_t buf[4];
467
41
  WriteJxlpBoxCounter(counter, last, buf);
468
41
  JXL_RETURN_IF_ERROR(buffer.append(buf, 4));
469
41
  return true;
470
41
}
471
472
void QueueFrame(
473
    const JxlEncoderFrameSettings* frame_settings,
474
2.90k
    jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedFrame>& frame) {
475
2.90k
  if (frame_settings->values.lossless) {
476
0
    frame->option_values.cparams.SetLossless();
477
0
  }
478
479
2.90k
  jxl::JxlEncoderQueuedInput queued_input(frame_settings->enc->memory_manager);
480
2.90k
  int om = frame->option_values.cparams.output_mode;
481
2.90k
  if (om < 0) om = (frame->option_values.cparams.buffering == 3 ? 1 : 0);
482
2.90k
  queued_input.output_mode = om;
483
2.90k
  queued_input.frame = std::move(frame);
484
2.90k
  frame_settings->enc->input_queue.emplace_back(std::move(queued_input));
485
2.90k
  frame_settings->enc->num_queued_frames++;
486
2.90k
}
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
41
              jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedBox>& box) {
502
41
  jxl::JxlEncoderQueuedInput queued_input(enc->memory_manager);
503
41
  queued_input.box = std::move(box);
504
41
  enc->input_queue.emplace_back(std::move(queued_input));
505
41
  enc->num_queued_boxes++;
506
41
}
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
6.78k
int VerifyLevelSettings(const JxlEncoder* enc, std::string* debug_string) {
561
6.78k
  const auto& m = enc->metadata.m;
562
563
6.78k
  uint64_t xsize = enc->metadata.size.xsize();
564
6.78k
  uint64_t ysize = enc->metadata.size.ysize();
565
  // The uncompressed ICC size, if it is used.
566
6.78k
  size_t icc_size = 0;
567
6.78k
  if (m.color_encoding.WantICC()) {
568
0
    icc_size = m.color_encoding.ICC().size();
569
0
  }
570
571
  // Level 10 checks
572
573
6.78k
  if (xsize > (1ull << 30ull) || ysize > (1ull << 30ull) ||
574
6.78k
      xsize * ysize > (1ull << 40ull)) {
575
0
    if (debug_string) *debug_string = "Too large image dimensions";
576
0
    return -1;
577
0
  }
578
6.78k
  if (icc_size > (1ull << 28)) {
579
0
    if (debug_string) *debug_string = "Too large ICC profile size";
580
0
    return -1;
581
0
  }
582
6.78k
  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
6.78k
  if (!m.modular_16_bit_buffer_sufficient) {
590
2.37k
    if (debug_string) *debug_string = "Too high modular bit depth";
591
2.37k
    return 10;
592
2.37k
  }
593
4.41k
  if (xsize > (1ull << 18ull) || ysize > (1ull << 18ull) ||
594
4.41k
      xsize * ysize > (1ull << 28ull)) {
595
0
    if (debug_string) *debug_string = "Too large image dimensions";
596
0
    return 10;
597
0
  }
598
4.41k
  if (icc_size > (1ull << 22)) {
599
0
    if (debug_string) *debug_string = "Too large ICC profile";
600
0
    return 10;
601
0
  }
602
4.41k
  if (m.num_extra_channels > 4) {
603
0
    if (debug_string) *debug_string = "Too many extra channels";
604
0
    return 10;
605
0
  }
606
4.41k
  for (const auto& eci : m.extra_channel_info) {
607
538
    if (eci.type == jxl::ExtraChannel::kBlack) {
608
0
      if (debug_string) *debug_string = "CMYK channel not allowed";
609
0
      return 10;
610
0
    }
611
538
  }
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
4.41k
  return 5;
629
4.41k
}
630
631
JxlEncoderStatus CheckValidBitdepth(uint32_t bits_per_sample,
632
3.87k
                                    uint32_t exponent_bits_per_sample) {
633
3.87k
  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
3.23k
    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
3.23k
  } else if ((exponent_bits_per_sample > 8) ||
640
642
             (bits_per_sample > 24 + exponent_bits_per_sample) ||
641
642
             (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
3.87k
  return JxlErrorOrStatus::Success();
647
3.87k
}
648
649
JxlEncoderStatus VerifyInputBitDepth(JxlBitDepth bit_depth,
650
2.90k
                                     JxlPixelFormat format) {
651
2.90k
  return JxlErrorOrStatus::Success();
652
2.90k
}
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
970
                         size_t alpha_c, size_t alpha_bits) {
770
970
  if (!buffer || format.num_channels <= alpha_c) return false;
771
970
  size_t bytes_per_pixel = jxl::BytesPerPixel(format);
772
970
  if (bytes_per_pixel == 0) return false;
773
970
  const uint8_t* p = reinterpret_cast<const uint8_t*>(buffer);
774
775
970
  if (format.data_type == JXL_TYPE_UINT8) {
776
180
    size_t offset = alpha_c;
777
180
    uint8_t expected =
778
180
        (alpha_bits > 0 && alpha_bits <= 8) ? ((1u << alpha_bits) - 1) : 255;
779
345
    for (size_t y = 0; y < ysize; ++y) {
780
343
      const uint8_t* row = p + y * row_offset;
781
22.4k
      for (size_t x = 0; x < xsize; ++x) {
782
22.3k
        if (row[x * bytes_per_pixel + offset] != expected) {
783
178
          return false;
784
178
        }
785
22.3k
      }
786
343
    }
787
2
    return true;
788
790
  } else if (format.data_type == JXL_TYPE_UINT16) {
789
490
    size_t offset = alpha_c * 2;
790
490
    bool swap = SwapEndianness(format.endianness);
791
490
    uint16_t expected =
792
490
        (alpha_bits > 0 && alpha_bits <= 16) ? ((1u << alpha_bits) - 1) : 65535;
793
517
    for (size_t y = 0; y < ysize; ++y) {
794
517
      const uint8_t* row = p + y * row_offset;
795
2.79k
      for (size_t x = 0; x < xsize; ++x) {
796
2.76k
        uint16_t val;
797
2.76k
        memcpy(&val, row + x * bytes_per_pixel + offset, 2);
798
2.76k
        if (swap) val = JXL_BSWAP16(val);
799
2.76k
        if (val != expected) {
800
490
          return false;
801
490
        }
802
2.76k
      }
803
517
    }
804
0
    return true;
805
490
  } else if (format.data_type == JXL_TYPE_FLOAT) {
806
300
    size_t offset = alpha_c * 4;
807
300
    bool swap = SwapEndianness(format.endianness);
808
300
    for (size_t y = 0; y < ysize; ++y) {
809
300
      const uint8_t* row = p + y * row_offset;
810
300
      for (size_t x = 0; x < xsize; ++x) {
811
300
        uint32_t bits;
812
300
        memcpy(&bits, row + x * bytes_per_pixel + offset, 4);
813
300
        if (swap) bits = JXL_BSWAP32(bits);
814
300
        if (bits != 0x3F800000) {
815
300
          return false;
816
300
        }
817
300
      }
818
300
    }
819
0
    return true;
820
300
  } 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
970
}
838
839
}  // namespace
840
841
2.94k
jxl::Status JxlEncoder::ProcessOneEnqueuedInput() {
842
2.94k
  jxl::PaddedBytes header_bytes{&memory_manager};
843
844
2.94k
  jxl::JxlEncoderQueuedInput& input = input_queue[0];
845
846
2.94k
  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
2.94k
  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
2.94k
  if (!wrote_bytes) {
860
2.90k
    jxl::JxlEncoderQueuedFrame* first_frame = nullptr;
861
2.94k
    for (auto& qi : input_queue) {
862
2.94k
      if (qi.frame) {
863
2.90k
        first_frame = qi.frame.get();
864
2.90k
        break;
865
2.90k
      }
866
2.94k
    }
867
868
2.90k
    if (metadata.m.HasAlpha()) {
869
970
      const size_t alpha_ec_idx = metadata.m.Find(jxl::ExtraChannel::kAlpha) -
870
970
                                  metadata.m.extra_channel_info.data();
871
970
      const size_t alpha_bits =
872
970
          metadata.m.extra_channel_info[alpha_ec_idx].bit_depth.bits_per_sample;
873
970
      const int strip_alpha = first_frame
874
970
                                  ? first_frame->option_values.strip_alpha
875
970
                                  : kStripAlphaAuto;
876
970
      const bool is_lossless =
877
970
          first_frame && first_frame->option_values.lossless;
878
879
      // Only auto-strip alpha for single-frame images with exactly one extra
880
      // channel.
881
970
      const bool is_multiframe_or_animation =
882
970
          metadata.m.have_animation || !frames_closed ||
883
970
          num_queued_frames != 1 || metadata.m.num_extra_channels != 1;
884
885
970
      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
970
      if (!should_strip && !is_multiframe_or_animation && first_frame &&
890
970
          alpha_ec_idx < first_frame->ec_initialized.size() &&
891
970
          first_frame->ec_initialized[alpha_ec_idx] &&
892
970
          (strip_alpha == kStripAlphaIfOpaque ||
893
970
           (strip_alpha == kStripAlphaAuto && !is_lossless))) {
894
970
        JxlChunkedFrameInputSource src =
895
970
            first_frame->frame_data.GetInputSource();
896
970
        if (src.get_color_channels_pixel_format &&
897
970
            src.get_color_channel_data_at && src.release_buffer) {
898
970
          JxlPixelFormat color_fmt;
899
970
          src.get_color_channels_pixel_format(src.opaque, &color_fmt);
900
970
          const bool has_interleaved =
901
970
              color_fmt.num_channels == 2 || color_fmt.num_channels == 4;
902
970
          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
970
          if (has_interleaved || has_extra_channel) {
907
970
            JxlPixelFormat ec_fmt;
908
970
            if (has_extra_channel) {
909
0
              src.get_extra_channel_pixel_format(src.opaque, alpha_ec_idx,
910
0
                                                 &ec_fmt);
911
0
            }
912
970
            const JxlPixelFormat& fmt = has_interleaved ? color_fmt : ec_fmt;
913
970
            const size_t alpha_c =
914
970
                has_interleaved ? (color_fmt.num_channels - 1) : 0;
915
916
970
            auto is_chunk_opaque = [&](size_t x, size_t y, size_t xs,
917
970
                                       size_t ys) -> bool {
918
970
              size_t row_offset = 0;
919
970
              if (has_interleaved) {
920
970
                auto buf = jxl::GetColorBuffer(src, x, y, xs, ys, &row_offset);
921
970
                return buf &&
922
970
                       IsAlphaBufferOpaque(buf.get(), fmt, xs, ys, row_offset,
923
970
                                           alpha_c, alpha_bits);
924
970
              } 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
970
            };
932
933
970
            constexpr size_t kChunkDimY = 256;
934
970
            constexpr size_t kChunkDimX = 2048;
935
970
            const size_t xsize = metadata.xsize();
936
970
            const size_t ysize = metadata.ysize();
937
970
            bool all_opaque = true;
938
939
1.94k
            for (size_t y = 0; y < ysize && all_opaque; y += kChunkDimY) {
940
970
              const size_t chunk_ysize = std::min(kChunkDimY, ysize - y);
941
972
              for (size_t x = 0; x < xsize; x += kChunkDimX) {
942
970
                const size_t chunk_xsize = std::min(kChunkDimX, xsize - x);
943
970
                if (!is_chunk_opaque(x, y, chunk_xsize, chunk_ysize)) {
944
968
                  all_opaque = false;
945
968
                  break;
946
968
                }
947
970
              }
948
970
            }
949
970
            should_strip = all_opaque;
950
970
          }
951
970
        }
952
970
      }
953
954
970
      if (should_strip) {
955
2
        metadata.m.extra_channel_info.erase(
956
2
            metadata.m.extra_channel_info.begin() + alpha_ec_idx);
957
2
        metadata.m.num_extra_channels--;
958
2
        basic_info.num_extra_channels = metadata.m.num_extra_channels;
959
2
        basic_info.alpha_bits = 0;
960
2
        basic_info.alpha_exponent_bits = 0;
961
2
        basic_info.alpha_premultiplied = JXL_FALSE;
962
963
2
        for (auto& qi : input_queue) {
964
2
          if (qi.frame) {
965
2
            if (alpha_ec_idx < qi.frame->ec_initialized.size()) {
966
2
              qi.frame->ec_initialized.erase(qi.frame->ec_initialized.begin() +
967
2
                                             alpha_ec_idx);
968
2
            }
969
2
            if (alpha_ec_idx <
970
2
                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
2
            if (alpha_ec_idx <
976
2
                qi.frame->option_values.cparams.ec_distance.size()) {
977
2
              qi.frame->option_values.cparams.ec_distance.erase(
978
2
                  qi.frame->option_values.cparams.ec_distance.begin() +
979
2
                  alpha_ec_idx);
980
2
            }
981
2
          }
982
2
        }
983
2
      }
984
970
    }
985
986
    // First time encoding any data, verify the level 5 vs level 10 settings
987
2.90k
    std::string level_message;
988
2.90k
    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
2.90k
    JXL_ENSURE(required_level == -1 || required_level == 5 ||
992
2.90k
               required_level == 10);
993
    // codestream_level == -1 means auto-set to the required level
994
2.90k
    if (codestream_level == -1) codestream_level = required_level;
995
2.90k
    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
2.90k
    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
2.90k
    jxl::AuxOut* aux_out =
1012
2.90k
        first_frame ? first_frame->option_values.aux_out : nullptr;
1013
2.90k
    jxl::BitWriter writer{&memory_manager};
1014
2.90k
    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
2.90k
    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
2.90k
    JXL_RETURN_IF_ERROR(
1029
2.90k
        writer.WithMaxBits(8, jxl::LayerType::Header, aux_out, [&] {
1030
2.90k
          writer.ZeroPadToByte();
1031
2.90k
          return true;
1032
2.90k
        }));
1033
1034
2.90k
    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
2.90k
    codestream_bytes_written_end_of_frame += header_bytes.size();
1039
1040
2.90k
    if (MustUseContainer(output_mode)) {
1041
      // If any queued input uses output mode 2, ftyp version 1 is needed.
1042
832
      int ftyp_version = (output_mode == 2) ? 1 : 0;
1043
873
      for (const auto& qi : input_queue) {
1044
873
        if (qi.output_mode == 2) {
1045
0
          ftyp_version = 1;
1046
0
          break;
1047
0
        }
1048
873
      }
1049
832
      container_ftyp_version = ftyp_version;
1050
      // Add "JXL " and ftyp box.
1051
832
      JXL_RETURN_IF_ERROR(
1052
832
          AppendData(output_processor, jxl::MakeContainerHeader(ftyp_version)));
1053
1054
832
      if (codestream_level != 5) {
1055
        // Add jxll box directly after the ftyp box to indicate the codestream
1056
        // level.
1057
790
        const uint8_t level = static_cast<uint8_t>(codestream_level);
1058
790
        std::vector<uint8_t> jxll_box;
1059
790
        jxl::AppendBoxHeader(jxl::MakeBoxType("jxll"), 1,
1060
790
                             /*unbounded=*/false, &jxll_box);
1061
790
        jxll_box.push_back(level);
1062
790
        JXL_RETURN_IF_ERROR(AppendData(output_processor, jxll_box));
1063
790
      }
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
832
      bool partial_header =
1072
832
          store_jpeg_metadata ||
1073
832
          (use_boxes && (!input.frame && !input.fast_lossless_frame));
1074
1075
832
      if (partial_header) {
1076
41
        auto write_box = [&]() -> jxl::Status {
1077
41
          JXL_ASSIGN_OR_RETURN(
1078
41
              auto buffer, output_processor.GetBuffer(header_bytes.size() + 4));
1079
41
          JXL_RETURN_IF_ERROR(
1080
41
              WriteJxlpBoxCounter(jxlp_counter++, /*last=*/false, buffer));
1081
41
          JXL_RETURN_IF_ERROR(buffer.append(header_bytes));
1082
41
          return jxl::OkStatus();
1083
41
        };
1084
41
        JXL_RETURN_IF_ERROR(AppendBox(jxl::MakeBoxType("jxlp"),
1085
41
                                      /*unbounded=*/false,
1086
41
                                      header_bytes.size() + 4, write_box));
1087
41
        header_bytes.clear();
1088
41
      }
1089
1090
832
      if (store_jpeg_metadata && !jpeg_metadata.empty()) {
1091
0
        JXL_RETURN_IF_ERROR(
1092
0
            AppendBoxWithContents(jxl::MakeBoxType("jbrd"), jpeg_metadata));
1093
0
      }
1094
832
    }
1095
2.90k
    wrote_bytes = true;
1096
2.90k
  }
1097
1098
2.94k
  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
2.94k
  if (input.frame || input.fast_lossless_frame) {
1103
2.90k
    jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedFrame> input_frame =
1104
2.90k
        std::move(input.frame);
1105
2.90k
    jxl::FJXLFrameUniquePtr fast_lossless_frame =
1106
2.90k
        std::move(input.fast_lossless_frame);
1107
2.90k
    input_queue.erase(input_queue.begin());
1108
2.90k
    num_queued_frames--;
1109
2.90k
    if (input_frame) {
1110
3.87k
      for (unsigned idx = 0; idx < input_frame->ec_initialized.size(); idx++) {
1111
968
        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
968
      }
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
2.90k
      if (metadata.m.xyb_encoded) {
1126
2.90k
        input_frame->option_values.cparams.color_transform =
1127
2.90k
            jxl::ColorTransform::kXYB;
1128
2.90k
      } 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
2.90k
    }
1134
1135
2.90k
    uint32_t duration;
1136
2.90k
    uint32_t timecode;
1137
2.90k
    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
2.90k
    } 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
2.90k
      duration = 0;
1146
2.90k
      timecode = 0;
1147
2.90k
    }
1148
1149
2.90k
    const bool last_frame = frames_closed && (num_queued_frames == 0);
1150
1151
2.90k
    uint32_t max_bits_per_sample = metadata.m.bit_depth.bits_per_sample;
1152
2.90k
    for (const auto& info : metadata.m.extra_channel_info) {
1153
968
      max_bits_per_sample =
1154
968
          std::max(max_bits_per_sample, info.bit_depth.bits_per_sample);
1155
968
    }
1156
    // Heuristic upper bound on how many bits a single pixel in a single channel
1157
    // can use.
1158
2.90k
    uint32_t bits_per_channels_estimate =
1159
2.90k
        std::max(24u, max_bits_per_sample + 3);
1160
2.90k
    size_t upper_bound_on_compressed_size_bits =
1161
2.90k
        metadata.xsize() * metadata.ysize() *
1162
2.90k
        (metadata.m.color_encoding.Channels() + metadata.m.num_extra_channels) *
1163
2.90k
        bits_per_channels_estimate;
1164
    // Add a 1MB = 0x100000 for an heuristic upper bound on small sizes.
1165
2.90k
    size_t upper_bound_on_compressed_size_bytes =
1166
2.90k
        0x100000 + (upper_bound_on_compressed_size_bits >> 3);
1167
2.90k
    bool use_large_box = upper_bound_on_compressed_size_bytes >=
1168
2.90k
                         jxl::kLargeBoxContentSizeThreshold;
1169
2.90k
    size_t box_header_size =
1170
2.90k
        use_large_box ? jxl::kLargeBoxHeaderSize : jxl::kSmallBoxHeaderSize;
1171
1172
2.90k
    size_t frame_start_pos = output_processor.CurrentPosition();
1173
2.90k
    const size_t n0 = jxlp_counter;
1174
1175
2.90k
    if (MustUseContainer(output_mode) && output_mode != 2) {
1176
832
      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
41
        box_header_size += 4;  // jxlp_counter field
1181
41
      }
1182
832
      JXL_RETURN_IF_ERROR(
1183
832
          output_processor.Seek(frame_start_pos + box_header_size));
1184
832
    }
1185
2.90k
    const size_t content_start = output_processor.CurrentPosition();
1186
1187
2.90k
    if (!header_bytes.empty()) {
1188
2.86k
      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
2.86k
      JXL_RETURN_IF_ERROR(AppendData(output_processor, header_bytes));
1199
2.86k
    }
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
2.90k
    if (output_mode == 2) {
1204
0
      frame_start_pos = output_processor.CurrentPosition();
1205
0
      box_header_size = 12;
1206
0
    }
1207
2.90k
    const uint32_t n1 = jxlp_counter;
1208
1209
2.90k
    if (input_frame) {
1210
2.90k
      frame_index_box.AddFrame(codestream_bytes_written_end_of_frame, duration,
1211
2.90k
                               input_frame->option_values.frame_index_box);
1212
1213
2.90k
      size_t save_as_reference =
1214
2.90k
          input_frame->option_values.header.layer_info.save_as_reference;
1215
2.90k
      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
2.90k
      jxl::FrameInfo frame_info;
1223
2.90k
      frame_info.is_last = last_frame;
1224
2.90k
      frame_info.save_as_reference = save_as_reference;
1225
2.90k
      frame_info.source =
1226
2.90k
          input_frame->option_values.header.layer_info.blend_info.source;
1227
2.90k
      frame_info.clamp = FROM_JXL_BOOL(
1228
2.90k
          input_frame->option_values.header.layer_info.blend_info.clamp);
1229
2.90k
      frame_info.alpha_channel =
1230
2.90k
          input_frame->option_values.header.layer_info.blend_info.alpha;
1231
2.90k
      frame_info.extra_channel_blending_info.resize(
1232
2.90k
          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
2.90k
      JxlBlendInfo default_blend_info =
1236
2.90k
          input_frame->option_values.header.layer_info.blend_info;
1237
3.87k
      for (size_t i = 0; i < metadata.m.num_extra_channels; ++i) {
1238
968
        auto& to = frame_info.extra_channel_blending_info[i];
1239
968
        const auto& from =
1240
968
            i < input_frame->option_values.extra_channel_blend_info.size()
1241
968
                ? input_frame->option_values.extra_channel_blend_info[i]
1242
968
                : default_blend_info;
1243
968
        to.mode = static_cast<jxl::BlendMode>(from.blendmode);
1244
968
        to.source = from.source;
1245
968
        to.alpha_channel = from.alpha;
1246
968
        to.clamp = (from.clamp != 0);
1247
968
      }
1248
2.90k
      frame_info.origin.x0 =
1249
2.90k
          input_frame->option_values.header.layer_info.crop_x0;
1250
2.90k
      frame_info.origin.y0 =
1251
2.90k
          input_frame->option_values.header.layer_info.crop_y0;
1252
2.90k
      frame_info.blendmode = static_cast<jxl::BlendMode>(
1253
2.90k
          input_frame->option_values.header.layer_info.blend_info.blendmode);
1254
2.90k
      frame_info.blend =
1255
2.90k
          input_frame->option_values.header.layer_info.blend_info.blendmode !=
1256
2.90k
          JXL_BLEND_REPLACE;
1257
2.90k
      frame_info.image_bit_depth = input_frame->option_values.image_bit_depth;
1258
2.90k
      frame_info.duration = duration;
1259
2.90k
      frame_info.timecode = timecode;
1260
2.90k
      frame_info.name = input_frame->option_values.frame_name;
1261
2.90k
      jxl::CompressParams frame_cparams = input_frame->option_values.cparams;
1262
2.90k
      frame_cparams.output_mode = output_mode;
1263
2.90k
      uint32_t jxlp_ctr = static_cast<uint32_t>(jxlp_counter);
1264
2.90k
      if (!jxl::EncodeFrame(&memory_manager, frame_cparams, frame_info,
1265
2.90k
                            &metadata, input_frame->frame_data, cms,
1266
2.90k
                            thread_pool.get(), &output_processor,
1267
2.90k
                            input_frame->option_values.aux_out, &jxlp_ctr)) {
1268
102
        return JXL_API_ERROR(this, JXL_ENC_ERR_GENERIC,
1269
102
                             "Failed to encode frame");
1270
102
      }
1271
2.80k
      jxlp_counter = jxlp_ctr;
1272
2.80k
      last_used_cparams = input_frame->option_values.cparams;
1273
2.80k
    } 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
2.80k
    const size_t content_size =
1286
2.80k
        output_processor.CurrentPosition() - content_start;
1287
1288
2.80k
    codestream_bytes_written_end_of_frame +=
1289
2.80k
        content_size - header_bytes.size() - (jxlp_counter - n0) * 12;
1290
1291
2.80k
    if (MustUseContainer(output_mode) &&
1292
750
        (output_mode != 2 || jxlp_counter == n1)) {
1293
750
      JXL_RETURN_IF_ERROR(output_processor.Seek(frame_start_pos));
1294
750
      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
750
      const size_t frame_content_size =
1298
750
          output_mode == 2
1299
750
              ? content_size - (frame_start_pos - content_start) - 12
1300
750
              : content_size;
1301
750
      if (!use_large_box &&
1302
750
          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
750
      if (last_frame && jxlp_counter == 0) {
1311
709
        size_t n = jxl::WriteBoxHeader(
1312
709
            jxl::MakeBoxType("jxlc"), frame_content_size,
1313
709
            /*unbounded=*/false, use_large_box, box_header.data());
1314
709
        JXL_ENSURE(n == box_header_size);
1315
709
      } else {
1316
41
        size_t n = jxl::WriteBoxHeader(
1317
41
            jxl::MakeBoxType("jxlp"), frame_content_size + 4,
1318
41
            /*unbounded=*/false, use_large_box, box_header.data());
1319
41
        JXL_ENSURE(n == box_header_size - 4);
1320
41
        WriteJxlpBoxCounter(jxlp_counter++, last_frame,
1321
41
                            &box_header[box_header_size - 4]);
1322
41
      }
1323
750
      JXL_RETURN_IF_ERROR(AppendData(output_processor, box_header));
1324
750
      JXL_ENSURE(output_processor.CurrentPosition() ==
1325
750
                 frame_start_pos + box_header_size);
1326
750
      JXL_RETURN_IF_ERROR(output_processor.Seek(content_start + content_size));
1327
750
    }
1328
2.80k
    JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
1329
2.80k
    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
2.80k
  } else {
1338
    // Not a frame, so is a box instead
1339
41
    jxl::MemoryManagerUniquePtr<jxl::JxlEncoderQueuedBox> box =
1340
41
        std::move(input.box);
1341
41
    input_queue.erase(input_queue.begin());
1342
41
    num_queued_boxes--;
1343
1344
41
    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
41
    } else {
1359
41
      JXL_RETURN_IF_ERROR(AppendBoxWithContents(box->type, box->contents));
1360
41
    }
1361
41
  }
1362
1363
2.84k
  return jxl::OkStatus();
1364
2.94k
}
1365
1366
JxlEncoderStatus JxlEncoderSetColorEncoding(JxlEncoder* enc,
1367
2.90k
                                            const JxlColorEncoding* color) {
1368
2.90k
  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
2.90k
  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
2.90k
  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
2.90k
  if (enc->metadata.m.color_encoding.GetColorSpace() ==
1379
2.90k
      jxl::ColorSpace::kGray) {
1380
181
    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
2.72k
  } else {
1386
2.72k
    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
2.72k
  }
1392
2.90k
  enc->color_encoding_set = true;
1393
2.90k
  if (!enc->intensity_target_set) {
1394
2.90k
    jxl::SetIntensityTarget(&enc->metadata.m);
1395
2.90k
  }
1396
2.90k
  return JxlErrorOrStatus::Success();
1397
2.90k
}
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
5.96k
void JxlEncoderInitBasicInfo(JxlBasicInfo* info) {
1451
5.96k
  info->have_container = JXL_FALSE;
1452
5.96k
  info->xsize = 0;
1453
5.96k
  info->ysize = 0;
1454
5.96k
  info->bits_per_sample = 8;
1455
5.96k
  info->exponent_bits_per_sample = 0;
1456
5.96k
  info->intensity_target = 0.f;
1457
5.96k
  info->min_nits = 0.f;
1458
5.96k
  info->relative_to_max_display = JXL_FALSE;
1459
5.96k
  info->linear_below = 0.f;
1460
5.96k
  info->uses_original_profile = JXL_FALSE;
1461
5.96k
  info->have_preview = JXL_FALSE;
1462
5.96k
  info->have_animation = JXL_FALSE;
1463
5.96k
  info->orientation = JXL_ORIENT_IDENTITY;
1464
5.96k
  info->num_color_channels = 3;
1465
5.96k
  info->num_extra_channels = 0;
1466
5.96k
  info->alpha_bits = 0;
1467
5.96k
  info->alpha_exponent_bits = 0;
1468
5.96k
  info->alpha_premultiplied = JXL_FALSE;
1469
5.96k
  info->preview.xsize = 0;
1470
5.96k
  info->preview.ysize = 0;
1471
5.96k
  info->intrinsic_xsize = 0;
1472
5.96k
  info->intrinsic_ysize = 0;
1473
5.96k
  info->animation.tps_numerator = 10;
1474
5.96k
  info->animation.tps_denominator = 1;
1475
5.96k
  info->animation.num_loops = 0;
1476
5.96k
  info->animation.have_timecodes = JXL_FALSE;
1477
5.96k
}
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
2.98k
                                        const JxlBasicInfo* info) {
1519
2.98k
  if (!enc->metadata.size.Set(info->xsize, info->ysize)) {
1520
73
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid dimensions");
1521
73
  }
1522
2.90k
  if (JXL_ENC_SUCCESS != CheckValidBitdepth(info->bits_per_sample,
1523
2.90k
                                            info->exponent_bits_per_sample)) {
1524
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid bit depth");
1525
0
  }
1526
1527
2.90k
  enc->metadata.m.bit_depth.bits_per_sample = info->bits_per_sample;
1528
2.90k
  enc->metadata.m.bit_depth.exponent_bits_per_sample =
1529
2.90k
      info->exponent_bits_per_sample;
1530
2.90k
  enc->metadata.m.bit_depth.floating_point_sample =
1531
2.90k
      (info->exponent_bits_per_sample != 0u);
1532
2.90k
  enc->metadata.m.modular_16_bit_buffer_sufficient =
1533
2.90k
      (!FROM_JXL_BOOL(info->uses_original_profile) ||
1534
0
       info->bits_per_sample <= 12) &&
1535
2.90k
      info->alpha_bits <= 12;
1536
2.90k
  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
2.90k
  enc->metadata.m.num_extra_channels = info->num_extra_channels;
1552
2.90k
  enc->metadata.m.extra_channel_info.resize(enc->metadata.m.num_extra_channels);
1553
2.90k
  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
2.90k
  if (info->alpha_bits) {
1562
970
    JxlExtraChannelInfo channel_info;
1563
970
    JxlEncoderInitExtraChannelInfo(JXL_CHANNEL_ALPHA, &channel_info);
1564
970
    channel_info.bits_per_sample = info->alpha_bits;
1565
970
    channel_info.exponent_bits_per_sample = info->alpha_exponent_bits;
1566
970
    channel_info.alpha_premultiplied = info->alpha_premultiplied;
1567
970
    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
970
  }
1572
1573
2.90k
  enc->metadata.m.xyb_encoded = !FROM_JXL_BOOL(info->uses_original_profile);
1574
2.90k
  if (info->orientation > 0 && info->orientation <= 8) {
1575
2.90k
    enc->metadata.m.orientation = info->orientation;
1576
2.90k
  } else {
1577
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
1578
0
                         "Invalid value for orientation field");
1579
0
  }
1580
2.90k
  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
2.90k
  if (info->intensity_target != 0) {
1585
0
    enc->metadata.m.SetIntensityTarget(info->intensity_target);
1586
0
    enc->intensity_target_set = true;
1587
2.90k
  } 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
2.90k
  enc->metadata.m.tone_mapping.min_nits = info->min_nits;
1595
2.90k
  enc->metadata.m.tone_mapping.relative_to_max_display =
1596
2.90k
      FROM_JXL_BOOL(info->relative_to_max_display);
1597
2.90k
  enc->metadata.m.tone_mapping.linear_below = info->linear_below;
1598
2.90k
  enc->basic_info = *info;
1599
2.90k
  enc->basic_info_set = true;
1600
1601
2.90k
  enc->metadata.m.have_animation = FROM_JXL_BOOL(info->have_animation);
1602
2.90k
  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
2.90k
  std::string level_message;
1619
2.90k
  int required_level = VerifyLevelSettings(enc, &level_message);
1620
2.90k
  int verified_level = (required_level == -1) ? 10 : enc->codestream_level;
1621
2.90k
  if (required_level == -1 ||
1622
2.90k
      (static_cast<int>(enc->codestream_level) < required_level &&
1623
2.90k
       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
2.90k
  return JxlErrorOrStatus::Success();
1631
2.90k
}
1632
1633
void JxlEncoderInitExtraChannelInfo(JxlExtraChannelType type,
1634
970
                                    JxlExtraChannelInfo* info) {
1635
970
  info->type = type;
1636
970
  info->bits_per_sample = 8;
1637
970
  info->exponent_bits_per_sample = 0;
1638
970
  info->dim_shift = 0;
1639
970
  info->name_length = 0;
1640
970
  info->alpha_premultiplied = JXL_FALSE;
1641
970
  info->spot_color[0] = 0;
1642
970
  info->spot_color[1] = 0;
1643
970
  info->spot_color[2] = 0;
1644
970
  info->spot_color[3] = 0;
1645
970
  info->cfa_channel = 0;
1646
970
}
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
970
    JxlEncoder* enc, size_t index, const JxlExtraChannelInfo* info) {
1701
970
  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
970
  if (JXL_ENC_SUCCESS != CheckValidBitdepth(info->bits_per_sample,
1706
970
                                            info->exponent_bits_per_sample)) {
1707
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE, "Invalid bit depth");
1708
0
  }
1709
1710
970
  jxl::ExtraChannelInfo& channel = enc->metadata.m.extra_channel_info[index];
1711
970
  channel.type = static_cast<jxl::ExtraChannel>(info->type);
1712
970
  channel.bit_depth.bits_per_sample = info->bits_per_sample;
1713
970
  enc->metadata.m.modular_16_bit_buffer_sufficient &=
1714
970
      info->bits_per_sample <= 12;
1715
970
  channel.bit_depth.exponent_bits_per_sample = info->exponent_bits_per_sample;
1716
970
  channel.bit_depth.floating_point_sample = info->exponent_bits_per_sample != 0;
1717
970
  channel.dim_shift = info->dim_shift;
1718
970
  channel.name = "";
1719
970
  channel.alpha_associated = (info->alpha_premultiplied != 0);
1720
970
  channel.cfa_channel = info->cfa_channel;
1721
970
  channel.spot_color[0] = info->spot_color[0];
1722
970
  channel.spot_color[1] = info->spot_color[1];
1723
970
  channel.spot_color[2] = info->spot_color[2];
1724
970
  channel.spot_color[3] = info->spot_color[3];
1725
970
  std::string level_message;
1726
970
  int required_level = VerifyLevelSettings(enc, &level_message);
1727
970
  int verified_level = (required_level == -1) ? 10 : enc->codestream_level;
1728
970
  if (required_level == -1 ||
1729
970
      (static_cast<int>(enc->codestream_level) < required_level &&
1730
970
       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
970
  return JxlErrorOrStatus::Success();
1738
970
}
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
2.90k
    JxlEncoder* enc, const JxlEncoderFrameSettings* source) {
1755
2.90k
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(opts, JxlEncoderFrameSettings,
1756
2.90k
                                           (&enc->memory_manager), nullptr);
1757
2.90k
  opts->enc = enc;
1758
2.90k
  if (source != nullptr) {
1759
0
    opts->values = source->values;
1760
2.90k
  } else {
1761
2.90k
    opts->values.lossless = false;
1762
2.90k
  }
1763
2.90k
  opts->values.cparams.level = enc->codestream_level;
1764
2.90k
  opts->values.cparams.ec_distance.resize(enc->metadata.m.num_extra_channels,
1765
2.90k
                                          0);
1766
1767
2.90k
  JxlEncoderFrameSettings* ret = opts.get();
1768
2.90k
  enc->encoder_options.emplace_back(std::move(opts));
1769
2.90k
  return ret;
1770
2.90k
}
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_COMPRESS_BOXES:
1857
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF:
1858
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP:
1859
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF:
1860
0
      if (value < -1 || value > 1) {
1861
0
        return JXL_API_ERROR(
1862
0
            frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1863
0
            "Option value has to be -1 (default), 0 (off) or 1 (on)");
1864
0
      }
1865
0
      break;
1866
0
    default:
1867
0
      break;
1868
0
  }
1869
1870
0
  switch (option) {
1871
0
    case JXL_ENC_FRAME_SETTING_EFFORT:
1872
0
      if (frame_settings->enc->allow_expert_options) {
1873
0
        if (value < 1 || value > 11) {
1874
0
          return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
1875
0
                               "Encode effort has to be in [1..11]");
1876
0
        }
1877
0
      } else {
1878
0
        if (value < 1 || value > 10) {
1879
0
          return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
1880
0
                               "Encode effort has to be in [1..10]");
1881
0
        }
1882
0
      }
1883
0
      frame_settings->values.cparams.speed_tier =
1884
0
          static_cast<jxl::SpeedTier>(10 - value);
1885
0
      break;
1886
0
    case JXL_ENC_FRAME_SETTING_BROTLI_EFFORT:
1887
0
      if (value < -1 || value > 11) {
1888
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1889
0
                             "Brotli effort has to be in [-1..11]");
1890
0
      }
1891
      // set cparams for brotli use in JPEG frames
1892
0
      frame_settings->values.cparams.brotli_effort = value;
1893
      // set enc option for brotli use in brob boxes
1894
0
      frame_settings->enc->brotli_effort = value;
1895
0
      break;
1896
0
    case JXL_ENC_FRAME_SETTING_DECODING_SPEED:
1897
0
      if (value < 0 || value > 4) {
1898
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
1899
0
                             "Decoding speed has to be in [0..4]");
1900
0
      }
1901
0
      frame_settings->values.cparams.decoding_speed_tier = value;
1902
0
      break;
1903
0
    case JXL_ENC_FRAME_SETTING_RESAMPLING:
1904
0
      if (value != -1 && value != 1 && value != 2 && value != 4 && value != 8) {
1905
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1906
0
                             "Resampling factor has to be 1, 2, 4 or 8");
1907
0
      }
1908
0
      frame_settings->values.cparams.resampling = value;
1909
0
      break;
1910
0
    case JXL_ENC_FRAME_SETTING_EXTRA_CHANNEL_RESAMPLING:
1911
      // TODO(lode): the jxl codestream allows choosing a different resampling
1912
      // factor for each extra channel, independently per frame. Move this
1913
      // option to a JxlEncoderFrameSettings-option that can be set per extra
1914
      // channel, so needs its own function rather than
1915
      // JxlEncoderFrameSettingsSetOption due to the extra channel index
1916
      // argument required.
1917
0
      if (value != -1 && value != 1 && value != 2 && value != 4 && value != 8) {
1918
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1919
0
                             "Resampling factor has to be 1, 2, 4 or 8");
1920
0
      }
1921
0
      frame_settings->values.cparams.ec_resampling = value;
1922
0
      break;
1923
0
    case JXL_ENC_FRAME_SETTING_ALREADY_DOWNSAMPLED:
1924
0
      if (value < 0 || value > 1) {
1925
0
        return JxlErrorOrStatus::Error();
1926
0
      }
1927
0
      frame_settings->values.cparams.already_downsampled = (value == 1);
1928
0
      break;
1929
0
    case JXL_ENC_FRAME_SETTING_NOISE:
1930
0
      frame_settings->values.cparams.noise = static_cast<jxl::Override>(value);
1931
0
      break;
1932
0
    case JXL_ENC_FRAME_SETTING_DOTS:
1933
0
      frame_settings->values.cparams.dots = static_cast<jxl::Override>(value);
1934
0
      break;
1935
0
    case JXL_ENC_FRAME_SETTING_PATCHES:
1936
0
      frame_settings->values.cparams.patches =
1937
0
          static_cast<jxl::Override>(value);
1938
0
      break;
1939
0
    case JXL_ENC_FRAME_SETTING_EPF:
1940
0
      if (value < -1 || value > 3) {
1941
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1942
0
                             "EPF value has to be in [-1..3]");
1943
0
      }
1944
0
      frame_settings->values.cparams.epf = static_cast<int>(value);
1945
0
      break;
1946
0
    case JXL_ENC_FRAME_SETTING_GABORISH:
1947
0
      frame_settings->values.cparams.gaborish =
1948
0
          static_cast<jxl::Override>(value);
1949
0
      break;
1950
0
    case JXL_ENC_FRAME_SETTING_MODULAR:
1951
0
      frame_settings->values.cparams.modular_mode = (value == 1);
1952
0
      break;
1953
0
    case JXL_ENC_FRAME_SETTING_KEEP_INVISIBLE:
1954
0
      frame_settings->values.cparams.keep_invisible =
1955
0
          static_cast<jxl::Override>(value);
1956
0
      break;
1957
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER:
1958
0
      frame_settings->values.cparams.centerfirst = (value == 1);
1959
0
      break;
1960
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_X:
1961
0
      if (value < -1) {
1962
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1963
0
                             "Center x coordinate has to be -1 or positive");
1964
0
      }
1965
0
      frame_settings->values.cparams.center_x = static_cast<size_t>(value);
1966
0
      break;
1967
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_Y:
1968
0
      if (value < -1) {
1969
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1970
0
                             "Center y coordinate has to be -1 or positive");
1971
0
      }
1972
0
      frame_settings->values.cparams.center_y = static_cast<size_t>(value);
1973
0
      break;
1974
0
    case JXL_ENC_FRAME_SETTING_RESPONSIVE:
1975
0
      frame_settings->values.cparams.responsive = value;
1976
0
      break;
1977
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_AC:
1978
0
      frame_settings->values.cparams.progressive_mode =
1979
0
          static_cast<jxl::Override>(value);
1980
0
      break;
1981
0
    case JXL_ENC_FRAME_SETTING_QPROGRESSIVE_AC:
1982
0
      frame_settings->values.cparams.qprogressive_mode =
1983
0
          static_cast<jxl::Override>(value);
1984
0
      break;
1985
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_DC:
1986
0
      if (value < -1 || value > 2) {
1987
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1988
0
                             "Progressive DC has to be in [-1..2]");
1989
0
      }
1990
0
      frame_settings->values.cparams.progressive_dc = value;
1991
0
      break;
1992
0
    case JXL_ENC_FRAME_SETTING_PALETTE_COLORS:
1993
0
      if (value < -1 || value > 70913) {
1994
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
1995
0
                             "Option value has to be in [-1..70913]");
1996
0
      }
1997
0
      if (value == -1) {
1998
0
        frame_settings->values.cparams.palette_colors = 1 << 10;
1999
0
      } else {
2000
0
        frame_settings->values.cparams.palette_colors = value;
2001
0
      }
2002
0
      break;
2003
0
    case JXL_ENC_FRAME_SETTING_LOSSY_PALETTE:
2004
      // TODO(lode): the defaults of some palette settings depend on others.
2005
      // See the logic in cjxl. Similar for other settings. This should be
2006
      // handled in the encoder during JxlEncoderProcessOutput (or,
2007
      // alternatively, in the cjxl binary like now)
2008
0
      frame_settings->values.cparams.lossy_palette = default_to_false(value);
2009
0
      break;
2010
0
    case JXL_ENC_FRAME_SETTING_COLOR_TRANSFORM:
2011
0
      if (value < -1 || value > 2) {
2012
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2013
0
                             "Option value has to be in [-1..2]");
2014
0
      }
2015
0
      if (value == -1) {
2016
0
        frame_settings->values.cparams.color_transform =
2017
0
            jxl::ColorTransform::kXYB;
2018
0
      } else {
2019
0
        frame_settings->values.cparams.color_transform =
2020
0
            static_cast<jxl::ColorTransform>(value);
2021
0
      }
2022
0
      break;
2023
0
    case JXL_ENC_FRAME_SETTING_MODULAR_COLOR_SPACE:
2024
0
      if (value < -1 || value > 41) {
2025
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2026
0
                             "Option value has to be in [-1..41]");
2027
0
      }
2028
0
      frame_settings->values.cparams.colorspace = value;
2029
0
      break;
2030
0
    case JXL_ENC_FRAME_SETTING_MODULAR_GROUP_SIZE:
2031
0
      if (value < -1 || value > 3) {
2032
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2033
0
                             "Option value has to be in [-1..3]");
2034
0
      }
2035
0
      frame_settings->values.cparams.modular_group_size_shift = value;
2036
0
      break;
2037
0
    case JXL_ENC_FRAME_SETTING_MODULAR_PREDICTOR:
2038
0
      if (value < -1 || value > 15) {
2039
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2040
0
                             "Option value has to be in [-1..15]");
2041
0
      }
2042
0
      frame_settings->values.cparams.options.predictor =
2043
0
          static_cast<jxl::Predictor>(value);
2044
0
      break;
2045
0
    case JXL_ENC_FRAME_SETTING_MODULAR_NB_PREV_CHANNELS:
2046
      // The max allowed value can in theory be higher. However, it depends on
2047
      // the effort setting. 11 is the highest safe value that doesn't cause
2048
      // tree_samples to be >= 64 in the encoder. The specification may allow
2049
      // more than this. With more fine tuning higher values could be allowed.
2050
      // For N-channel images, the largest useful value is N-1.
2051
0
      if (value < -1 || value > 11) {
2052
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2053
0
                             "Option value has to be in [-1..11]");
2054
0
      }
2055
0
      if (value == -1) {
2056
0
        frame_settings->values.cparams.options.max_properties = 0;
2057
0
      } else {
2058
0
        frame_settings->values.cparams.options.max_properties = value;
2059
0
      }
2060
0
      break;
2061
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_CFL:
2062
0
      frame_settings->values.cparams.force_cfl_jpeg_recompression =
2063
0
          default_to_true(value);
2064
0
      break;
2065
0
    case JXL_ENC_FRAME_INDEX_BOX:
2066
0
      if (value < 0 || value > 1) {
2067
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2068
0
                             "Option value has to be 0 or 1");
2069
0
      }
2070
0
      frame_settings->values.frame_index_box = true;
2071
0
      break;
2072
0
    case JXL_ENC_FRAME_SETTING_PHOTON_NOISE:
2073
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2074
0
                           "Float option, try setting it with "
2075
0
                           "JxlEncoderFrameSettingsSetFloatOption");
2076
0
    case JXL_ENC_FRAME_SETTING_JPEG_COMPRESS_BOXES:
2077
0
      frame_settings->values.cparams.jpeg_compress_boxes =
2078
0
          default_to_true(value);
2079
0
      break;
2080
0
    case JXL_ENC_FRAME_SETTING_BUFFERING:
2081
0
      if (value < -1 || value > 3) {
2082
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2083
0
                             "Buffering has to be in [-1..3]");
2084
0
      }
2085
0
      frame_settings->values.cparams.buffering = value;
2086
0
      break;
2087
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF:
2088
0
      frame_settings->values.cparams.jpeg_keep_exif = default_to_true(value);
2089
0
      break;
2090
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP:
2091
0
      frame_settings->values.cparams.jpeg_keep_xmp = default_to_true(value);
2092
0
      break;
2093
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF:
2094
0
      frame_settings->values.cparams.jpeg_keep_jumbf = default_to_true(value);
2095
0
      break;
2096
0
    case JXL_ENC_FRAME_SETTING_USE_FULL_IMAGE_HEURISTICS:
2097
0
      if (value < 0 || value > 1) {
2098
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2099
0
                             "Option value has to be 0 or 1");
2100
0
      }
2101
0
      frame_settings->values.cparams.use_full_image_heuristics =
2102
0
          default_to_false(value);
2103
0
      break;
2104
0
    case JXL_ENC_FRAME_SETTING_DISABLE_PERCEPTUAL_HEURISTICS:
2105
0
      if (value < 0 || value > 1) {
2106
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2107
0
                             "Option value has to be 0 or 1");
2108
0
      }
2109
0
      frame_settings->values.cparams.disable_perceptual_optimizations =
2110
0
          default_to_false(value);
2111
0
      if (frame_settings->values.cparams.disable_perceptual_optimizations &&
2112
0
          frame_settings->enc->basic_info_set &&
2113
0
          frame_settings->enc->metadata.m.xyb_encoded) {
2114
0
        return JXL_API_ERROR(
2115
0
            frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2116
0
            "Set uses_original_profile=true for non-perceptual encoding");
2117
0
      }
2118
0
      break;
2119
0
    case JXL_ENC_FRAME_SETTING_OUTPUT_MODE:
2120
0
      if (value < -1 || value > 2) {
2121
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2122
0
                             "Output mode has to be in [-1..2]");
2123
0
      }
2124
0
      frame_settings->values.cparams.output_mode = value;
2125
0
      break;
2126
0
    case JXL_ENC_FRAME_SETTING_STRIP_ALPHA:
2127
0
      if (value < -1 || value > 2) {
2128
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2129
0
                             "Strip alpha has to be in [-1..2]");
2130
0
      }
2131
0
      frame_settings->values.strip_alpha = static_cast<int>(value);
2132
0
      break;
2133
2134
0
    default:
2135
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2136
0
                           "Unknown option");
2137
0
  }
2138
0
  return JxlErrorOrStatus::Success();
2139
0
}
2140
2141
JxlEncoderStatus JxlEncoderFrameSettingsSetFloatOption(
2142
    JxlEncoderFrameSettings* frame_settings, JxlEncoderFrameSettingId option,
2143
0
    float value) {
2144
0
  switch (option) {
2145
0
    case JXL_ENC_FRAME_SETTING_PHOTON_NOISE:
2146
0
      if (value < 0) return JXL_ENC_ERROR;
2147
      // TODO(lode): add encoder setting to set the 8 floating point values of
2148
      // the noise synthesis parameters per frame for more fine grained control.
2149
0
      frame_settings->values.cparams.photon_noise_iso = value;
2150
0
      return JxlErrorOrStatus::Success();
2151
0
    case JXL_ENC_FRAME_SETTING_MODULAR_MA_TREE_LEARNING_PERCENT:
2152
0
      if (value < -1.f || value > 100.f) {
2153
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2154
0
                             "Option value has to be smaller than 100");
2155
0
      }
2156
      // This value is called "iterations" or "nb_repeats" in cjxl, but is in
2157
      // fact a fraction in range 0.0-1.0, with the default value 0.5.
2158
      // Convert from floating point percentage to floating point fraction here.
2159
0
      if (value < -.5f) {
2160
        // TODO(lode): for this and many other settings (also in
2161
        // JxlEncoderFrameSettingsSetOption), avoid duplicating the default
2162
        // values here and in enc_params.h and options.h, have one location
2163
        // where the defaults are specified.
2164
0
        frame_settings->values.cparams.options.nb_repeats = 0.5f;
2165
0
      } else {
2166
0
        frame_settings->values.cparams.options.nb_repeats = value * 0.01f;
2167
0
      }
2168
0
      return JxlErrorOrStatus::Success();
2169
0
    case JXL_ENC_FRAME_SETTING_CHANNEL_COLORS_GLOBAL_PERCENT:
2170
0
      if (value < -1.f || value > 100.f) {
2171
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2172
0
                             "Option value has to be in [-1..100]");
2173
0
      }
2174
0
      if (value < -.5f) {
2175
0
        frame_settings->values.cparams.channel_colors_pre_transform_percent =
2176
0
            95.0f;
2177
0
      } else {
2178
0
        frame_settings->values.cparams.channel_colors_pre_transform_percent =
2179
0
            value;
2180
0
      }
2181
0
      return JxlErrorOrStatus::Success();
2182
0
    case JXL_ENC_FRAME_SETTING_CHANNEL_COLORS_GROUP_PERCENT:
2183
0
      if (value < -1.f || value > 100.f) {
2184
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2185
0
                             "Option value has to be in [-1..100]");
2186
0
      }
2187
0
      if (value < -.5f) {
2188
0
        frame_settings->values.cparams.channel_colors_percent = 80.0f;
2189
0
      } else {
2190
0
        frame_settings->values.cparams.channel_colors_percent = value;
2191
0
      }
2192
0
      return JxlErrorOrStatus::Success();
2193
0
    case JXL_ENC_FRAME_SETTING_EFFORT:
2194
0
    case JXL_ENC_FRAME_SETTING_DECODING_SPEED:
2195
0
    case JXL_ENC_FRAME_SETTING_RESAMPLING:
2196
0
    case JXL_ENC_FRAME_SETTING_EXTRA_CHANNEL_RESAMPLING:
2197
0
    case JXL_ENC_FRAME_SETTING_ALREADY_DOWNSAMPLED:
2198
0
    case JXL_ENC_FRAME_SETTING_NOISE:
2199
0
    case JXL_ENC_FRAME_SETTING_DOTS:
2200
0
    case JXL_ENC_FRAME_SETTING_PATCHES:
2201
0
    case JXL_ENC_FRAME_SETTING_EPF:
2202
0
    case JXL_ENC_FRAME_SETTING_GABORISH:
2203
0
    case JXL_ENC_FRAME_SETTING_MODULAR:
2204
0
    case JXL_ENC_FRAME_SETTING_KEEP_INVISIBLE:
2205
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER:
2206
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_X:
2207
0
    case JXL_ENC_FRAME_SETTING_GROUP_ORDER_CENTER_Y:
2208
0
    case JXL_ENC_FRAME_SETTING_RESPONSIVE:
2209
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_AC:
2210
0
    case JXL_ENC_FRAME_SETTING_QPROGRESSIVE_AC:
2211
0
    case JXL_ENC_FRAME_SETTING_PROGRESSIVE_DC:
2212
0
    case JXL_ENC_FRAME_SETTING_PALETTE_COLORS:
2213
0
    case JXL_ENC_FRAME_SETTING_LOSSY_PALETTE:
2214
0
    case JXL_ENC_FRAME_SETTING_COLOR_TRANSFORM:
2215
0
    case JXL_ENC_FRAME_SETTING_MODULAR_COLOR_SPACE:
2216
0
    case JXL_ENC_FRAME_SETTING_MODULAR_GROUP_SIZE:
2217
0
    case JXL_ENC_FRAME_SETTING_MODULAR_PREDICTOR:
2218
0
    case JXL_ENC_FRAME_SETTING_MODULAR_NB_PREV_CHANNELS:
2219
0
    case JXL_ENC_FRAME_SETTING_JPEG_RECON_CFL:
2220
0
    case JXL_ENC_FRAME_INDEX_BOX:
2221
0
    case JXL_ENC_FRAME_SETTING_BROTLI_EFFORT:
2222
0
    case JXL_ENC_FRAME_SETTING_FILL_ENUM:
2223
0
    case JXL_ENC_FRAME_SETTING_JPEG_COMPRESS_BOXES:
2224
0
    case JXL_ENC_FRAME_SETTING_BUFFERING:
2225
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_EXIF:
2226
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_XMP:
2227
0
    case JXL_ENC_FRAME_SETTING_JPEG_KEEP_JUMBF:
2228
0
    case JXL_ENC_FRAME_SETTING_USE_FULL_IMAGE_HEURISTICS:
2229
0
    case JXL_ENC_FRAME_SETTING_STRIP_ALPHA:
2230
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2231
0
                           "Int option, try setting it with "
2232
0
                           "JxlEncoderFrameSettingsSetOption");
2233
0
    default:
2234
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2235
0
                           "Unknown option");
2236
0
  }
2237
0
}
2238
2.98k
JxlEncoder* JxlEncoderCreate(const JxlMemoryManager* memory_manager) {
2239
2.98k
  JxlMemoryManager local_memory_manager;
2240
2.98k
  if (!jxl::MemoryManagerInit(&local_memory_manager, memory_manager)) {
2241
0
    return nullptr;
2242
0
  }
2243
2244
2.98k
  void* alloc =
2245
2.98k
      jxl::MemoryManagerAlloc(&local_memory_manager, sizeof(JxlEncoder));
2246
2.98k
  if (!alloc) return nullptr;
2247
2.98k
  JxlEncoder* enc = new (alloc) JxlEncoder();
2248
2.98k
  enc->memory_manager = local_memory_manager;
2249
  // TODO(sboukortt): add an API function to set this.
2250
2.98k
  enc->cms = *JxlGetDefaultCms();
2251
2.98k
  enc->cms_set = true;
2252
2253
  // Initialize all the field values.
2254
2.98k
  JxlEncoderReset(enc);
2255
2256
2.98k
  return enc;
2257
2.98k
}
2258
2259
2.98k
void JxlEncoderReset(JxlEncoder* enc) {
2260
2.98k
  enc->thread_pool.reset();
2261
2.98k
  enc->input_queue.clear();
2262
2.98k
  enc->num_queued_frames = 0;
2263
2.98k
  enc->num_queued_boxes = 0;
2264
2.98k
  enc->encoder_options.clear();
2265
2.98k
  enc->codestream_bytes_written_end_of_frame = 0;
2266
2.98k
  enc->wrote_bytes = false;
2267
2.98k
  enc->jxlp_counter = 0;
2268
2.98k
  enc->metadata = jxl::CodecMetadata();
2269
2.98k
  enc->last_used_cparams = jxl::CompressParams();
2270
2.98k
  enc->frames_closed = false;
2271
2.98k
  enc->boxes_closed = false;
2272
2.98k
  enc->basic_info_set = false;
2273
2.98k
  enc->color_encoding_set = false;
2274
2.98k
  enc->intensity_target_set = false;
2275
2.98k
  enc->use_container = false;
2276
2.98k
  enc->use_boxes = false;
2277
2.98k
  enc->container_ftyp_version = -1;
2278
2.98k
  enc->store_jpeg_metadata = false;
2279
2.98k
  enc->codestream_level = -1;
2280
2.98k
  enc->output_processor =
2281
2.98k
      JxlEncoderOutputProcessorWrapper(&enc->memory_manager);
2282
2.98k
  JxlEncoderInitBasicInfo(&enc->basic_info);
2283
2284
  // jxl::JxlEncoderFrameIndexBox frame_index_box;
2285
  // JxlEncoderError error = JxlEncoderError::JXL_ENC_ERR_OK;
2286
  // bool allow_expert_options = false;
2287
  // int brotli_effort = -1;
2288
2.98k
}
2289
2290
2.98k
void JxlEncoderDestroy(JxlEncoder* enc) {
2291
2.98k
  if (enc) {
2292
2.98k
    JxlMemoryManager local_memory_manager = enc->memory_manager;
2293
    // Call destructor directly since custom free function is used.
2294
2.98k
    enc->~JxlEncoder();
2295
2.98k
    jxl::MemoryManagerFree(&local_memory_manager, enc);
2296
2.98k
  }
2297
2.98k
}
2298
2299
0
JxlEncoderError JxlEncoderGetError(JxlEncoder* enc) { return enc->error; }
2300
2301
JxlEncoderStatus JxlEncoderUseContainer(JxlEncoder* enc,
2302
0
                                        JXL_BOOL use_container) {
2303
0
  if (enc->wrote_bytes) {
2304
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2305
0
                         "this setting can only be set at the beginning");
2306
0
  }
2307
0
  enc->use_container = FROM_JXL_BOOL(use_container);
2308
0
  return JxlErrorOrStatus::Success();
2309
0
}
2310
2311
JxlEncoderStatus JxlEncoderStoreJPEGMetadata(JxlEncoder* enc,
2312
0
                                             JXL_BOOL store_jpeg_metadata) {
2313
0
  if (enc->wrote_bytes) {
2314
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2315
0
                         "this setting can only be set at the beginning");
2316
0
  }
2317
0
  enc->store_jpeg_metadata = FROM_JXL_BOOL(store_jpeg_metadata);
2318
0
  return JxlErrorOrStatus::Success();
2319
0
}
2320
2321
0
JxlEncoderStatus JxlEncoderSetCodestreamLevel(JxlEncoder* enc, int level) {
2322
0
  if (level != -1 && level != 5 && level != 10) {
2323
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_NOT_SUPPORTED, "invalid level");
2324
0
  }
2325
0
  if (enc->wrote_bytes) {
2326
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2327
0
                         "this setting can only be set at the beginning");
2328
0
  }
2329
0
  enc->codestream_level = level;
2330
0
  return JxlErrorOrStatus::Success();
2331
0
}
2332
2333
0
int JxlEncoderGetRequiredCodestreamLevel(const JxlEncoder* enc) {
2334
0
  return VerifyLevelSettings(enc, nullptr);
2335
0
}
2336
2337
0
void JxlEncoderSetCms(JxlEncoder* enc, JxlCmsInterface cms) {
2338
0
  jxl::msan::MemoryIsInitialized(&cms, sizeof(cms));
2339
0
  enc->cms = cms;
2340
0
  enc->cms_set = true;
2341
0
}
2342
2343
JxlEncoderStatus JxlEncoderSetParallelRunner(JxlEncoder* enc,
2344
                                             JxlParallelRunner parallel_runner,
2345
2.98k
                                             void* parallel_runner_opaque) {
2346
2.98k
  if (enc->thread_pool) {
2347
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2348
0
                         "parallel runner already set");
2349
0
  }
2350
2.98k
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2351
2.98k
      thread_pool, jxl::ThreadPool,
2352
2.98k
      (&enc->memory_manager, parallel_runner, parallel_runner_opaque),
2353
2.98k
      JXL_API_ERROR(enc, JXL_ENC_ERR_OOM, "can not allocate thread pool"));
2354
2.98k
  enc->thread_pool = std::move(thread_pool);
2355
2.98k
  return JxlErrorOrStatus::Success();
2356
2.98k
}
2357
2358
namespace {
2359
JxlEncoderStatus GetCurrentDimensions(
2360
    const JxlEncoderFrameSettings* frame_settings, size_t& xsize,
2361
2.90k
    size_t& ysize) {
2362
2.90k
  xsize = frame_settings->enc->metadata.xsize();
2363
2.90k
  ysize = frame_settings->enc->metadata.ysize();
2364
2.90k
  if (frame_settings->values.header.layer_info.have_crop) {
2365
0
    xsize = frame_settings->values.header.layer_info.xsize;
2366
0
    ysize = frame_settings->values.header.layer_info.ysize;
2367
0
  }
2368
2.90k
  if (frame_settings->values.cparams.already_downsampled) {
2369
0
    size_t factor = frame_settings->values.cparams.resampling;
2370
0
    xsize = jxl::DivCeil(xsize, factor);
2371
0
    ysize = jxl::DivCeil(ysize, factor);
2372
0
  }
2373
2.90k
  if (xsize == 0 || ysize == 0) {
2374
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2375
0
                         "zero-sized frame is not allowed");
2376
0
  }
2377
2.90k
  return JxlErrorOrStatus::Success();
2378
2.90k
}
2379
}  // namespace
2380
2381
JxlEncoderStatus JxlEncoderAddJPEGFrame(
2382
    const JxlEncoderFrameSettings* frame_settings, const uint8_t* buffer,
2383
0
    size_t size) {
2384
0
  JxlMemoryManager* memory_manager = &frame_settings->enc->memory_manager;
2385
0
  if (frame_settings->enc->frames_closed) {
2386
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2387
0
                         "Frame input is already closed");
2388
0
  }
2389
2390
0
  std::unique_ptr<jxl::jpeg::JPEGData> jpeg_data;
2391
0
  auto decode_jpg = [&]() -> jxl::Status {
2392
0
    JXL_ASSIGN_OR_RETURN(
2393
0
        jpeg_data,
2394
0
        jxl::jpeg::ParseJPG(memory_manager, jxl::Bytes(buffer, size)));
2395
0
    return true;
2396
0
  };
2397
0
  jxl::Status status = decode_jpg();
2398
0
  if (!status) {
2399
0
    if (status.code() == jxl::StatusCode::kUnsupported) {
2400
0
      return JXL_API_ERROR(
2401
0
          frame_settings->enc, JXL_ENC_ERR_NOT_SUPPORTED,
2402
0
          "Unsupported JPEG feature (CMYK, arithmetic coding, etc.)");
2403
0
    } else {
2404
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_BAD_INPUT,
2405
0
                           "Error during decode of input JPEG");
2406
0
    }
2407
0
  }
2408
2409
0
  if (!frame_settings->enc->color_encoding_set) {
2410
0
    if (!SetColorEncodingFromJpegData(
2411
0
            *jpeg_data, &frame_settings->enc->metadata.m.color_encoding)) {
2412
0
      return JXL_API_ERROR(
2413
0
          frame_settings->enc, JXL_ENC_ERR_BAD_INPUT,
2414
0
          "Error decoding the ICC profile embedded in the input JPEG");
2415
0
    }
2416
0
    frame_settings->enc->color_encoding_set = true;
2417
0
  }
2418
2419
0
  if (!frame_settings->enc->basic_info_set) {
2420
0
    JxlBasicInfo basic_info;
2421
0
    JxlEncoderInitBasicInfo(&basic_info);
2422
0
    basic_info.xsize = jpeg_data->width;
2423
0
    basic_info.ysize = jpeg_data->height;
2424
0
    basic_info.uses_original_profile = JXL_TRUE;
2425
0
    if (JxlEncoderSetBasicInfo(frame_settings->enc, &basic_info) !=
2426
0
        JXL_ENC_SUCCESS) {
2427
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2428
0
                           "Error setting basic info");
2429
0
    }
2430
0
  }
2431
2432
0
  size_t xsize;
2433
0
  size_t ysize;
2434
0
  if (GetCurrentDimensions(frame_settings, xsize, ysize) != JXL_ENC_SUCCESS) {
2435
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2436
0
                         "bad dimensions");
2437
0
  }
2438
0
  if (xsize != static_cast<size_t>(jpeg_data->width) ||
2439
0
      ysize != static_cast<size_t>(jpeg_data->height)) {
2440
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2441
0
                         "JPEG dimensions don't match frame dimensions");
2442
0
  }
2443
2444
0
  if (frame_settings->enc->metadata.m.xyb_encoded) {
2445
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2446
0
                         "Can't XYB encode a lossless JPEG");
2447
0
  }
2448
2449
0
  jxl::jpeg::Blobs blobs;
2450
0
  if (!SetBlobsFromJpegData(*jpeg_data, &blobs)) {
2451
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_BAD_INPUT,
2452
0
                         "Error during parsing of input JPEG blobs");
2453
0
  }
2454
2455
0
  if (!blobs.exif.empty()) {
2456
0
    JxlOrientation orientation = static_cast<JxlOrientation>(
2457
0
        frame_settings->enc->metadata.m.orientation);
2458
0
    jxl::InterpretExif(blobs.exif, &orientation);
2459
0
    frame_settings->enc->metadata.m.orientation = orientation;
2460
0
  }
2461
0
  if (!blobs.exif.empty() && frame_settings->values.cparams.jpeg_keep_exif) {
2462
0
    size_t exif_size = blobs.exif.size();
2463
    // Exif data in JPEG is limited to 64k
2464
0
    if (exif_size > 0xFFFF) {
2465
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2466
0
                           "Exif larger than possible in JPEG?");
2467
0
    }
2468
0
    exif_size += 4;  // prefix 4 zero bytes for tiff offset
2469
0
    std::vector<uint8_t> exif(exif_size);
2470
0
    memcpy(exif.data() + 4, blobs.exif.data(), blobs.exif.size());
2471
0
    JxlEncoderUseBoxes(frame_settings->enc);
2472
0
    JxlEncoderAddBox(
2473
0
        frame_settings->enc, "Exif", exif.data(), exif_size,
2474
0
        TO_JXL_BOOL(frame_settings->values.cparams.jpeg_compress_boxes));
2475
0
  }
2476
0
  if (!blobs.xmp.empty() && frame_settings->values.cparams.jpeg_keep_xmp) {
2477
0
    JxlEncoderUseBoxes(frame_settings->enc);
2478
0
    JxlEncoderAddBox(
2479
0
        frame_settings->enc, "xml ", blobs.xmp.data(), blobs.xmp.size(),
2480
0
        TO_JXL_BOOL(frame_settings->values.cparams.jpeg_compress_boxes));
2481
0
  }
2482
0
  if (!blobs.jumbf.empty() && frame_settings->values.cparams.jpeg_keep_jumbf) {
2483
0
    JxlEncoderUseBoxes(frame_settings->enc);
2484
0
    JxlEncoderAddBox(
2485
0
        frame_settings->enc, "jumb", blobs.jumbf.data(), blobs.jumbf.size(),
2486
0
        TO_JXL_BOOL(frame_settings->values.cparams.jpeg_compress_boxes));
2487
0
  }
2488
0
  if (frame_settings->enc->store_jpeg_metadata) {
2489
0
    if (!frame_settings->values.cparams.jpeg_keep_exif ||
2490
0
        !frame_settings->values.cparams.jpeg_keep_xmp) {
2491
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2492
0
                           "Need to preserve EXIF and XMP to allow JPEG "
2493
0
                           "bitstream reconstruction");
2494
0
    }
2495
0
    std::vector<uint8_t> jpeg_metadata;
2496
0
    if (!jxl::jpeg::EncodeJPEGData(&frame_settings->enc->memory_manager,
2497
0
                                   *jpeg_data, &jpeg_metadata,
2498
0
                                   frame_settings->values.cparams)) {
2499
0
      return JXL_API_ERROR(
2500
0
          frame_settings->enc, JXL_ENC_ERR_JBRD,
2501
0
          "JPEG bitstream reconstruction data cannot be encoded");
2502
0
    }
2503
0
    frame_settings->enc->jpeg_metadata = jpeg_metadata;
2504
0
  }
2505
2506
0
  jxl::JxlEncoderChunkedFrameAdapter frame_data(
2507
0
      xsize, ysize, frame_settings->enc->metadata.m.num_extra_channels);
2508
0
  frame_data.SetJPEGData(std::move(jpeg_data));
2509
2510
  // JxlEncoderQueuedFrame is a struct with no constructors, so we use the
2511
  // default move constructor there.
2512
0
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2513
0
      queued_frame, jxl::JxlEncoderQueuedFrame,
2514
0
      (&frame_settings->enc->memory_manager,
2515
0
       jxl::JxlEncoderQueuedFrame{
2516
0
           frame_settings->values, std::move(frame_data), {}}),
2517
0
      JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_OOM,
2518
0
                    "can not allocate queued frame"));
2519
0
  queued_frame->ec_initialized.resize(
2520
0
      frame_settings->enc->metadata.m.num_extra_channels);
2521
2522
0
  QueueFrame(frame_settings, queued_frame);
2523
0
  return JxlErrorOrStatus::Success();
2524
0
}
2525
2526
static bool CanDoFastLossless(const JxlEncoderFrameSettings* frame_settings,
2527
                              const JxlPixelFormat* pixel_format,
2528
2.90k
                              bool has_alpha) {
2529
2.90k
  if (!frame_settings->values.lossless) {
2530
2.90k
    return false;
2531
2.90k
  }
2532
0
  if (has_alpha && frame_settings->values.strip_alpha > 0) {
2533
0
    return false;
2534
0
  }
2535
  // TODO(veluca): many of the following options could be made to work, but are
2536
  // just not implemented in FJXL's frame header handling yet.
2537
0
  if (frame_settings->values.frame_index_box) {
2538
0
    return false;
2539
0
  }
2540
0
  if (frame_settings->values.header.layer_info.have_crop) {
2541
0
    return false;
2542
0
  }
2543
0
  if (frame_settings->enc->metadata.m.have_animation) {
2544
0
    return false;
2545
0
  }
2546
0
  if (frame_settings->values.cparams.speed_tier != jxl::SpeedTier::kLightning) {
2547
0
    return false;
2548
0
  }
2549
0
  if (frame_settings->values.image_bit_depth.type ==
2550
0
          JxlBitDepthType::JXL_BIT_DEPTH_CUSTOM &&
2551
0
      frame_settings->values.image_bit_depth.bits_per_sample !=
2552
0
          frame_settings->enc->metadata.m.bit_depth.bits_per_sample) {
2553
0
    return false;
2554
0
  }
2555
  // TODO(veluca): implement support for LSB-padded input in fast_lossless.
2556
0
  if (frame_settings->values.image_bit_depth.type ==
2557
0
          JxlBitDepthType::JXL_BIT_DEPTH_FROM_PIXEL_FORMAT &&
2558
0
      frame_settings->enc->metadata.m.bit_depth.bits_per_sample % 8 != 0) {
2559
0
    return false;
2560
0
  }
2561
0
  if (!frame_settings->values.frame_name.empty()) {
2562
0
    return false;
2563
0
  }
2564
  // No extra channels other than alpha.
2565
0
  if (!(has_alpha && frame_settings->enc->metadata.m.num_extra_channels == 1) &&
2566
0
      frame_settings->enc->metadata.m.num_extra_channels != 0) {
2567
0
    return false;
2568
0
  }
2569
0
  if (frame_settings->enc->metadata.m.bit_depth.bits_per_sample > 16) {
2570
0
    return false;
2571
0
  }
2572
0
  if (pixel_format->data_type != JxlDataType::JXL_TYPE_FLOAT16 &&
2573
0
      pixel_format->data_type != JxlDataType::JXL_TYPE_UINT16 &&
2574
0
      pixel_format->data_type != JxlDataType::JXL_TYPE_UINT8) {
2575
0
    return false;
2576
0
  }
2577
0
  if ((frame_settings->enc->metadata.m.bit_depth.bits_per_sample > 8) !=
2578
0
      (pixel_format->data_type == JxlDataType::JXL_TYPE_UINT16 ||
2579
0
       pixel_format->data_type == JxlDataType::JXL_TYPE_FLOAT16)) {
2580
0
    return false;
2581
0
  }
2582
0
  if (!((pixel_format->num_channels == 1 || pixel_format->num_channels == 3) &&
2583
0
        !has_alpha) &&
2584
0
      !((pixel_format->num_channels == 2 || pixel_format->num_channels == 4) &&
2585
0
        has_alpha)) {
2586
0
    return false;
2587
0
  }
2588
2589
0
  return true;
2590
0
}
2591
2592
namespace {
2593
JxlEncoderStatus JxlEncoderAddImageFrameInternal(
2594
    const JxlEncoderFrameSettings* frame_settings, size_t xsize, size_t ysize,
2595
2.90k
    bool streaming, jxl::JxlEncoderChunkedFrameAdapter&& frame_data) {
2596
2.90k
  JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
2597
2.90k
  {
2598
2.90k
    JxlChunkedFrameInputSource input = frame_data.GetInputSource();
2599
2.90k
    input.get_color_channels_pixel_format(input.opaque, &pixel_format);
2600
2.90k
  }
2601
2.90k
  uint32_t num_channels = pixel_format.num_channels;
2602
2.90k
  size_t has_interleaved_alpha =
2603
2.90k
      static_cast<size_t>(num_channels == 2 || num_channels == 4);
2604
2605
2.90k
  if (!frame_settings->enc->basic_info_set) {
2606
    // Basic Info must be set. Otherwise, this is an API misuse.
2607
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2608
0
                         "Basic info or color encoding not set yet");
2609
0
  }
2610
2.90k
  if (frame_settings->enc->frames_closed) {
2611
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2612
0
                         "Frame input already closed");
2613
0
  }
2614
2.90k
  if (num_channels < 3) {
2615
181
    if (frame_settings->enc->basic_info.num_color_channels != 1) {
2616
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2617
0
                           "Grayscale pixel format input for an RGB image");
2618
0
    }
2619
2.72k
  } else {
2620
2.72k
    if (frame_settings->enc->basic_info.num_color_channels != 3) {
2621
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2622
0
                           "RGB pixel format input for a grayscale image");
2623
0
    }
2624
2.72k
  }
2625
2.90k
  if (frame_settings->values.lossless &&
2626
0
      frame_settings->enc->metadata.m.xyb_encoded) {
2627
0
    return JXL_API_ERROR(
2628
0
        frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2629
0
        "Set uses_original_profile=true for lossless encoding");
2630
0
  }
2631
2.90k
  if (frame_settings->values.cparams.disable_perceptual_optimizations &&
2632
0
      frame_settings->enc->metadata.m.xyb_encoded) {
2633
0
    return JXL_API_ERROR(
2634
0
        frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2635
0
        "Set uses_original_profile=true for non-perceptual encoding");
2636
0
  }
2637
2.90k
  if (JXL_ENC_SUCCESS !=
2638
2.90k
      VerifyInputBitDepth(frame_settings->values.image_bit_depth,
2639
2.90k
                          pixel_format)) {
2640
0
    return JXL_API_ERROR_NOSET("Invalid input bit depth");
2641
0
  }
2642
2.90k
  if (has_interleaved_alpha >
2643
2.90k
      frame_settings->enc->metadata.m.num_extra_channels) {
2644
0
    if (frame_settings->values.strip_alpha == kStripAlphaForce) {
2645
0
      has_interleaved_alpha = 0;
2646
0
    } else {
2647
0
      return JXL_API_ERROR(
2648
0
          frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2649
0
          "number of extra channels mismatch (need 1 extra channel for alpha)");
2650
0
    }
2651
0
  }
2652
2653
2.90k
  bool has_alpha = frame_settings->enc->metadata.m.HasAlpha();
2654
2655
  // All required conditions to do fast-lossless.
2656
2.90k
  if (CanDoFastLossless(frame_settings, &pixel_format, has_alpha)) {
2657
0
    const bool big_endian =
2658
0
        pixel_format.endianness == JXL_BIG_ENDIAN ||
2659
0
        (pixel_format.endianness == JXL_NATIVE_ENDIAN && !IsLittleEndian());
2660
2661
0
    RunnerTicket ticket{frame_settings->enc->thread_pool.get()};
2662
0
    JXL_BOOL oneshot = TO_JXL_BOOL(!frame_data.StreamingInput());
2663
0
    auto* frame_state = JxlFastLosslessPrepareFrame(
2664
0
        frame_data.GetInputSource(), xsize, ysize, num_channels,
2665
0
        frame_settings->enc->metadata.m.bit_depth.bits_per_sample, big_endian,
2666
0
        /*effort=*/2, oneshot);
2667
0
    if (!frame_state) {
2668
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2669
0
                           "Internal: JxlFastLosslessPrepareFrame failed");
2670
0
    }
2671
0
    if (!streaming) {
2672
0
      bool ok =
2673
0
          JxlFastLosslessProcessFrame(frame_state, /*is_last=*/false, &ticket,
2674
0
                                      &FastLosslessRunnerAdapter, nullptr);
2675
0
      if (!ok || ticket.has_error) {
2676
0
        return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2677
0
                             "Internal: JxlFastLosslessProcessFrame failed");
2678
0
      }
2679
0
    }
2680
0
    QueueFastLosslessFrame(frame_settings, frame_state);
2681
0
    return JxlErrorOrStatus::Success();
2682
0
  }
2683
2684
2.90k
  if (!streaming) {
2685
    // The input callbacks are only guaranteed to be available during frame
2686
    // encoding when both the input and the output is streaming. In all other
2687
    // cases we need to create an internal copy of the frame data.
2688
2.90k
    if (!frame_data.CopyBuffers()) {
2689
0
      return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2690
0
                           "Invalid chunked frame input source");
2691
0
    }
2692
2.90k
  }
2693
2694
2.90k
  if (!frame_settings->enc->color_encoding_set) {
2695
0
    jxl::ColorEncoding c_current;
2696
0
    if ((pixel_format.data_type == JXL_TYPE_FLOAT) ||
2697
0
        (pixel_format.data_type == JXL_TYPE_FLOAT16)) {
2698
0
      c_current = jxl::ColorEncoding::LinearSRGB(num_channels < 3);
2699
0
    } else {
2700
0
      c_current = jxl::ColorEncoding::SRGB(num_channels < 3);
2701
0
    }
2702
0
    frame_settings->enc->metadata.m.color_encoding = c_current;
2703
0
  }
2704
  // JxlEncoderQueuedFrame is a struct with no constructors, so we use the
2705
  // default move constructor there.
2706
2.90k
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2707
2.90k
      queued_frame, jxl::JxlEncoderQueuedFrame,
2708
2.90k
      (&frame_settings->enc->memory_manager,
2709
2.90k
       jxl::JxlEncoderQueuedFrame{
2710
2.90k
           frame_settings->values, std::move(frame_data), {}}),
2711
2.90k
      JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_OOM,
2712
2.90k
                    "can not allocate queued frame"));
2713
2714
2.90k
  for (auto& ec_info : frame_settings->enc->metadata.m.extra_channel_info) {
2715
970
    if (has_interleaved_alpha && ec_info.type == jxl::ExtraChannel::kAlpha) {
2716
970
      queued_frame->ec_initialized.push_back(1);
2717
970
      has_interleaved_alpha = 0;  // only first Alpha is initialized
2718
970
    } else {
2719
0
      queued_frame->ec_initialized.push_back(0);
2720
0
    }
2721
970
  }
2722
2.90k
  queued_frame->option_values.cparams.level =
2723
2.90k
      frame_settings->enc->codestream_level;
2724
2725
2.90k
  QueueFrame(frame_settings, queued_frame);
2726
2.90k
  return JxlErrorOrStatus::Success();
2727
2.90k
}
2728
}  // namespace
2729
2730
JxlEncoderStatus JxlEncoderAddImageFrame(
2731
    const JxlEncoderFrameSettings* frame_settings,
2732
2.90k
    const JxlPixelFormat* pixel_format, const void* buffer, size_t size) {
2733
2.90k
  size_t xsize;
2734
2.90k
  size_t ysize;
2735
2.90k
  if (GetCurrentDimensions(frame_settings, xsize, ysize) != JXL_ENC_SUCCESS) {
2736
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2737
0
                         "bad dimensions");
2738
0
  }
2739
2.90k
  jxl::JxlEncoderChunkedFrameAdapter frame_data(
2740
2.90k
      xsize, ysize, frame_settings->enc->metadata.m.num_extra_channels);
2741
2.90k
  if (!frame_data.SetFromBuffer(0, reinterpret_cast<const uint8_t*>(buffer),
2742
2.90k
                                size, *pixel_format)) {
2743
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2744
0
                         "provided image buffer too small");
2745
0
  }
2746
2.90k
  return JxlEncoderAddImageFrameInternal(frame_settings, xsize, ysize,
2747
2.90k
                                         /*streaming=*/false,
2748
2.90k
                                         std::move(frame_data));
2749
2.90k
}
2750
2751
JxlEncoderStatus JxlEncoderAddChunkedFrame(
2752
    const JxlEncoderFrameSettings* frame_settings, JXL_BOOL is_last_frame,
2753
0
    JxlChunkedFrameInputSource chunked_frame_input) {
2754
0
  size_t xsize;
2755
0
  size_t ysize;
2756
0
  if (GetCurrentDimensions(frame_settings, xsize, ysize) != JXL_ENC_SUCCESS) {
2757
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_GENERIC,
2758
0
                         "bad dimensions");
2759
0
  }
2760
0
  bool streaming = frame_settings->enc->output_processor.OutputProcessorSet();
2761
0
  jxl::JxlEncoderChunkedFrameAdapter frame_data(
2762
0
      xsize, ysize, frame_settings->enc->metadata.m.num_extra_channels);
2763
0
  frame_data.SetInputSource(chunked_frame_input);
2764
0
  auto status = JxlEncoderAddImageFrameInternal(
2765
0
      frame_settings, xsize, ysize, streaming, std::move(frame_data));
2766
0
  if (status != JXL_ENC_SUCCESS) return status;
2767
2768
0
  auto& queued_frame = frame_settings->enc->input_queue.back();
2769
0
  if (queued_frame.frame) {
2770
0
    for (auto& val : queued_frame.frame->ec_initialized) val = 1;
2771
0
  }
2772
2773
0
  if (is_last_frame) {
2774
0
    JxlEncoderCloseFrames(frame_settings->enc);
2775
0
  }
2776
0
  if (streaming) {
2777
0
    return JxlEncoderFlushInput(frame_settings->enc);
2778
0
  }
2779
0
  return JxlErrorOrStatus::Success();
2780
0
}
2781
2782
42
JxlEncoderStatus JxlEncoderUseBoxes(JxlEncoder* enc) {
2783
42
  if (enc->wrote_bytes) {
2784
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2785
0
                         "this setting can only be set at the beginning");
2786
0
  }
2787
42
  enc->use_boxes = true;
2788
42
  return JxlErrorOrStatus::Success();
2789
42
}
2790
2791
JxlEncoderStatus JxlEncoderAddBox(JxlEncoder* enc, const JxlBoxType type,
2792
                                  const uint8_t* contents, size_t size,
2793
41
                                  JXL_BOOL compress_box) {
2794
41
  if (!enc->use_boxes) {
2795
0
    return JXL_API_ERROR(
2796
0
        enc, JXL_ENC_ERR_API_USAGE,
2797
0
        "must set JxlEncoderUseBoxes at the beginning to add boxes");
2798
0
  }
2799
41
  if (enc->boxes_closed) {
2800
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2801
0
                         "Box input already closed");
2802
0
  }
2803
41
  if (compress_box) {
2804
0
    if (memcmp("jxl", type, 3) == 0) {
2805
0
      return JXL_API_ERROR(
2806
0
          enc, JXL_ENC_ERR_API_USAGE,
2807
0
          "brob box may not contain a type starting with \"jxl\"");
2808
0
    }
2809
0
    if (memcmp("jbrd", type, 4) == 0) {
2810
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2811
0
                           "jbrd box may not be brob compressed");
2812
0
    }
2813
0
    if (memcmp("brob", type, 4) == 0) {
2814
      // The compress_box will compress an existing non-brob box into a brob
2815
      // box. If already giving a valid brotli-compressed brob box, set
2816
      // compress_box to false since it is already compressed.
2817
0
      return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2818
0
                           "a brob box cannot contain another brob box");
2819
0
    }
2820
0
  }
2821
2822
41
  JXL_MEMORY_MANAGER_MAKE_UNIQUE_OR_RETURN(
2823
41
      box, jxl::JxlEncoderQueuedBox, (&enc->memory_manager),
2824
41
      JXL_API_ERROR(enc, JXL_ENC_ERR_OOM, "can not allocate queued box"));
2825
2826
41
  box->type = jxl::MakeBoxType(type);
2827
41
  box->contents.assign(contents, contents + size);
2828
41
  box->compress_box = FROM_JXL_BOOL(compress_box);
2829
41
  QueueBox(enc, box);
2830
41
  return JxlErrorOrStatus::Success();
2831
41
}
2832
2833
JXL_EXPORT JxlEncoderStatus JxlEncoderSetExtraChannelBuffer(
2834
    const JxlEncoderFrameSettings* frame_settings,
2835
    const JxlPixelFormat* pixel_format, const void* buffer, size_t size,
2836
0
    uint32_t index) {
2837
0
  if (index >= frame_settings->enc->metadata.m.num_extra_channels) {
2838
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2839
0
                         "Invalid value for the index of extra channel");
2840
0
  }
2841
0
  if (!frame_settings->enc->basic_info_set ||
2842
0
      !frame_settings->enc->color_encoding_set) {
2843
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2844
0
                         "Basic info has to be set first");
2845
0
  }
2846
0
  if (frame_settings->enc->input_queue.empty()) {
2847
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2848
0
                         "First add image frame, then extra channels");
2849
0
  }
2850
0
  if (frame_settings->enc->frames_closed) {
2851
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2852
0
                         "Frame input already closed");
2853
0
  }
2854
0
  JxlPixelFormat ec_format = *pixel_format;
2855
0
  ec_format.num_channels = 1;
2856
0
  if (JXL_ENC_SUCCESS !=
2857
0
      VerifyInputBitDepth(frame_settings->values.image_bit_depth, ec_format)) {
2858
0
    return JXL_API_ERROR_NOSET("Invalid input bit depth");
2859
0
  }
2860
0
  const uint8_t* uint8_buffer = reinterpret_cast<const uint8_t*>(buffer);
2861
0
  auto* queued_frame = frame_settings->enc->input_queue.back().frame.get();
2862
0
  if (!queued_frame->frame_data.SetFromBuffer(1 + index, uint8_buffer, size,
2863
0
                                              ec_format)) {
2864
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2865
0
                         "provided image buffer too small");
2866
0
  }
2867
0
  queued_frame->ec_initialized[index] = 1;
2868
2869
0
  return JxlErrorOrStatus::Success();
2870
0
}
2871
2872
2.90k
void JxlEncoderCloseFrames(JxlEncoder* enc) { enc->frames_closed = true; }
2873
2874
2.94k
void JxlEncoderCloseBoxes(JxlEncoder* enc) { enc->boxes_closed = true; }
2875
2876
2.90k
void JxlEncoderCloseInput(JxlEncoder* enc) {
2877
2.90k
  JxlEncoderCloseFrames(enc);
2878
2.90k
  JxlEncoderCloseBoxes(enc);
2879
2.90k
}
2880
2881
0
JXL_EXPORT JxlEncoderStatus JxlEncoderFlushInput(JxlEncoder* enc) {
2882
0
  if (!enc->output_processor.OutputProcessorSet()) {
2883
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2884
0
                         "Cannot flush input without setting output "
2885
0
                         "processor with JxlEncoderSetOutputProcessor");
2886
0
  }
2887
0
  while (!enc->input_queue.empty()) {
2888
0
    if (!enc->ProcessOneEnqueuedInput()) {
2889
0
      return JxlErrorOrStatus::Error();
2890
0
    }
2891
0
  }
2892
0
  return JxlErrorOrStatus::Success();
2893
0
}
2894
2895
JXL_EXPORT JxlEncoderStatus JxlEncoderSetOutputProcessor(
2896
0
    JxlEncoder* enc, JxlEncoderOutputProcessor output_processor) {
2897
0
  if (enc->output_processor.HasAvailOut()) {
2898
0
    return JXL_API_ERROR(
2899
0
        enc, JXL_ENC_ERR_API_USAGE,
2900
0
        "Cannot set an output processor when some output was already produced");
2901
0
  }
2902
0
  if (!output_processor.set_finalized_position ||
2903
0
      !output_processor.get_buffer || !output_processor.release_buffer) {
2904
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2905
0
                         "Missing output processor functions");
2906
0
  }
2907
0
  enc->output_processor =
2908
0
      JxlEncoderOutputProcessorWrapper(&enc->memory_manager, output_processor);
2909
0
  return JxlErrorOrStatus::Success();
2910
0
}
2911
2912
JxlEncoderStatus JxlEncoderProcessOutput(JxlEncoder* enc, uint8_t** next_out,
2913
2.90k
                                         size_t* avail_out) {
2914
2.90k
  if (enc->output_processor.OutputProcessorSet()) {
2915
0
    return JXL_API_ERROR(enc, JXL_ENC_ERR_API_USAGE,
2916
0
                         "Cannot call JxlEncoderProcessOutput after calling "
2917
0
                         "JxlEncoderSetOutputProcessor");
2918
0
  }
2919
2.90k
  if (!enc->output_processor.SetAvailOut(next_out, avail_out)) {
2920
0
    return JxlErrorOrStatus::Error();
2921
0
  }
2922
5.75k
  while (*avail_out != 0 && !enc->input_queue.empty()) {
2923
2.94k
    if (!enc->ProcessOneEnqueuedInput()) {
2924
102
      return JxlErrorOrStatus::Error();
2925
102
    }
2926
2.94k
  }
2927
2928
2.80k
  if (!enc->input_queue.empty() || enc->output_processor.HasOutputToWrite()) {
2929
2
    return JxlErrorOrStatus::MoreOutput();
2930
2
  }
2931
2.80k
  return JxlErrorOrStatus::Success();
2932
2.80k
}
2933
2934
JxlEncoderStatus JxlEncoderSetFrameHeader(
2935
    JxlEncoderFrameSettings* frame_settings,
2936
0
    const JxlFrameHeader* frame_header) {
2937
0
  if (frame_header->layer_info.blend_info.source > 3) {
2938
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2939
0
                         "invalid blending source index");
2940
0
  }
2941
  // If there are no extra channels, it's ok for the value to be 0.
2942
0
  if (frame_header->layer_info.blend_info.alpha != 0 &&
2943
0
      frame_header->layer_info.blend_info.alpha >=
2944
0
          frame_settings->enc->metadata.m.extra_channel_info.size()) {
2945
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2946
0
                         "alpha blend channel index out of bounds");
2947
0
  }
2948
2949
0
  frame_settings->values.header = *frame_header;
2950
  // Setting the frame header resets the frame name, it must be set again with
2951
  // JxlEncoderSetFrameName if desired.
2952
0
  frame_settings->values.frame_name = "";
2953
2954
0
  return JxlErrorOrStatus::Success();
2955
0
}
2956
2957
JxlEncoderStatus JxlEncoderSetExtraChannelBlendInfo(
2958
    JxlEncoderFrameSettings* frame_settings, size_t index,
2959
0
    const JxlBlendInfo* blend_info) {
2960
0
  if (index >= frame_settings->enc->metadata.m.num_extra_channels) {
2961
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2962
0
                         "Invalid value for the index of extra channel");
2963
0
  }
2964
2965
0
  if (frame_settings->values.extra_channel_blend_info.size() !=
2966
0
      frame_settings->enc->metadata.m.num_extra_channels) {
2967
0
    JxlBlendInfo default_blend_info;
2968
0
    JxlEncoderInitBlendInfo(&default_blend_info);
2969
0
    frame_settings->values.extra_channel_blend_info.resize(
2970
0
        frame_settings->enc->metadata.m.num_extra_channels, default_blend_info);
2971
0
  }
2972
0
  frame_settings->values.extra_channel_blend_info[index] = *blend_info;
2973
0
  return JxlErrorOrStatus::Success();
2974
0
}
2975
2976
JxlEncoderStatus JxlEncoderSetFrameName(JxlEncoderFrameSettings* frame_settings,
2977
0
                                        const char* frame_name) {
2978
0
  std::string str = frame_name ? frame_name : "";
2979
0
  if (str.size() > 1071) {
2980
0
    return JXL_API_ERROR(frame_settings->enc, JXL_ENC_ERR_API_USAGE,
2981
0
                         "frame name can be max 1071 bytes long");
2982
0
  }
2983
0
  frame_settings->values.frame_name = str;
2984
0
  frame_settings->values.header.name_length = str.size();
2985
0
  return JxlErrorOrStatus::Success();
2986
0
}
2987
2988
JxlEncoderStatus JxlEncoderSetFrameBitDepth(
2989
0
    JxlEncoderFrameSettings* frame_settings, const JxlBitDepth* bit_depth) {
2990
0
  if (bit_depth->type != JXL_BIT_DEPTH_FROM_PIXEL_FORMAT &&
2991
0
      bit_depth->type != JXL_BIT_DEPTH_FROM_CODESTREAM) {
2992
0
    return JXL_API_ERROR_NOSET(
2993
0
        "Only JXL_BIT_DEPTH_FROM_PIXEL_FORMAT and "
2994
0
        "JXL_BIT_DEPTH_FROM_CODESTREAM is implemented "
2995
0
        "for input buffers.");
2996
0
  }
2997
0
  frame_settings->values.image_bit_depth = *bit_depth;
2998
0
  return JxlErrorOrStatus::Success();
2999
0
}
3000
3001
void JxlColorEncodingSetToSRGB(JxlColorEncoding* color_encoding,
3002
2.89k
                               JXL_BOOL is_gray) {
3003
2.89k
  *color_encoding =
3004
2.89k
      jxl::ColorEncoding::SRGB(FROM_JXL_BOOL(is_gray)).ToExternal();
3005
2.89k
}
3006
3007
void JxlColorEncodingSetToLinearSRGB(JxlColorEncoding* color_encoding,
3008
9
                                     JXL_BOOL is_gray) {
3009
9
  *color_encoding =
3010
9
      jxl::ColorEncoding::LinearSRGB(FROM_JXL_BOOL(is_gray)).ToExternal();
3011
9
}
3012
3013
0
void JxlEncoderAllowExpertOptions(JxlEncoder* enc) {
3014
0
  enc->allow_expert_options = true;
3015
0
}
3016
3017
JXL_EXPORT void JxlEncoderSetDebugImageCallback(
3018
    JxlEncoderFrameSettings* frame_settings, JxlDebugImageCallback callback,
3019
0
    void* opaque) {
3020
0
  frame_settings->values.cparams.debug_image = callback;
3021
0
  frame_settings->values.cparams.debug_image_opaque = opaque;
3022
0
}
3023
3024
0
JXL_EXPORT JxlEncoderStats* JxlEncoderStatsCreate() {
3025
0
  JxlEncoderStats* result = new JxlEncoderStats();
3026
0
  result->aux_out = jxl::make_unique<jxl::AuxOut>();
3027
0
  return result;
3028
0
}
3029
3030
0
JXL_EXPORT void JxlEncoderStatsDestroy(JxlEncoderStats* stats) { delete stats; }
3031
3032
JXL_EXPORT void JxlEncoderCollectStats(JxlEncoderFrameSettings* frame_settings,
3033
0
                                       JxlEncoderStats* stats) {
3034
0
  if (!stats) return;
3035
0
  frame_settings->values.aux_out = stats->aux_out.get();
3036
0
}
3037
3038
JXL_EXPORT size_t JxlEncoderStatsGet(const JxlEncoderStats* stats,
3039
0
                                     JxlEncoderStatsKey key) {
3040
0
  if (!stats) return 0;
3041
0
  const jxl::AuxOut& aux_out = *stats->aux_out;
3042
0
  switch (key) {
3043
0
    case JXL_ENC_STAT_HEADER_BITS:
3044
0
      return aux_out.layer(jxl::LayerType::Header).total_bits;
3045
0
    case JXL_ENC_STAT_TOC_BITS:
3046
0
      return aux_out.layer(jxl::LayerType::Toc).total_bits;
3047
0
    case JXL_ENC_STAT_DICTIONARY_BITS:
3048
0
      return aux_out.layer(jxl::LayerType::Dictionary).total_bits;
3049
0
    case JXL_ENC_STAT_SPLINES_BITS:
3050
0
      return aux_out.layer(jxl::LayerType::Splines).total_bits;
3051
0
    case JXL_ENC_STAT_NOISE_BITS:
3052
0
      return aux_out.layer(jxl::LayerType::Noise).total_bits;
3053
0
    case JXL_ENC_STAT_QUANT_BITS:
3054
0
      return aux_out.layer(jxl::LayerType::Quant).total_bits;
3055
0
    case JXL_ENC_STAT_MODULAR_TREE_BITS:
3056
0
      return aux_out.layer(jxl::LayerType::ModularTree).total_bits;
3057
0
    case JXL_ENC_STAT_MODULAR_GLOBAL_BITS:
3058
0
      return aux_out.layer(jxl::LayerType::ModularGlobal).total_bits;
3059
0
    case JXL_ENC_STAT_DC_BITS:
3060
0
      return aux_out.layer(jxl::LayerType::Dc).total_bits;
3061
0
    case JXL_ENC_STAT_MODULAR_DC_GROUP_BITS:
3062
0
      return aux_out.layer(jxl::LayerType::ModularDcGroup).total_bits;
3063
0
    case JXL_ENC_STAT_CONTROL_FIELDS_BITS:
3064
0
      return aux_out.layer(jxl::LayerType::ControlFields).total_bits;
3065
0
    case JXL_ENC_STAT_COEF_ORDER_BITS:
3066
0
      return aux_out.layer(jxl::LayerType::Order).total_bits;
3067
0
    case JXL_ENC_STAT_AC_HISTOGRAM_BITS:
3068
0
      return aux_out.layer(jxl::LayerType::Ac).total_bits;
3069
0
    case JXL_ENC_STAT_AC_BITS:
3070
0
      return aux_out.layer(jxl::LayerType::AcTokens).total_bits;
3071
0
    case JXL_ENC_STAT_MODULAR_AC_GROUP_BITS:
3072
0
      return aux_out.layer(jxl::LayerType::ModularAcGroup).total_bits;
3073
0
    case JXL_ENC_STAT_NUM_SMALL_BLOCKS:
3074
0
      return aux_out.num_small_blocks;
3075
0
    case JXL_ENC_STAT_NUM_DCT4X8_BLOCKS:
3076
0
      return aux_out.num_dct4x8_blocks;
3077
0
    case JXL_ENC_STAT_NUM_AFV_BLOCKS:
3078
0
      return aux_out.num_afv_blocks;
3079
0
    case JXL_ENC_STAT_NUM_DCT8_BLOCKS:
3080
0
      return aux_out.num_dct8_blocks;
3081
0
    case JXL_ENC_STAT_NUM_DCT8X32_BLOCKS:
3082
0
      return aux_out.num_dct16_blocks;
3083
0
    case JXL_ENC_STAT_NUM_DCT16_BLOCKS:
3084
0
      return aux_out.num_dct16x32_blocks;
3085
0
    case JXL_ENC_STAT_NUM_DCT16X32_BLOCKS:
3086
0
      return aux_out.num_dct32_blocks;
3087
0
    case JXL_ENC_STAT_NUM_DCT32_BLOCKS:
3088
0
      return aux_out.num_dct32x64_blocks;
3089
0
    case JXL_ENC_STAT_NUM_DCT32X64_BLOCKS:
3090
0
      return aux_out.num_dct32x64_blocks;
3091
0
    case JXL_ENC_STAT_NUM_DCT64_BLOCKS:
3092
0
      return aux_out.num_dct64_blocks;
3093
0
    case JXL_ENC_STAT_NUM_BUTTERAUGLI_ITERS:
3094
0
      return aux_out.num_butteraugli_iters;
3095
0
    default:
3096
0
      return 0;
3097
0
  }
3098
0
}
3099
3100
JXL_EXPORT void JxlEncoderStatsMerge(JxlEncoderStats* stats,
3101
0
                                     const JxlEncoderStats* other) {
3102
0
  if (!stats || !other) return;
3103
0
  stats->aux_out->Assimilate(*other->aux_out);
3104
0
}