Coverage Report

Created: 2025-07-23 08:18

/src/libjxl/lib/jxl/enc_frame.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/enc_frame.h"
7
8
#include <jxl/cms_interface.h>
9
#include <jxl/encode.h>
10
#include <jxl/memory_manager.h>
11
#include <jxl/types.h>
12
13
#include <algorithm>
14
#include <array>
15
#include <cmath>
16
#include <cstddef>
17
#include <cstdint>
18
#include <memory>
19
#include <numeric>
20
#include <utility>
21
#include <vector>
22
23
#include "lib/jxl/ac_context.h"
24
#include "lib/jxl/ac_strategy.h"
25
#include "lib/jxl/base/bits.h"
26
#include "lib/jxl/base/common.h"
27
#include "lib/jxl/base/compiler_specific.h"
28
#include "lib/jxl/base/data_parallel.h"
29
#include "lib/jxl/base/override.h"
30
#include "lib/jxl/base/printf_macros.h"
31
#include "lib/jxl/base/rect.h"
32
#include "lib/jxl/base/span.h"
33
#include "lib/jxl/base/status.h"
34
#include "lib/jxl/chroma_from_luma.h"
35
#include "lib/jxl/coeff_order.h"
36
#include "lib/jxl/coeff_order_fwd.h"
37
#include "lib/jxl/color_encoding_internal.h"
38
#include "lib/jxl/common.h"  // kMaxNumPasses
39
#include "lib/jxl/dct_util.h"
40
#include "lib/jxl/dec_external_image.h"
41
#include "lib/jxl/dec_modular.h"
42
#include "lib/jxl/enc_ac_strategy.h"
43
#include "lib/jxl/enc_adaptive_quantization.h"
44
#include "lib/jxl/enc_ans.h"
45
#include "lib/jxl/enc_ans_params.h"
46
#include "lib/jxl/enc_aux_out.h"
47
#include "lib/jxl/enc_bit_writer.h"
48
#include "lib/jxl/enc_cache.h"
49
#include "lib/jxl/enc_chroma_from_luma.h"
50
#include "lib/jxl/enc_coeff_order.h"
51
#include "lib/jxl/enc_context_map.h"
52
#include "lib/jxl/enc_entropy_coder.h"
53
#include "lib/jxl/enc_external_image.h"
54
#include "lib/jxl/enc_fields.h"
55
#include "lib/jxl/enc_group.h"
56
#include "lib/jxl/enc_heuristics.h"
57
#include "lib/jxl/enc_modular.h"
58
#include "lib/jxl/enc_noise.h"
59
#include "lib/jxl/enc_params.h"
60
#include "lib/jxl/enc_patch_dictionary.h"
61
#include "lib/jxl/enc_photon_noise.h"
62
#include "lib/jxl/enc_progressive_split.h"
63
#include "lib/jxl/enc_quant_weights.h"
64
#include "lib/jxl/enc_splines.h"
65
#include "lib/jxl/enc_toc.h"
66
#include "lib/jxl/enc_xyb.h"
67
#include "lib/jxl/encode_internal.h"
68
#include "lib/jxl/fields.h"
69
#include "lib/jxl/frame_dimensions.h"
70
#include "lib/jxl/frame_header.h"
71
#include "lib/jxl/image.h"
72
#include "lib/jxl/image_bundle.h"
73
#include "lib/jxl/image_metadata.h"
74
#include "lib/jxl/image_ops.h"
75
#include "lib/jxl/jpeg/enc_jpeg_data.h"
76
#include "lib/jxl/jpeg/jpeg_data.h"
77
#include "lib/jxl/loop_filter.h"
78
#include "lib/jxl/modular/options.h"
79
#include "lib/jxl/noise.h"
80
#include "lib/jxl/padded_bytes.h"
81
#include "lib/jxl/passes_state.h"
82
#include "lib/jxl/quant_weights.h"
83
#include "lib/jxl/quantizer.h"
84
#include "lib/jxl/splines.h"
85
#include "lib/jxl/toc.h"
86
87
namespace jxl {
88
89
3.13k
Status ParamsPostInit(CompressParams* p) {
90
3.13k
  if (!p->manual_noise.empty() &&
91
3.13k
      p->manual_noise.size() != NoiseParams::kNumNoisePoints) {
92
0
    return JXL_FAILURE("Invalid number of noise lut entries");
93
0
  }
94
3.13k
  if (!p->manual_xyb_factors.empty() && p->manual_xyb_factors.size() != 3) {
95
0
    return JXL_FAILURE("Invalid number of XYB quantization factors");
96
0
  }
97
3.13k
  if (!p->modular_mode && p->butteraugli_distance < kMinButteraugliDistance) {
98
0
    p->butteraugli_distance = kMinButteraugliDistance;
99
0
  }
100
3.13k
  if (p->original_butteraugli_distance == -1.0) {
101
2.13k
    p->original_butteraugli_distance = p->butteraugli_distance;
102
2.13k
  }
103
3.13k
  if (p->resampling <= 0) {
104
2.13k
    p->resampling = 1;
105
    // For very low bit rates, using 2x2 resampling gives better results on
106
    // most photographic images, with an adjusted butteraugli score chosen to
107
    // give roughly the same amount of bits per pixel.
108
2.13k
    if (!p->already_downsampled && p->butteraugli_distance >= 10) {
109
      // TODO(Jonnyawsom3): Explore 4x4 resampling at distance 25. Lower bpp
110
      // but results are inconsistent and images under 4K become far too blurry.
111
0
      p->resampling = 2;
112
      // Adding 0.25 balances photo with non-photo, shifting towards lower bpp
113
      // to avoid large overshoot while maintaining quality equal to before.
114
0
      p->butteraugli_distance = (p->butteraugli_distance * 0.25) + 0.25;
115
0
    }
116
2.13k
  }
117
3.13k
  if (p->ec_resampling <= 0) {
118
2.13k
    p->ec_resampling = p->resampling;
119
2.13k
  }
120
3.13k
  return true;
121
3.13k
}
122
123
namespace {
124
125
template <typename T>
126
uint32_t GetBitDepth(JxlBitDepth bit_depth, const T& metadata,
127
3.13k
                     JxlPixelFormat format) {
128
3.13k
  if (bit_depth.type == JXL_BIT_DEPTH_FROM_PIXEL_FORMAT) {
129
3.13k
    return BitsPerChannel(format.data_type);
130
3.13k
  } else if (bit_depth.type == JXL_BIT_DEPTH_FROM_CODESTREAM) {
131
0
    return metadata.bit_depth.bits_per_sample;
132
0
  } else if (bit_depth.type == JXL_BIT_DEPTH_CUSTOM) {
133
0
    return bit_depth.bits_per_sample;
134
0
  } else {
135
0
    return 0;
136
0
  }
137
3.13k
}
enc_frame.cc:unsigned int jxl::(anonymous namespace)::GetBitDepth<jxl::ImageMetadata>(JxlBitDepth, jxl::ImageMetadata const&, JxlPixelFormat)
Line
Count
Source
127
3.13k
                     JxlPixelFormat format) {
128
3.13k
  if (bit_depth.type == JXL_BIT_DEPTH_FROM_PIXEL_FORMAT) {
129
3.13k
    return BitsPerChannel(format.data_type);
130
3.13k
  } else if (bit_depth.type == JXL_BIT_DEPTH_FROM_CODESTREAM) {
131
0
    return metadata.bit_depth.bits_per_sample;
132
0
  } else if (bit_depth.type == JXL_BIT_DEPTH_CUSTOM) {
133
0
    return bit_depth.bits_per_sample;
134
0
  } else {
135
0
    return 0;
136
0
  }
137
3.13k
}
Unexecuted instantiation: enc_frame.cc:unsigned int jxl::(anonymous namespace)::GetBitDepth<jxl::ExtraChannelInfo>(JxlBitDepth, jxl::ExtraChannelInfo const&, JxlPixelFormat)
138
139
Status CopyColorChannels(JxlChunkedFrameInputSource input, Rect rect,
140
                         const FrameInfo& frame_info,
141
                         const ImageMetadata& metadata, ThreadPool* pool,
142
                         Image3F* color, ImageF* alpha,
143
3.13k
                         bool* has_interleaved_alpha) {
144
3.13k
  JxlPixelFormat format = {4, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
145
3.13k
  input.get_color_channels_pixel_format(input.opaque, &format);
146
3.13k
  *has_interleaved_alpha = format.num_channels == 2 || format.num_channels == 4;
147
3.13k
  size_t bits_per_sample =
148
3.13k
      GetBitDepth(frame_info.image_bit_depth, metadata, format);
149
3.13k
  size_t row_offset;
150
3.13k
  auto buffer = GetColorBuffer(input, rect.x0(), rect.y0(), rect.xsize(),
151
3.13k
                               rect.ysize(), &row_offset);
152
3.13k
  if (!buffer) {
153
0
    return JXL_FAILURE("no buffer for color channels given");
154
0
  }
155
3.13k
  size_t color_channels = frame_info.ib_needs_color_transform
156
3.13k
                              ? metadata.color_encoding.Channels()
157
3.13k
                              : 3;
158
3.13k
  if (format.num_channels < color_channels) {
159
0
    return JXL_FAILURE("Expected %" PRIuS
160
0
                       " color channels, received only %u channels",
161
0
                       color_channels, format.num_channels);
162
0
  }
163
3.13k
  const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.get());
164
12.4k
  for (size_t c = 0; c < color_channels; ++c) {
165
9.36k
    JXL_RETURN_IF_ERROR(ConvertFromExternalNoSizeCheck(
166
9.36k
        data, rect.xsize(), rect.ysize(), row_offset, bits_per_sample, format,
167
9.36k
        c, pool, &color->Plane(c)));
168
9.36k
  }
169
3.13k
  if (color_channels == 1) {
170
18
    JXL_RETURN_IF_ERROR(CopyImageTo(color->Plane(0), &color->Plane(1)));
171
18
    JXL_RETURN_IF_ERROR(CopyImageTo(color->Plane(0), &color->Plane(2)));
172
18
  }
173
3.13k
  if (alpha) {
174
0
    if (*has_interleaved_alpha) {
175
0
      JXL_RETURN_IF_ERROR(ConvertFromExternalNoSizeCheck(
176
0
          data, rect.xsize(), rect.ysize(), row_offset, bits_per_sample, format,
177
0
          format.num_channels - 1, pool, alpha));
178
0
    } else {
179
      // if alpha is not passed, but it is expected, then assume
180
      // it is all-opaque
181
0
      FillImage(1.0f, alpha);
182
0
    }
183
0
  }
184
3.13k
  return true;
185
3.13k
}
186
187
Status CopyExtraChannels(JxlChunkedFrameInputSource input, Rect rect,
188
                         const FrameInfo& frame_info,
189
                         const ImageMetadata& metadata,
190
                         bool has_interleaved_alpha, ThreadPool* pool,
191
3.13k
                         std::vector<ImageF>* extra_channels) {
192
3.13k
  for (size_t ec = 0; ec < metadata.num_extra_channels; ec++) {
193
0
    if (has_interleaved_alpha &&
194
0
        metadata.extra_channel_info[ec].type == ExtraChannel::kAlpha) {
195
      // Skip this alpha channel, but still request additional alpha channels
196
      // if they exist.
197
0
      has_interleaved_alpha = false;
198
0
      continue;
199
0
    }
200
0
    JxlPixelFormat ec_format = {1, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
201
0
    input.get_extra_channel_pixel_format(input.opaque, ec, &ec_format);
202
0
    ec_format.num_channels = 1;
203
0
    size_t row_offset;
204
0
    auto buffer =
205
0
        GetExtraChannelBuffer(input, ec, rect.x0(), rect.y0(), rect.xsize(),
206
0
                              rect.ysize(), &row_offset);
207
0
    if (!buffer) {
208
0
      return JXL_FAILURE("no buffer for extra channel given");
209
0
    }
210
0
    size_t bits_per_sample = GetBitDepth(
211
0
        frame_info.image_bit_depth, metadata.extra_channel_info[ec], ec_format);
212
0
    if (!ConvertFromExternalNoSizeCheck(
213
0
            reinterpret_cast<const uint8_t*>(buffer.get()), rect.xsize(),
214
0
            rect.ysize(), row_offset, bits_per_sample, ec_format, 0, pool,
215
0
            &(*extra_channels)[ec])) {
216
0
      return JXL_FAILURE("Failed to set buffer for extra channel");
217
0
    }
218
0
  }
219
3.13k
  return true;
220
3.13k
}
221
222
void SetProgressiveMode(const CompressParams& cparams,
223
3.13k
                        ProgressiveSplitter* progressive_splitter) {
224
3.13k
  constexpr PassDefinition progressive_passes_dc_vlf_lf_full_ac[] = {
225
3.13k
      {/*num_coefficients=*/2, /*shift=*/0,
226
3.13k
       /*suitable_for_downsampling_of_at_least=*/4},
227
3.13k
      {/*num_coefficients=*/3, /*shift=*/0,
228
3.13k
       /*suitable_for_downsampling_of_at_least=*/2},
229
3.13k
      {/*num_coefficients=*/8, /*shift=*/0,
230
3.13k
       /*suitable_for_downsampling_of_at_least=*/0},
231
3.13k
  };
232
3.13k
  constexpr PassDefinition progressive_passes_dc_quant_ac_full_ac[] = {
233
3.13k
      {/*num_coefficients=*/8, /*shift=*/1,
234
3.13k
       /*suitable_for_downsampling_of_at_least=*/2},
235
3.13k
      {/*num_coefficients=*/8, /*shift=*/0,
236
3.13k
       /*suitable_for_downsampling_of_at_least=*/0},
237
3.13k
  };
238
3.13k
  bool progressive_mode = ApplyOverride(cparams.progressive_mode, false);
239
3.13k
  bool qprogressive_mode = ApplyOverride(cparams.qprogressive_mode, false);
240
3.13k
  if (cparams.custom_progressive_mode) {
241
0
    progressive_splitter->SetProgressiveMode(*cparams.custom_progressive_mode);
242
3.13k
  } else if (qprogressive_mode) {
243
0
    progressive_splitter->SetProgressiveMode(
244
0
        ProgressiveMode{progressive_passes_dc_quant_ac_full_ac});
245
3.13k
  } else if (progressive_mode) {
246
0
    progressive_splitter->SetProgressiveMode(
247
0
        ProgressiveMode{progressive_passes_dc_vlf_lf_full_ac});
248
0
  }
249
3.13k
}
250
251
3.13k
uint64_t FrameFlagsFromParams(const CompressParams& cparams) {
252
3.13k
  uint64_t flags = 0;
253
254
3.13k
  const float dist = cparams.butteraugli_distance;
255
256
  // We don't add noise at low butteraugli distances because the original
257
  // noise is stored within the compressed image and adding noise makes things
258
  // worse.
259
3.13k
  if (ApplyOverride(cparams.noise, dist >= kMinButteraugliForNoise) ||
260
3.13k
      cparams.photon_noise_iso > 0 ||
261
3.13k
      cparams.manual_noise.size() == NoiseParams::kNumNoisePoints) {
262
0
    flags |= FrameHeader::kNoise;
263
0
  }
264
265
3.13k
  if (cparams.progressive_dc > 0 && cparams.modular_mode == false) {
266
0
    flags |= FrameHeader::kUseDcFrame;
267
0
  }
268
269
3.13k
  return flags;
270
3.13k
}
271
272
Status LoopFilterFromParams(const CompressParams& cparams, bool streaming_mode,
273
3.13k
                            FrameHeader* JXL_RESTRICT frame_header) {
274
3.13k
  LoopFilter* loop_filter = &frame_header->loop_filter;
275
276
  // Gaborish defaults to enabled in Hare or slower.
277
3.13k
  loop_filter->gab = ApplyOverride(
278
3.13k
      cparams.gaborish, cparams.speed_tier <= SpeedTier::kHare &&
279
3.13k
                            frame_header->encoding == FrameEncoding::kVarDCT &&
280
3.13k
                            cparams.decoding_speed_tier < 4 &&
281
3.13k
                            cparams.butteraugli_distance > 0.5f &&
282
3.13k
                            !cparams.disable_perceptual_optimizations);
283
284
3.13k
  if (cparams.epf != -1) {
285
0
    loop_filter->epf_iters = cparams.epf;
286
3.13k
  } else if (cparams.disable_perceptual_optimizations) {
287
0
    loop_filter->epf_iters = 0;
288
0
    return true;
289
3.13k
  } else {
290
3.13k
    if (frame_header->encoding == FrameEncoding::kModular) {
291
1.00k
      loop_filter->epf_iters = 0;
292
2.13k
    } else {
293
2.13k
      constexpr float kThresholds[3] = {0.7, 1.5, 4.0};
294
2.13k
      loop_filter->epf_iters = 0;
295
2.13k
      if (cparams.decoding_speed_tier < 3) {
296
8.52k
        for (size_t i = cparams.decoding_speed_tier == 2 ? 1 : 0; i < 3; i++) {
297
6.39k
          if (cparams.butteraugli_distance >= kThresholds[i]) {
298
4.26k
            loop_filter->epf_iters++;
299
4.26k
          }
300
6.39k
        }
301
2.13k
      }
302
2.13k
    }
303
3.13k
  }
304
  // Strength of EPF in modular mode.
305
3.13k
  if (frame_header->encoding == FrameEncoding::kModular &&
306
3.13k
      !cparams.IsLossless()) {
307
    // TODO(veluca): this formula is nonsense.
308
1.00k
    loop_filter->epf_sigma_for_modular =
309
1.00k
        std::max(cparams.butteraugli_distance, 1.0f);
310
1.00k
  }
311
3.13k
  if (frame_header->encoding == FrameEncoding::kModular &&
312
3.13k
      cparams.lossy_palette) {
313
0
    loop_filter->epf_sigma_for_modular = 1.0f;
314
0
  }
315
316
3.13k
  return true;
317
3.13k
}
318
319
Status MakeFrameHeader(size_t xsize, size_t ysize,
320
                       const CompressParams& cparams,
321
                       const ProgressiveSplitter& progressive_splitter,
322
                       const FrameInfo& frame_info,
323
                       const jpeg::JPEGData* jpeg_data, bool streaming_mode,
324
3.13k
                       FrameHeader* JXL_RESTRICT frame_header) {
325
3.13k
  frame_header->nonserialized_is_preview = frame_info.is_preview;
326
3.13k
  frame_header->is_last = frame_info.is_last;
327
3.13k
  frame_header->save_before_color_transform =
328
3.13k
      frame_info.save_before_color_transform;
329
3.13k
  frame_header->frame_type = frame_info.frame_type;
330
3.13k
  frame_header->name = frame_info.name;
331
332
3.13k
  JXL_RETURN_IF_ERROR(progressive_splitter.InitPasses(&frame_header->passes));
333
334
3.13k
  if (cparams.modular_mode) {
335
1.00k
    frame_header->encoding = FrameEncoding::kModular;
336
1.00k
    if (cparams.modular_group_size_shift == -1) {
337
      // By default, use the smallest group size for faster decoding 2
338
      // and higher. Greatly speeds up decoding via multithreading at
339
      // the cost of density.
340
1.00k
      if (cparams.decoding_speed_tier >= 2 ||
341
        // Force decoding speed to tier 2 for progressive lossless.
342
1.00k
        (cparams.decoding_speed_tier >= 1 && cparams.responsive == 1
343
1.00k
        && cparams.IsLossless())) {
344
0
        frame_header->group_size_shift = 0;
345
      // no point using groups when only one group is full and the others are
346
      // less than half full: multithreading will not really help much, while
347
      // compression does suffer; but no reason to have group larger than image.
348
1.00k
      } else if (xsize <= 128 && ysize <= 128) {
349
848
        frame_header->group_size_shift = 0;
350
848
      } else if (xsize <= 256 && ysize <= 256) {
351
153
        frame_header->group_size_shift = 1;
352
153
      } else if (xsize <= 400 && ysize <= 400) {
353
0
        frame_header->group_size_shift = 2;
354
0
      } else {
355
0
        frame_header->group_size_shift = 1;
356
0
      }
357
1.00k
    } else {
358
0
      frame_header->group_size_shift = cparams.modular_group_size_shift;
359
0
    }
360
1.00k
  }
361
362
3.13k
  if (jpeg_data) {
363
    // we are transcoding a JPEG, so we don't get to choose
364
0
    frame_header->encoding = FrameEncoding::kVarDCT;
365
0
    frame_header->x_qm_scale = 2;
366
0
    frame_header->b_qm_scale = 2;
367
0
    JXL_RETURN_IF_ERROR(SetChromaSubsamplingFromJpegData(
368
0
        *jpeg_data, &frame_header->chroma_subsampling));
369
0
    JXL_RETURN_IF_ERROR(SetColorTransformFromJpegData(
370
0
        *jpeg_data, &frame_header->color_transform));
371
3.13k
  } else {
372
3.13k
    frame_header->color_transform = cparams.color_transform;
373
3.13k
    if (!cparams.modular_mode &&
374
3.13k
        (frame_header->chroma_subsampling.MaxHShift() != 0 ||
375
2.13k
         frame_header->chroma_subsampling.MaxVShift() != 0)) {
376
0
      return JXL_FAILURE(
377
0
          "Chroma subsampling is not supported in VarDCT mode when not "
378
0
          "recompressing JPEGs");
379
0
    }
380
3.13k
  }
381
3.13k
  if (frame_header->color_transform != ColorTransform::kYCbCr &&
382
3.13k
      (frame_header->chroma_subsampling.MaxHShift() != 0 ||
383
3.13k
       frame_header->chroma_subsampling.MaxVShift() != 0)) {
384
0
    return JXL_FAILURE(
385
0
        "Chroma subsampling is not supported when color transform is not "
386
0
        "YCbCr");
387
0
  }
388
389
3.13k
  frame_header->flags = FrameFlagsFromParams(cparams);
390
  // Non-photon noise is not supported in the Modular encoder for now.
391
3.13k
  if (frame_header->encoding != FrameEncoding::kVarDCT &&
392
3.13k
      cparams.photon_noise_iso == 0 && cparams.manual_noise.empty()) {
393
1.00k
    frame_header->UpdateFlag(false, FrameHeader::Flags::kNoise);
394
1.00k
  }
395
396
3.13k
  JXL_RETURN_IF_ERROR(
397
3.13k
      LoopFilterFromParams(cparams, streaming_mode, frame_header));
398
399
3.13k
  frame_header->dc_level = frame_info.dc_level;
400
3.13k
  if (frame_header->dc_level > 2) {
401
    // With 3 or more progressive_dc frames, the implementation does not yet
402
    // work, see enc_cache.cc.
403
0
    return JXL_FAILURE("progressive_dc > 2 is not yet supported");
404
0
  }
405
3.13k
  if (cparams.progressive_dc > 0 &&
406
3.13k
      (cparams.ec_resampling != 1 || cparams.resampling != 1)) {
407
0
    return JXL_FAILURE("Resampling not supported with DC frames");
408
0
  }
409
3.13k
  if (cparams.resampling != 1 && cparams.resampling != 2 &&
410
3.13k
      cparams.resampling != 4 && cparams.resampling != 8) {
411
0
    return JXL_FAILURE("Invalid resampling factor");
412
0
  }
413
3.13k
  if (cparams.ec_resampling != 1 && cparams.ec_resampling != 2 &&
414
3.13k
      cparams.ec_resampling != 4 && cparams.ec_resampling != 8) {
415
0
    return JXL_FAILURE("Invalid ec_resampling factor");
416
0
  }
417
  // Resized frames.
418
3.13k
  if (frame_info.frame_type != FrameType::kDCFrame) {
419
3.13k
    frame_header->frame_origin = frame_info.origin;
420
3.13k
    size_t ups = 1;
421
3.13k
    if (cparams.already_downsampled) ups = cparams.resampling;
422
423
    // TODO(lode): this is not correct in case of odd original image sizes in
424
    // combination with cparams.already_downsampled. Likely these values should
425
    // be set to respectively frame_header->default_xsize() and
426
    // frame_header->default_ysize() instead, the original (non downsampled)
427
    // intended decoded image dimensions. But it may be more subtle than that
428
    // if combined with crop. This issue causes custom_size_or_origin to be
429
    // incorrectly set to true in case of already_downsampled with odd output
430
    // image size when no cropping is used.
431
3.13k
    frame_header->frame_size.xsize = xsize * ups;
432
3.13k
    frame_header->frame_size.ysize = ysize * ups;
433
3.13k
    if (frame_info.origin.x0 != 0 || frame_info.origin.y0 != 0 ||
434
3.13k
        frame_header->frame_size.xsize != frame_header->default_xsize() ||
435
3.13k
        frame_header->frame_size.ysize != frame_header->default_ysize()) {
436
1.00k
      frame_header->custom_size_or_origin = true;
437
1.00k
    }
438
3.13k
  }
439
  // Upsampling.
440
3.13k
  frame_header->upsampling = cparams.resampling;
441
3.13k
  const std::vector<ExtraChannelInfo>& extra_channels =
442
3.13k
      frame_header->nonserialized_metadata->m.extra_channel_info;
443
3.13k
  frame_header->extra_channel_upsampling.clear();
444
3.13k
  frame_header->extra_channel_upsampling.resize(extra_channels.size(),
445
3.13k
                                                cparams.ec_resampling);
446
3.13k
  frame_header->save_as_reference = frame_info.save_as_reference;
447
448
  // Set blending-related information.
449
3.13k
  if (frame_info.blend || frame_header->custom_size_or_origin) {
450
    // Set blend_channel to the first alpha channel. These values are only
451
    // encoded in case a blend mode involving alpha is used and there are more
452
    // than one extra channels.
453
1.00k
    size_t index = 0;
454
1.00k
    if (frame_info.alpha_channel == -1) {
455
1.00k
      if (extra_channels.size() > 1) {
456
0
        for (size_t i = 0; i < extra_channels.size(); i++) {
457
0
          if (extra_channels[i].type == ExtraChannel::kAlpha) {
458
0
            index = i;
459
0
            break;
460
0
          }
461
0
        }
462
0
      }
463
1.00k
    } else {
464
0
      index = static_cast<size_t>(frame_info.alpha_channel);
465
0
      JXL_ENSURE(index == 0 || index < extra_channels.size());
466
0
    }
467
1.00k
    frame_header->blending_info.alpha_channel = index;
468
1.00k
    frame_header->blending_info.mode =
469
1.00k
        frame_info.blend ? frame_info.blendmode : BlendMode::kReplace;
470
1.00k
    frame_header->blending_info.source = frame_info.source;
471
1.00k
    frame_header->blending_info.clamp = frame_info.clamp;
472
1.00k
    const auto& extra_channel_info = frame_info.extra_channel_blending_info;
473
1.00k
    for (size_t i = 0; i < extra_channels.size(); i++) {
474
0
      if (i < extra_channel_info.size()) {
475
0
        frame_header->extra_channel_blending_info[i] = extra_channel_info[i];
476
0
      } else {
477
0
        frame_header->extra_channel_blending_info[i].alpha_channel = index;
478
0
        BlendMode default_blend = frame_info.blendmode;
479
0
        if (extra_channels[i].type != ExtraChannel::kBlack && i != index) {
480
          // K needs to be blended, spot colors and other stuff gets added
481
0
          default_blend = BlendMode::kAdd;
482
0
        }
483
0
        frame_header->extra_channel_blending_info[i].mode =
484
0
            frame_info.blend ? default_blend : BlendMode::kReplace;
485
0
        frame_header->extra_channel_blending_info[i].source = 1;
486
0
      }
487
0
    }
488
1.00k
  }
489
490
3.13k
  frame_header->animation_frame.duration = frame_info.duration;
491
3.13k
  frame_header->animation_frame.timecode = frame_info.timecode;
492
493
3.13k
  if (jpeg_data) {
494
0
    frame_header->UpdateFlag(false, FrameHeader::kUseDcFrame);
495
0
    frame_header->UpdateFlag(true, FrameHeader::kSkipAdaptiveDCSmoothing);
496
0
  }
497
498
3.13k
  return true;
499
3.13k
}
500
501
// Invisible (alpha = 0) pixels tend to be a mess in optimized PNGs.
502
// Since they have no visual impact whatsoever, we can replace them with
503
// something that compresses better and reduces artifacts near the edges. This
504
// does some kind of smooth stuff that seems to work.
505
// Replace invisible pixels with a weighted average of the pixel to the left,
506
// the pixel to the topright, and non-invisible neighbours.
507
// Produces downward-blurry smears, with in the upwards direction only a 1px
508
// edge duplication but not more. It would probably be better to smear in all
509
// directions. That requires an alpha-weighed convolution with a large enough
510
// kernel though, which might be overkill...
511
0
void SimplifyInvisible(Image3F* image, const ImageF& alpha, bool lossless) {
512
0
  for (size_t c = 0; c < 3; ++c) {
513
0
    for (size_t y = 0; y < image->ysize(); ++y) {
514
0
      float* JXL_RESTRICT row = image->PlaneRow(c, y);
515
0
      const float* JXL_RESTRICT prow =
516
0
          (y > 0 ? image->PlaneRow(c, y - 1) : nullptr);
517
0
      const float* JXL_RESTRICT nrow =
518
0
          (y + 1 < image->ysize() ? image->PlaneRow(c, y + 1) : nullptr);
519
0
      const float* JXL_RESTRICT a = alpha.Row(y);
520
0
      const float* JXL_RESTRICT pa = (y > 0 ? alpha.Row(y - 1) : nullptr);
521
0
      const float* JXL_RESTRICT na =
522
0
          (y + 1 < image->ysize() ? alpha.Row(y + 1) : nullptr);
523
0
      for (size_t x = 0; x < image->xsize(); ++x) {
524
0
        if (a[x] == 0) {
525
0
          if (lossless) {
526
0
            row[x] = 0;
527
0
            continue;
528
0
          }
529
0
          float d = 0.f;
530
0
          row[x] = 0;
531
0
          if (x > 0) {
532
0
            row[x] += row[x - 1];
533
0
            d++;
534
0
            if (a[x - 1] > 0.f) {
535
0
              row[x] += row[x - 1];
536
0
              d++;
537
0
            }
538
0
          }
539
0
          if (x + 1 < image->xsize()) {
540
0
            if (y > 0) {
541
0
              row[x] += prow[x + 1];
542
0
              d++;
543
0
            }
544
0
            if (a[x + 1] > 0.f) {
545
0
              row[x] += 2.f * row[x + 1];
546
0
              d += 2.f;
547
0
            }
548
0
            if (y > 0 && pa[x + 1] > 0.f) {
549
0
              row[x] += 2.f * prow[x + 1];
550
0
              d += 2.f;
551
0
            }
552
0
            if (y + 1 < image->ysize() && na[x + 1] > 0.f) {
553
0
              row[x] += 2.f * nrow[x + 1];
554
0
              d += 2.f;
555
0
            }
556
0
          }
557
0
          if (y > 0 && pa[x] > 0.f) {
558
0
            row[x] += 2.f * prow[x];
559
0
            d += 2.f;
560
0
          }
561
0
          if (y + 1 < image->ysize() && na[x] > 0.f) {
562
0
            row[x] += 2.f * nrow[x];
563
0
            d += 2.f;
564
0
          }
565
0
          if (d > 1.f) row[x] /= d;
566
0
        }
567
0
      }
568
0
    }
569
0
  }
570
0
}
571
572
struct PixelStatsForChromacityAdjustment {
573
  float dx = 0;
574
  float db = 0;
575
  float exposed_blue = 0;
576
2.13k
  static float CalcPlane(const ImageF* JXL_RESTRICT plane, const Rect& rect) {
577
2.13k
    float xmax = 0;
578
2.13k
    float ymax = 0;
579
509k
    for (size_t ty = 1; ty < rect.ysize(); ++ty) {
580
185M
      for (size_t tx = 1; tx < rect.xsize(); ++tx) {
581
184M
        float cur = rect.Row(plane, ty)[tx];
582
184M
        float prev_row = rect.Row(plane, ty - 1)[tx];
583
184M
        float prev = rect.Row(plane, ty)[tx - 1];
584
184M
        xmax = std::max(xmax, std::abs(cur - prev));
585
184M
        ymax = std::max(ymax, std::abs(cur - prev_row));
586
184M
      }
587
507k
    }
588
2.13k
    return std::max(xmax, ymax);
589
2.13k
  }
590
  void CalcExposedBlue(const ImageF* JXL_RESTRICT plane_y,
591
2.13k
                       const ImageF* JXL_RESTRICT plane_b, const Rect& rect) {
592
2.13k
    float eb = 0;
593
2.13k
    float xmax = 0;
594
2.13k
    float ymax = 0;
595
509k
    for (size_t ty = 1; ty < rect.ysize(); ++ty) {
596
185M
      for (size_t tx = 1; tx < rect.xsize(); ++tx) {
597
184M
        float cur_y = rect.Row(plane_y, ty)[tx];
598
184M
        float cur_b = rect.Row(plane_b, ty)[tx];
599
184M
        float exposed_b = cur_b - cur_y * 1.2;
600
184M
        float diff_b = cur_b - cur_y;
601
184M
        float prev_row = rect.Row(plane_b, ty - 1)[tx];
602
184M
        float prev = rect.Row(plane_b, ty)[tx - 1];
603
184M
        float diff_prev_row = prev_row - rect.Row(plane_y, ty - 1)[tx];
604
184M
        float diff_prev = prev - rect.Row(plane_y, ty)[tx - 1];
605
184M
        xmax = std::max(xmax, std::abs(diff_b - diff_prev));
606
184M
        ymax = std::max(ymax, std::abs(diff_b - diff_prev_row));
607
184M
        if (exposed_b >= 0) {
608
26.8M
          exposed_b *= std::abs(cur_b - prev) + std::abs(cur_b - prev_row);
609
26.8M
          eb = std::max(eb, exposed_b);
610
26.8M
        }
611
184M
      }
612
507k
    }
613
2.13k
    exposed_blue = eb;
614
2.13k
    db = std::max(xmax, ymax);
615
2.13k
  }
616
2.13k
  void Calc(const Image3F* JXL_RESTRICT opsin, const Rect& rect) {
617
2.13k
    dx = CalcPlane(&opsin->Plane(0), rect);
618
2.13k
    CalcExposedBlue(&opsin->Plane(1), &opsin->Plane(2), rect);
619
2.13k
  }
620
2.13k
  int HowMuchIsXChannelPixelized() const {
621
2.13k
    if (dx >= 0.026) {
622
858
      return 3;
623
858
    }
624
1.27k
    if (dx >= 0.022) {
625
108
      return 2;
626
108
    }
627
1.16k
    if (dx >= 0.015) {
628
286
      return 1;
629
286
    }
630
879
    return 0;
631
1.16k
  }
632
2.13k
  int HowMuchIsBChannelPixelized() const {
633
2.13k
    int add = exposed_blue >= 0.13 ? 1 : 0;
634
2.13k
    if (db > 0.38) {
635
946
      return 2 + add;
636
946
    }
637
1.18k
    if (db > 0.33) {
638
41
      return 1 + add;
639
41
    }
640
1.14k
    if (db > 0.28) {
641
58
      return add;
642
58
    }
643
1.08k
    return 0;
644
1.14k
  }
645
};
646
647
void ComputeChromacityAdjustments(const CompressParams& cparams,
648
                                  const Image3F& opsin, const Rect& rect,
649
3.13k
                                  FrameHeader* frame_header) {
650
3.13k
  if (frame_header->encoding != FrameEncoding::kVarDCT ||
651
3.13k
      cparams.max_error_mode) {
652
1.00k
    return;
653
1.00k
  }
654
  // 1) Distance based approach for chromacity adjustment:
655
2.13k
  float x_qm_scale_steps[3] = {2.5f, 5.5f, 9.5f};
656
2.13k
  frame_header->x_qm_scale = 3;
657
6.39k
  for (float x_qm_scale_step : x_qm_scale_steps) {
658
6.39k
    if (cparams.original_butteraugli_distance > x_qm_scale_step) {
659
0
      frame_header->x_qm_scale++;
660
0
    }
661
6.39k
  }
662
  // 2) Pixel-based approach for chromacity adjustment:
663
  // look at the individual pixels and make a guess how difficult
664
  // the image would be based on the worst case pixel.
665
2.13k
  PixelStatsForChromacityAdjustment pixel_stats;
666
2.13k
  if (cparams.speed_tier <= SpeedTier::kSquirrel) {
667
2.13k
    pixel_stats.Calc(&opsin, rect);
668
2.13k
  }
669
  // For X take the most severe adjustment.
670
2.13k
  frame_header->x_qm_scale = std::max<int>(
671
2.13k
      frame_header->x_qm_scale, 2 + pixel_stats.HowMuchIsXChannelPixelized());
672
  // B only adjusted by pixel-based approach.
673
2.13k
  frame_header->b_qm_scale = 2 + pixel_stats.HowMuchIsBChannelPixelized();
674
2.13k
}
675
676
void ComputeNoiseParams(const CompressParams& cparams, bool streaming_mode,
677
                        bool color_is_jpeg, const Image3F& opsin,
678
                        const FrameDimensions& frame_dim,
679
3.13k
                        FrameHeader* frame_header, NoiseParams* noise_params) {
680
3.13k
  if (cparams.photon_noise_iso > 0) {
681
0
    *noise_params = SimulatePhotonNoise(frame_dim.xsize, frame_dim.ysize,
682
0
                                        cparams.photon_noise_iso);
683
3.13k
  } else if (cparams.manual_noise.size() == NoiseParams::kNumNoisePoints) {
684
0
    for (size_t i = 0; i < NoiseParams::kNumNoisePoints; i++) {
685
0
      noise_params->lut[i] = cparams.manual_noise[i];
686
0
    }
687
3.13k
  } else if (frame_header->encoding == FrameEncoding::kVarDCT &&
688
3.13k
             frame_header->flags & FrameHeader::kNoise && !color_is_jpeg &&
689
3.13k
             !streaming_mode) {
690
    // Don't start at zero amplitude since adding noise is expensive -- it
691
    // significantly slows down decoding, and this is unlikely to
692
    // completely go away even with advanced optimizations. After the
693
    // kNoiseModelingRampUpDistanceRange we have reached the full level,
694
    // i.e. noise is no longer represented by the compressed image, so we
695
    // can add full noise by the noise modeling itself.
696
0
    static const float kNoiseModelingRampUpDistanceRange = 0.6;
697
0
    static const float kNoiseLevelAtStartOfRampUp = 0.25;
698
0
    static const float kNoiseRampupStart = 1.0;
699
    // TODO(user) test and properly select quality_coef with smooth
700
    // filter
701
0
    float quality_coef = 1.0f;
702
0
    const float rampup = (cparams.butteraugli_distance - kNoiseRampupStart) /
703
0
                         kNoiseModelingRampUpDistanceRange;
704
0
    if (rampup < 1.0f) {
705
0
      quality_coef = kNoiseLevelAtStartOfRampUp +
706
0
                     (1.0f - kNoiseLevelAtStartOfRampUp) * rampup;
707
0
    }
708
0
    if (rampup < 0.0f) {
709
0
      quality_coef = kNoiseRampupStart;
710
0
    }
711
0
    if (!GetNoiseParameter(opsin, noise_params, quality_coef)) {
712
0
      frame_header->flags &= ~FrameHeader::kNoise;
713
0
    }
714
0
  }
715
3.13k
}
716
717
Status DownsampleColorChannels(const CompressParams& cparams,
718
                               const FrameHeader& frame_header,
719
3.13k
                               bool color_is_jpeg, Image3F* opsin) {
720
3.13k
  if (color_is_jpeg || frame_header.upsampling == 1 ||
721
3.13k
      cparams.already_downsampled) {
722
3.13k
    return true;
723
3.13k
  }
724
0
  if (frame_header.encoding == FrameEncoding::kVarDCT &&
725
0
      frame_header.upsampling == 2) {
726
    // TODO(lode): use the regular DownsampleImage, or adapt to the custom
727
    // coefficients, if there is are custom upscaling coefficients in
728
    // CustomTransformData
729
0
    if (cparams.speed_tier <= SpeedTier::kGlacier) {
730
      // TODO(Jonnyawsom3): Until optimized, enabled only for Glacier and
731
      // TectonicPlate. It's an 80% slowdown and downsampling is only active
732
      // at high distances by default anyway, making improvements negligible.
733
0
      JXL_RETURN_IF_ERROR(DownsampleImage2_Iterative(opsin));
734
0
    } else {
735
0
      JXL_RETURN_IF_ERROR(DownsampleImage2_Sharper(opsin));
736
0
    }
737
0
  } else {
738
0
    JXL_ASSIGN_OR_RETURN(*opsin,
739
0
                         DownsampleImage(*opsin, frame_header.upsampling));
740
0
  }
741
0
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
742
0
    JXL_RETURN_IF_ERROR(PadImageToBlockMultipleInPlace(opsin));
743
0
  }
744
0
  return true;
745
0
}
746
747
template <size_t L, typename V, typename R>
748
0
void FindIndexOfSumMaximum(const V* array, R* idx, V* sum) {
749
0
  static_assert(L > 0, "Empty arrays have undefined maximum");
750
0
  V maxval = 0;
751
0
  V val = 0;
752
0
  R maxidx = 0;
753
0
  for (size_t i = 0; i < L; ++i) {
754
0
    val += array[i];
755
0
    if (val > maxval) {
756
0
      maxval = val;
757
0
      maxidx = i;
758
0
    }
759
0
  }
760
0
  *idx = maxidx;
761
0
  *sum = maxval;
762
0
}
763
764
Status ComputeJPEGTranscodingData(const jpeg::JPEGData& jpeg_data,
765
                                  const FrameHeader& frame_header,
766
                                  ThreadPool* pool,
767
                                  ModularFrameEncoder* enc_modular,
768
0
                                  PassesEncoderState* enc_state) {
769
0
  PassesSharedState& shared = enc_state->shared;
770
0
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
771
0
  const FrameDimensions& frame_dim = shared.frame_dim;
772
773
0
  const size_t xsize = frame_dim.xsize_padded;
774
0
  const size_t ysize = frame_dim.ysize_padded;
775
0
  const size_t xsize_blocks = frame_dim.xsize_blocks;
776
0
  const size_t ysize_blocks = frame_dim.ysize_blocks;
777
778
  // no-op chroma from luma
779
0
  JXL_ASSIGN_OR_RETURN(shared.cmap, ColorCorrelationMap::Create(
780
0
                                        memory_manager, xsize, ysize, false));
781
0
  shared.ac_strategy.FillDCT8();
782
0
  FillImage(static_cast<uint8_t>(0), &shared.epf_sharpness);
783
784
0
  enc_state->coeffs.clear();
785
0
  while (enc_state->coeffs.size() < enc_state->passes.size()) {
786
0
    JXL_ASSIGN_OR_RETURN(
787
0
        std::unique_ptr<ACImageT<int32_t>> coeffs,
788
0
        ACImageT<int32_t>::Make(memory_manager, kGroupDim * kGroupDim,
789
0
                                frame_dim.num_groups));
790
0
    enc_state->coeffs.emplace_back(std::move(coeffs));
791
0
  }
792
793
  // convert JPEG quantization table to a Quantizer object
794
0
  float dcquantization[3];
795
0
  std::vector<QuantEncoding> qe(kNumQuantTables, QuantEncoding::Library<0>());
796
797
0
  auto jpeg_c_map =
798
0
      JpegOrder(frame_header.color_transform, jpeg_data.components.size() == 1);
799
800
0
  std::vector<int> qt(192);
801
0
  std::array<int32_t, 3> qt_dc;
802
0
  for (size_t c = 0; c < 3; c++) {
803
0
    size_t jpeg_c = jpeg_c_map[c];
804
0
    const int32_t* quant =
805
0
        jpeg_data.quant[jpeg_data.components[jpeg_c].quant_idx].values.data();
806
807
0
    dcquantization[c] = 255 * 8.0f / quant[0];
808
0
    for (size_t y = 0; y < 8; y++) {
809
0
      for (size_t x = 0; x < 8; x++) {
810
        // JPEG XL transposes the DCT, JPEG doesn't.
811
0
        qt[c * 64 + 8 * x + y] = quant[8 * y + x];
812
0
      }
813
0
    }
814
0
    qt_dc[c] = qt[c * 64];
815
0
  }
816
0
  JXL_RETURN_IF_ERROR(DequantMatricesSetCustomDC(
817
0
      memory_manager, &shared.matrices, dcquantization));
818
0
  float dcquantization_r[3] = {1.0f / dcquantization[0],
819
0
                               1.0f / dcquantization[1],
820
0
                               1.0f / dcquantization[2]};
821
822
0
  std::vector<int32_t> scaled_qtable(192);
823
0
  for (size_t c = 0; c < 3; c++) {
824
0
    for (size_t i = 0; i < 64; i++) {
825
0
      scaled_qtable[64 * c + i] =
826
0
          (1 << kCFLFixedPointPrecision) * qt[64 + i] / qt[64 * c + i];
827
0
    }
828
0
  }
829
830
0
  qe[static_cast<size_t>(AcStrategyType::DCT)] =
831
0
      QuantEncoding::RAW(std::move(qt));
832
0
  JXL_RETURN_IF_ERROR(
833
0
      DequantMatricesSetCustom(&shared.matrices, qe, enc_modular));
834
835
  // Ensure that InvGlobalScale() is 1.
836
0
  shared.quantizer = Quantizer(shared.matrices, 1, kGlobalScaleDenom);
837
  // Recompute MulDC() and InvMulDC().
838
0
  shared.quantizer.RecomputeFromGlobalScale();
839
840
  // Per-block dequant scaling should be 1.
841
0
  FillImage(static_cast<int32_t>(shared.quantizer.InvGlobalScale()),
842
0
            &shared.raw_quant_field);
843
844
0
  auto jpeg_row = [&](size_t c, size_t y) {
845
0
    return jpeg_data.components[jpeg_c_map[c]].coeffs.data() +
846
0
           jpeg_data.components[jpeg_c_map[c]].width_in_blocks * kDCTBlockSize *
847
0
               y;
848
0
  };
849
850
0
  bool DCzero = (frame_header.color_transform == ColorTransform::kYCbCr);
851
  // Compute chroma-from-luma for AC (doesn't seem to be useful for DC)
852
0
  if (frame_header.chroma_subsampling.Is444() &&
853
0
      enc_state->cparams.force_cfl_jpeg_recompression &&
854
0
      jpeg_data.components.size() == 3) {
855
0
    for (size_t c : {0, 2}) {
856
0
      ImageSB* map = (c == 0 ? &shared.cmap.ytox_map : &shared.cmap.ytob_map);
857
0
      const float kScale = kDefaultColorFactor;
858
0
      const int kOffset = 127;
859
0
      const float kBase = c == 0 ? shared.cmap.base().YtoXRatio(0)
860
0
                                 : shared.cmap.base().YtoBRatio(0);
861
0
      const float kZeroThresh =
862
0
          kScale * kZeroBiasDefault[c] *
863
0
          0.9999f;  // just epsilon less for better rounding
864
865
0
      auto process_row = [&](const uint32_t task,
866
0
                             const size_t thread) -> Status {
867
0
        size_t ty = task;
868
0
        int8_t* JXL_RESTRICT row_out = map->Row(ty);
869
0
        for (size_t tx = 0; tx < map->xsize(); ++tx) {
870
0
          const size_t y0 = ty * kColorTileDimInBlocks;
871
0
          const size_t x0 = tx * kColorTileDimInBlocks;
872
0
          const size_t y1 = std::min(frame_dim.ysize_blocks,
873
0
                                     (ty + 1) * kColorTileDimInBlocks);
874
0
          const size_t x1 = std::min(frame_dim.xsize_blocks,
875
0
                                     (tx + 1) * kColorTileDimInBlocks);
876
0
          int32_t d_num_zeros[257] = {0};
877
          // TODO(veluca): this needs SIMD + fixed point adaptation, and/or
878
          // conversion to the new CfL algorithm.
879
0
          for (size_t y = y0; y < y1; ++y) {
880
0
            const int16_t* JXL_RESTRICT row_m = jpeg_row(1, y);
881
0
            const int16_t* JXL_RESTRICT row_s = jpeg_row(c, y);
882
0
            for (size_t x = x0; x < x1; ++x) {
883
0
              for (size_t coeffpos = 1; coeffpos < kDCTBlockSize; coeffpos++) {
884
0
                const float scaled_m = row_m[x * kDCTBlockSize + coeffpos] *
885
0
                                       scaled_qtable[64 * c + coeffpos] *
886
0
                                       (1.0f / (1 << kCFLFixedPointPrecision));
887
0
                const float scaled_s =
888
0
                    kScale * row_s[x * kDCTBlockSize + coeffpos] +
889
0
                    (kOffset - kBase * kScale) * scaled_m;
890
0
                if (std::abs(scaled_m) > 1e-8f) {
891
0
                  float from;
892
0
                  float to;
893
0
                  if (scaled_m > 0) {
894
0
                    from = (scaled_s - kZeroThresh) / scaled_m;
895
0
                    to = (scaled_s + kZeroThresh) / scaled_m;
896
0
                  } else {
897
0
                    from = (scaled_s + kZeroThresh) / scaled_m;
898
0
                    to = (scaled_s - kZeroThresh) / scaled_m;
899
0
                  }
900
0
                  if (from < 0.0f) {
901
0
                    from = 0.0f;
902
0
                  }
903
0
                  if (to > 255.0f) {
904
0
                    to = 255.0f;
905
0
                  }
906
                  // Instead of clamping the both values
907
                  // we just check that range is sane.
908
0
                  if (from <= to) {
909
0
                    d_num_zeros[static_cast<int>(std::ceil(from))]++;
910
0
                    d_num_zeros[static_cast<int>(std::floor(to + 1))]--;
911
0
                  }
912
0
                }
913
0
              }
914
0
            }
915
0
          }
916
0
          int best = 0;
917
0
          int32_t best_sum = 0;
918
0
          FindIndexOfSumMaximum<256>(d_num_zeros, &best, &best_sum);
919
0
          int32_t offset_sum = 0;
920
0
          for (int i = 0; i < 256; ++i) {
921
0
            if (i <= kOffset) {
922
0
              offset_sum += d_num_zeros[i];
923
0
            }
924
0
          }
925
0
          row_out[tx] = 0;
926
0
          if (best_sum > offset_sum + 1) {
927
0
            row_out[tx] = best - kOffset;
928
0
          }
929
0
        }
930
0
        return true;
931
0
      };
932
933
0
      JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, map->ysize(), ThreadPool::NoInit,
934
0
                                    process_row, "FindCorrelation"));
935
0
    }
936
0
  }
