Coverage Report

Created: 2026-05-16 07:22

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