Coverage Report

Created: 2026-06-30 07:12

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