937
938
0
  JXL_ASSIGN_OR_RETURN(
939
0
      Image3F dc, Image3F::Create(memory_manager, xsize_blocks, ysize_blocks));
940
0
  if (!frame_header.chroma_subsampling.Is444()) {
941
0
    ZeroFillImage(&dc);
942
0
    for (auto& coeff : enc_state->coeffs) {
943
0
      coeff->ZeroFill();
944
0
    }
945
0
  }
946
  // JPEG DC is from -1024 to 1023.
947
0
  std::vector<size_t> dc_counts[3] = {};
948
0
  dc_counts[0].resize(2048);
949
0
  dc_counts[1].resize(2048);
950
0
  dc_counts[2].resize(2048);
951
0
  size_t total_dc[3] = {};
952
0
  for (size_t c : {1, 0, 2}) {
953
0
    if (jpeg_data.components.size() == 1 && c != 1) {
954
0
      for (auto& coeff : enc_state->coeffs) {
955
0
        coeff->ZeroFillPlane(c);
956
0
      }
957
0
      ZeroFillImage(&dc.Plane(c));
958
      // Ensure no division by 0.
959
0
      dc_counts[c][1024] = 1;
960
0
      total_dc[c] = 1;
961
0
      continue;
962
0
    }
963
0
    size_t hshift = frame_header.chroma_subsampling.HShift(c);
964
0
    size_t vshift = frame_header.chroma_subsampling.VShift(c);
965
0
    ImageSB& map = (c == 0 ? shared.cmap.ytox_map : shared.cmap.ytob_map);
966
0
    for (size_t group_index = 0; group_index < frame_dim.num_groups;
967
0
         group_index++) {
968
0
      const size_t gx = group_index % frame_dim.xsize_groups;
969
0
      const size_t gy = group_index / frame_dim.xsize_groups;
970
0
      int32_t* coeffs[kMaxNumPasses];
971
0
      for (size_t i = 0; i < enc_state->coeffs.size(); i++) {
972
0
        coeffs[i] = enc_state->coeffs[i]->PlaneRow(c, group_index, 0).ptr32;
973
0
      }
974
0
      int32_t block[64];
975
0
      for (size_t by = gy * kGroupDimInBlocks;
976
0
           by < ysize_blocks && by < (gy + 1) * kGroupDimInBlocks; ++by) {
977
0
        if ((by >> vshift) << vshift != by) continue;
978
0
        const int16_t* JXL_RESTRICT inputjpeg = jpeg_row(c, by >> vshift);
979
0
        const int16_t* JXL_RESTRICT inputjpegY = jpeg_row(1, by);
980
0
        float* JXL_RESTRICT fdc = dc.PlaneRow(c, by >> vshift);
981
0
        const int8_t* JXL_RESTRICT cm =
982
0
            map.ConstRow(by / kColorTileDimInBlocks);
983
0
        for (size_t bx = gx * kGroupDimInBlocks;
984
0
             bx < xsize_blocks && bx < (gx + 1) * kGroupDimInBlocks; ++bx) {
985
0
          if ((bx >> hshift) << hshift != bx) continue;
986
0
          size_t base = (bx >> hshift) * kDCTBlockSize;
987
0
          int idc;
988
0
          if (DCzero) {
989
0
            idc = inputjpeg[base];
990
0
          } else {
991
0
            idc = inputjpeg[base] + 1024 / qt_dc[c];
992
0
          }
993
0
          dc_counts[c][std::min(static_cast<uint32_t>(idc + 1024),
994
0
                                static_cast<uint32_t>(2047))]++;
995
0
          total_dc[c]++;
996
0
          fdc[bx >> hshift] = idc * dcquantization_r[c];
997
0
          if (c == 1 || !enc_state->cparams.force_cfl_jpeg_recompression ||
998
0
              !frame_header.chroma_subsampling.Is444()) {
999
0
            for (size_t y = 0; y < 8; y++) {
1000
0
              for (size_t x = 0; x < 8; x++) {
1001
0
                block[y * 8 + x] = inputjpeg[base + x * 8 + y];
1002
0
              }
1003
0
            }
1004
0
          } else {
1005
0
            const int32_t scale =
1006
0
                ColorCorrelation::RatioJPEG(cm[bx / kColorTileDimInBlocks]);
1007
1008
0
            for (size_t y = 0; y < 8; y++) {
1009
0
              for (size_t x = 0; x < 8; x++) {
1010
0
                int Y = inputjpegY[kDCTBlockSize * bx + x * 8 + y];
1011
0
                int QChroma = inputjpeg[kDCTBlockSize * bx + x * 8 + y];
1012
                // Fixed-point multiply of CfL scale with quant table ratio
1013
                // first, and Y value second.
1014
0
                int coeff_scale = (scale * scaled_qtable[64 * c + y * 8 + x] +
1015
0
                                   (1 << (kCFLFixedPointPrecision - 1))) >>
1016
0
                                  kCFLFixedPointPrecision;
1017
0
                int cfl_factor =
1018
0
                    (Y * coeff_scale + (1 << (kCFLFixedPointPrecision - 1))) >>
1019
0
                    kCFLFixedPointPrecision;
1020
0
                int QCR = QChroma - cfl_factor;
1021
0
                block[y * 8 + x] = QCR;
1022
0
              }
1023
0
            }
1024
0
          }
1025
0
          enc_state->progressive_splitter.SplitACCoefficients(
1026
0
              block, AcStrategy::FromRawStrategy(AcStrategyType::DCT), bx, by,
1027
0
              coeffs);
1028
0
          for (size_t i = 0; i < enc_state->coeffs.size(); i++) {
1029
0
            coeffs[i] += kDCTBlockSize;
1030
0
          }
1031
0
        }
1032
0
      }
1033
0
    }
1034
0
  }
