Coverage Report

Created: 2026-06-07 07:20

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