Coverage Report

Created: 2025-10-12 07:48

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