1035
1036
0
  auto& dct = enc_state->shared.block_ctx_map.dc_thresholds;
1037
0
  auto& num_dc_ctxs = enc_state->shared.block_ctx_map.num_dc_ctxs;
1038
0
  num_dc_ctxs = 1;
1039
0
  for (size_t i = 0; i < 3; i++) {
1040
0
    dct[i].clear();
1041
0
    int num_thresholds = (CeilLog2Nonzero(total_dc[i]) - 12) / 2;
1042
    // up to 3 buckets per channel:
1043
    // dark/medium/bright, yellow/unsat/blue, green/unsat/red
1044
0
    num_thresholds = jxl::Clamp1(num_thresholds, 0, 2);
1045
0
    size_t cumsum = 0;
1046
0
    size_t cut = total_dc[i] / (num_thresholds + 1);
1047
0
    for (int j = 0; j < 2048; j++) {
1048
0
      cumsum += dc_counts[i][j];
1049
0
      if (cumsum > cut) {
1050
0
        dct[i].push_back(j - 1025);
1051
0
        cut = total_dc[i] * (dct[i].size() + 1) / (num_thresholds + 1);
1052
0
      }
1053
0
    }
1054
0
    num_dc_ctxs *= dct[i].size() + 1;
1055
0
  }
1056
1057
0
  auto& ctx_map = enc_state->shared.block_ctx_map.ctx_map;
