Coverage Report

Created: 2026-11-12 07:35

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