Coverage Report

Created: 2026-03-31 06:56

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