1058
0
  ctx_map.clear();
1059
0
  ctx_map.resize(3 * kNumOrders * num_dc_ctxs, 0);
1060
1061
0
  int lbuckets = (dct[1].size() + 1);
1062
0
  for (size_t i = 0; i < num_dc_ctxs; i++) {
1063
    // up to 9 contexts for luma
1064
0
    ctx_map[i] = i / lbuckets;
1065
    // up to 3 contexts for chroma
1066
0
    ctx_map[kNumOrders * num_dc_ctxs + i] =
1067
0
        ctx_map[2 * kNumOrders * num_dc_ctxs + i] =
1068
0
            num_dc_ctxs / lbuckets + (i % lbuckets);
1069
0
  }
1070
0
  enc_state->shared.block_ctx_map.num_ctxs =
1071
0
      *std::max_element(ctx_map.begin(), ctx_map.end()) + 1;
1072
1073
  // disable DC frame for now
1074
0
  auto compute_dc_coeffs = [&](const uint32_t group_index,
1075
0
                               size_t /* thread */) -> Status {
1076
0
    const Rect r = enc_state->shared.frame_dim.DCGroupRect(group_index);
1077
0
    JXL_RETURN_IF_ERROR(enc_modular->AddVarDCTDC(frame_header, dc, r,
1078
0
                                                 group_index,
1079
0
                                                 /*nl_dc=*/false, enc_state,
1080
0
                                                 /*jpeg_transcode=*/true));
1081
0
    JXL_RETURN_IF_ERROR(enc_modular->AddACMetadata(
1082
0
        r, group_index, /*jpeg_transcode=*/true, enc_state));
1083
0
    return true;
1084
0
  };
1085
0
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, shared.frame_dim.num_dc_groups,
1086
0
                                ThreadPool::NoInit, compute_dc_coeffs,
1087
0
                                "Compute DC coeffs"));
1088
1089
0
  return true;
1090
0
}
1091
1092
Status ComputeVarDCTEncodingData(const FrameHeader& frame_header,
1093
                                 const Image3F* linear,
1094
                                 Image3F* JXL_RESTRICT opsin, const Rect& rect,
1095
                                 const JxlCmsInterface& cms, ThreadPool* pool,
1096
                                 ModularFrameEncoder* enc_modular,
1097
                                 PassesEncoderState* enc_state,
1098
2.13k
                                 AuxOut* aux_out) {
1099
2.13k
  JXL_ENSURE((rect.xsize() % kBlockDim) == 0 &&
1100
2.13k
             (rect.ysize() % kBlockDim) == 0);
1101
2.13k
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
1102
  // Save pre-Gaborish opsin for AR control field heuristics computation.
1103
2.13k
  Image3F orig_opsin;
1104
2.13k
  JXL_ASSIGN_OR_RETURN(
1105
2.13k
      orig_opsin, Image3F::Create(memory_manager, rect.xsize(), rect.ysize()));
1106
2.13k
  JXL_RETURN_IF_ERROR(CopyImageTo(rect, *opsin, Rect(orig_opsin), &orig_opsin));
1107
2.13k
  JXL_RETURN_IF_ERROR(orig_opsin.ShrinkTo(enc_state->shared.frame_dim.xsize,
1108
2.13k
                                          enc_state->shared.frame_dim.ysize));
1109
1110
2.13k
  JXL_RETURN_IF_ERROR(LossyFrameHeuristics(frame_header, enc_state, enc_modular,
1111
2.13k
                                           linear, opsin, rect, cms, pool,
1112
2.13k
                                           aux_out));
1113
1114
2.13k
  JXL_RETURN_IF_ERROR(InitializePassesEncoder(
1115
2.13k
      frame_header, *opsin, rect, cms, pool, enc_state, enc_modular, aux_out));
1116
1117
2.13k
  JXL_RETURN_IF_ERROR(
1118
2.13k
      ComputeARHeuristics(frame_header, enc_state, orig_opsin, rect, pool));
1119
1120
2.13k
  JXL_RETURN_IF_ERROR(ComputeACMetadata(pool, enc_state, enc_modular));
1121
1122
2.13k
  return true;
1123
2.13k
}
1124
1125
Status ComputeAllCoeffOrders(PassesEncoderState& enc_state,
1126
2.13k
                             const FrameDimensions& frame_dim) {
1127
2.13k
  auto used_orders_info = ComputeUsedOrders(
1128
2.13k
      enc_state.cparams.speed_tier, enc_state.shared.ac_strategy,
1129
2.13k
      Rect(enc_state.shared.raw_quant_field));
1130
2.13k
  enc_state.used_orders.resize(enc_state.progressive_splitter.GetNumPasses());
1131
4.26k
  for (size_t i = 0; i < enc_state.progressive_splitter.GetNumPasses(); i++) {
1132
2.13k
    JXL_RETURN_IF_ERROR(ComputeCoeffOrder(
1133
2.13k
        enc_state.cparams.speed_tier, *enc_state.coeffs[i],
1134
2.13k
        enc_state.shared.ac_strategy, frame_dim, enc_state.used_orders[i],
1135
2.13k
        enc_state.used_acs, used_orders_info.first, used_orders_info.second,
1136
2.13k
        &enc_state.shared.coeff_orders[i * enc_state.shared.coeff_order_size]));
1137
2.13k
  }
1138
2.13k
  enc_state.used_acs |= used_orders_info.first;
1139
2.13k
  return true;
1140
2.13k
}
1141
1142
// Working area for TokenizeCoefficients (per-group!)
1143
struct EncCache {
1144
  // Allocates memory when first called.
1145
5.26k
  Status InitOnce(JxlMemoryManager* memory_manager) {
1146
5.26k
    if (num_nzeroes.xsize() == 0) {
1147
2.13k
      JXL_ASSIGN_OR_RETURN(num_nzeroes,
1148
2.13k
                           Image3I::Create(memory_manager, kGroupDimInBlocks,
1149
2.13k
                                           kGroupDimInBlocks));
1150
2.13k
    }
1151
5.26k
    return true;
1152
5.26k
  }
1153
  // TokenizeCoefficients
1154
  Image3I num_nzeroes;
1155
};
1156
1157
Status TokenizeAllCoefficients(const FrameHeader& frame_header,
1158
                               ThreadPool* pool,
1159
2.13k
                               PassesEncoderState* enc_state) {
1160
2.13k
  PassesSharedState& shared = enc_state->shared;
1161
2.13k
  std::vector<EncCache> group_caches;
1162
2.13k
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
1163
2.13k
  const auto tokenize_group_init = [&](const size_t num_threads) -> Status {
1164
2.13k
    group_caches.resize(num_threads);
1165
2.13k
    return true;
1166
2.13k
  };
1167
2.13k
  const auto tokenize_group = [&](const uint32_t group_index,
1168
5.26k
                                  const size_t thread) -> Status {
1169
    // Tokenize coefficients.
1170
5.26k
    const Rect rect = shared.frame_dim.BlockGroupRect(group_index);
1171
10.5k
    for (size_t idx_pass = 0; idx_pass < enc_state->passes.size(); idx_pass++) {
1172
5.26k
      JXL_ENSURE(enc_state->coeffs[idx_pass]->Type() == ACType::k32);
1173
5.26k
      const int32_t* JXL_RESTRICT ac_rows[3] = {
1174
5.26k
          enc_state->coeffs[idx_pass]->PlaneRow(0, group_index, 0).ptr32,
1175
5.26k
          enc_state->coeffs[idx_pass]->PlaneRow(1, group_index, 0).ptr32,
1176
5.26k
          enc_state->coeffs[idx_pass]->PlaneRow(2, group_index, 0).ptr32,
1177
5.26k
      };
1178
      // Ensure group cache is initialized.
1179
5.26k
      JXL_RETURN_IF_ERROR(group_caches[thread].InitOnce(memory_manager));
1180
5.26k
      JXL_RETURN_IF_ERROR(TokenizeCoefficients(
1181
5.26k
          &shared.coeff_orders[idx_pass * shared.coeff_order_size], rect,
1182
5.26k
          ac_rows, shared.ac_strategy, frame_header.chroma_subsampling,
1183
5.26k
          &group_caches[thread].num_nzeroes,
1184
5.26k
          &enc_state->passes[idx_pass].ac_tokens[group_index], shared.quant_dc,
1185
5.26k
          shared.raw_quant_field, shared.block_ctx_map));
1186
5.26k
    }
1187
5.26k
    return true;
1188
5.26k
  };
1189
2.13k
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, shared.frame_dim.num_groups,
1190
2.13k
                                tokenize_group_init, tokenize_group,
1191
2.13k
                                "TokenizeGroup"));
1192
2.13k
  return true;
1193
2.13k
}
1194
1195
Status EncodeGlobalDCInfo(const PassesSharedState& shared, BitWriter* writer,
1196
2.13k
                          AuxOut* aux_out) {
1197
  // Encode quantizer DC and global scale.
1198
2.13k
  QuantizerParams params = shared.quantizer.GetParams();
1199
2.13k
  JXL_RETURN_IF_ERROR(
1200
2.13k
      WriteQuantizerParams(params, writer, LayerType::Quant, aux_out));
1201
2.13k
  JXL_RETURN_IF_ERROR(EncodeBlockCtxMap(shared.block_ctx_map, writer, aux_out));
1202
2.13k
  JXL_RETURN_IF_ERROR(ColorCorrelationEncodeDC(shared.cmap.base(), writer,
1203
2.13k
                                               LayerType::Dc, aux_out));
1204
2.13k
  return true;
1205
2.13k
}
1206
1207
// In streaming mode, this function only performs the histogram clustering and
1208
// saves the histogram bitstreams in enc_state, the actual AC global bitstream
1209
// is written in OutputAcGlobal() function after all the groups are processed.
1210
Status EncodeGlobalACInfo(PassesEncoderState* enc_state, BitWriter* writer,
1211
2.13k
                          ModularFrameEncoder* enc_modular, AuxOut* aux_out) {
1212
2.13k
  PassesSharedState& shared = enc_state->shared;
1213
2.13k
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
1214
2.13k
  JXL_RETURN_IF_ERROR(DequantMatricesEncode(memory_manager, shared.matrices,
1215
2.13k
                                            writer, LayerType::Quant, aux_out,
1216
2.13k
                                            enc_modular));
1217
2.13k
  size_t num_histo_bits = CeilLog2Nonzero(shared.frame_dim.num_groups);
1218
2.13k
  if (!enc_state->streaming_mode && num_histo_bits != 0) {
1219
1.06k
    JXL_RETURN_IF_ERROR(
1220
1.06k
        writer->WithMaxBits(num_histo_bits, LayerType::Ac, aux_out, [&] {
1221
1.06k
          writer->Write(num_histo_bits, shared.num_histograms - 1);
1222
1.06k
          return true;
1223
1.06k
        }));
1224
1.06k
  }
1225
1226
4.26k
  for (size_t i = 0; i < enc_state->progressive_splitter.GetNumPasses(); i++) {
1227
    // Encode coefficient orders.
1228
2.13k
    if (!enc_state->streaming_mode) {
1229
2.13k
      size_t order_bits = 0;
1230
2.13k
      JXL_RETURN_IF_ERROR(U32Coder::CanEncode(
1231
2.13k
          kOrderEnc, enc_state->used_orders[i], &order_bits));
1232
2.13k
      JXL_RETURN_IF_ERROR(
1233
2.13k
          writer->WithMaxBits(order_bits, LayerType::Order, aux_out, [&] {
1234
2.13k
            return U32Coder::Write(kOrderEnc, enc_state->used_orders[i],
1235
2.13k
                                   writer);
1236
2.13k
          }));
1237
2.13k
      JXL_RETURN_IF_ERROR(
1238
2.13k
          EncodeCoeffOrders(enc_state->used_orders[i],
1239
2.13k
                            &shared.coeff_orders[i * shared.coeff_order_size],
1240
2.13k
                            writer, LayerType::Order, aux_out));
1241
2.13k
    }
1242
1243
    // Encode histograms.
1244
2.13k
    HistogramParams hist_params(enc_state->cparams.speed_tier,
1245
2.13k
                                shared.block_ctx_map.NumACContexts());
1246
2.13k
    if (enc_state->cparams.speed_tier > SpeedTier::kTortoise) {
1247
2.13k
      hist_params.lz77_method = HistogramParams::LZ77Method::kNone;
1248
2.13k
    }
1249
2.13k
    if (enc_state->cparams.decoding_speed_tier >= 1) {
1250
0
      hist_params.max_histograms = 6;
1251
0
    }
1252
2.13k
    size_t num_histogram_groups = shared.num_histograms;
1253
2.13k
    if (enc_state->streaming_mode) {
1254
0
      size_t prev_num_histograms =
1255
0
          enc_state->passes[i].codes.encoding_info.size();
1256
0
      if (enc_state->initialize_global_state) {
1257
0
        prev_num_histograms += kNumFixedHistograms;
1258
0
        hist_params.add_fixed_histograms = true;
1259
0
      }
1260
0
      size_t remaining_histograms = kClustersLimit - prev_num_histograms;
1261
      // Heuristic to assign budget of new histograms to DC groups.
1262
      // TODO(szabadka) Tune this together with the DC group ordering.
1263
0
      size_t max_histograms = remaining_histograms < 20
1264
0
                                  ? std::min<size_t>(remaining_histograms, 4)
1265
0
                                  : remaining_histograms / 4;
1266
0
      hist_params.max_histograms =
1267
0
          std::min(max_histograms, hist_params.max_histograms);
1268
0
      num_histogram_groups = 1;
1269
0
    }
1270
2.13k
    hist_params.streaming_mode = enc_state->streaming_mode;
1271
2.13k
    hist_params.initialize_global_state = enc_state->initialize_global_state;
1272
2.13k
    JXL_ASSIGN_OR_RETURN(
1273
2.13k
        size_t cost,
1274
2.13k
        BuildAndEncodeHistograms(
1275
2.13k
            memory_manager, hist_params,
1276
2.13k
            num_histogram_groups * shared.block_ctx_map.NumACContexts(),
1277
2.13k
            enc_state->passes[i].ac_tokens, &enc_state->passes[i].codes, writer,
1278
2.13k
            LayerType::Ac, aux_out));
1279
2.13k
    (void)cost;
1280
2.13k
  }
1281
1282
2.13k
  return true;
1283
2.13k
}
1284
Status EncodeGroups(const FrameHeader& frame_header,
1285
                    PassesEncoderState* enc_state,
1286
                    ModularFrameEncoder* enc_modular, ThreadPool* pool,
1287
                    std::vector<std::unique_ptr<BitWriter>>* group_codes,
1288
3.13k
                    AuxOut* aux_out) {
1289
3.13k
  const PassesSharedState& shared = enc_state->shared;
1290
3.13k
  JxlMemoryManager* memory_manager = shared.memory_manager;
1291
3.13k
  const FrameDimensions& frame_dim = shared.frame_dim;
1292
3.13k
  const size_t num_groups = frame_dim.num_groups;
1293
3.13k
  const size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
1294
3.13k
  const size_t global_ac_index = frame_dim.num_dc_groups + 1;
1295
3.13k
  const bool is_small_image =
1296
3.13k
      !enc_state->streaming_mode && num_groups == 1 && num_passes == 1;
1297
3.13k
  const size_t num_toc_entries =
1298
3.13k
      is_small_image ? 1
1299
3.13k
                     : AcGroupIndex(0, 0, num_groups, frame_dim.num_dc_groups) +
1300
1.06k
                           num_groups * num_passes;
1301
3.13k
  JXL_ENSURE(group_codes->empty());
1302
3.13k
  group_codes->reserve(num_toc_entries);
1303
12.5k
  for (size_t i = 0; i < num_toc_entries; ++i) {
1304
9.45k
    group_codes->emplace_back(jxl::make_unique<BitWriter>(memory_manager));
1305
9.45k
  }
1306
1307
29.3k
  const auto get_output = [&](const size_t index) -> BitWriter* {
1308
29.3k
    return (*group_codes)[is_small_image ? 0 : index].get();
1309
29.3k
  };
1310
11.5k
  auto ac_group_code = [&](size_t pass, size_t group) {
1311
11.5k
    return get_output(AcGroupIndex(pass, group, frame_dim.num_groups,
1312
11.5k
                                   frame_dim.num_dc_groups));
1313
11.5k
  };
1314
1315
3.13k
  if (enc_state->initialize_global_state) {
1316
3.13k
    if (frame_header.flags & FrameHeader::kPatches) {
1317
1.00k
      JXL_RETURN_IF_ERROR(PatchDictionaryEncoder::Encode(
1318
1.00k
          shared.image_features.patches, get_output(0), LayerType::Dictionary,
1319
1.00k
          aux_out));
1320
1.00k
    }
1321
3.13k
    if (frame_header.flags & FrameHeader::kSplines) {
1322
0
      JXL_RETURN_IF_ERROR(EncodeSplines(shared.image_features.splines,
1323
0
                                        get_output(0), LayerType::Splines,
1324
0
                                        HistogramParams(), aux_out));
1325
0
    }
1326
3.13k
    if (frame_header.flags & FrameHeader::kNoise) {
1327
0
      JXL_RETURN_IF_ERROR(EncodeNoise(shared.image_features.noise_params,
1328
0
                                      get_output(0), LayerType::Noise,
1329
0
                                      aux_out));
1330
0
    }
1331
1332
3.13k
    JXL_RETURN_IF_ERROR(DequantMatricesEncodeDC(shared.matrices, get_output(0),
1333
3.13k
                                                LayerType::Quant, aux_out));
1334
3.13k
    if (frame_header.encoding == FrameEncoding::kVarDCT) {
1335
2.13k
      JXL_RETURN_IF_ERROR(EncodeGlobalDCInfo(shared, get_output(0), aux_out));
1336
2.13k
    }
1337
3.13k
    JXL_RETURN_IF_ERROR(enc_modular->EncodeGlobalInfo(enc_state->streaming_mode,
1338
3.13k
                                                      get_output(0), aux_out));
1339
3.13k
    JXL_RETURN_IF_ERROR(enc_modular->EncodeStream(get_output(0), aux_out,
1340
3.13k
                                                  LayerType::ModularGlobal,
1341
3.13k
                                                  ModularStreamId::Global()));
1342
3.13k
  }
1343
1344
3.13k
  std::vector<std::unique_ptr<AuxOut>> aux_outs;
1345
3.13k
  auto resize_aux_outs = [&aux_outs,
1346
9.39k
                          aux_out](const size_t num_threads) -> Status {
1347
9.39k
    if (aux_out == nullptr) {
1348
9.39k
      aux_outs.resize(num_threads);
1349
9.39k
    } else {
1350
0
      while (aux_outs.size() > num_threads) {
1351
0
        aux_out->Assimilate(*aux_outs.back());
1352
0
        aux_outs.pop_back();
1353
0
      }
1354
0
      while (num_threads > aux_outs.size()) {
1355
0
        aux_outs.emplace_back(jxl::make_unique<AuxOut>());
1356
0
      }
1357
0
    }
1358
9.39k
    return true;
1359
9.39k
  };
1360
1361
3.13k
  const auto process_dc_group = [&](const uint32_t group_index,
1362
3.13k
                                    const size_t thread) -> Status {
1363
3.13k
    AuxOut* my_aux_out = aux_outs[thread].get();
1364
3.13k
    uint32_t input_index = enc_state->streaming_mode ? 0 : group_index;
1365
3.13k
    BitWriter* output = get_output(input_index + 1);
1366
3.13k
    if (frame_header.encoding == FrameEncoding::kVarDCT &&
1367
3.13k
        !(frame_header.flags & FrameHeader::kUseDcFrame)) {
1368
2.13k
      JXL_RETURN_IF_ERROR(
1369
2.13k
          output->WithMaxBits(2, LayerType::Dc, my_aux_out, [&] {
1370
2.13k
            output->Write(2, enc_modular->extra_dc_precision[group_index]);
1371
2.13k
            return true;
1372
2.13k
          }));
1373
2.13k
      JXL_RETURN_IF_ERROR(
1374
2.13k
          enc_modular->EncodeStream(output, my_aux_out, LayerType::Dc,
1375
2.13k
                                    ModularStreamId::VarDCTDC(group_index)));
1376
2.13k
    }
1377
3.13k
    JXL_RETURN_IF_ERROR(
1378
3.13k
        enc_modular->EncodeStream(output, my_aux_out, LayerType::ModularDcGroup,
1379
3.13k
                                  ModularStreamId::ModularDC(group_index)));
1380
3.13k
    if (frame_header.encoding == FrameEncoding::kVarDCT) {
1381
2.13k
      const Rect& rect = enc_state->shared.frame_dim.DCGroupRect(input_index);
1382
2.13k
      size_t nb_bits = CeilLog2Nonzero(rect.xsize() * rect.ysize());
1383
2.13k
      if (nb_bits != 0) {
1384
2.08k
        JXL_RETURN_IF_ERROR(output->WithMaxBits(
1385
2.08k
            nb_bits, LayerType::ControlFields, my_aux_out, [&] {
1386
2.08k
              output->Write(nb_bits,
1387
2.08k
                            enc_modular->ac_metadata_size[group_index] - 1);
1388
2.08k
              return true;
1389
2.08k
            }));
1390
2.08k
      }
1391
2.13k
      JXL_RETURN_IF_ERROR(enc_modular->EncodeStream(
1392
2.13k
          output, my_aux_out, LayerType::ControlFields,
1393
2.13k
          ModularStreamId::ACMetadata(group_index)));
1394
2.13k
    }
1395
3.13k
    return true;
1396
3.13k
  };
1397
3.13k
  if (enc_state->streaming_mode) {
1398
0
    JXL_ENSURE(frame_dim.num_dc_groups == 1);
1399
0
    JXL_RETURN_IF_ERROR(resize_aux_outs(1));
1400
0
    JXL_RETURN_IF_ERROR(process_dc_group(enc_state->dc_group_index, 0));
1401
3.13k
  } else {
1402
3.13k
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, frame_dim.num_dc_groups,
1403
3.13k
                                  resize_aux_outs, process_dc_group,
1404
3.13k
                                  "EncodeDCGroup"));
