Coverage Report

Created: 2026-06-16 07:20

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