Coverage Report

Created: 2025-11-16 07:22

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