1405
3.13k
  }
1406
3.13k
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
1407
2.13k
    JXL_RETURN_IF_ERROR(EncodeGlobalACInfo(
1408
2.13k
        enc_state, get_output(global_ac_index), enc_modular, aux_out));
1409
2.13k
  }
1410
1411
3.13k
  const auto process_group = [&](const uint32_t group_index,
1412
6.26k
                                 const size_t thread) -> Status {
1413
6.26k
    AuxOut* my_aux_out = aux_outs[thread].get();
1414
1415
6.26k
    size_t ac_group_id =
1416
6.26k
        enc_state->streaming_mode
1417
6.26k
            ? enc_modular->ComputeStreamingAbsoluteAcGroupId(
1418
0
                  enc_state->dc_group_index, group_index, shared.frame_dim)
1419
6.26k
            : group_index;
1420
1421
12.5k
    for (size_t i = 0; i < num_passes; i++) {
1422
6.26k
      JXL_DEBUG_V(2, "Encoding AC group %u [abs %" PRIuS "] pass %" PRIuS,
1423
6.26k
                  group_index, ac_group_id, i);
1424
6.26k
      if (frame_header.encoding == FrameEncoding::kVarDCT) {
1425
5.26k
        JXL_RETURN_IF_ERROR(EncodeGroupTokenizedCoefficients(
1426
5.26k
            group_index, i, enc_state->histogram_idx[group_index], *enc_state,
1427
5.26k
            ac_group_code(i, group_index), my_aux_out));
1428
5.26k
      }
1429
      // Write all modular encoded data (color?, alpha, depth, extra channels)
1430
6.26k
      JXL_RETURN_IF_ERROR(enc_modular->EncodeStream(
1431
6.26k
          ac_group_code(i, group_index), my_aux_out, LayerType::ModularAcGroup,
1432
6.26k
          ModularStreamId::ModularAC(ac_group_id, i)));
1433
6.26k
      JXL_DEBUG_V(2,
1434
6.26k
                  "AC group %u [abs %" PRIuS "] pass %" PRIuS
1435
6.26k
                  " encoded size is %" PRIuS " bits",
1436
6.26k
                  group_index, ac_group_id, i,
1437
6.26k
                  ac_group_code(i, group_index)->BitsWritten());
1438
6.26k
    }
1439
6.26k
    return true;
1440
6.26k
  };
1441
3.13k
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, num_groups, resize_aux_outs,
1442
3.13k
                                process_group, "EncodeGroupCoefficients"));
1443
  // Resizing aux_outs to 0 also Assimilates the array.
1444
3.13k
  static_cast<void>(resize_aux_outs(0));
1445
1446
9.45k
  for (std::unique_ptr<BitWriter>& bw : *group_codes) {
1447
9.45k
    JXL_RETURN_IF_ERROR(bw->WithMaxBits(8, LayerType::Ac, aux_out, [&] {
1448
9.45k
      bw->ZeroPadToByte();  // end of group.
1449
9.45k
      return true;
1450
9.45k
    }));
1451
9.45k
  }
1452
3.13k
  return true;
1453
3.13k
}
1454
1455
Status ComputeEncodingData(
1456
    const CompressParams& cparams, const FrameInfo& frame_info,
1457
    const CodecMetadata* metadata, JxlEncoderChunkedFrameAdapter& frame_data,
1458
    const jpeg::JPEGData* jpeg_data, size_t x0, size_t y0, size_t xsize,
1459
    size_t ysize, const JxlCmsInterface& cms, ThreadPool* pool,
1460
    FrameHeader& mutable_frame_header, ModularFrameEncoder& enc_modular,
1461
    PassesEncoderState& enc_state,
1462
3.13k
    std::vector<std::unique_ptr<BitWriter>>* group_codes, AuxOut* aux_out) {
1463
3.13k
  JXL_ENSURE(x0 + xsize <= frame_data.xsize);
1464
3.13k
  JXL_ENSURE(y0 + ysize <= frame_data.ysize);
1465
3.13k
  JxlMemoryManager* memory_manager = enc_state.memory_manager();
1466
3.13k
  const FrameHeader& frame_header = mutable_frame_header;
1467
3.13k
  PassesSharedState& shared = enc_state.shared;
1468
3.13k
  shared.metadata = metadata;
1469
3.13k
  if (enc_state.streaming_mode) {
1470
0
    shared.frame_dim.Set(
1471
0
        xsize, ysize, frame_header.group_size_shift,
1472
0
        /*max_hshift=*/0, /*max_vshift=*/0,
1473
0
        mutable_frame_header.encoding == FrameEncoding::kModular,
1474
0
        /*upsampling=*/1);
1475
3.13k
  } else {
1476
3.13k
    shared.frame_dim = frame_header.ToFrameDimensions();
1477
3.13k
  }
1478
1479
3.13k
  shared.image_features.patches.SetShared(&shared.reference_frames);
1480
3.13k
  const FrameDimensions& frame_dim = shared.frame_dim;
1481
3.13k
  JXL_ASSIGN_OR_RETURN(
1482
3.13k
      shared.ac_strategy,
1483
3.13k
      AcStrategyImage::Create(memory_manager, frame_dim.xsize_blocks,
1484
3.13k
                              frame_dim.ysize_blocks));
1485
3.13k
  JXL_ASSIGN_OR_RETURN(shared.raw_quant_field,
1486
3.13k
                       ImageI::Create(memory_manager, frame_dim.xsize_blocks,
1487
3.13k
                                      frame_dim.ysize_blocks));
1488
3.13k
  JXL_ASSIGN_OR_RETURN(shared.epf_sharpness,
1489
3.13k
                       ImageB::Create(memory_manager, frame_dim.xsize_blocks,
1490
3.13k
                                      frame_dim.ysize_blocks));
1491
3.13k
  JXL_ASSIGN_OR_RETURN(
1492
3.13k
      shared.cmap, ColorCorrelationMap::Create(memory_manager, frame_dim.xsize,
1493
3.13k
                                               frame_dim.ysize));
1494
3.13k
  shared.coeff_order_size = kCoeffOrderMaxSize;
1495
3.13k
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
1496
2.13k
    shared.coeff_orders.resize(frame_header.passes.num_passes *
1497
2.13k
                               kCoeffOrderMaxSize);
1498
2.13k
  }
1499
1500
3.13k
  JXL_ASSIGN_OR_RETURN(shared.quant_dc,
1501
3.13k
                       ImageB::Create(memory_manager, frame_dim.xsize_blocks,
1502
3.13k
                                      frame_dim.ysize_blocks));
1503
3.13k
  JXL_ASSIGN_OR_RETURN(shared.dc_storage,
1504
3.13k
                       Image3F::Create(memory_manager, frame_dim.xsize_blocks,
1505
3.13k
                                       frame_dim.ysize_blocks));
1506
3.13k
  shared.dc = &shared.dc_storage;
1507
1508
3.13k
  const size_t num_extra_channels = metadata->m.num_extra_channels;
1509
3.13k
  const ExtraChannelInfo* alpha_eci = metadata->m.Find(ExtraChannel::kAlpha);
1510
3.13k
  const ExtraChannelInfo* black_eci = metadata->m.Find(ExtraChannel::kBlack);
1511
3.13k
  const size_t alpha_idx = alpha_eci - metadata->m.extra_channel_info.data();
1512
3.13k
  const size_t black_idx = black_eci - metadata->m.extra_channel_info.data();
1513
3.13k
  const ColorEncoding c_enc = metadata->m.color_encoding;
1514
1515
  // Make the image patch bigger than the currently processed group in streaming
1516
  // mode so that we can take into account border pixels around the group when
1517
  // computing inverse Gaborish and adaptive quantization map.
1518
3.13k
  int max_border = enc_state.streaming_mode ? kBlockDim : 0;
1519
3.13k
  Rect frame_rect(0, 0, frame_data.xsize, frame_data.ysize);
1520
3.13k
  Rect frame_area_rect = Rect(x0, y0, xsize, ysize);
1521
3.13k
  Rect patch_rect = frame_area_rect.Extend(max_border, frame_rect);
1522
3.13k
  JXL_ENSURE(patch_rect.IsInside(frame_rect));
1523
1524
  // Allocating a large enough image avoids a copy when padding.
1525
6.26k
  JXL_ASSIGN_OR_RETURN(
1526
6.26k
      Image3F color,
1527
6.26k
      Image3F::Create(memory_manager, RoundUpToBlockDim(patch_rect.xsize()),
1528
6.26k
                      RoundUpToBlockDim(patch_rect.ysize())));
1529
6.26k
  JXL_RETURN_IF_ERROR(color.ShrinkTo(patch_rect.xsize(), patch_rect.ysize()));
1530
3.13k
  std::vector<ImageF> extra_channels(num_extra_channels);
1531
3.13k
  for (auto& extra_channel : extra_channels) {
1532
0
    JXL_ASSIGN_OR_RETURN(
1533
0
        extra_channel,
1534
0
        ImageF::Create(memory_manager, patch_rect.xsize(), patch_rect.ysize()));
1535
0
  }
1536
3.13k
  ImageF* alpha = alpha_eci ? &extra_channels[alpha_idx] : nullptr;
1537
3.13k
  ImageF* black = black_eci ? &extra_channels[black_idx] : nullptr;
1538
3.13k
  bool has_interleaved_alpha = false;
1539
3.13k
  JxlChunkedFrameInputSource input = frame_data.GetInputSource();
1540
3.13k
  if (!jpeg_data) {
1541
3.13k
    JXL_RETURN_IF_ERROR(CopyColorChannels(input, patch_rect, frame_info,
1542
3.13k
                                          metadata->m, pool, &color, alpha,
1543
3.13k
                                          &has_interleaved_alpha));
1544
3.13k
  }
1545
3.13k
  JXL_RETURN_IF_ERROR(CopyExtraChannels(input, patch_rect, frame_info,
1546
3.13k
                                        metadata->m, has_interleaved_alpha,
1547
3.13k
                                        pool, &extra_channels));
1548
1549
3.13k
  enc_state.cparams = cparams;
1550
1551
3.13k
  Image3F linear_storage;
1552
3.13k
  Image3F* linear = nullptr;
1553
1554
3.13k
  if (!jpeg_data) {
1555
3.13k
    if (frame_header.color_transform == ColorTransform::kXYB &&
1556
3.13k
        frame_info.ib_needs_color_transform) {
1557
2.13k
      if (frame_header.encoding == FrameEncoding::kVarDCT &&
1558
2.13k
          cparams.speed_tier <= SpeedTier::kKitten) {
1559
0
        JXL_ASSIGN_OR_RETURN(linear_storage,
1560
0
                             Image3F::Create(memory_manager, patch_rect.xsize(),
1561
0
                                             patch_rect.ysize()));
1562
0
        linear = &linear_storage;
1563
0
      }
1564
2.13k
      JXL_RETURN_IF_ERROR(ToXYB(c_enc, metadata->m.IntensityTarget(), black,
1565
2.13k
                                pool, &color, cms, linear));
1566
2.13k
    } else {
1567
      // Nothing to do.
1568
      // RGB or YCbCr: forward YCbCr is not implemented, this is only used when
1569
      // the input is already in YCbCr
1570
      // If encoding a special DC or reference frame: input is already in XYB.
1571
1.00k
    }
1572
3.13k
    bool lossless = cparams.IsLossless();
1573
3.13k
    if (alpha && !alpha_eci->alpha_associated &&
1574
3.13k
        frame_header.frame_type == FrameType::kRegularFrame &&
1575
3.13k
        !ApplyOverride(cparams.keep_invisible, cparams.IsLossless()) &&
1576
3.13k
        cparams.ec_resampling == cparams.resampling &&
1577
3.13k
        !cparams.disable_perceptual_optimizations) {
1578
      // simplify invisible pixels
1579
0
      SimplifyInvisible(&color, *alpha, lossless);
1580
0
      if (linear) {
1581
0
        SimplifyInvisible(linear, *alpha, lossless);
1582
0
      }
1583
0
    }
1584
3.13k
    JXL_RETURN_IF_ERROR(PadImageToBlockMultipleInPlace(&color));
1585
3.13k
  }
1586
1587
  // Rectangle within color that corresponds to the currently processed group in
1588
  // streaming mode.
1589
3.13k
  Rect group_rect(x0 - patch_rect.x0(), y0 - patch_rect.y0(),
1590
3.13k
                  RoundUpToBlockDim(xsize), RoundUpToBlockDim(ysize));
1591
1592
3.13k
  if (enc_state.initialize_global_state && !jpeg_data) {
1593
3.13k
    ComputeChromacityAdjustments(cparams, color, group_rect,
1594
3.13k
                                 &mutable_frame_header);
1595
3.13k
  }
1596
1597
3.13k
  bool has_jpeg_data = (jpeg_data != nullptr);
1598
3.13k
  ComputeNoiseParams(cparams, enc_state.streaming_mode, has_jpeg_data, color,
1599
3.13k
                     frame_dim, &mutable_frame_header,
1600
3.13k
                     &shared.image_features.noise_params);
1601
1602
3.13k
  JXL_RETURN_IF_ERROR(
1603
3.13k
      DownsampleColorChannels(cparams, frame_header, has_jpeg_data, &color));
1604
1605
3.13k
  if (cparams.ec_resampling != 1 && !cparams.already_downsampled) {
1606
0
    for (ImageF& ec : extra_channels) {
1607
0
      JXL_ASSIGN_OR_RETURN(ec, DownsampleImage(ec, cparams.ec_resampling));
1608
0
    }
1609
0
  }
1610
1611
3.13k
  if (!enc_state.streaming_mode) {
1612
3.13k
    group_rect = Rect(color);
1613
3.13k
  }
1614
1615
3.13k
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
1616
2.13k
    enc_state.passes.resize(enc_state.progressive_splitter.GetNumPasses());
1617
2.13k
    for (PassesEncoderState::PassData& pass : enc_state.passes) {
1618
2.13k
      pass.ac_tokens.resize(shared.frame_dim.num_groups);
1619
2.13k
    }
1620
2.13k
    if (jpeg_data) {
1621
0
      JXL_RETURN_IF_ERROR(ComputeJPEGTranscodingData(
1622
0
          *jpeg_data, frame_header, pool, &enc_modular, &enc_state));
1623
2.13k
    } else {
1624
2.13k
      JXL_RETURN_IF_ERROR(ComputeVarDCTEncodingData(
1625
2.13k
          frame_header, linear, &color, group_rect, cms, pool, &enc_modular,
1626
2.13k
          &enc_state, aux_out));
1627
2.13k
    }
1628
2.13k
    JXL_RETURN_IF_ERROR(ComputeAllCoeffOrders(enc_state, frame_dim));
1629
2.13k
    if (!enc_state.streaming_mode) {
1630
2.13k
      shared.num_histograms = 1;
1631
2.13k
      enc_state.histogram_idx.resize(frame_dim.num_groups);
1632
2.13k
    }
1633
2.13k
    JXL_RETURN_IF_ERROR(
1634
2.13k
        TokenizeAllCoefficients(frame_header, pool, &enc_state));
1635
2.13k
  }
1636
1637
3.13k
  if (cparams.modular_mode || !extra_channels.empty()) {
1638
1.00k
    JXL_RETURN_IF_ERROR(enc_modular.ComputeEncodingData(
1639
1.00k
        frame_header, metadata->m, &color, extra_channels, group_rect,
1640
1.00k
        frame_dim, frame_area_rect, &enc_state, cms, pool, aux_out,
1641
1.00k
        /*do_color=*/cparams.modular_mode));
1642
1.00k
  }
1643
1644
3.13k
  if (!enc_state.streaming_mode) {
1645
    // If checks pass here, a Global MA tree is used.
1646
3.13k
    if (cparams.speed_tier < SpeedTier::kTortoise ||
1647
3.13k
        !cparams.ModularPartIsLossless() || cparams.lossy_palette ||
1648
3.13k
        (cparams.responsive == 1 && !cparams.IsLossless()) ||
1649
        // Allow Local trees for progressive lossless but not lossy.
1650
3.13k
        (cparams.buffering && cparams.responsive < 0) ||
1651
3.13k
        !cparams.custom_fixed_tree.empty()) {
1652
      // Use local trees if doing lossless modular, unless at very slow speeds.
1653
3.13k
      JXL_RETURN_IF_ERROR(enc_modular.ComputeTree(pool));
1654
3.13k
      JXL_RETURN_IF_ERROR(enc_modular.ComputeTokens(pool));
1655
3.13k
    }
1656
3.13k
    mutable_frame_header.UpdateFlag(shared.image_features.patches.HasAny(),
1657
3.13k
                                    FrameHeader::kPatches);
1658
3.13k
    mutable_frame_header.UpdateFlag(shared.image_features.splines.HasAny(),
1659
3.13k
                                    FrameHeader::kSplines);
1660
3.13k
  }
1661
1662
3.13k
  JXL_RETURN_IF_ERROR(EncodeGroups(frame_header, &enc_state, &enc_modular, pool,
1663
3.13k
                                   group_codes, aux_out));
1664
3.13k
  if (enc_state.streaming_mode) {
1665
0
    const size_t group_index = enc_state.dc_group_index;
1666
0
    enc_modular.ClearStreamData(ModularStreamId::VarDCTDC(group_index));
1667
0
    enc_modular.ClearStreamData(ModularStreamId::ACMetadata(group_index));
1668
0
    enc_modular.ClearModularStreamData();
1669
0
  }
1670
3.13k
  return true;
1671
3.13k
}
1672
1673
Status PermuteGroups(const CompressParams& cparams,
1674
                     const FrameDimensions& frame_dim, size_t num_passes,
1675
                     std::vector<coeff_order_t>* permutation,
1676
3.13k
                     std::vector<std::unique_ptr<BitWriter>>* group_codes) {
1677
3.13k
  const size_t num_groups = frame_dim.num_groups;
1678
3.13k
  if (!cparams.centerfirst || (num_passes == 1 && num_groups == 1)) {
1679
3.13k
    return true;
1680
3.13k
  }
1681
  // Don't permute global DC/AC or DC.
1682
0
  permutation->resize(frame_dim.num_dc_groups + 2);
1683
0
  std::iota(permutation->begin(), permutation->end(), 0);
1684
0
  std::vector<coeff_order_t> ac_group_order(num_groups);
1685
0
  std::iota(ac_group_order.begin(), ac_group_order.end(), 0);
1686
0
  size_t group_dim = frame_dim.group_dim;
1687
1688
  // The center of the image is either given by parameters or chosen
1689
  // to be the middle of the image by default if center_x, center_y resp.
1690
  // are not provided.
1691
1692
0
  int64_t imag_cx;
1693
0
  if (cparams.center_x != static_cast<size_t>(-1)) {
1694
0
    JXL_RETURN_IF_ERROR(cparams.center_x < frame_dim.xsize);
1695
0
    imag_cx = cparams.center_x;
1696
0
  } else {
1697
0
    imag_cx = frame_dim.xsize / 2;
1698
0
  }
1699
1700
0
  int64_t imag_cy;
1701
0
  if (cparams.center_y != static_cast<size_t>(-1)) {
1702
0
    JXL_RETURN_IF_ERROR(cparams.center_y < frame_dim.ysize);
1703
0
    imag_cy = cparams.center_y;
1704
0
  } else {
1705
0
    imag_cy = frame_dim.ysize / 2;
1706
0
  }
1707
1708
  // The center of the group containing the center of the image.
1709
0
  int64_t cx = (imag_cx / group_dim) * group_dim + group_dim / 2;
1710
0
  int64_t cy = (imag_cy / group_dim) * group_dim + group_dim / 2;
1711
  // This identifies in what area of the central group the center of the image
1712
  // lies in.
1713
0
  double direction = -std::atan2(imag_cy - cy, imag_cx - cx);
1714
  // This identifies the side of the central group the center of the image
1715
  // lies closest to. This can take values 0, 1, 2, 3 corresponding to left,
1716
  // bottom, right, top.
1717
0
  int64_t side = std::fmod((direction + 5 * kPi / 4), 2 * kPi) * 2 / kPi;
1718
0
  auto get_distance_from_center = [&](size_t gid) {
1719
0
    Rect r = frame_dim.GroupRect(gid);
1720
0
    int64_t gcx = r.x0() + group_dim / 2;
1721
0
    int64_t gcy = r.y0() + group_dim / 2;
1722
0
    int64_t dx = gcx - cx;
1723
0
    int64_t dy = gcy - cy;
1724
    // The angle is determined by taking atan2 and adding an appropriate
1725
    // starting point depending on the side we want to start on.
1726
0
    double angle = std::remainder(
1727
0
        std::atan2(dy, dx) + kPi / 4 + side * (kPi / 2), 2 * kPi);
1728
    // Concentric squares in clockwise order.
1729
0
    return std::make_pair(std::max(std::abs(dx), std::abs(dy)), angle);
1730
0
  };
1731
0
  std::sort(ac_group_order.begin(), ac_group_order.end(),
1732
0
            [&](coeff_order_t a, coeff_order_t b) {
1733
0
              return get_distance_from_center(a) < get_distance_from_center(b);
1734
0
            });
1735
0
  std::vector<coeff_order_t> inv_ac_group_order(ac_group_order.size(), 0);
1736
0
  for (size_t i = 0; i < ac_group_order.size(); i++) {
1737
0
    inv_ac_group_order[ac_group_order[i]] = i;
1738
0
  }
1739
0
  for (size_t i = 0; i < num_passes; i++) {
1740
0
    size_t pass_start = permutation->size();
1741
0
    for (coeff_order_t v : inv_ac_group_order) {
1742
0
      permutation->push_back(pass_start + v);
1743
0
    }
1744
0
  }
1745
0
  std::vector<std::unique_ptr<BitWriter>> new_group_codes(group_codes->size());
1746
0
  for (size_t i = 0; i < permutation->size(); i++) {
1747
0
    new_group_codes[(*permutation)[i]] = std::move((*group_codes)[i]);
1748
0
  }
1749
0
  group_codes->swap(new_group_codes);
1750
0
  return true;
1751
0
}
1752
1753
bool CanDoStreamingEncoding(const CompressParams& cparams,
1754
                            const FrameInfo& frame_info,
1755
                            const CodecMetadata& metadata,
1756
3.13k
                            const JxlEncoderChunkedFrameAdapter& frame_data) {
1757
3.13k
  if (cparams.buffering == 0) {
1758
0
    return false;
1759
0
  }
1760
3.13k
  if (cparams.buffering == -1) {
1761
3.13k
    if (cparams.speed_tier < SpeedTier::kTortoise) return false;
1762
3.13k
    if (cparams.speed_tier < SpeedTier::kSquirrel &&
1763
3.13k
        cparams.butteraugli_distance > 0.5f) {
1764
0
      return false;
1765
0
    }
1766
3.13k
    if (cparams.speed_tier == SpeedTier::kSquirrel &&
1767
3.13k
        cparams.butteraugli_distance >= 3.f) {
1768
0
      return false;
1769
0
    }
1770
3.13k
  }
1771
1772
  // TODO(veluca): handle different values of `buffering`.
1773
3.13k
  if (frame_data.xsize <= 2048 && frame_data.ysize <= 2048) {
1774
3.13k
    return false;
1775
3.13k
  }
1776
0
  if (frame_data.IsJPEG()) {
1777
0
    return false;
1778
0
  }
1779
0
  if (cparams.noise == Override::kOn || cparams.patches == Override::kOn) {
1780
0
    return false;
1781
0
  }
1782
0
  if (cparams.progressive_dc != 0 || frame_info.dc_level != 0) {
1783
0
    return false;
1784
0
  }
1785
0
  if (cparams.custom_progressive_mode ||
1786
0
      cparams.qprogressive_mode == Override::kOn ||
1787
0
      cparams.progressive_mode == Override::kOn) {
1788
0
    return false;
1789
0
  }
1790
0
  if (cparams.resampling != 1 || cparams.ec_resampling != 1) {
1791
0
    return false;
1792
0
  }
1793
0
  if (cparams.lossy_palette) {
1794
0
    return false;
1795
0
  }
1796
0
  if (cparams.max_error_mode) {
1797
0
    return false;
1798
0
  }
1799
  // Progressive lossless uses Local MA trees, but requires a full
1800
  // buffer to compress well, so no special check.
1801
0
  if (!cparams.ModularPartIsLossless() || cparams.responsive > 0) {
1802
0
    if (metadata.m.num_extra_channels > 0 || cparams.modular_mode) {
1803
0
      return false;
1804
0
    }
1805
0
  }
1806
0
  ColorTransform ok_color_transform =
1807
0
      cparams.modular_mode ? ColorTransform::kNone : ColorTransform::kXYB;
1808
0
  if (cparams.color_transform != ok_color_transform) {
1809
0
    return false;
1810
0
  }
1811
0
  return true;
1812
0
}
1813
1814
Status ComputePermutationForStreaming(size_t xsize, size_t ysize,
1815
                                      size_t group_size, size_t num_passes,
1816
                                      std::vector<coeff_order_t>& permutation,
1817
0
                                      std::vector<size_t>& dc_group_order) {
1818
  // This is only valid in VarDCT mode, otherwise there can be group shift.
1819
0
  const size_t dc_group_size = group_size * kBlockDim;
1820
0
  const size_t group_xsize = DivCeil(xsize, group_size);
1821
0
  const size_t group_ysize = DivCeil(ysize, group_size);
1822
0
  const size_t dc_group_xsize = DivCeil(xsize, dc_group_size);
1823
0
  const size_t dc_group_ysize = DivCeil(ysize, dc_group_size);
1824
0
  const size_t num_groups = group_xsize * group_ysize;
1825
0
  const size_t num_dc_groups = dc_group_xsize * dc_group_ysize;
1826
0
  const size_t num_sections = 2 + num_dc_groups + num_passes * num_groups;
1827
0
  permutation.resize(num_sections);
1828
0
  size_t new_ix = 0;
1829
  // DC Global is first
1830
0
  permutation[0] = new_ix++;
1831
  // TODO(szabadka) Change the dc group order to center-first.
1832
0
  for (size_t dc_y = 0; dc_y < dc_group_ysize; ++dc_y) {
1833
0
    for (size_t dc_x = 0; dc_x < dc_group_xsize; ++dc_x) {
1834
0
      size_t dc_ix = dc_y * dc_group_xsize + dc_x;
1835
0
      dc_group_order.push_back(dc_ix);
1836
0
      permutation[1 + dc_ix] = new_ix++;
1837
0
      size_t ac_y0 = dc_y * kBlockDim;
1838
0
      size_t ac_x0 = dc_x * kBlockDim;
1839
0
      size_t ac_y1 = std::min<size_t>(group_ysize, ac_y0 + kBlockDim);
1840
0
      size_t ac_x1 = std::min<size_t>(group_xsize, ac_x0 + kBlockDim);
1841
0
      for (size_t pass = 0; pass < num_passes; ++pass) {
1842
0
        for (size_t ac_y = ac_y0; ac_y < ac_y1; ++ac_y) {
1843
0
          for (size_t ac_x = ac_x0; ac_x < ac_x1; ++ac_x) {
1844
0
            size_t group_ix = ac_y * group_xsize + ac_x;
1845
0
            size_t old_ix =
1846
0
                AcGroupIndex(pass, group_ix, num_groups, num_dc_groups);
1847
0
            permutation[old_ix] = new_ix++;
1848
0
          }
1849
0
        }
1850
0
      }
1851
0
    }
1852
0
  }
1853
  // AC Global is last
1854
0
  permutation[1 + num_dc_groups] = new_ix++;
1855
0
  JXL_ENSURE(new_ix == num_sections);
1856
0
  return true;
1857
0
}
1858
1859
constexpr size_t kGroupSizeOffset[4] = {
1860
    static_cast<size_t>(0),
1861
    static_cast<size_t>(1024),
1862
    static_cast<size_t>(17408),
1863
    static_cast<size_t>(4211712),
1864
};
1865
constexpr size_t kTOCBits[4] = {12, 16, 24, 32};
1866
1867
0
size_t TOCBucket(size_t group_size) {
1868
0
  size_t bucket = 0;
1869
0
  while (bucket < 3 && group_size >= kGroupSizeOffset[bucket + 1]) ++bucket;
1870
0
  return bucket;
1871
0
}
1872
1873
0
size_t TOCSize(const std::vector<size_t>& group_sizes) {
1874
0
  size_t toc_bits = 0;
1875
0
  for (size_t group_size : group_sizes) {
1876
0
    toc_bits += kTOCBits[TOCBucket(group_size)];
1877
0
  }
1878
0
  return (toc_bits + 7) / 8;
1879
0
}
1880
1881
StatusOr<PaddedBytes> EncodeTOC(JxlMemoryManager* memory_manager,
1882
                                const std::vector<size_t>& group_sizes,
1883
0
                                AuxOut* aux_out) {
1884
0
  BitWriter writer{memory_manager};
1885
0
  JXL_RETURN_IF_ERROR(writer.WithMaxBits(
1886
0
      32 * group_sizes.size(), LayerType::Toc, aux_out, [&]() -> Status {
1887
0
        for (size_t group_size : group_sizes) {
1888
0
          JXL_RETURN_IF_ERROR(U32Coder::Write(kTocDist, group_size, &writer));
1889
0
        }
1890
0
        writer.ZeroPadToByte();  // before first group
1891
0
        return true;
1892
0
      }));
1893
0
  return std::move(writer).TakeBytes();
1894
0
}
1895
1896
Status ComputeGroupDataOffset(size_t frame_header_size, size_t dc_global_size,
1897
                              size_t num_sections, size_t& min_dc_global_size,
1898
0
                              size_t& group_offset) {
1899
0
  size_t max_toc_bits = (num_sections - 1) * 32;
1900
0
  size_t min_toc_bits = (num_sections - 1) * 12;
1901
0
  size_t max_padding = (max_toc_bits - min_toc_bits + 7) / 8;
1902
0
  min_dc_global_size = dc_global_size;
1903
0
  size_t dc_global_bucket = TOCBucket(min_dc_global_size);
1904
0
  while (TOCBucket(min_dc_global_size + max_padding) > dc_global_bucket) {
1905
0
    dc_global_bucket = TOCBucket(min_dc_global_size + max_padding);
1906
0
    min_dc_global_size = kGroupSizeOffset[dc_global_bucket];
1907
0
  }
1908
0
  JXL_ENSURE(TOCBucket(min_dc_global_size) == dc_global_bucket);
1909
0
  JXL_ENSURE(TOCBucket(min_dc_global_size + max_padding) == dc_global_bucket);
1910
0
  max_toc_bits += kTOCBits[dc_global_bucket];
1911
0
  size_t max_toc_size = (max_toc_bits + 7) / 8;
1912
0
  group_offset = frame_header_size + max_toc_size + min_dc_global_size;
1913
0
  return true;
1914
0
}
1915
1916
size_t ComputeDcGlobalPadding(const std::vector<size_t>& group_sizes,
1917
                              size_t frame_header_size,
1918
                              size_t group_data_offset,
1919
0
                              size_t min_dc_global_size) {
1920
0
  std::vector<size_t> new_group_sizes = group_sizes;
1921
0
  new_group_sizes[0] = min_dc_global_size;
1922
0
  size_t toc_size = TOCSize(new_group_sizes);
1923
0
  size_t actual_offset = frame_header_size + toc_size + group_sizes[0];
1924
0
  return group_data_offset - actual_offset;
1925
0
}
1926
1927
Status OutputGroups(std::vector<std::unique_ptr<BitWriter>>&& group_codes,
1928
                    std::vector<size_t>* group_sizes,
1929
0
                    JxlEncoderOutputProcessorWrapper* output_processor) {
1930
0
  JXL_ENSURE(group_codes.size() >= 4);
1931
0
  {
1932
0
    PaddedBytes dc_group = std::move(*group_codes[1]).TakeBytes();
1933
0
    group_sizes->push_back(dc_group.size());
1934
0
    JXL_RETURN_IF_ERROR(AppendData(*output_processor, dc_group));
1935
0
  }
1936
0
  for (size_t i = 3; i < group_codes.size(); ++i) {
1937
0
    PaddedBytes ac_group = std::move(*group_codes[i]).TakeBytes();
1938
0
    group_sizes->push_back(ac_group.size());
1939
0
    JXL_RETURN_IF_ERROR(AppendData(*output_processor, ac_group));
1940
0
  }
1941
0
  return true;
1942
0
}
1943
1944
0
void RemoveUnusedHistograms(EntropyEncodingData& codes) {
1945
0
  std::vector<int> remap(256, -1);
1946
0
  std::vector<uint8_t> inv_remap;
1947
0
  for (uint8_t& context : codes.context_map) {
1948
0
    const uint8_t histo_ix = context;
1949
0
    if (remap[histo_ix] == -1) {
1950
0
      remap[histo_ix] = inv_remap.size();
1951
0
      inv_remap.push_back(histo_ix);
1952
0
    }
1953
0
    context = remap[histo_ix];
1954
0
  }
1955
0
  EntropyEncodingData new_codes;
1956
0
  new_codes.use_prefix_code = codes.use_prefix_code;
1957
0
  new_codes.lz77 = codes.lz77;
1958
0
  new_codes.context_map = std::move(codes.context_map);
1959
0
  for (uint8_t histo_idx : inv_remap) {
1960
0
    new_codes.encoding_info.emplace_back(
1961
0
        std::move(codes.encoding_info[histo_idx]));
1962
0
    new_codes.uint_config.emplace_back(codes.uint_config[histo_idx]);
1963
0
    new_codes.encoded_histograms.emplace_back(
1964
0
        std::move(codes.encoded_histograms[histo_idx]));
1965
0
  }
1966
0
  codes = std::move(new_codes);
1967
0
}
1968
1969
Status OutputAcGlobal(PassesEncoderState& enc_state,
1970
                      const FrameDimensions& frame_dim,
1971
                      std::vector<size_t>* group_sizes,
1972
                      JxlEncoderOutputProcessorWrapper* output_processor,
1973
0
                      AuxOut* aux_out) {
1974
0
  JXL_ENSURE(frame_dim.num_groups > 1);
1975
0
  JxlMemoryManager* memory_manager = enc_state.memory_manager();
1976
0
  BitWriter writer{memory_manager};
1977
0
  {
1978
0
    size_t num_histo_bits = CeilLog2Nonzero(frame_dim.num_groups);
1979
0
    JXL_RETURN_IF_ERROR(
1980
0
        writer.WithMaxBits(num_histo_bits + 1, LayerType::Ac, aux_out, [&] {
1981
0
          writer.Write(1, 1);  // default dequant matrices
1982
0
          writer.Write(num_histo_bits, frame_dim.num_dc_groups - 1);
1983
0
          return true;
1984
0
        }));
1985
0
  }
1986
0
  const PassesSharedState& shared = enc_state.shared;
1987
0
  for (size_t i = 0; i < enc_state.progressive_splitter.GetNumPasses(); i++) {
1988
    // Encode coefficient orders.
1989
0
    size_t order_bits = 0;
1990
0
    JXL_RETURN_IF_ERROR(
1991
0
        U32Coder::CanEncode(kOrderEnc, enc_state.used_orders[i], &order_bits));
1992
0
    JXL_RETURN_IF_ERROR(
1993
0
        writer.WithMaxBits(order_bits, LayerType::Order, aux_out, [&] {
1994
0
          return U32Coder::Write(kOrderEnc, enc_state.used_orders[i], &writer);
1995
0
        }));
1996
0
    JXL_RETURN_IF_ERROR(
1997
0
        EncodeCoeffOrders(enc_state.used_orders[i],
1998
0
                          &shared.coeff_orders[i * shared.coeff_order_size],
1999
0
                          &writer, LayerType::Order, aux_out));
2000
    // Fix up context map and entropy codes to remove any fix histograms that
2001
    // were not selected by clustering.
2002
0
    RemoveUnusedHistograms(enc_state.passes[i].codes);
2003
0
    JXL_RETURN_IF_ERROR(EncodeHistograms(enc_state.passes[i].codes, &writer,
2004
0
                                         LayerType::Ac, aux_out));
2005
0
  }
2006
0
  JXL_RETURN_IF_ERROR(writer.WithMaxBits(8, LayerType::Ac, aux_out, [&] {
2007
0
    writer.ZeroPadToByte();  // end of group.
2008
0
    return true;
2009
0
  }));
2010
0
  PaddedBytes ac_global = std::move(writer).TakeBytes();
2011
0
  group_sizes->push_back(ac_global.size());
2012
0
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, ac_global));
2013
0
  return true;
2014
0
}
2015
2016
JXL_NOINLINE Status EncodeFrameStreaming(
2017
    JxlMemoryManager* memory_manager, const CompressParams& cparams,
2018
    const FrameInfo& frame_info, const CodecMetadata* metadata,
2019
    JxlEncoderChunkedFrameAdapter& frame_data, const JxlCmsInterface& cms,
2020
    ThreadPool* pool, JxlEncoderOutputProcessorWrapper* output_processor,
2021
0
    AuxOut* aux_out) {
2022
0
  auto enc_state = jxl::make_unique<PassesEncoderState>(memory_manager);
2023
0
  SetProgressiveMode(cparams, &enc_state->progressive_splitter);
2024
0
  FrameHeader frame_header(metadata);
2025
0
  std::unique_ptr<jpeg::JPEGData> jpeg_data;
2026
0
  if (frame_data.IsJPEG()) {
2027
0
    jpeg_data = frame_data.TakeJPEGData();
2028
0
    JXL_ENSURE(jpeg_data);
2029
0
  }
2030
0
  JXL_RETURN_IF_ERROR(MakeFrameHeader(frame_data.xsize, frame_data.ysize,
2031
0
                                      cparams, enc_state->progressive_splitter,
2032
0
                                      frame_info, jpeg_data.get(), true,
2033
0
                                      &frame_header));
2034
0
  const size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
2035
0
  JXL_ASSIGN_OR_RETURN(
2036
0
      auto enc_modular,
2037
0
      ModularFrameEncoder::Create(memory_manager, frame_header, cparams, true));
2038
0
  std::vector<coeff_order_t> permutation;
2039
0
  std::vector<size_t> dc_group_order;
2040
0
  size_t group_size = frame_header.ToFrameDimensions().group_dim;
2041
0
  JXL_RETURN_IF_ERROR(ComputePermutationForStreaming(
2042
0
      frame_data.xsize, frame_data.ysize, group_size, num_passes, permutation,
2043
0
      dc_group_order));
2044
0
  enc_state->shared.num_histograms = dc_group_order.size();
2045
0
  size_t dc_group_size = group_size * kBlockDim;
2046
0
  size_t dc_group_xsize = DivCeil(frame_data.xsize, dc_group_size);
2047
0
  size_t min_dc_global_size = 0;
2048
0
  size_t group_data_offset = 0;
2049
0
  PaddedBytes frame_header_bytes{memory_manager};
2050
0
  PaddedBytes dc_global_bytes{memory_manager};
2051
0
  std::vector<size_t> group_sizes;
2052
0
  size_t start_pos = output_processor->CurrentPosition();
2053
0
  for (size_t i = 0; i < dc_group_order.size(); ++i) {
2054
0
    size_t dc_ix = dc_group_order[i];
2055
0
    size_t dc_y = dc_ix / dc_group_xsize;
2056
0
    size_t dc_x = dc_ix % dc_group_xsize;
2057
0
    size_t y0 = dc_y * dc_group_size;
2058
0
    size_t x0 = dc_x * dc_group_size;
2059
0
    size_t ysize = std::min<size_t>(dc_group_size, frame_data.ysize - y0);
2060
0
    size_t xsize = std::min<size_t>(dc_group_size, frame_data.xsize - x0);
2061
0
    size_t group_xsize = DivCeil(xsize, group_size);
2062
0
    size_t group_ysize = DivCeil(ysize, group_size);
2063
0
    JXL_DEBUG_V(2,
2064
0
                "Encoding DC group #%" PRIuS " dc_y = %" PRIuS " dc_x = %" PRIuS
2065
0
                " (x0, y0) = (%" PRIuS ", %" PRIuS ") (xsize, ysize) = (%" PRIuS
2066
0
                ", %" PRIuS ")",
2067
0
                dc_ix, dc_y, dc_x, x0, y0, xsize, ysize);
2068
0
    enc_state->streaming_mode = true;
2069
0
    enc_state->initialize_global_state = (i == 0);
2070
0
    enc_state->dc_group_index = dc_ix;
2071
0
    enc_state->histogram_idx =
2072
0
        std::vector<size_t>(group_xsize * group_ysize, i);
2073
0
    std::vector<std::unique_ptr<BitWriter>> group_codes;
2074
0
    JXL_RETURN_IF_ERROR(ComputeEncodingData(
2075
0
        cparams, frame_info, metadata, frame_data, jpeg_data.get(), x0, y0,
2076
0
        xsize, ysize, cms, pool, frame_header, *enc_modular, *enc_state,
2077
0
        &group_codes, aux_out));
2078
0
    JXL_ENSURE(enc_state->special_frames.empty());
2079
0
    if (i == 0) {
2080
0
      BitWriter writer{memory_manager};
2081
0
      JXL_RETURN_IF_ERROR(WriteFrameHeader(frame_header, &writer, aux_out));
2082
0
      JXL_RETURN_IF_ERROR(
2083
0
          writer.WithMaxBits(8, LayerType::Header, aux_out, [&]() -> Status {
2084
0
            writer.Write(1, 1);  // write permutation
2085
0
            JXL_RETURN_IF_ERROR(EncodePermutation(
2086
0
                permutation.data(), /*skip=*/0, permutation.size(), &writer,
2087
0
                LayerType::Header, aux_out));
2088
0
            writer.ZeroPadToByte();
2089
0
            return true;
2090
0
          }));
2091
0
      frame_header_bytes = std::move(writer).TakeBytes();
2092
0
      dc_global_bytes = std::move(*group_codes[0]).TakeBytes();
2093
0
      JXL_RETURN_IF_ERROR(ComputeGroupDataOffset(
2094
0
          frame_header_bytes.size(), dc_global_bytes.size(), permutation.size(),
2095
0
          min_dc_global_size, group_data_offset));
2096
0
      JXL_DEBUG_V(2, "Frame header size: %" PRIuS, frame_header_bytes.size());
2097
0
      JXL_DEBUG_V(2, "DC global size: %" PRIuS ", min size for TOC: %" PRIuS,
2098
0
                  dc_global_bytes.size(), min_dc_global_size);
2099
0
      JXL_DEBUG_V(2, "Num groups: %" PRIuS " group data offset: %" PRIuS,
2100
0
                  permutation.size(), group_data_offset);
2101
0
      group_sizes.push_back(dc_global_bytes.size());
2102
0
      JXL_RETURN_IF_ERROR(
2103
0
          output_processor->Seek(start_pos + group_data_offset));
2104
0
    }
2105
0
    JXL_RETURN_IF_ERROR(
2106
0
        OutputGroups(std::move(group_codes), &group_sizes, output_processor));
2107
0
  }
2108
0
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
2109
0
    JXL_RETURN_IF_ERROR(
2110
0
        OutputAcGlobal(*enc_state, frame_header.ToFrameDimensions(),
2111
0
                       &group_sizes, output_processor, aux_out));
2112
0
  } else {
2113
0
    group_sizes.push_back(0);
2114
0
  }
2115
0
  JXL_ENSURE(group_sizes.size() == permutation.size());
2116
0
  size_t end_pos = output_processor->CurrentPosition();
2117
0
  JXL_RETURN_IF_ERROR(output_processor->Seek(start_pos));
2118
0
  size_t padding_size =
2119
0
      ComputeDcGlobalPadding(group_sizes, frame_header_bytes.size(),
2120
0
                             group_data_offset, min_dc_global_size);
2121
0
  group_sizes[0] += padding_size;
2122
0
  JXL_ASSIGN_OR_RETURN(PaddedBytes toc_bytes,
2123
0
                       EncodeTOC(memory_manager, group_sizes, aux_out));
2124
0
  std::vector<uint8_t> padding_bytes(padding_size);
2125
0
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, frame_header_bytes));
2126
0
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, toc_bytes));
2127
0
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, dc_global_bytes));
2128
0
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, padding_bytes));
2129
0
  JXL_DEBUG_V(2, "TOC size: %" PRIuS " padding bytes after DC global: %" PRIuS,
2130
0
              toc_bytes.size(), padding_size);
2131
0
  JXL_ENSURE(output_processor->CurrentPosition() ==
2132
0
             start_pos + group_data_offset);
2133
0
  JXL_RETURN_IF_ERROR(output_processor->Seek(end_pos));
2134
0
  return true;
2135
0
}
2136
2137
Status EncodeFrameOneShot(JxlMemoryManager* memory_manager,
2138
                          const CompressParams& cparams,
2139
                          const FrameInfo& frame_info,
2140
                          const CodecMetadata* metadata,
2141
                          JxlEncoderChunkedFrameAdapter& frame_data,
2142
                          const JxlCmsInterface& cms, ThreadPool* pool,
2143
                          JxlEncoderOutputProcessorWrapper* output_processor,
2144
3.13k
                          AuxOut* aux_out) {
2145
3.13k
  auto enc_state = jxl::make_unique<PassesEncoderState>(memory_manager);
2146
3.13k
  SetProgressiveMode(cparams, &enc_state->progressive_splitter);
2147
3.13k
  FrameHeader frame_header(metadata);
2148
3.13k
  std::unique_ptr<jpeg::JPEGData> jpeg_data;
2149
3.13k
  if (frame_data.IsJPEG()) {
2150
0
    jpeg_data = frame_data.TakeJPEGData();
2151
0
    JXL_ENSURE(jpeg_data);
2152
0
  }
2153
3.13k
  JXL_RETURN_IF_ERROR(MakeFrameHeader(frame_data.xsize, frame_data.ysize,
2154
3.13k
                                      cparams, enc_state->progressive_splitter,
2155
3.13k
                                      frame_info, jpeg_data.get(), false,
2156
3.13k
                                      &frame_header));
2157
3.13k
  const size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
2158
3.13k
  JXL_ASSIGN_OR_RETURN(auto enc_modular,
2159
3.13k
                       ModularFrameEncoder::Create(memory_manager, frame_header,
2160
3.13k
                                                   cparams, false));
2161
3.13k
  std::vector<std::unique_ptr<BitWriter>> group_codes;
2162
3.13k
  JXL_RETURN_IF_ERROR(ComputeEncodingData(
2163
3.13k
      cparams, frame_info, metadata, frame_data, jpeg_data.get(), 0, 0,
2164
3.13k
      frame_data.xsize, frame_data.ysize, cms, pool, frame_header, *enc_modular,
2165
3.13k
      *enc_state, &group_codes, aux_out));
2166
2167
3.13k
  BitWriter writer{memory_manager};
2168
3.13k
  JXL_RETURN_IF_ERROR(writer.AppendByteAligned(enc_state->special_frames));
2169
3.13k
  JXL_RETURN_IF_ERROR(WriteFrameHeader(frame_header, &writer, aux_out));
2170
2171
3.13k
  std::vector<coeff_order_t> permutation;
2172
3.13k
  JXL_RETURN_IF_ERROR(PermuteGroups(cparams, enc_state->shared.frame_dim,
2173
3.13k
                                    num_passes, &permutation, &group_codes));
2174
2175
3.13k
  JXL_RETURN_IF_ERROR(
2176
3.13k
      WriteGroupOffsets(group_codes, permutation, &writer, aux_out));
2177
2178
3.13k
  JXL_RETURN_IF_ERROR(writer.AppendByteAligned(group_codes));
2179
3.13k
  PaddedBytes frame_bytes = std::move(writer).TakeBytes();
2180
3.13k
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, frame_bytes));
2181
2182
3.13k
  return true;
2183
3.13k
}
2184
2185
}  // namespace
2186
2187
std::vector<CompressParams> TectonicPlateSettingsLessPalette(
2188
0
    const CompressParams& cparams_orig) {
2189
0
  std::vector<CompressParams> all_params;
2190
0
  CompressParams cparams_attempt = cparams_orig;
2191
0
  cparams_attempt.speed_tier = SpeedTier::kGlacier;
2192
2193
0
  cparams_attempt.options.max_properties = 4;
2194
0
  cparams_attempt.options.nb_repeats = 1.0f;
2195
0
  cparams_attempt.modular_group_size_shift = 0;
2196
0
  cparams_attempt.channel_colors_percent = 0;
2197
0
  cparams_attempt.options.predictor = Predictor::Variable;
2198
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2199
0
  cparams_attempt.palette_colors = 1024;
2200
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2201
0
  cparams_attempt.patches = Override::kDefault;
2202
0
  all_params.push_back(cparams_attempt);
2203
0
  cparams_attempt.channel_colors_percent = 80.f;
2204
0
  cparams_attempt.modular_group_size_shift = 1;
2205
0
  cparams_attempt.palette_colors = 0;
2206
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2207
0
  all_params.push_back(cparams_attempt);
2208
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2209
0
  cparams_attempt.modular_group_size_shift = 2;
2210
0
  all_params.push_back(cparams_attempt);
2211
0
  cparams_attempt.modular_group_size_shift = 3;
2212
0
  cparams_attempt.patches = Override::kOff;
2213
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2214
0
  all_params.push_back(cparams_attempt);
2215
0
  cparams_attempt.palette_colors = 1024;
2216
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2217
0
  all_params.push_back(cparams_attempt);
2218
0
  cparams_attempt.patches = Override::kDefault;
2219
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2220
0
  all_params.push_back(cparams_attempt);
2221
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2222
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2223
0
  all_params.push_back(cparams_attempt);
2224
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2225
0
  cparams_attempt.options.nb_repeats = 0.9f;
2226
0
  cparams_attempt.modular_group_size_shift = 2;
2227
0
  all_params.push_back(cparams_attempt);
2228
0
  cparams_attempt.modular_group_size_shift = 3;
2229
0
  cparams_attempt.palette_colors = 0;
2230
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2231
0
  all_params.push_back(cparams_attempt);
2232
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2233
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2234
0
  all_params.push_back(cparams_attempt);
2235
0
  cparams_attempt.palette_colors = 1024;
2236
0
  cparams_attempt.options.nb_repeats = 0.95f;
2237
0
  cparams_attempt.modular_group_size_shift = 1;
2238
0
  cparams_attempt.channel_colors_percent = 0;
2239
0
  all_params.push_back(cparams_attempt);
2240
0
  cparams_attempt.modular_group_size_shift = 2;
2241
0
  cparams_attempt.palette_colors = 0;
2242
0
  all_params.push_back(cparams_attempt);
2243
0
  cparams_attempt.channel_colors_percent = 80.f;
2244
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2245
0
  all_params.push_back(cparams_attempt);
2246
0
  cparams_attempt.palette_colors = 1024;
2247
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2248
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2249
0
  cparams_attempt.modular_group_size_shift = 3;
2250
0
  all_params.push_back(cparams_attempt);
2251
0
  cparams_attempt.palette_colors = 0;
2252
0
  cparams_attempt.patches = Override::kOff;
2253
0
  all_params.push_back(cparams_attempt);
2254
0
  cparams_attempt.patches = Override::kDefault;
2255
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2256
0
  all_params.push_back(cparams_attempt);
2257
0
  cparams_attempt.palette_colors = 1024;
2258
0
  cparams_attempt.patches = Override::kOff;
2259
0
  all_params.push_back(cparams_attempt);
2260
0
  cparams_attempt.options.nb_repeats = 0.5f;
2261
0
  cparams_attempt.patches = Override::kDefault;
2262
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2263
0
  all_params.push_back(cparams_attempt);
2264
0
  cparams_attempt.options.predictor = Predictor::Zero;
2265
0
  cparams_attempt.options.nb_repeats = 0;
2266
0
  cparams_attempt.channel_colors_percent = 0;
2267
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2268
0
  cparams_attempt.patches = Override::kOff;
2269
0
  all_params.push_back(cparams_attempt);
2270
0
  cparams_attempt.channel_colors_percent = 80.f;
2271
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2272
0
  cparams_attempt.options.nb_repeats = 1.0f;
2273
0
  cparams_attempt.palette_colors = 0;
2274
0
  all_params.push_back(cparams_attempt);
2275
0
  cparams_attempt.patches = Override::kDefault;
2276
0
  cparams_attempt.options.predictor = Predictor::Best;
2277
0
  all_params.push_back(cparams_attempt);
2278
0
  cparams_attempt.options.nb_repeats = 0.9f;
2279
0
  cparams_attempt.patches = Override::kOff;
2280
0
  all_params.push_back(cparams_attempt);
2281
0
  cparams_attempt.palette_colors = 1024;
2282
0
  cparams_attempt.patches = Override::kDefault;
2283
0
  cparams_attempt.options.predictor = Predictor::Weighted;
2284
0
  cparams_attempt.options.nb_repeats = 1.0f;
2285
0
  all_params.push_back(cparams_attempt);
2286
0
  cparams_attempt.options.nb_repeats = 0.95f;
2287
0
  cparams_attempt.modular_group_size_shift = 2;
2288
0
  cparams_attempt.palette_colors = 0;
2289
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2290
0
  all_params.push_back(cparams_attempt);
2291
0
  return all_params;
2292
0
}
2293
2294
std::vector<CompressParams> TectonicPlateSettingsMorePalette(
2295
0
    const CompressParams& cparams_orig) {
2296
0
  std::vector<CompressParams> all_params;
2297
0
  CompressParams cparams_attempt = cparams_orig;
2298
0
  cparams_attempt.speed_tier = SpeedTier::kGlacier;
2299
2300
0
  cparams_attempt.options.max_properties = 4;
2301
0
  cparams_attempt.options.nb_repeats = 1.0f;
2302
0
  cparams_attempt.modular_group_size_shift = 0;
2303
0
  cparams_attempt.palette_colors = 70000;
2304
0
  cparams_attempt.options.predictor = Predictor::Variable;
2305
0
  cparams_attempt.channel_colors_percent = 80.f;
2306
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2307
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2308
0
  cparams_attempt.patches = Override::kDefault;
2309
0
  all_params.push_back(cparams_attempt);
2310
0
  cparams_attempt.modular_group_size_shift = 2;
2311
0
  cparams_attempt.channel_colors_percent = 0;
2312
0
  cparams_attempt.patches = Override::kOff;
2313
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2314
0
  all_params.push_back(cparams_attempt);
2315
0
  cparams_attempt.channel_colors_percent = 80.f;
2316
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2317
0
  cparams_attempt.modular_group_size_shift = 3;
2318
0
  all_params.push_back(cparams_attempt);
2319
0
  cparams_attempt.options.nb_repeats = 0.9f;
2320
0
  all_params.push_back(cparams_attempt);
2321
0
  cparams_attempt.patches = Override::kDefault;
2322
0
  cparams_attempt.options.nb_repeats = 0.95f;
2323
0
  cparams_attempt.modular_group_size_shift = 0;
2324
0
  all_params.push_back(cparams_attempt);
2325
0
  cparams_attempt.modular_group_size_shift = 3;
2326
0
  all_params.push_back(cparams_attempt);
2327
0
  cparams_attempt.patches = Override::kOff;
2328
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2329
0
  all_params.push_back(cparams_attempt);
2330
0
  cparams_attempt.options.nb_repeats = 0.5f;
2331
0
  all_params.push_back(cparams_attempt);
2332
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2333
0
  cparams_attempt.options.predictor = Predictor::Zero;
2334
0
  cparams_attempt.options.nb_repeats = 0;
2335
0
  all_params.push_back(cparams_attempt);
2336
0
  cparams_attempt.patches = Override::kDefault;
2337
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2338
0
  all_params.push_back(cparams_attempt);
2339
0
  cparams_attempt.options.nb_repeats = 0.01f;
2340
0
  cparams_attempt.palette_colors = 0;
2341
0
  cparams_attempt.patches = Override::kOff;
2342
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2343
0
  all_params.push_back(cparams_attempt);
2344
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2345
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2346
0
  cparams_attempt.palette_colors = 70000;
2347
0
  all_params.push_back(cparams_attempt);
2348
0
  cparams_attempt.options.nb_repeats = 1.0f;
2349
0
  cparams_attempt.modular_group_size_shift = 0;
2350
0
  cparams_attempt.channel_colors_percent = 0;
2351
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2352
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2353
0
  all_params.push_back(cparams_attempt);
2354
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2355
0
  cparams_attempt.modular_group_size_shift = 1;
2356
0
  all_params.push_back(cparams_attempt);
2357
0
  cparams_attempt.modular_group_size_shift = 2;
2358
0
  all_params.push_back(cparams_attempt);
2359
0
  cparams_attempt.channel_colors_percent = 80.f;
2360
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2361
0
  cparams_attempt.modular_group_size_shift = 3;
2362
0
  all_params.push_back(cparams_attempt);
2363
0
  cparams_attempt.options.nb_repeats = 0.5f;
2364
0
  cparams_attempt.modular_group_size_shift = 1;
2365
0
  cparams_attempt.channel_colors_percent = 0;
2366
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2367
0
  all_params.push_back(cparams_attempt);
2368
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2369
0
  cparams_attempt.modular_group_size_shift = 2;
2370
0
  all_params.push_back(cparams_attempt);
2371
0
  cparams_attempt.channel_colors_percent = 80.f;
2372
0
  cparams_attempt.modular_group_size_shift = 3;
2373
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2374
0
  all_params.push_back(cparams_attempt);
2375
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2376
0
  cparams_attempt.options.predictor = Predictor::Select;
2377
0
  cparams_attempt.options.nb_repeats = 1.0f;
2378
0
  all_params.push_back(cparams_attempt);
2379
0
  return all_params;
2380
0
}
2381
2382
Status EncodeFrame(JxlMemoryManager* memory_manager,
2383
                   const CompressParams& cparams_orig,
2384
                   const FrameInfo& frame_info, const CodecMetadata* metadata,
2385
                   JxlEncoderChunkedFrameAdapter& frame_data,
2386
                   const JxlCmsInterface& cms, ThreadPool* pool,
2387
                   JxlEncoderOutputProcessorWrapper* output_processor,
2388
3.13k
                   AuxOut* aux_out) {
2389
3.13k
  CompressParams cparams = cparams_orig;
2390
3.13k
  if (cparams.speed_tier == SpeedTier::kTectonicPlate &&
2391
3.13k
      !cparams.IsLossless()) {
2392
0
    cparams.speed_tier = SpeedTier::kGlacier;
2393
0
  }
2394
  // Lightning mode is handled externally, so switch to Thunder mode to handle
2395
  // potentially weird cases.
2396
3.13k
  if (cparams.speed_tier == SpeedTier::kLightning) {
2397
0
    cparams.speed_tier = SpeedTier::kThunder;
2398
0
  }
2399
3.13k
  if (cparams.speed_tier == SpeedTier::kTectonicPlate) {
2400
    // Test palette performance to inform later trials.
2401
0
    std::vector<CompressParams> all_params;
2402
0
    CompressParams cparams_attempt = cparams_orig;
2403
0
    cparams_attempt.speed_tier = SpeedTier::kGlacier;
2404
2405
0
    cparams_attempt.options.max_properties = 4;
2406
0
    cparams_attempt.options.nb_repeats = 1.0f;
2407
0
    cparams_attempt.modular_group_size_shift = 3;
2408
0
    cparams_attempt.palette_colors = 0;
2409
0
    cparams_attempt.options.predictor = Predictor::Variable;
2410
0
    cparams_attempt.channel_colors_percent = 80.f;
2411
0
    cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2412
0
    cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2413
0
    cparams_attempt.patches = Override::kDefault;
2414
0
    all_params.push_back(cparams_attempt);
2415
0
    cparams_attempt.options.predictor = Predictor::Zero;
2416
0
    cparams_attempt.options.nb_repeats = 0.01f;
2417
0
    cparams_attempt.palette_colors = 70000;
2418
0
    cparams_attempt.patches = Override::kOff;
2419
0
    cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2420
0
    all_params.push_back(cparams_attempt);
2421
2422
0
    std::vector<size_t> size;
2423
0
    size.resize(all_params.size());
2424
2425
0
    const auto process_variant = [&](size_t task, size_t) -> Status {
2426
0
      JxlEncoderOutputProcessorWrapper local_output(memory_manager);
2427
0
      JXL_RETURN_IF_ERROR(EncodeFrame(memory_manager, all_params[task],
2428
0
                                      frame_info, metadata, frame_data, cms,
2429
0
                                      nullptr, &local_output, aux_out));
2430
0
      size[task] = local_output.CurrentPosition();
2431
0
      return true;
2432
0
    };
2433
0
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, all_params.size(),
2434
0
                                  ThreadPool::NoInit, process_variant,
2435
0
                                  "Compress kTectonicPlate"));
2436
2437
0
    std::vector<CompressParams> all_params_test = all_params;
2438
0
    std::vector<size_t> size_test = size;
2439
0
    size_t best_idx_test = 0;
2440
2441
0
    if (size_test[0] <= size_test[1]) {
2442
0
      all_params = TectonicPlateSettingsLessPalette(cparams_orig);
2443
0
    } else {
2444
0
      best_idx_test = 1;
2445
0
      all_params = TectonicPlateSettingsMorePalette(cparams_orig);
2446
0
    }
2447
2448
0
    size.clear();
2449
0
    size.resize(all_params.size());
2450
2451
0
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, all_params.size(),
2452
0
                                  ThreadPool::NoInit, process_variant,
2453
0
                                  "Compress kTectonicPlate"));
2454
2455
0
    size_t best_idx = 0;
2456
0
    for (size_t i = 1; i < all_params.size(); i++) {
2457
0
      if (size[best_idx] > size[i]) {
2458
0
        best_idx = i;
2459
0
      }
2460
0
    }
2461
0
    if (size[best_idx] < size_test[best_idx_test]) {
2462
0
      cparams = all_params[best_idx];
2463
0
    } else {
2464
0
      cparams = all_params_test[best_idx_test];
2465
0
    }
2466
0
  }
2467
2468
3.13k
  JXL_RETURN_IF_ERROR(ParamsPostInit(&cparams));
2469
2470
3.13k
  if (cparams.butteraugli_distance < 0) {
2471
0
    return JXL_FAILURE("Expected non-negative distance");
2472
0
  }
2473
2474
3.13k
  if (cparams.progressive_dc < 0) {
2475
2.13k
    if (cparams.progressive_dc != -1) {
2476
0
      return JXL_FAILURE("Invalid progressive DC setting value (%d)",
2477
0
                         cparams.progressive_dc);
2478
0
    }
2479
2.13k
    cparams.progressive_dc = 0;
2480
2.13k
  }
2481
3.13k
  if (cparams.ec_resampling < cparams.resampling) {
2482
0
    cparams.ec_resampling = cparams.resampling;
2483
0
  }
2484
3.13k
  if (cparams.resampling > 1 || frame_info.is_preview) {
2485
0
    cparams.progressive_dc = 0;
2486
0
  }
2487
2488
3.13k
  if (frame_info.dc_level + cparams.progressive_dc > 4) {
2489
0
    return JXL_FAILURE("Too many levels of progressive DC");
2490
0
  }
2491
2492
3.13k
  if (cparams.modular_mode == false &&
2493
3.13k
      cparams.butteraugli_distance < kMinButteraugliDistance) {
2494
0
    return JXL_FAILURE("Butteraugli distance is too low (%f)",
2495
0
                       cparams.butteraugli_distance);
2496
0
  }
2497
2498
3.13k
  if (frame_data.IsJPEG()) {
2499
0
    cparams.gaborish = Override::kOff;
2500
0
    cparams.epf = 0;
2501
0
    cparams.modular_mode = false;
2502
0
  }
2503
2504
3.13k
  if (frame_data.xsize == 0 || frame_data.ysize == 0) {
2505
0
    return JXL_FAILURE("Empty image");
2506
0
  }
2507
2508
  // Assert that this metadata is correctly set up for the compression params,
2509
  // this should have been done by enc_file.cc
2510
3.13k
  JXL_ENSURE(metadata->m.xyb_encoded ==
2511
3.13k
             (cparams.color_transform == ColorTransform::kXYB));
2512
2513
3.13k
  if (frame_data.IsJPEG() && cparams.color_transform == ColorTransform::kXYB) {
2514
0
    return JXL_FAILURE("Can't add JPEG frame to XYB codestream");
2515
0
  }
2516
2517
3.13k
  if (CanDoStreamingEncoding(cparams, frame_info, *metadata, frame_data)) {
2518
0
    return EncodeFrameStreaming(memory_manager, cparams, frame_info, metadata,
2519
0
                                frame_data, cms, pool, output_processor,
2520
0
                                aux_out);
2521
3.13k
  } else {
2522
3.13k
    return EncodeFrameOneShot(memory_manager, cparams, frame_info, metadata,
2523
3.13k
                              frame_data, cms, pool, output_processor, aux_out);
2524
3.13k
  }
2525
3.13k
}
2526
2527
Status EncodeFrame(JxlMemoryManager* memory_manager,
2528
                   const CompressParams& cparams_orig,
2529
                   const FrameInfo& frame_info, const CodecMetadata* metadata,
2530
                   ImageBundle& ib, const JxlCmsInterface& cms,
2531
1.00k
                   ThreadPool* pool, BitWriter* writer, AuxOut* aux_out) {
2532
1.00k
  JxlEncoderChunkedFrameAdapter frame_data(ib.xsize(), ib.ysize(),
2533
1.00k
                                           ib.extra_channels().size());
2534
1.00k
  std::vector<uint8_t> color;
2535
1.00k
  if (ib.IsJPEG()) {
2536
0
    frame_data.SetJPEGData(std::move(ib.jpeg_data));
2537
1.00k
  } else {
2538
1.00k
    uint32_t num_channels =
2539
1.00k
        ib.IsGray() && frame_info.ib_needs_color_transform ? 1 : 3;
2540
1.00k
    size_t stride = ib.xsize() * num_channels * 4;
2541
1.00k
    color.resize(ib.ysize() * stride);
2542
1.00k
    JXL_RETURN_IF_ERROR(ConvertToExternal(
2543
1.00k
        ib, /*bits_per_sample=*/32, /*float_out=*/true, num_channels,
2544
1.00k
        JXL_NATIVE_ENDIAN, stride, pool, color.data(), color.size(),
2545
1.00k
        /*out_callback=*/{}, Orientation::kIdentity));
2546
1.00k
    JxlPixelFormat format{num_channels, JXL_TYPE_FLOAT, JXL_NATIVE_ENDIAN, 0};
2547
1.00k
    frame_data.SetFromBuffer(0, color.data(), color.size(), format);
2548
1.00k
  }
2549
1.00k
  for (size_t ec = 0; ec < ib.extra_channels().size(); ++ec) {
2550
0
    JxlPixelFormat ec_format{1, JXL_TYPE_FLOAT, JXL_NATIVE_ENDIAN, 0};
2551
0
    size_t ec_stride = ib.xsize() * 4;
2552
0
    std::vector<uint8_t> ec_data(ib.ysize() * ec_stride);
2553
0
    const ImageF* channel = &ib.extra_channels()[ec];
2554
0
    JXL_RETURN_IF_ERROR(ConvertChannelsToExternal(
2555
0
        &channel, 1,
2556
0
        /*bits_per_sample=*/32,
2557
0
        /*float_out=*/true, JXL_NATIVE_ENDIAN, ec_stride, pool, ec_data.data(),
2558
0
        ec_data.size(), /*out_callback=*/{}, Orientation::kIdentity));
2559
0
    frame_data.SetFromBuffer(1 + ec, ec_data.data(), ec_data.size(), ec_format);
2560
0
  }
2561
1.00k
  FrameInfo fi = frame_info;
2562
1.00k
  fi.origin = ib.origin;
2563
1.00k
  fi.blend = ib.blend;
2564
1.00k
  fi.blendmode = ib.blendmode;
2565
1.00k
  fi.duration = ib.duration;
2566
1.00k
  fi.timecode = ib.timecode;
2567
1.00k
  fi.name = ib.name;
2568
1.00k
  JxlEncoderOutputProcessorWrapper output_processor(memory_manager);
2569
1.00k
  JXL_RETURN_IF_ERROR(EncodeFrame(memory_manager, cparams_orig, fi, metadata,
2570
1.00k
                                  frame_data, cms, pool, &output_processor,
2571
1.00k
                                  aux_out));
2572
1.00k
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
2573
1.00k
  std::vector<uint8_t> output;
2574
1.00k
  JXL_RETURN_IF_ERROR(output_processor.CopyOutput(output));
2575
1.00k
  JXL_RETURN_IF_ERROR(writer->AppendByteAligned(Bytes(output)));
2576
1.00k
  return true;
2577
1.00k
}
2578
2579
}  // namespace jxl