Coverage Report

Created: 2026-10-14 06:45

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
0
Status ParamsPostInit(CompressParams* p) {
91
0
  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
0
  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
0
  if (!p->modular_mode && p->butteraugli_distance < kMinButteraugliDistance) {
99
0
    p->butteraugli_distance = kMinButteraugliDistance;
100
0
  }
101
0
  if (p->original_butteraugli_distance == -1.0) {
102
0
    p->original_butteraugli_distance = p->butteraugli_distance;
103
0
  }
104
0
  if (p->resampling <= 0) {
105
0
    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
0
    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
0
  }
118
0
  if (p->ec_resampling <= 0) {
119
0
    p->ec_resampling = p->resampling;
120
0
  }
121
  // Modular has to be squeezed to show progressive HF passes.
122
0
  if (p->progressive_mode == Override::kOn ||
123
0
      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
0
  return true;
130
0
}
131
132
namespace {
133
134
uint32_t GetGroupSizeShift(size_t xsize, size_t ysize,
135
0
                           const CompressParams& cparams) {
136
0
  if (!cparams.modular_mode) return 1;
137
0
  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
0
  if (cparams.decoding_speed_tier >= 2 ||
144
0
      (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
0
  if (xsize <= 128 && ysize <= 128) return 0;
152
0
  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
0
                                const CompressParams& cparams) {
159
0
  const size_t group_size_shift = GetGroupSizeShift(xsize, ysize, cparams);
160
0
  const size_t group_dim = (kGroupDim >> 1) << group_size_shift;
161
0
  return DivCeil(xsize, group_dim) * DivCeil(ysize, group_dim);
162
0
}
163
164
template <typename T>
165
uint32_t GetBitDepth(JxlBitDepth bit_depth, const T& metadata,
166
0
                     JxlPixelFormat format) {
167
0
  if (bit_depth.type == JXL_BIT_DEPTH_FROM_PIXEL_FORMAT) {
168
0
    return BitsPerChannel(format.data_type);
169
0
  } 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
0
}
Unexecuted instantiation: enc_frame.cc:unsigned int jxl::(anonymous namespace)::GetBitDepth<jxl::ImageMetadata>(JxlBitDepth, jxl::ImageMetadata const&, JxlPixelFormat)
Unexecuted instantiation: enc_frame.cc:unsigned int jxl::(anonymous namespace)::GetBitDepth<jxl::ExtraChannelInfo>(JxlBitDepth, jxl::ExtraChannelInfo const&, JxlPixelFormat)
177
178
Status CopyColorChannels(JxlChunkedFrameInputSource input, Rect rect,
179
                         const FrameInfo& frame_info,
180
                         const ImageMetadata& metadata, ThreadPool* pool,
181
                         Image3F* color, ImageF* alpha,
182
0
                         bool* has_interleaved_alpha) {
183
0
  JxlPixelFormat format = {4, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
184
0
  input.get_color_channels_pixel_format(input.opaque, &format);
185
0
  format.align = 0;  // align must be ignored.
186
0
  *has_interleaved_alpha = format.num_channels == 2 || format.num_channels == 4;
187
0
  size_t bits_per_sample =
188
0
      GetBitDepth(frame_info.image_bit_depth, metadata, format);
189
0
  size_t row_offset;
190
0
  auto buffer = GetColorBuffer(input, rect.x0(), rect.y0(), rect.xsize(),
191
0
                               rect.ysize(), &row_offset);
192
0
  if (!buffer) {
193
0
    return JXL_FAILURE("no buffer for color channels given");
194
0
  }
195
0
  size_t color_channels = frame_info.ib_needs_color_transform
196
0
                              ? metadata.color_encoding.Channels()
197
0
                              : 3;
198
0
  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
0
  const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.get());
204
0
  for (size_t c = 0; c < color_channels; ++c) {
205
0
    JXL_RETURN_IF_ERROR(ConvertFromExternalPlaneNoSizeCheck(
206
0
        data, rect.xsize(), rect.ysize(), row_offset, bits_per_sample, format,
207
0
        c, pool, &color->Plane(c)));
208
0
  }
209
0
  if (color_channels == 1) {
210
0
    JXL_RETURN_IF_ERROR(CopyImageTo(color->Plane(0), &color->Plane(1)));
211
0
    JXL_RETURN_IF_ERROR(CopyImageTo(color->Plane(0), &color->Plane(2)));
212
0
  }
213
0
  if (alpha) {
214
0
    if (*has_interleaved_alpha) {
215
0
      JXL_RETURN_IF_ERROR(ConvertFromExternalPlaneNoSizeCheck(
216
0
          data, rect.xsize(), rect.ysize(), row_offset, bits_per_sample, format,
217
0
          format.num_channels - 1, pool, alpha));
218
0
    } else {
219
      // if alpha is not passed, but it is expected, then assume
220
      // it is all-opaque
221
0
      FillImage(1.0f, alpha);
222
0
    }
223
0
  }
224
0
  return true;
225
0
}
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
0
                         std::vector<ImageF>* extra_channels) {
232
0
  for (size_t ec = 0; ec < metadata.num_extra_channels; ec++) {
233
0
    if (has_interleaved_alpha &&
234
0
        metadata.extra_channel_info[ec].type == ExtraChannel::kAlpha) {
235
      // Skip this alpha channel, but still request additional alpha channels
236
      // if they exist.
237
0
      has_interleaved_alpha = false;
238
0
      continue;
239
0
    }
240
0
    JxlPixelFormat ec_format = {1, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0};
241
0
    input.get_extra_channel_pixel_format(input.opaque, ec, &ec_format);
242
0
    ec_format.num_channels = 1;
243
0
    size_t row_offset;
244
0
    auto buffer =
245
0
        GetExtraChannelBuffer(input, ec, rect.x0(), rect.y0(), rect.xsize(),
246
0
                              rect.ysize(), &row_offset);
247
0
    if (!buffer) {
248
0
      return JXL_FAILURE("no buffer for extra channel given");
249
0
    }
250
0
    size_t bits_per_sample = GetBitDepth(
251
0
        frame_info.image_bit_depth, metadata.extra_channel_info[ec], ec_format);
252
0
    if (!ConvertFromExternalPlaneNoSizeCheck(
253
0
            reinterpret_cast<const uint8_t*>(buffer.get()), rect.xsize(),
254
0
            rect.ysize(), row_offset, bits_per_sample, ec_format, 0, pool,
255
0
            &(*extra_channels)[ec])) {
256
0
      return JXL_FAILURE("Failed to set buffer for extra channel");
257
0
    }
258
0
  }
259
0
  return true;
260
0
}
261
262
void SetProgressiveMode(const CompressParams& cparams,
263
0
                        ProgressiveSplitter* progressive_splitter) {
264
0
  constexpr PassDefinition progressive_passes_dc_vlf_lf_full_ac[] = {
265
0
      {/*num_coefficients=*/2, /*shift=*/0,
266
0
       /*suitable_for_downsampling_of_at_least=*/4},
267
0
      {/*num_coefficients=*/3, /*shift=*/0,
268
0
       /*suitable_for_downsampling_of_at_least=*/2},
269
0
      {/*num_coefficients=*/8, /*shift=*/0,
270
0
       /*suitable_for_downsampling_of_at_least=*/0},
271
0
  };
272
0
  constexpr PassDefinition progressive_passes_dc_quant_ac_full_ac[] = {
273
0
      {/*num_coefficients=*/8, /*shift=*/1,
274
0
       /*suitable_for_downsampling_of_at_least=*/2},
275
0
      {/*num_coefficients=*/8, /*shift=*/0,
276
0
       /*suitable_for_downsampling_of_at_least=*/0},
277
0
  };
278
0
  bool progressive_mode = ApplyOverride(cparams.progressive_mode, false);
279
0
  bool qprogressive_mode = ApplyOverride(cparams.qprogressive_mode, false);
280
0
  if (cparams.custom_progressive_mode) {
281
0
    progressive_splitter->SetProgressiveMode(*cparams.custom_progressive_mode);
282
0
  } else if (qprogressive_mode) {
283
0
    progressive_splitter->SetProgressiveMode(
284
0
        ProgressiveMode{progressive_passes_dc_quant_ac_full_ac});
285
0
  } else if (progressive_mode) {
286
0
    progressive_splitter->SetProgressiveMode(
287
0
        ProgressiveMode{progressive_passes_dc_vlf_lf_full_ac});
288
0
  }
289
0
}
290
291
0
uint64_t FrameFlagsFromParams(const CompressParams& cparams) {
292
0
  uint64_t flags = 0;
293
294
0
  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
0
  if (ApplyOverride(cparams.noise, dist >= kMinButteraugliForNoise) ||
300
0
      cparams.photon_noise_iso > 0 ||
301
0
      cparams.manual_noise.size() == NoiseParams::kNumNoisePoints) {
302
0
    flags |= FrameHeader::kNoise;
303
0
  }
304
305
0
  if (cparams.progressive_dc > 0 && cparams.modular_mode == false) {
306
0
    flags |= FrameHeader::kUseDcFrame;
307
0
  }
308
309
0
  return flags;
310
0
}
311
312
Status LoopFilterFromParams(const CompressParams& cparams, bool streaming_mode,
313
0
                            FrameHeader* JXL_RESTRICT frame_header) {
314
0
  LoopFilter* loop_filter = &frame_header->loop_filter;
315
316
  // Gaborish defaults to enabled in Hare or slower.
317
0
  loop_filter->gab = ApplyOverride(
318
0
      cparams.gaborish, cparams.speed_tier <= SpeedTier::kHare &&
319
0
                            frame_header->encoding == FrameEncoding::kVarDCT &&
320
0
                            cparams.decoding_speed_tier < 4 &&
321
0
                            cparams.butteraugli_distance > 0.5f &&
322
0
                            !cparams.disable_perceptual_optimizations);
323
324
0
  if (cparams.epf != -1) {
325
0
    loop_filter->epf_iters = cparams.epf;
326
0
  } else if (cparams.disable_perceptual_optimizations) {
327
0
    loop_filter->epf_iters = 0;
328
0
    return true;
329
0
  } else {
330
0
    if (frame_header->encoding == FrameEncoding::kModular) {
331
0
      loop_filter->epf_iters = 0;
332
0
    } else {
333
0
      constexpr float kThresholds[3] = {0.7, 1.5, 4.0};
334
0
      loop_filter->epf_iters = 0;
335
0
      if (cparams.decoding_speed_tier < 3) {
336
0
        for (size_t i = cparams.decoding_speed_tier == 2 ? 1 : 0; i < 3; i++) {
337
0
          if (cparams.butteraugli_distance >= kThresholds[i]) {
338
0
            loop_filter->epf_iters++;
339
0
          }
340
0
        }
341
0
      }
342
0
    }
343
0
  }
344
  // Strength of EPF in modular mode.
345
0
  if (frame_header->encoding == FrameEncoding::kModular &&
346
0
      !cparams.IsLossless()) {
347
    // TODO(veluca): this formula is nonsense.
348
0
    loop_filter->epf_sigma_for_modular =
349
0
        std::max(cparams.butteraugli_distance, 1.0f);
350
0
  }
351
0
  if (frame_header->encoding == FrameEncoding::kModular &&
352
0
      cparams.lossy_palette) {
353
0
    loop_filter->epf_sigma_for_modular = 1.0f;
354
0
  }
355
356
0
  return true;
357
0
}
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
0
                       FrameHeader* JXL_RESTRICT frame_header) {
365
0
  frame_header->nonserialized_is_preview = frame_info.is_preview;
366
0
  frame_header->is_last = frame_info.is_last;
367
0
  frame_header->save_before_color_transform =
368
0
      frame_info.save_before_color_transform;
369
0
  frame_header->frame_type = frame_info.frame_type;
370
0
  frame_header->name = frame_info.name;
371
372
0
  JXL_RETURN_IF_ERROR(progressive_splitter.InitPasses(&frame_header->passes));
373
374
0
  if (cparams.modular_mode) {
375
0
    frame_header->encoding = FrameEncoding::kModular;
376
0
    frame_header->group_size_shift = GetGroupSizeShift(xsize, ysize, cparams);
377
0
  }
378
379
0
  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
0
  } else {
389
0
    frame_header->color_transform = cparams.color_transform;
390
0
    if (!cparams.modular_mode &&
391
0
        (frame_header->chroma_subsampling.MaxHShift() != 0 ||
392
0
         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
0
  }
398
399
0
  if (frame_header->color_transform != ColorTransform::kYCbCr &&
400
0
      (frame_header->chroma_subsampling.MaxHShift() != 0 ||
401
0
       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
0
  frame_header->flags = FrameFlagsFromParams(cparams);
408
  // Non-photon noise is not supported in the Modular encoder for now.
409
0
  if (frame_header->encoding != FrameEncoding::kVarDCT &&
410
0
      cparams.photon_noise_iso == 0 && cparams.manual_noise.empty()) {
411
0
    frame_header->UpdateFlag(false, FrameHeader::Flags::kNoise);
412
0
  }
413
414
0
  JXL_RETURN_IF_ERROR(
415
0
      LoopFilterFromParams(cparams, streaming_mode, frame_header));
416
417
0
  frame_header->dc_level = frame_info.dc_level;
418
0
  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
0
  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
0
  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
0
  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
0
  if (frame_info.frame_type != FrameType::kDCFrame) {
437
0
    frame_header->frame_origin = frame_info.origin;
438
0
    size_t ups = 1;
439
0
    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
0
    frame_header->frame_size.xsize = xsize * ups;
450
0
    frame_header->frame_size.ysize = ysize * ups;
451
0
    if (frame_info.origin.x0 != 0 || frame_info.origin.y0 != 0 ||
452
0
        frame_header->frame_size.xsize != frame_header->default_xsize() ||
453
0
        frame_header->frame_size.ysize != frame_header->default_ysize()) {
454
0
      frame_header->custom_size_or_origin = true;
455
0
    }
456
0
  }
457
  // Upsampling.
458
0
  frame_header->upsampling = cparams.resampling;
459
0
  const std::vector<ExtraChannelInfo>& extra_channels =
460
0
      frame_header->nonserialized_metadata->m.extra_channel_info;
461
0
  frame_header->extra_channel_upsampling.clear();
462
0
  frame_header->extra_channel_upsampling.resize(extra_channels.size(),
463
0
                                                cparams.ec_resampling);
464
0
  frame_header->save_as_reference = frame_info.save_as_reference;
465
466
  // Set blending-related information.
467
0
  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
0
    size_t index = 0;
472
0
    if (frame_info.alpha_channel == -1) {
473
0
      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
0
    } 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
0
    frame_header->blending_info.alpha_channel = index;
486
0
    frame_header->blending_info.mode =
487
0
        frame_info.blend ? frame_info.blendmode : BlendMode::kReplace;
488
0
    frame_header->blending_info.source = frame_info.source;
489
0
    frame_header->blending_info.clamp = frame_info.clamp;
490
0
    const auto& extra_channel_info = frame_info.extra_channel_blending_info;
491
0
    for (size_t i = 0; i < extra_channels.size(); i++) {
492
0
      if (i < extra_channel_info.size()) {
493
0
        frame_header->extra_channel_blending_info[i] = extra_channel_info[i];
494
0
      } else {
495
0
        frame_header->extra_channel_blending_info[i].alpha_channel = index;
496
0
        BlendMode default_blend = frame_info.blendmode;
497
0
        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
0
        frame_header->extra_channel_blending_info[i].mode =
502
0
            frame_info.blend ? default_blend : BlendMode::kReplace;
503
0
        frame_header->extra_channel_blending_info[i].source = 1;
504
0
      }
505
0
    }
506
0
  }
507
508
0
  frame_header->animation_frame.duration = frame_info.duration;
509
0
  frame_header->animation_frame.timecode = frame_info.timecode;
510
511
0
  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
0
  return true;
524
0
}
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
0
void SimplifyInvisible(Image3F* image, const ImageF& alpha, bool lossless) {
537
0
  for (size_t c = 0; c < 3; ++c) {
538
0
    for (size_t y = 0; y < image->ysize(); ++y) {
539
0
      float* JXL_RESTRICT row = image->PlaneRow(c, y);
540
0
      const float* JXL_RESTRICT prow =
541
0
          (y > 0 ? image->PlaneRow(c, y - 1) : nullptr);
542
0
      const float* JXL_RESTRICT nrow =
543
0
          (y + 1 < image->ysize() ? image->PlaneRow(c, y + 1) : nullptr);
544
0
      const float* JXL_RESTRICT a = alpha.Row(y);
545
0
      const float* JXL_RESTRICT pa = (y > 0 ? alpha.Row(y - 1) : nullptr);
546
0
      const float* JXL_RESTRICT na =
547
0
          (y + 1 < image->ysize() ? alpha.Row(y + 1) : nullptr);
548
0
      for (size_t x = 0; x < image->xsize(); ++x) {
549
0
        if (a[x] == 0) {
550
0
          if (lossless) {
551
0
            row[x] = 0;
552
0
            continue;
553
0
          }
554
0
          float d = 0.f;
555
0
          row[x] = 0;
556
0
          if (x > 0) {
557
0
            row[x] += row[x - 1];
558
0
            d++;
559
0
            if (a[x - 1] > 0.f) {
560
0
              row[x] += row[x - 1];
561
0
              d++;
562
0
            }
563
0
          }
564
0
          if (x + 1 < image->xsize()) {
565
0
            if (y > 0) {
566
0
              row[x] += prow[x + 1];
567
0
              d++;
568
0
            }
569
0
            if (a[x + 1] > 0.f) {
570
0
              row[x] += 2.f * row[x + 1];
571
0
              d += 2.f;
572
0
            }
573
0
            if (y > 0 && pa[x + 1] > 0.f) {
574
0
              row[x] += 2.f * prow[x + 1];
575
0
              d += 2.f;
576
0
            }
577
0
            if (y + 1 < image->ysize() && na[x + 1] > 0.f) {
578
0
              row[x] += 2.f * nrow[x + 1];
579
0
              d += 2.f;
580
0
            }
581
0
          }
582
0
          if (y > 0 && pa[x] > 0.f) {
583
0
            row[x] += 2.f * prow[x];
584
0
            d += 2.f;
585
0
          }
586
0
          if (y + 1 < image->ysize() && na[x] > 0.f) {
587
0
            row[x] += 2.f * nrow[x];
588
0
            d += 2.f;
589
0
          }
590
0
          if (d > 1.f) row[x] /= d;
591
0
        }
592
0
      }
593
0
    }
594
0
  }
595
0
}
596
597
struct PixelStatsForChromacityAdjustment {
598
  float dx = 0;
599
  float db = 0;
600
  float exposed_blue = 0;
601
0
  static float CalcPlane(const ImageF* JXL_RESTRICT plane, const Rect& rect) {
602
0
    float xmax = 0;
603
0
    float ymax = 0;
604
0
    for (size_t ty = 1; ty < rect.ysize(); ++ty) {
605
0
      for (size_t tx = 1; tx < rect.xsize(); ++tx) {
606
0
        float cur = rect.Row(plane, ty)[tx];
607
0
        float prev_row = rect.Row(plane, ty - 1)[tx];
608
0
        float prev = rect.Row(plane, ty)[tx - 1];
609
0
        xmax = std::max(xmax, std::abs(cur - prev));
610
0
        ymax = std::max(ymax, std::abs(cur - prev_row));
611
0
      }
612
0
    }
613
0
    return std::max(xmax, ymax);
614
0
  }
615
  void CalcExposedBlue(const ImageF* JXL_RESTRICT plane_y,
616
0
                       const ImageF* JXL_RESTRICT plane_b, const Rect& rect) {
617
0
    float eb = 0;
618
0
    float xmax = 0;
619
0
    float ymax = 0;
620
0
    for (size_t ty = 1; ty < rect.ysize(); ++ty) {
621
0
      for (size_t tx = 1; tx < rect.xsize(); ++tx) {
622
0
        float cur_y = rect.Row(plane_y, ty)[tx];
623
0
        float cur_b = rect.Row(plane_b, ty)[tx];
624
0
        float exposed_b = cur_b - cur_y * 1.2;
625
0
        float diff_b = cur_b - cur_y;
626
0
        float prev_row = rect.Row(plane_b, ty - 1)[tx];
627
0
        float prev = rect.Row(plane_b, ty)[tx - 1];
628
0
        float diff_prev_row = prev_row - rect.Row(plane_y, ty - 1)[tx];
629
0
        float diff_prev = prev - rect.Row(plane_y, ty)[tx - 1];
630
0
        xmax = std::max(xmax, std::abs(diff_b - diff_prev));
631
0
        ymax = std::max(ymax, std::abs(diff_b - diff_prev_row));
632
0
        if (exposed_b >= 0) {
633
0
          exposed_b *= std::abs(cur_b - prev) + std::abs(cur_b - prev_row);
634
0
          eb = std::max(eb, exposed_b);
635
0
        }
636
0
      }
637
0
    }
638
0
    exposed_blue = eb;
639
0
    db = std::max(xmax, ymax);
640
0
  }
641
0
  void Calc(const Image3F* JXL_RESTRICT opsin, const Rect& rect) {
642
0
    dx = CalcPlane(&opsin->Plane(0), rect);
643
0
    CalcExposedBlue(&opsin->Plane(1), &opsin->Plane(2), rect);
644
0
  }
645
0
  int HowMuchIsXChannelPixelized() const {
646
0
    if (dx >= 0.026) {
647
0
      return 3;
648
0
    }
649
0
    if (dx >= 0.022) {
650
0
      return 2;
651
0
    }
652
0
    if (dx >= 0.015) {
653
0
      return 1;
654
0
    }
655
0
    return 0;
656
0
  }
657
0
  int HowMuchIsBChannelPixelized() const {
658
0
    int add = exposed_blue >= 0.13 ? 1 : 0;
659
0
    if (db > 0.38) {
660
0
      return 2 + add;
661
0
    }
662
0
    if (db > 0.33) {
663
0
      return 1 + add;
664
0
    }
665
0
    if (db > 0.28) {
666
0
      return add;
667
0
    }
668
0
    return 0;
669
0
  }
670
};
671
672
void ComputeChromacityAdjustments(const CompressParams& cparams,
673
                                  const Image3F& opsin, const Rect& rect,
674
0
                                  FrameHeader* frame_header) {
675
0
  if (frame_header->encoding != FrameEncoding::kVarDCT ||
676
0
      cparams.max_error_mode) {
677
0
    return;
678
0
  }
679
  // 1) Distance based approach for chromacity adjustment:
680
0
  float x_qm_scale_steps[3] = {2.5f, 5.5f, 9.5f};
681
0
  frame_header->x_qm_scale = 3;
682
0
  for (float x_qm_scale_step : x_qm_scale_steps) {
683
0
    if (cparams.original_butteraugli_distance > x_qm_scale_step) {
684
0
      frame_header->x_qm_scale++;
685
0
    }
686
0
  }
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
0
  PixelStatsForChromacityAdjustment pixel_stats;
691
0
  if (cparams.speed_tier <= SpeedTier::kSquirrel) {
692
0
    pixel_stats.Calc(&opsin, rect);
693
0
  }
694
  // For X take the most severe adjustment.
695
0
  frame_header->x_qm_scale = std::max<int>(
696
0
      frame_header->x_qm_scale, 2 + pixel_stats.HowMuchIsXChannelPixelized());
697
  // B only adjusted by pixel-based approach.
698
0
  frame_header->b_qm_scale = 2 + pixel_stats.HowMuchIsBChannelPixelized();
699
0
}
700
701
void ComputeNoiseParams(const CompressParams& cparams, bool streaming_mode,
702
                        bool color_is_jpeg, const Image3F& opsin,
703
                        const FrameDimensions& frame_dim,
704
0
                        FrameHeader* frame_header, NoiseParams* noise_params) {
705
0
  if (frame_header->frame_type == FrameType::kDCFrame) {
706
0
    frame_header->flags &= ~FrameHeader::kNoise;
707
0
    return;
708
0
  }
709
0
  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
0
  } 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
0
  } else if (frame_header->encoding == FrameEncoding::kVarDCT &&
718
0
             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
0
}
746
747
Status DownsampleColorChannels(const CompressParams& cparams,
748
                               const FrameHeader& frame_header,
749
0
                               bool color_is_jpeg, Image3F* opsin) {
750
0
  if (color_is_jpeg || frame_header.upsampling == 1 ||
751
0
      cparams.already_downsampled) {
752
0
    return true;
753
0
  }
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
0
                                 AuxOut* aux_out) {
1151
0
  JXL_ENSURE((rect.xsize() % kBlockDim) == 0 &&
1152
0
             (rect.ysize() % kBlockDim) == 0);
1153
0
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
1154
  // Save pre-Gaborish opsin for AR control field heuristics computation.
1155
0
  Image3F orig_opsin;
1156
0
  JXL_ASSIGN_OR_RETURN(
1157
0
      orig_opsin, Image3F::Create(memory_manager, rect.xsize(), rect.ysize()));
1158
0
  JXL_RETURN_IF_ERROR(CopyImageTo(rect, *opsin, Rect(orig_opsin), &orig_opsin));
1159
0
  JXL_RETURN_IF_ERROR(orig_opsin.ShrinkTo(enc_state->shared.frame_dim.xsize,
1160
0
                                          enc_state->shared.frame_dim.ysize));
1161
1162
0
  JXL_RETURN_IF_ERROR(LossyFrameHeuristics(frame_header, enc_state, enc_modular,
1163
0
                                           linear, opsin, rect, cms, pool,
1164
0
                                           aux_out));
1165
1166
0
  JXL_RETURN_IF_ERROR(InitializePassesEncoder(
1167
0
      frame_header, *opsin, rect, cms, pool, enc_state, enc_modular, aux_out));
1168
1169
0
  JXL_RETURN_IF_ERROR(
1170
0
      ComputeARHeuristics(frame_header, enc_state, orig_opsin, rect, pool));
1171
1172
0
  JXL_RETURN_IF_ERROR(ComputeACMetadata(pool, enc_state, enc_modular));
1173
1174
0
  return true;
1175
0
}
1176
1177
Status ComputeAllCoeffOrders(PassesEncoderState& enc_state,
1178
0
                             const FrameDimensions& frame_dim) {
1179
0
  auto used_orders_info = ComputeUsedOrders(
1180
0
      enc_state.cparams.speed_tier, enc_state.shared.ac_strategy,
1181
0
      Rect(enc_state.shared.raw_quant_field));
1182
0
  enc_state.used_orders.resize(enc_state.progressive_splitter.GetNumPasses());
1183
0
  for (size_t i = 0; i < enc_state.progressive_splitter.GetNumPasses(); i++) {
1184
0
    JXL_RETURN_IF_ERROR(ComputeCoeffOrder(
1185
0
        enc_state.cparams.speed_tier, *enc_state.coeffs[i],
1186
0
        enc_state.shared.ac_strategy, frame_dim, enc_state.used_orders[i],
1187
0
        enc_state.used_acs, used_orders_info.first, used_orders_info.second,
1188
0
        &enc_state.shared.coeff_orders[i * enc_state.shared.coeff_order_size]));
1189
0
  }
1190
0
  enc_state.used_acs |= used_orders_info.first;
1191
0
  return true;
1192
0
}
1193
1194
// Working area for TokenizeCoefficients (per-group!)
1195
struct EncCache {
1196
  // Allocates memory when first called.
1197
0
  Status InitOnce(JxlMemoryManager* memory_manager) {
1198
0
    if (num_nzeroes.xsize() == 0) {
1199
0
      JXL_ASSIGN_OR_RETURN(num_nzeroes,
1200
0
                           Image3I::Create(memory_manager, kGroupDimInBlocks,
1201
0
                                           kGroupDimInBlocks));
1202
0
    }
1203
0
    return true;
1204
0
  }
1205
  // TokenizeCoefficients
1206
  Image3I num_nzeroes;
1207
};
1208
1209
Status TokenizeAllCoefficients(const FrameHeader& frame_header,
1210
                               ThreadPool* pool,
1211
0
                               PassesEncoderState* enc_state) {
1212
0
  PassesSharedState& shared = enc_state->shared;
1213
0
  std::vector<EncCache> group_caches;
1214
0
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
1215
0
  const auto tokenize_group_init = [&](const size_t num_threads) -> Status {
1216
0
    group_caches.resize(num_threads);
1217
0
    return true;
1218
0
  };
1219
0
  const auto tokenize_group = [&](const uint32_t group_index,
1220
0
                                  const size_t thread) -> Status {
1221
    // Tokenize coefficients.
1222
0
    const Rect rect = shared.frame_dim.BlockGroupRect(group_index);
1223
0
    for (size_t idx_pass = 0; idx_pass < enc_state->passes.size(); idx_pass++) {
1224
0
      JXL_ENSURE(enc_state->coeffs[idx_pass]->Type() == ACType::k32);
1225
0
      const int32_t* JXL_RESTRICT ac_rows[3] = {
1226
0
          enc_state->coeffs[idx_pass]->PlaneRow(0, group_index, 0).ptr32,
1227
0
          enc_state->coeffs[idx_pass]->PlaneRow(1, group_index, 0).ptr32,
1228
0
          enc_state->coeffs[idx_pass]->PlaneRow(2, group_index, 0).ptr32,
1229
0
      };
1230
      // Ensure group cache is initialized.
1231
0
      JXL_RETURN_IF_ERROR(group_caches[thread].InitOnce(memory_manager));
1232
0
      JXL_RETURN_IF_ERROR(TokenizeCoefficients(
1233
0
          &shared.coeff_orders[idx_pass * shared.coeff_order_size], rect,
1234
0
          ac_rows, shared.ac_strategy, frame_header.chroma_subsampling,
1235
0
          &group_caches[thread].num_nzeroes,
1236
0
          &enc_state->passes[idx_pass].ac_tokens[group_index], shared.quant_dc,
1237
0
          shared.raw_quant_field, shared.block_ctx_map));
1238
0
    }
1239
0
    return true;
1240
0
  };
1241
0
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, shared.frame_dim.num_groups,
1242
0
                                tokenize_group_init, tokenize_group,
1243
0
                                "TokenizeGroup"));
1244
0
  return true;
1245
0
}
1246
1247
Status EncodeGlobalDCInfo(const PassesSharedState& shared, BitWriter* writer,
1248
0
                          AuxOut* aux_out) {
1249
  // Encode quantizer DC and global scale.
1250
0
  QuantizerParams params = shared.quantizer.GetParams();
1251
0
  JXL_RETURN_IF_ERROR(
1252
0
      WriteQuantizerParams(params, writer, LayerType::Quant, aux_out));
1253
0
  JXL_RETURN_IF_ERROR(EncodeBlockCtxMap(shared.block_ctx_map, writer, aux_out));
1254
0
  JXL_RETURN_IF_ERROR(ColorCorrelationEncodeDC(shared.cmap.base(), writer,
1255
0
                                               LayerType::Dc, aux_out));
1256
0
  return true;
1257
0
}
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
0
                          ModularFrameEncoder* enc_modular, AuxOut* aux_out) {
1264
0
  PassesSharedState& shared = enc_state->shared;
1265
0
  JxlMemoryManager* memory_manager = enc_state->memory_manager();
1266
0
  JXL_RETURN_IF_ERROR(DequantMatricesEncode(memory_manager, shared.matrices,
1267
0
                                            writer, LayerType::Quant, aux_out,
1268
0
                                            enc_modular));
1269
0
  size_t num_histo_bits = CeilLog2Nonzero(shared.frame_dim.num_groups);
1270
0
  if (!enc_state->streaming_mode && num_histo_bits != 0) {
1271
0
    JXL_RETURN_IF_ERROR(
1272
0
        writer->WithMaxBits(num_histo_bits, LayerType::Ac, aux_out, [&] {
1273
0
          writer->Write(num_histo_bits, shared.num_histograms - 1);
1274
0
          return true;
1275
0
        }));
1276
0
  }
1277
1278
0
  for (size_t i = 0; i < enc_state->progressive_splitter.GetNumPasses(); i++) {
1279
    // Encode coefficient orders.
1280
0
    if (!enc_state->streaming_mode) {
1281
0
      size_t order_bits = 0;
1282
0
      JXL_RETURN_IF_ERROR(U32Coder::CanEncode(
1283
0
          kOrderEnc, enc_state->used_orders[i], &order_bits));
1284
0
      JXL_RETURN_IF_ERROR(
1285
0
          writer->WithMaxBits(order_bits, LayerType::Order, aux_out, [&] {
1286
0
            return U32Coder::Write(kOrderEnc, enc_state->used_orders[i],
1287
0
                                   writer);
1288
0
          }));
1289
0
      JXL_RETURN_IF_ERROR(
1290
0
          EncodeCoeffOrders(enc_state->used_orders[i],
1291
0
                            &shared.coeff_orders[i * shared.coeff_order_size],
1292
0
                            writer, LayerType::Order, aux_out));
1293
0
    }
1294
1295
    // Encode histograms.
1296
0
    HistogramParams hist_params(enc_state->cparams.speed_tier,
1297
0
                                shared.block_ctx_map.NumACContexts());
1298
0
    if (enc_state->cparams.speed_tier > SpeedTier::kTortoise) {
1299
0
      hist_params.lz77_method = HistogramParams::LZ77Method::kNone;
1300
0
    }
1301
0
    if (enc_state->cparams.decoding_speed_tier >= 1) {
1302
0
      hist_params.max_histograms = 6;
1303
0
    }
1304
0
    size_t num_histogram_groups = shared.num_histograms;
1305
0
    if (enc_state->streaming_mode) {
1306
0
      size_t prev_num_histograms =
1307
0
          enc_state->passes[i].codes.encoding_info.size();
1308
0
      if (enc_state->initialize_global_state) {
1309
0
        prev_num_histograms += kNumFixedHistograms;
1310
0
        hist_params.add_fixed_histograms = true;
1311
0
      }
1312
0
      size_t remaining_histograms = kClustersLimit - prev_num_histograms;
1313
      // Heuristic to assign budget of new histograms to DC groups.
1314
      // TODO(szabadka) Tune this together with the DC group ordering.
1315
0
      size_t max_histograms = remaining_histograms < 20
1316
0
                                  ? std::min<size_t>(remaining_histograms, 4)
1317
0
                                  : remaining_histograms / 4;
1318
0
      hist_params.max_histograms =
1319
0
          std::min(max_histograms, hist_params.max_histograms);
1320
0
      num_histogram_groups = 1;
1321
0
    }
1322
0
    hist_params.streaming_mode = enc_state->streaming_mode;
1323
0
    hist_params.initialize_global_state = enc_state->initialize_global_state;
1324
0
    JXL_ASSIGN_OR_RETURN(
1325
0
        size_t cost,
1326
0
        BuildAndEncodeHistograms(
1327
0
            memory_manager, hist_params,
1328
0
            num_histogram_groups * shared.block_ctx_map.NumACContexts(),
1329
0
            enc_state->passes[i].ac_tokens, &enc_state->passes[i].codes, writer,
1330
0
            LayerType::Ac, aux_out));
1331
0
    (void)cost;
1332
0
  }
1333
1334
0
  return true;
1335
0
}
1336
Status EncodeGroups(const FrameHeader& frame_header,
1337
                    PassesEncoderState* enc_state,
1338
                    ModularFrameEncoder* enc_modular, ThreadPool* pool,
1339
                    std::vector<std::unique_ptr<BitWriter>>* group_codes,
1340
0
                    AuxOut* aux_out) {
1341
0
  const PassesSharedState& shared = enc_state->shared;
1342
0
  JxlMemoryManager* memory_manager = shared.memory_manager;
1343
0
  const FrameDimensions& frame_dim = shared.frame_dim;
1344
0
  const size_t num_groups = frame_dim.num_groups;
1345
0
  const size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
1346
0
  const size_t global_ac_index = frame_dim.num_dc_groups + 1;
1347
0
  const bool is_small_image =
1348
0
      !enc_state->streaming_mode && num_groups == 1 && num_passes == 1;
1349
0
  const size_t num_toc_entries =
1350
0
      is_small_image ? 1
1351
0
                     : AcGroupIndex(0, 0, num_groups, frame_dim.num_dc_groups) +
1352
0
                           num_groups * num_passes;
1353
0
  JXL_ENSURE(group_codes->empty());
1354
0
  group_codes->reserve(num_toc_entries);
1355
0
  for (size_t i = 0; i < num_toc_entries; ++i) {
1356
0
    group_codes->emplace_back(jxl::make_unique<BitWriter>(memory_manager));
1357
0
  }
1358
1359
0
  const auto get_output = [&](const size_t index) -> BitWriter* {
1360
0
    return (*group_codes)[is_small_image ? 0 : index].get();
1361
0
  };
1362
0
  auto ac_group_code = [&](size_t pass, size_t group) {
1363
0
    return get_output(AcGroupIndex(pass, group, frame_dim.num_groups,
1364
0
                                   frame_dim.num_dc_groups));
1365
0
  };
1366
1367
0
  if (enc_state->initialize_global_state) {
1368
0
    if (frame_header.flags & FrameHeader::kPatches) {
1369
0
      JXL_RETURN_IF_ERROR(PatchDictionaryEncoder::Encode(
1370
0
          shared.image_features.patches, get_output(0), LayerType::Dictionary,
1371
0
          aux_out));
1372
0
    }
1373
0
    if (frame_header.flags & FrameHeader::kSplines) {
1374
0
      JXL_RETURN_IF_ERROR(EncodeSplines(shared.image_features.splines,
1375
0
                                        get_output(0), LayerType::Splines,
1376
0
                                        HistogramParams(), aux_out));
1377
0
    }
1378
0
    if (frame_header.flags & FrameHeader::kNoise) {
1379
0
      JXL_RETURN_IF_ERROR(EncodeNoise(shared.image_features.noise_params,
1380
0
                                      get_output(0), LayerType::Noise,
1381
0
                                      aux_out));
1382
0
    }
1383
1384
0
    JXL_RETURN_IF_ERROR(DequantMatricesEncodeDC(shared.matrices, get_output(0),
1385
0
                                                LayerType::Quant, aux_out));
1386
0
    if (frame_header.encoding == FrameEncoding::kVarDCT) {
1387
0
      JXL_RETURN_IF_ERROR(EncodeGlobalDCInfo(shared, get_output(0), aux_out));
1388
0
    }
1389
0
    JXL_RETURN_IF_ERROR(enc_modular->EncodeGlobalInfo(enc_state->streaming_mode,
1390
0
                                                      get_output(0), aux_out));
1391
0
    JXL_RETURN_IF_ERROR(enc_modular->EncodeStream(get_output(0), aux_out,
1392
0
                                                  LayerType::ModularGlobal,
1393
0
                                                  ModularStreamId::Global()));
1394
0
  }
1395
1396
0
  std::vector<std::unique_ptr<AuxOut>> aux_outs;
1397
0
  auto resize_aux_outs = [&aux_outs,
1398
0
                          aux_out](const size_t num_threads) -> Status {
1399
0
    if (aux_out == nullptr) {
1400
0
      aux_outs.resize(num_threads);
1401
0
    } else {
1402
0
      while (aux_outs.size() > num_threads) {
1403
0
        aux_out->Assimilate(*aux_outs.back());
1404
0
        aux_outs.pop_back();
1405
0
      }
1406
0
      while (num_threads > aux_outs.size()) {
1407
0
        aux_outs.emplace_back(jxl::make_unique<AuxOut>());
1408
0
      }
1409
0
    }
1410
0
    return true;
1411
0
  };
1412
1413
0
  const auto process_dc_group = [&](const uint32_t group_index,
1414
0
                                    const size_t thread) -> Status {
1415
0
    AuxOut* my_aux_out = aux_outs[thread].get();
1416
0
    uint32_t input_index = enc_state->streaming_mode ? 0 : group_index;
1417
0
    BitWriter* output = get_output(input_index + 1);
1418
0
    if (frame_header.encoding == FrameEncoding::kVarDCT &&
1419
0
        !(frame_header.flags & FrameHeader::kUseDcFrame)) {
1420
0
      JXL_RETURN_IF_ERROR(
1421
0
          output->WithMaxBits(2, LayerType::Dc, my_aux_out, [&] {
1422
0
            output->Write(2, enc_modular->extra_dc_precision[group_index]);
1423
0
            return true;
1424
0
          }));
1425
0
      JXL_RETURN_IF_ERROR(
1426
0
          enc_modular->EncodeStream(output, my_aux_out, LayerType::Dc,
1427
0
                                    ModularStreamId::VarDCTDC(group_index)));
1428
0
    }
1429
0
    JXL_RETURN_IF_ERROR(
1430
0
        enc_modular->EncodeStream(output, my_aux_out, LayerType::ModularDcGroup,
1431
0
                                  ModularStreamId::ModularDC(group_index)));
1432
0
    if (frame_header.encoding == FrameEncoding::kVarDCT) {
1433
0
      const Rect& rect = enc_state->shared.frame_dim.DCGroupRect(input_index);
1434
0
      size_t nb_bits = CeilLog2Nonzero(rect.xsize() * rect.ysize());
1435
0
      if (nb_bits != 0) {
1436
0
        JXL_RETURN_IF_ERROR(output->WithMaxBits(
1437
0
            nb_bits, LayerType::ControlFields, my_aux_out, [&] {
1438
0
              output->Write(nb_bits,
1439
0
                            enc_modular->ac_metadata_size[group_index] - 1);
1440
0
              return true;
1441
0
            }));
1442
0
      }
1443
0
      JXL_RETURN_IF_ERROR(enc_modular->EncodeStream(
1444
0
          output, my_aux_out, LayerType::ControlFields,
1445
0
          ModularStreamId::ACMetadata(group_index)));
1446
0
    }
1447
0
    return true;
1448
0
  };
1449
0
  if (enc_state->streaming_mode) {
1450
0
    JXL_ENSURE(frame_dim.num_dc_groups == 1);
1451
0
    JXL_RETURN_IF_ERROR(resize_aux_outs(1));
1452
0
    JXL_RETURN_IF_ERROR(process_dc_group(enc_state->dc_group_index, 0));
1453
0
  } else {
1454
0
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, frame_dim.num_dc_groups,
1455
0
                                  resize_aux_outs, process_dc_group,
1456
0
                                  "EncodeDCGroup"));
1457
0
  }
1458
0
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
1459
0
    JXL_RETURN_IF_ERROR(EncodeGlobalACInfo(
1460
0
        enc_state, get_output(global_ac_index), enc_modular, aux_out));
1461
0
  }
1462
1463
0
  const auto process_group = [&](const uint32_t group_index,
1464
0
                                 const size_t thread) -> Status {
1465
0
    AuxOut* my_aux_out = aux_outs[thread].get();
1466
1467
0
    size_t ac_group_id =
1468
0
        enc_state->streaming_mode
1469
0
            ? enc_modular->ComputeStreamingAbsoluteAcGroupId(
1470
0
                  enc_state->dc_group_index, group_index, shared.frame_dim)
1471
0
            : group_index;
1472
1473
0
    for (size_t i = 0; i < num_passes; i++) {
1474
0
      JXL_DEBUG_V(2, "Encoding AC group %u [abs %" PRIuS "] pass %" PRIuS,
1475
0
                  group_index, ac_group_id, i);
1476
0
      if (frame_header.encoding == FrameEncoding::kVarDCT) {
1477
0
        JXL_RETURN_IF_ERROR(EncodeGroupTokenizedCoefficients(
1478
0
            group_index, i, enc_state->histogram_idx[group_index], *enc_state,
1479
0
            ac_group_code(i, group_index), my_aux_out));
1480
0
      }
1481
      // Write all modular encoded data (color?, alpha, depth, extra channels)
1482
0
      JXL_RETURN_IF_ERROR(enc_modular->EncodeStream(
1483
0
          ac_group_code(i, group_index), my_aux_out, LayerType::ModularAcGroup,
1484
0
          ModularStreamId::ModularAC(ac_group_id, i)));
1485
0
      JXL_DEBUG_V(2,
1486
0
                  "AC group %u [abs %" PRIuS "] pass %" PRIuS
1487
0
                  " encoded size is %" PRIuS " bits",
1488
0
                  group_index, ac_group_id, i,
1489
0
                  ac_group_code(i, group_index)->BitsWritten());
1490
0
    }
1491
0
    return true;
1492
0
  };
1493
0
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, num_groups, resize_aux_outs,
1494
0
                                process_group, "EncodeGroupCoefficients"));
1495
  // Resizing aux_outs to 0 also Assimilates the array.
1496
0
  static_cast<void>(resize_aux_outs(0));
1497
1498
0
  for (std::unique_ptr<BitWriter>& bw : *group_codes) {
1499
0
    JXL_RETURN_IF_ERROR(bw->WithMaxBits(8, LayerType::Ac, aux_out, [&] {
1500
0
      bw->ZeroPadToByte();  // end of group.
1501
0
      return true;
1502
0
    }));
1503
0
  }
1504
0
  return true;
1505
0
}
1506
1507
Status ComputeEncodingData(
1508
    const CompressParams& cparams, const FrameInfo& frame_info,
1509
    const CodecMetadata* metadata, JxlEncoderChunkedFrameAdapter& frame_data,
1510
    const jpeg::JPEGData* jpeg_data, size_t x0, size_t y0, size_t xsize,
1511
    size_t ysize, const JxlCmsInterface& cms, ThreadPool* pool,
1512
    FrameHeader& mutable_frame_header, ModularFrameEncoder& enc_modular,
1513
    PassesEncoderState& enc_state,
1514
0
    std::vector<std::unique_ptr<BitWriter>>* group_codes, AuxOut* aux_out) {
1515
0
  JXL_ENSURE(x0 + xsize <= frame_data.xsize);
1516
0
  JXL_ENSURE(y0 + ysize <= frame_data.ysize);
1517
0
  JxlMemoryManager* memory_manager = enc_state.memory_manager();
1518
0
  const FrameHeader& frame_header = mutable_frame_header;
1519
0
  PassesSharedState& shared = enc_state.shared;
1520
0
  shared.metadata = metadata;
1521
0
  if (enc_state.streaming_mode) {
1522
0
    shared.frame_dim.Set(
1523
0
        xsize, ysize, frame_header.group_size_shift,
1524
0
        /*max_hshift=*/0, /*max_vshift=*/0,
1525
0
        mutable_frame_header.encoding == FrameEncoding::kModular,
1526
0
        /*upsampling=*/1);
1527
0
  } else {
1528
0
    shared.frame_dim = frame_header.ToFrameDimensions();
1529
0
  }
1530
1531
0
  shared.image_features.patches.SetShared(&shared.reference_frames);
1532
0
  const FrameDimensions& frame_dim = shared.frame_dim;
1533
0
  JXL_ASSIGN_OR_RETURN(
1534
0
      shared.ac_strategy,
1535
0
      AcStrategyImage::Create(memory_manager, frame_dim.xsize_blocks,
1536
0
                              frame_dim.ysize_blocks));
1537
0
  JXL_ASSIGN_OR_RETURN(shared.raw_quant_field,
1538
0
                       ImageI::Create(memory_manager, frame_dim.xsize_blocks,
1539
0
                                      frame_dim.ysize_blocks));
1540
0
  JXL_ASSIGN_OR_RETURN(shared.epf_sharpness,
1541
0
                       ImageB::Create(memory_manager, frame_dim.xsize_blocks,
1542
0
                                      frame_dim.ysize_blocks));
1543
0
  JXL_ASSIGN_OR_RETURN(
1544
0
      shared.cmap, ColorCorrelationMap::Create(memory_manager, frame_dim.xsize,
1545
0
                                               frame_dim.ysize));
1546
0
  shared.coeff_order_size = kCoeffOrderMaxSize;
1547
0
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
1548
0
    shared.coeff_orders.resize(frame_header.passes.num_passes *
1549
0
                               kCoeffOrderMaxSize);
1550
0
  }
1551
1552
0
  JXL_ASSIGN_OR_RETURN(shared.quant_dc,
1553
0
                       ImageB::Create(memory_manager, frame_dim.xsize_blocks,
1554
0
                                      frame_dim.ysize_blocks));
1555
0
  JXL_ASSIGN_OR_RETURN(shared.dc_storage,
1556
0
                       Image3F::Create(memory_manager, frame_dim.xsize_blocks,
1557
0
                                       frame_dim.ysize_blocks));
1558
0
  shared.dc = &shared.dc_storage;
1559
1560
0
  const size_t num_extra_channels = metadata->m.num_extra_channels;
1561
0
  const ExtraChannelInfo* alpha_eci = metadata->m.Find(ExtraChannel::kAlpha);
1562
0
  const ExtraChannelInfo* black_eci = metadata->m.Find(ExtraChannel::kBlack);
1563
0
  const size_t alpha_idx = alpha_eci - metadata->m.extra_channel_info.data();
1564
0
  const size_t black_idx = black_eci - metadata->m.extra_channel_info.data();
1565
0
  const ColorEncoding c_enc = metadata->m.color_encoding;
1566
1567
  // Make the image patch bigger than the currently processed group in
1568
  // streaming mode so that we can take into account border pixels around the
1569
  // group when computing inverse Gaborish and adaptive quantization map.
1570
0
  int max_border = enc_state.streaming_mode ? kBlockDim : 0;
1571
0
  Rect frame_rect(0, 0, frame_data.xsize, frame_data.ysize);
1572
0
  Rect frame_area_rect = Rect(x0, y0, xsize, ysize);
1573
0
  Rect patch_rect = frame_area_rect.Extend(max_border, frame_rect);
1574
0
  JXL_ENSURE(patch_rect.IsInside(frame_rect));
1575
1576
  // Allocating a large enough image avoids a copy when padding.
1577
0
  JXL_ASSIGN_OR_RETURN(
1578
0
      Image3F color,
1579
0
      Image3F::Create(memory_manager, RoundUpToBlockDim(patch_rect.xsize()),
1580
0
                      RoundUpToBlockDim(patch_rect.ysize())));
1581
0
  JXL_RETURN_IF_ERROR(color.ShrinkTo(patch_rect.xsize(), patch_rect.ysize()));
1582
0
  std::vector<ImageF> extra_channels(num_extra_channels);
1583
0
  for (auto& extra_channel : extra_channels) {
1584
0
    JXL_ASSIGN_OR_RETURN(
1585
0
        extra_channel,
1586
0
        ImageF::Create(memory_manager, patch_rect.xsize(), patch_rect.ysize()));
1587
0
  }
1588
0
  ImageF* alpha = alpha_eci ? &extra_channels[alpha_idx] : nullptr;
1589
0
  ImageF* black = black_eci ? &extra_channels[black_idx] : nullptr;
1590
0
  bool has_interleaved_alpha = false;
1591
0
  JxlChunkedFrameInputSource input = frame_data.GetInputSource();
1592
0
  if (!jpeg_data) {
1593
0
    JXL_RETURN_IF_ERROR(CopyColorChannels(input, patch_rect, frame_info,
1594
0
                                          metadata->m, pool, &color, alpha,
1595
0
                                          &has_interleaved_alpha));
1596
0
  }
1597
0
  JXL_RETURN_IF_ERROR(CopyExtraChannels(input, patch_rect, frame_info,
1598
0
                                        metadata->m, has_interleaved_alpha,
1599
0
                                        pool, &extra_channels));
1600
1601
0
  enc_state.cparams = cparams;
1602
1603
0
  Image3F linear_storage;
1604
0
  Image3F* linear = nullptr;
1605
1606
0
  if (!jpeg_data) {
1607
0
    if (frame_header.color_transform == ColorTransform::kXYB &&
1608
0
        frame_info.ib_needs_color_transform) {
1609
0
      if (frame_header.encoding == FrameEncoding::kVarDCT &&
1610
0
          cparams.speed_tier <= SpeedTier::kKitten) {
1611
0
        JXL_ASSIGN_OR_RETURN(linear_storage,
1612
0
                             Image3F::Create(memory_manager, patch_rect.xsize(),
1613
0
                                             patch_rect.ysize()));
1614
0
        linear = &linear_storage;
1615
0
      }
1616
0
      JXL_RETURN_IF_ERROR(ToXYB(c_enc, metadata->m.IntensityTarget(), black,
1617
0
                                pool, &color, cms, linear));
1618
0
    } else {
1619
      // Nothing to do.
1620
      // RGB or YCbCr: forward YCbCr is not implemented, this is only used
1621
      // when the input is already in YCbCr If encoding a special DC or
1622
      // reference frame: input is already in XYB.
1623
0
    }
1624
0
    bool lossless = cparams.IsLossless();
1625
0
    if (alpha && !alpha_eci->alpha_associated &&
1626
0
        frame_header.frame_type == FrameType::kRegularFrame &&
1627
0
        !ApplyOverride(cparams.keep_invisible, cparams.IsLossless()) &&
1628
0
        cparams.ec_resampling == cparams.resampling &&
1629
0
        !cparams.disable_perceptual_optimizations) {
1630
      // simplify invisible pixels
1631
0
      SimplifyInvisible(&color, *alpha, lossless);
1632
0
      if (linear) {
1633
0
        SimplifyInvisible(linear, *alpha, lossless);
1634
0
      }
1635
0
    }
1636
0
    JXL_RETURN_IF_ERROR(PadImageToBlockMultipleInPlace(&color));
1637
0
  }
1638
1639
  // Rectangle within color that corresponds to the currently processed group
1640
  // in streaming mode.
1641
0
  Rect group_rect(x0 - patch_rect.x0(), y0 - patch_rect.y0(),
1642
0
                  RoundUpToBlockDim(xsize), RoundUpToBlockDim(ysize));
1643
1644
0
  if (enc_state.initialize_global_state && !jpeg_data) {
1645
0
    ComputeChromacityAdjustments(cparams, color, group_rect,
1646
0
                                 &mutable_frame_header);
1647
0
  }
1648
1649
0
  bool has_jpeg_data = (jpeg_data != nullptr);
1650
0
  ComputeNoiseParams(cparams, enc_state.streaming_mode, has_jpeg_data, color,
1651
0
                     frame_dim, &mutable_frame_header,
1652
0
                     &shared.image_features.noise_params);
1653
1654
0
  JXL_RETURN_IF_ERROR(
1655
0
      DownsampleColorChannels(cparams, frame_header, has_jpeg_data, &color));
1656
1657
0
  if (cparams.ec_resampling != 1 && !cparams.already_downsampled) {
1658
0
    for (ImageF& ec : extra_channels) {
1659
0
      JXL_ASSIGN_OR_RETURN(ec, DownsampleImage(ec, cparams.ec_resampling));
1660
0
    }
1661
0
  }
1662
1663
0
  if (!enc_state.streaming_mode) {
1664
0
    group_rect = Rect(color);
1665
0
  }
1666
1667
0
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
1668
0
    enc_state.passes.resize(enc_state.progressive_splitter.GetNumPasses());
1669
0
    for (PassesEncoderState::PassData& pass : enc_state.passes) {
1670
0
      pass.ac_tokens.resize(shared.frame_dim.num_groups);
1671
0
    }
1672
0
    if (jpeg_data) {
1673
0
      JXL_RETURN_IF_ERROR(ComputeJPEGTranscodingData(
1674
0
          *jpeg_data, frame_header, pool, &enc_modular, &enc_state));
1675
0
    } else {
1676
0
      JXL_RETURN_IF_ERROR(ComputeVarDCTEncodingData(
1677
0
          frame_header, linear, &color, group_rect, cms, pool, &enc_modular,
1678
0
          &enc_state, aux_out));
1679
0
    }
1680
0
    JXL_RETURN_IF_ERROR(ComputeAllCoeffOrders(enc_state, frame_dim));
1681
0
    if (!enc_state.streaming_mode) {
1682
0
      shared.num_histograms = 1;
1683
0
      enc_state.histogram_idx.resize(frame_dim.num_groups);
1684
0
    }
1685
0
    JXL_RETURN_IF_ERROR(
1686
0
        TokenizeAllCoefficients(frame_header, pool, &enc_state));
1687
0
  }
1688
1689
0
  if (cparams.modular_mode || !extra_channels.empty()) {
1690
0
    JXL_RETURN_IF_ERROR(enc_modular.ComputeEncodingData(
1691
0
        frame_header, metadata->m, &color, extra_channels, group_rect,
1692
0
        frame_dim, frame_area_rect, &enc_state, cms, pool, aux_out,
1693
0
        /*do_color=*/cparams.modular_mode));
1694
0
  }
1695
1696
0
  if (!enc_state.streaming_mode) {
1697
    // If checks pass here and CanDoStreamingEncoding returns false
1698
    // a Global MA tree is used.
1699
0
    if (cparams.speed_tier < SpeedTier::kTortoise ||
1700
0
        !cparams.ModularPartIsLossless() || cparams.lossy_palette ||
1701
        // Allow Local trees for progressive lossless.
1702
        // TODO(Jonnyawsom3): Figure out how to allow local trees for
1703
        // extra channels on VarDCT images without failing tests.
1704
0
        (!(cparams.responsive == 1 && cparams.IsLossless()) &&
1705
0
         cparams.buffering < 3) ||
1706
0
        !cparams.custom_fixed_tree.empty()) {
1707
0
      JXL_RETURN_IF_ERROR(enc_modular.ComputeTree(pool));
1708
0
      JXL_RETURN_IF_ERROR(enc_modular.ComputeTokens(pool));
1709
0
    }
1710
0
    mutable_frame_header.UpdateFlag(shared.image_features.patches.HasAny(),
1711
0
                                    FrameHeader::kPatches);
1712
0
    mutable_frame_header.UpdateFlag(shared.image_features.splines.HasAny(),
1713
0
                                    FrameHeader::kSplines);
1714
0
  }
1715
1716
0
  JXL_RETURN_IF_ERROR(EncodeGroups(frame_header, &enc_state, &enc_modular, pool,
1717
0
                                   group_codes, aux_out));
1718
0
  if (enc_state.streaming_mode) {
1719
0
    const size_t group_index = enc_state.dc_group_index;
1720
0
    enc_modular.ClearStreamData(ModularStreamId::VarDCTDC(group_index));
1721
0
    enc_modular.ClearStreamData(ModularStreamId::ACMetadata(group_index));
1722
0
    enc_modular.ClearModularStreamData();
1723
0
  }
1724
0
  return true;
1725
0
}
1726
1727
Status PermuteGroups(const CompressParams& cparams,
1728
                     const FrameDimensions& frame_dim,
1729
                     size_t num_passes, size_t dc_level,
1730
                     std::vector<coeff_order_t>* permutation,
1731
0
                     std::vector<std::unique_ptr<BitWriter>>* group_codes) {
1732
0
  const size_t num_groups = frame_dim.num_groups;
1733
0
  if (!cparams.centerfirst || (num_passes == 1 && num_groups == 1)) {
1734
0
    return true;
1735
0
  }
1736
  // Don't permute global DC/AC or DC.
1737
0
  permutation->resize(frame_dim.num_dc_groups + 2);
1738
0
  std::iota(permutation->begin(), permutation->end(), 0);
1739
0
  std::vector<coeff_order_t> ac_group_order(num_groups);
1740
0
  std::iota(ac_group_order.begin(), ac_group_order.end(), 0);
1741
0
  const size_t group_dim = frame_dim.group_dim;
1742
1743
  // The center of the image is either given by parameters or chosen
1744
  // to be the middle of the image by default if center_x, center_y resp.
1745
  // are not provided.
1746
1747
  // Calculate the coordinate scaling for LF frames.
1748
  // libjxl only implements 2 LF frames, so won't overflow.
1749
0
  const size_t dc_scale = size_t{1} << (3 * dc_level);
1750
  
1751
0
  int64_t imag_cx;
1752
0
  if (cparams.center_x != static_cast<size_t>(-1)) {
1753
0
    imag_cx = cparams.center_x / dc_scale;
1754
0
    JXL_RETURN_IF_ERROR(imag_cx < static_cast<int64_t>(frame_dim.xsize));
1755
0
  } else {
1756
0
    imag_cx = frame_dim.xsize / 2;
1757
0
  }
1758
1759
0
  int64_t imag_cy;
1760
0
  if (cparams.center_y != static_cast<size_t>(-1)) {
1761
0
    imag_cy = cparams.center_y / dc_scale;
1762
0
    JXL_RETURN_IF_ERROR(imag_cy < static_cast<int64_t>(frame_dim.ysize));
1763
0
  } else {
1764
0
    imag_cy = frame_dim.ysize / 2;
1765
0
  }
1766
1767
  // The center of the group containing the center of the image.
1768
0
  int64_t cx = (imag_cx / group_dim) * group_dim + group_dim / 2;
1769
0
  int64_t cy = (imag_cy / group_dim) * group_dim + group_dim / 2;
1770
  // This identifies in what area of the central group the center of the image
1771
  // lies in.
1772
0
  double direction = -std::atan2(imag_cy - cy, imag_cx - cx);
1773
  // This identifies the side of the central group the center of the image
1774
  // lies closest to. This can take values 0, 1, 2, 3 corresponding to left,
1775
  // bottom, right, top.
1776
0
  int64_t side = std::fmod((direction + 5 * kPi / 4), 2 * kPi) * 2 / kPi;
1777
0
  auto get_distance_from_center = [&](size_t gid) {
1778
0
    Rect r = frame_dim.GroupRect(gid);
1779
0
    int64_t gcx = r.x0() + group_dim / 2;
1780
0
    int64_t gcy = r.y0() + group_dim / 2;
1781
0
    int64_t dx = gcx - cx;
1782
0
    int64_t dy = gcy - cy;
1783
    // The angle is determined by taking atan2 and adding an appropriate
1784
    // starting point depending on the side we want to start on.
1785
0
    double angle = std::remainder(
1786
0
        std::atan2(dy, dx) + kPi / 4 + side * (kPi / 2), 2 * kPi);
1787
    // Concentric squares in clockwise order.
1788
0
    return std::make_pair(std::max(std::abs(dx), std::abs(dy)), angle);
1789
0
  };
1790
0
  std::sort(ac_group_order.begin(), ac_group_order.end(),
1791
0
            [&](coeff_order_t a, coeff_order_t b) {
1792
0
              return get_distance_from_center(a) < get_distance_from_center(b);
1793
0
            });
1794
0
  std::vector<coeff_order_t> inv_ac_group_order(ac_group_order.size(), 0);
1795
0
  for (size_t i = 0; i < ac_group_order.size(); i++) {
1796
0
    inv_ac_group_order[ac_group_order[i]] = i;
1797
0
  }
1798
0
  for (size_t i = 0; i < num_passes; i++) {
1799
0
    size_t pass_start = permutation->size();
1800
0
    for (coeff_order_t v : inv_ac_group_order) {
1801
0
      permutation->push_back(pass_start + v);
1802
0
    }
1803
0
  }
1804
0
  if (group_codes == nullptr) return true;
1805
0
  std::vector<std::unique_ptr<BitWriter>> new_group_codes(group_codes->size());
1806
0
  for (size_t i = 0; i < permutation->size(); i++) {
1807
0
    new_group_codes[(*permutation)[i]] = std::move((*group_codes)[i]);
1808
0
  }
1809
0
  group_codes->swap(new_group_codes);
1810
0
  return true;
1811
0
}
1812
1813
bool CanDoStreamingEncoding(const CompressParams& cparams,
1814
                            const FrameInfo& frame_info,
1815
                            const CodecMetadata& metadata,
1816
0
                            const JxlEncoderChunkedFrameAdapter& frame_data) {
1817
0
  if (cparams.buffering == -1) {
1818
0
    if (cparams.speed_tier < SpeedTier::kTortoise) return false;
1819
0
    if (cparams.speed_tier < SpeedTier::kSquirrel &&
1820
0
        cparams.butteraugli_distance > 0.5f) {
1821
0
      return false;
1822
0
    }
1823
0
    if (cparams.speed_tier == SpeedTier::kSquirrel &&
1824
0
        cparams.butteraugli_distance >= 3.f) {
1825
0
      return false;
1826
0
    }
1827
0
  }
1828
0
  if (cparams.buffering == 0) {
1829
0
    return false;
1830
0
  }
1831
0
  if (cparams.buffering == 1 && frame_data.xsize <= 2048 &&
1832
0
      frame_data.ysize <= 2048) {
1833
0
    return false;
1834
0
  }
1835
1836
  // Random heuristic: disable streaming for frames with less than 8 groups.
1837
  // (too little speed benefit, too much compression penalty)
1838
  // Can change this but have to make sure numgroups > 1, because the streaming
1839
  // path assumes that.
1840
0
  if (NumGroupsForFrame(frame_data.xsize, frame_data.ysize, cparams) <= 8) {
1841
0
    return false;
1842
0
  }
1843
0
  if (frame_data.IsJPEG()) {
1844
0
    return false;
1845
0
  }
1846
0
  if (cparams.noise == Override::kOn || cparams.patches == Override::kOn) {
1847
0
    return false;
1848
0
  }
1849
0
  if (cparams.progressive_dc != 0 || frame_info.dc_level != 0) {
1850
0
    return false;
1851
0
  }
1852
0
  if (cparams.custom_progressive_mode ||
1853
0
      cparams.qprogressive_mode == Override::kOn ||
1854
0
      cparams.progressive_mode == Override::kOn) {
1855
0
    return false;
1856
0
  }
1857
0
  if (cparams.resampling != 1 || cparams.ec_resampling != 1) {
1858
0
    return false;
1859
0
  }
1860
0
  if (cparams.lossy_palette) {
1861
0
    return false;
1862
0
  }
1863
0
  if (cparams.max_error_mode) {
1864
0
    return false;
1865
0
  }
1866
  // Progressive lossless uses Local MA trees, but requires a full
1867
  // buffer to compress well, so no special check.
1868
0
  if (!cparams.ModularPartIsLossless() || cparams.responsive > 0) {
1869
0
    if (metadata.m.num_extra_channels > 0 || cparams.modular_mode) {
1870
0
      return false;
1871
0
    }
1872
0
  }
1873
0
  ColorTransform ok_color_transform =
1874
0
      cparams.modular_mode ? ColorTransform::kNone : ColorTransform::kXYB;
1875
0
  if (cparams.color_transform != ok_color_transform) {
1876
0
    return false;
1877
0
  }
1878
0
  return true;
1879
0
}
1880
1881
Status ComputePermutationForStreaming(size_t xsize, size_t ysize,
1882
                                      size_t group_size, size_t num_passes,
1883
                                      std::vector<coeff_order_t>& permutation,
1884
0
                                      std::vector<size_t>& dc_group_order) {
1885
  // This is only valid in VarDCT mode, otherwise there can be group shift.
1886
0
  const size_t dc_group_size = group_size * kBlockDim;
1887
0
  const size_t group_xsize = DivCeil(xsize, group_size);
1888
0
  const size_t group_ysize = DivCeil(ysize, group_size);
1889
0
  const size_t dc_group_xsize = DivCeil(xsize, dc_group_size);
1890
0
  const size_t dc_group_ysize = DivCeil(ysize, dc_group_size);
1891
0
  const size_t num_groups = group_xsize * group_ysize;
1892
0
  const size_t num_dc_groups = dc_group_xsize * dc_group_ysize;
1893
0
  const size_t num_sections = 2 + num_dc_groups + num_passes * num_groups;
1894
0
  permutation.resize(num_sections);
1895
0
  size_t new_ix = 0;
1896
  // DC Global is first
1897
0
  permutation[0] = new_ix++;
1898
  // TODO(szabadka) Change the dc group order to center-first.
1899
0
  for (size_t dc_y = 0; dc_y < dc_group_ysize; ++dc_y) {
1900
0
    for (size_t dc_x = 0; dc_x < dc_group_xsize; ++dc_x) {
1901
0
      size_t dc_ix = dc_y * dc_group_xsize + dc_x;
1902
0
      dc_group_order.push_back(dc_ix);
1903
0
      permutation[1 + dc_ix] = new_ix++;
1904
0
      size_t ac_y0 = dc_y * kBlockDim;
1905
0
      size_t ac_x0 = dc_x * kBlockDim;
1906
0
      size_t ac_y1 = std::min<size_t>(group_ysize, ac_y0 + kBlockDim);
1907
0
      size_t ac_x1 = std::min<size_t>(group_xsize, ac_x0 + kBlockDim);
1908
0
      for (size_t pass = 0; pass < num_passes; ++pass) {
1909
0
        for (size_t ac_y = ac_y0; ac_y < ac_y1; ++ac_y) {
1910
0
          for (size_t ac_x = ac_x0; ac_x < ac_x1; ++ac_x) {
1911
0
            size_t group_ix = ac_y * group_xsize + ac_x;
1912
0
            size_t old_ix =
1913
0
                AcGroupIndex(pass, group_ix, num_groups, num_dc_groups);
1914
0
            permutation[old_ix] = new_ix++;
1915
0
          }
1916
0
        }
1917
0
      }
1918
0
    }
1919
0
  }
1920
  // AC Global is last
1921
0
  permutation[1 + num_dc_groups] = new_ix++;
1922
0
  JXL_ENSURE(new_ix == num_sections);
1923
0
  return true;
1924
0
}
1925
1926
constexpr size_t kGroupSizeOffset[4] = {
1927
    static_cast<size_t>(0),
1928
    static_cast<size_t>(1024),
1929
    static_cast<size_t>(17408),
1930
    static_cast<size_t>(4211712),
1931
};
1932
constexpr size_t kTOCBits[4] = {12, 16, 24, 32};
1933
1934
0
size_t TOCBucket(size_t group_size) {
1935
0
  size_t bucket = 0;
1936
0
  while (bucket < 3 && group_size >= kGroupSizeOffset[bucket + 1]) ++bucket;
1937
0
  return bucket;
1938
0
}
1939
1940
0
size_t TOCSize(const std::vector<size_t>& group_sizes) {
1941
0
  size_t toc_bits = 0;
1942
0
  for (size_t group_size : group_sizes) {
1943
0
    toc_bits += kTOCBits[TOCBucket(group_size)];
1944
0
  }
1945
0
  return (toc_bits + 7) / 8;
1946
0
}
1947
1948
Status ComputeGroupDataOffset(size_t frame_header_size, size_t dc_global_size,
1949
                              size_t num_sections, size_t& min_dc_global_size,
1950
0
                              size_t& group_offset) {
1951
0
  size_t max_toc_bits = (num_sections - 1) * 32;
1952
0
  size_t min_toc_bits = (num_sections - 1) * 12;
1953
0
  size_t max_padding = (max_toc_bits - min_toc_bits + 7) / 8;
1954
0
  min_dc_global_size = dc_global_size;
1955
0
  size_t dc_global_bucket = TOCBucket(min_dc_global_size);
1956
0
  while (TOCBucket(min_dc_global_size + max_padding) > dc_global_bucket) {
1957
0
    dc_global_bucket = TOCBucket(min_dc_global_size + max_padding);
1958
0
    min_dc_global_size = kGroupSizeOffset[dc_global_bucket];
1959
0
  }
1960
0
  JXL_ENSURE(TOCBucket(min_dc_global_size) == dc_global_bucket);
1961
0
  JXL_ENSURE(TOCBucket(min_dc_global_size + max_padding) == dc_global_bucket);
1962
0
  max_toc_bits += kTOCBits[dc_global_bucket];
1963
0
  size_t max_toc_size = (max_toc_bits + 7) / 8;
1964
0
  group_offset = frame_header_size + max_toc_size + min_dc_global_size;
1965
0
  return true;
1966
0
}
1967
1968
size_t ComputeDcGlobalPadding(const std::vector<size_t>& group_sizes,
1969
                              size_t frame_header_size,
1970
                              size_t group_data_offset,
1971
0
                              size_t min_dc_global_size) {
1972
0
  std::vector<size_t> new_group_sizes = group_sizes;
1973
0
  new_group_sizes[0] = min_dc_global_size;
1974
0
  size_t toc_size = TOCSize(new_group_sizes);
1975
0
  size_t actual_offset = frame_header_size + toc_size + group_sizes[0];
1976
0
  return group_data_offset - actual_offset;
1977
0
}
1978
1979
// write_fn is called once per section (dc_group, then each ac_group).
1980
Status OutputGroups(std::vector<std::unique_ptr<BitWriter>>&& group_codes,
1981
0
                    std::function<Status(PaddedBytes&&)> write_fn) {
1982
0
  JXL_ENSURE(group_codes.size() >= 4);
1983
0
  JXL_RETURN_IF_ERROR(write_fn(std::move(*group_codes[1]).TakeBytes()));
1984
0
  for (size_t i = 3; i < group_codes.size(); ++i) {
1985
0
    JXL_RETURN_IF_ERROR(write_fn(std::move(*group_codes[i]).TakeBytes()));
1986
0
  }
1987
0
  return true;
1988
0
}
1989
1990
0
void RemoveUnusedHistograms(EntropyEncodingData& codes) {
1991
0
  std::vector<int> remap(256, -1);
1992
0
  std::vector<uint8_t> inv_remap;
1993
0
  for (uint8_t& context : codes.context_map) {
1994
0
    const uint8_t histo_ix = context;
1995
0
    if (remap[histo_ix] == -1) {
1996
0
      remap[histo_ix] = inv_remap.size();
1997
0
      inv_remap.push_back(histo_ix);
1998
0
    }
1999
0
    context = remap[histo_ix];
2000
0
  }
2001
0
  EntropyEncodingData new_codes;
2002
0
  new_codes.use_prefix_code = codes.use_prefix_code;
2003
0
  new_codes.lz77 = codes.lz77;
2004
0
  new_codes.context_map = std::move(codes.context_map);
2005
0
  for (uint8_t histo_idx : inv_remap) {
2006
0
    new_codes.encoding_info.emplace_back(
2007
0
        std::move(codes.encoding_info[histo_idx]));
2008
0
    new_codes.uint_config.emplace_back(codes.uint_config[histo_idx]);
2009
0
    new_codes.encoded_histograms.emplace_back(
2010
0
        std::move(codes.encoded_histograms[histo_idx]));
2011
0
  }
2012
0
  codes = std::move(new_codes);
2013
0
}
2014
2015
StatusOr<std::unique_ptr<BitWriter>> OutputAcGlobal(
2016
    PassesEncoderState& enc_state, const FrameDimensions& frame_dim,
2017
0
    AuxOut* aux_out) {
2018
0
  JXL_ENSURE(frame_dim.num_groups > 1);
2019
0
  JxlMemoryManager* memory_manager = enc_state.memory_manager();
2020
0
  std::unique_ptr<BitWriter> writer =
2021
0
      jxl::make_unique<BitWriter>(memory_manager);
2022
0
  {
2023
0
    size_t num_histo_bits = CeilLog2Nonzero(frame_dim.num_groups);
2024
0
    JXL_RETURN_IF_ERROR(
2025
0
        writer->WithMaxBits(num_histo_bits + 1, LayerType::Ac, aux_out, [&] {
2026
0
          writer->Write(1, 1);  // default dequant matrices
2027
0
          writer->Write(num_histo_bits, frame_dim.num_dc_groups - 1);
2028
0
          return true;
2029
0
        }));
2030
0
  }
2031
0
  const PassesSharedState& shared = enc_state.shared;
2032
0
  for (size_t i = 0; i < enc_state.progressive_splitter.GetNumPasses(); i++) {
2033
    // Encode coefficient orders.
2034
0
    size_t order_bits = 0;
2035
0
    JXL_RETURN_IF_ERROR(
2036
0
        U32Coder::CanEncode(kOrderEnc, enc_state.used_orders[i], &order_bits));
2037
0
    JXL_RETURN_IF_ERROR(
2038
0
        writer->WithMaxBits(order_bits, LayerType::Order, aux_out, [&] {
2039
0
          return U32Coder::Write(kOrderEnc, enc_state.used_orders[i],
2040
0
                                 writer.get());
2041
0
        }));
2042
0
    JXL_RETURN_IF_ERROR(
2043
0
        EncodeCoeffOrders(enc_state.used_orders[i],
2044
0
                          &shared.coeff_orders[i * shared.coeff_order_size],
2045
0
                          writer.get(), LayerType::Order, aux_out));
2046
    // Fix up context map and entropy codes to remove any fix histograms that
2047
    // were not selected by clustering.
2048
0
    RemoveUnusedHistograms(enc_state.passes[i].codes);
2049
0
    JXL_RETURN_IF_ERROR(EncodeHistograms(enc_state.passes[i].codes,
2050
0
                                         writer.get(), LayerType::Ac, aux_out));
2051
0
  }
2052
0
  JXL_RETURN_IF_ERROR(writer->WithMaxBits(8, LayerType::Ac, aux_out, [&] {
2053
0
    writer->ZeroPadToByte();  // end of group.
2054
0
    return true;
2055
0
  }));
2056
0
  return writer;
2057
0
}
2058
2059
JXL_NOINLINE Status EncodeFrameStreaming(
2060
    JxlMemoryManager* memory_manager, const CompressParams& cparams,
2061
    const FrameInfo& frame_info, const CodecMetadata* metadata,
2062
    JxlEncoderChunkedFrameAdapter& frame_data, const JxlCmsInterface& cms,
2063
    ThreadPool* pool, JxlEncoderOutputProcessorWrapper* output_processor,
2064
0
    AuxOut* aux_out, uint32_t* jxlp_counter) {
2065
0
  const int output_mode = cparams.output_mode;
2066
0
  auto enc_state = jxl::make_unique<PassesEncoderState>(memory_manager);
2067
0
  SetProgressiveMode(cparams, &enc_state->progressive_splitter);
2068
0
  FrameHeader frame_header(metadata);
2069
0
  std::unique_ptr<jpeg::JPEGData> jpeg_data;
2070
0
  if (frame_data.IsJPEG()) {
2071
0
    jpeg_data = frame_data.TakeJPEGData();
2072
0
    JXL_ENSURE(jpeg_data);
2073
0
  }
2074
0
  JXL_RETURN_IF_ERROR(MakeFrameHeader(frame_data.xsize, frame_data.ysize,
2075
0
                                      cparams, enc_state->progressive_splitter,
2076
0
                                      frame_info, jpeg_data.get(), true,
2077
0
                                      &frame_header));
2078
0
  const size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
2079
0
  JXL_ASSIGN_OR_RETURN(
2080
0
      auto enc_modular,
2081
0
      ModularFrameEncoder::Create(memory_manager, frame_header, cparams, true));
2082
0
  std::vector<coeff_order_t> permutation;
2083
0
  std::vector<size_t> dc_group_order;
2084
0
  size_t group_size = frame_header.ToFrameDimensions().group_dim;
2085
0
  JXL_RETURN_IF_ERROR(ComputePermutationForStreaming(
2086
0
      frame_data.xsize, frame_data.ysize, group_size, num_passes, permutation,
2087
0
      dc_group_order));
2088
0
  enc_state->shared.num_histograms = dc_group_order.size();
2089
0
  size_t dc_group_size = group_size * kBlockDim;
2090
0
  size_t dc_group_xsize = DivCeil(frame_data.xsize, dc_group_size);
2091
0
  size_t min_dc_global_size = 0;
2092
0
  size_t group_data_offset = 0;
2093
0
  PaddedBytes frame_header_bytes{memory_manager};
2094
0
  PaddedBytes dc_global_bytes{memory_manager};
2095
0
  std::vector<size_t> group_sizes;
2096
0
  const bool streaming_output = (output_mode == 1);
2097
0
  const bool streaming = (output_mode >= 1);
2098
0
  const bool ooo = (output_mode == 2 && jxlp_counter != nullptr);
2099
0
  size_t start_pos = (streaming_output && output_processor)
2100
0
                         ? output_processor->CurrentPosition()
2101
0
                         : 0;
2102
0
  const size_t total_sections =
2103
0
      NumTocEntries(frame_header.ToFrameDimensions().num_groups,
2104
0
                    dc_group_order.size(), num_passes);
2105
0
  std::vector<std::unique_ptr<BitWriter>> global_group_codes(
2106
0
      streaming ? 0 : total_sections);
2107
2108
  // Compute group_order_perm for all modes (centerfirst, if requested).
2109
  // For ooo mode, also compute inv_perm (encoding_pos → canonical_idx).
2110
0
  std::vector<coeff_order_t> group_order_perm;
2111
0
  JXL_RETURN_IF_ERROR(PermuteGroups(cparams, frame_header.ToFrameDimensions(),
2112
0
                                    num_passes, frame_info.dc_level,
2113
0
                                    &group_order_perm, nullptr));
2114
0
  size_t encoding_pos = 0;
2115
0
  std::vector<size_t> inv_perm;
2116
0
  if (ooo) {
2117
0
    inv_perm.resize(permutation.size());
2118
0
    for (size_t j = 0; j < permutation.size(); j++) {
2119
0
      inv_perm[permutation[j]] = j;
2120
0
    }
2121
0
  }
2122
2123
0
  auto write_jxlp = [&](uint32_t counter, bool is_last,
2124
0
                        Span<const uint8_t> data) -> Status {
2125
0
    uint8_t hdr[kLargeBoxHeaderSize + 4];
2126
0
    const size_t hdr_size =
2127
0
        WriteBoxHeader(MakeBoxType("jxlp"), 4 + data.size(),
2128
0
                       /*unbounded=*/false, /*force_large_box=*/false, hdr);
2129
0
    StoreBE32(counter | (is_last ? 0x80000000u : 0u), hdr + hdr_size);
2130
0
    JXL_RETURN_IF_ERROR(
2131
0
        AppendData(*output_processor, Span<const uint8_t>(hdr, hdr_size + 4)));
2132
0
    return AppendData(*output_processor, data);
2133
0
  };
2134
2135
0
  const uint32_t jxlp_base = jxlp_counter ? *jxlp_counter : 0;
2136
2137
0
  auto write_group_section = [&](PaddedBytes&& bytes) -> Status {
2138
0
    group_sizes.push_back(bytes.size());
2139
0
    if (ooo) {
2140
0
      const size_t canonical_idx = inv_perm[encoding_pos++];
2141
0
      const size_t cs_pos = group_order_perm.empty()
2142
0
                                ? canonical_idx
2143
0
                                : group_order_perm[canonical_idx];
2144
0
      const bool is_last = (cs_pos + 1 == total_sections) && frame_info.is_last;
2145
0
      return write_jxlp(jxlp_base + static_cast<uint32_t>(cs_pos) + 2, is_last,
2146
0
                        Span<const uint8_t>(bytes.data(), bytes.size()));
2147
0
    }
2148
0
    return AppendData(*output_processor, bytes);
2149
0
  };
2150
0
  for (size_t i = 0; i < dc_group_order.size(); ++i) {
2151
0
    size_t dc_ix = dc_group_order[i];
2152
0
    size_t dc_y = dc_ix / dc_group_xsize;
2153
0
    size_t dc_x = dc_ix % dc_group_xsize;
2154
0
    size_t y0 = dc_y * dc_group_size;
2155
0
    size_t x0 = dc_x * dc_group_size;
2156
0
    size_t ysize = std::min<size_t>(dc_group_size, frame_data.ysize - y0);
2157
0
    size_t xsize = std::min<size_t>(dc_group_size, frame_data.xsize - x0);
2158
0
    size_t group_xsize = DivCeil(xsize, group_size);
2159
0
    size_t group_ysize = DivCeil(ysize, group_size);
2160
0
    JXL_DEBUG_V(2,
2161
0
                "Encoding DC group #%" PRIuS " dc_y = %" PRIuS " dc_x = %" PRIuS
2162
0
                " (x0, y0) = (%" PRIuS ", %" PRIuS ") (xsize, ysize) = (%" PRIuS
2163
0
                ", %" PRIuS ")",
2164
0
                dc_ix, dc_y, dc_x, x0, y0, xsize, ysize);
2165
0
    enc_state->streaming_mode = true;
2166
0
    enc_state->initialize_global_state = (i == 0);
2167
0
    enc_state->dc_group_index = dc_ix;
2168
0
    enc_state->histogram_idx =
2169
0
        std::vector<size_t>(group_xsize * group_ysize, i);
2170
0
    std::vector<std::unique_ptr<BitWriter>> group_codes;
2171
0
    JXL_RETURN_IF_ERROR(ComputeEncodingData(
2172
0
        cparams, frame_info, metadata, frame_data, jpeg_data.get(), x0, y0,
2173
0
        xsize, ysize, cms, pool, frame_header, *enc_modular, *enc_state,
2174
0
        &group_codes, aux_out));
2175
0
    JXL_ENSURE(enc_state->special_frames.empty());
2176
0
    if (i == 0) {
2177
0
      BitWriter writer{memory_manager};
2178
0
      JXL_RETURN_IF_ERROR(WriteFrameHeader(frame_header, &writer, aux_out));
2179
0
      JXL_RETURN_IF_ERROR(WriteTocPermutation(
2180
0
          streaming_output ? permutation : group_order_perm, &writer, aux_out));
2181
0
      frame_header_bytes = std::move(writer).TakeBytes();
2182
0
      if (streaming_output) {
2183
0
        dc_global_bytes = std::move(*group_codes[0]).TakeBytes();
2184
0
        JXL_RETURN_IF_ERROR(ComputeGroupDataOffset(
2185
0
            frame_header_bytes.size(), dc_global_bytes.size(),
2186
0
            permutation.size(), min_dc_global_size, group_data_offset));
2187
0
        JXL_DEBUG_V(2, "Frame header size: %" PRIuS, frame_header_bytes.size());
2188
0
        JXL_DEBUG_V(2, "DC global size: %" PRIuS ", min size for TOC: %" PRIuS,
2189
0
                    dc_global_bytes.size(), min_dc_global_size);
2190
0
        JXL_DEBUG_V(2, "Num groups: %" PRIuS " group data offset: %" PRIuS,
2191
0
                    permutation.size(), group_data_offset);
2192
0
        group_sizes.push_back(dc_global_bytes.size());
2193
0
        JXL_RETURN_IF_ERROR(
2194
0
            output_processor->Seek(start_pos + group_data_offset));
2195
0
      } else if (ooo) {
2196
0
        JXL_RETURN_IF_ERROR(
2197
0
            write_jxlp(jxlp_base, /*is_last=*/false,
2198
0
                       Span<const uint8_t>(frame_header_bytes.data(),
2199
0
                                           frame_header_bytes.size())));
2200
0
        JXL_RETURN_IF_ERROR(
2201
0
            write_group_section(std::move(*group_codes[0]).TakeBytes()));
2202
0
      }
2203
0
    }
2204
0
    if (streaming) {
2205
0
      JXL_RETURN_IF_ERROR(
2206
0
          OutputGroups(std::move(group_codes), write_group_section));
2207
0
    } else {
2208
0
      JXL_ENSURE(group_codes.size() >= 4);
2209
0
      if (i == 0) {
2210
0
        JXL_RETURN_IF_ERROR(group_codes[0]->Shrink());
2211
0
        global_group_codes[0] = std::move(group_codes[0]);
2212
0
      }
2213
0
      JXL_RETURN_IF_ERROR(group_codes[1]->Shrink());
2214
0
      global_group_codes[1 + i] = std::move(group_codes[1]);
2215
0
      for (size_t j = 3; j < group_codes.size(); j++) {
2216
0
        FrameDimensions patch_dim;
2217
0
        patch_dim.Set(xsize, ysize, frame_header.group_size_shift,
2218
0
                      /*max_hshift=*/0, /*max_vshift=*/0,
2219
0
                      frame_header.encoding == FrameEncoding::kModular,
2220
0
                      /*upsampling=*/1);
2221
0
        size_t global_ac_idx =
2222
0
            enc_modular->ComputeStreamingAbsoluteAcGroupId(i, j - 3, patch_dim);
2223
0
        JXL_RETURN_IF_ERROR(group_codes[j]->Shrink());
2224
0
        global_group_codes[2 + dc_group_order.size() + global_ac_idx] =
2225
0
            std::move(group_codes[j]);
2226
0
      }
2227
0
    }
2228
0
  }
2229
0
  if (frame_header.encoding == FrameEncoding::kVarDCT) {
2230
0
    JXL_ASSIGN_OR_RETURN(
2231
0
        std::unique_ptr<BitWriter> writer,
2232
0
        OutputAcGlobal(*enc_state, frame_header.ToFrameDimensions(), aux_out));
2233
0
    JXL_RETURN_IF_ERROR(writer->Shrink());
2234
0
    if (streaming) {
2235
0
      JXL_RETURN_IF_ERROR(write_group_section(std::move(*writer).TakeBytes()));
2236
0
    } else {
2237
0
      global_group_codes[1 + dc_group_order.size()] = std::move(writer);
2238
0
    }
2239
0
  } else {
2240
0
    if (streaming) {
2241
0
      JXL_RETURN_IF_ERROR(write_group_section(PaddedBytes{memory_manager}));
2242
0
    } else {
2243
0
      global_group_codes[1 + dc_group_order.size()] =
2244
0
          jxl::make_unique<BitWriter>(memory_manager);
2245
0
    }
2246
0
  }
2247
0
  if (streaming_output) {
2248
0
    JXL_ENSURE(group_sizes.size() == permutation.size());
2249
0
    size_t end_pos = output_processor->CurrentPosition();
2250
0
    JXL_RETURN_IF_ERROR(output_processor->Seek(start_pos));
2251
0
    size_t padding_size =
2252
0
        ComputeDcGlobalPadding(group_sizes, frame_header_bytes.size(),
2253
0
                               group_data_offset, min_dc_global_size);
2254
0
    group_sizes[0] += padding_size;
2255
0
    BitWriter toc_writer{memory_manager};
2256
0
    JXL_RETURN_IF_ERROR(WriteTocSizes(group_sizes, &toc_writer, aux_out));
2257
0
    PaddedBytes toc_bytes = std::move(toc_writer).TakeBytes();
2258
0
    std::vector<uint8_t> padding_bytes(padding_size);
2259
0
    JXL_RETURN_IF_ERROR(AppendData(*output_processor, frame_header_bytes));
2260
0
    JXL_RETURN_IF_ERROR(AppendData(*output_processor, toc_bytes));
2261
0
    JXL_RETURN_IF_ERROR(AppendData(*output_processor, dc_global_bytes));
2262
0
    JXL_RETURN_IF_ERROR(AppendData(*output_processor, padding_bytes));
2263
0
    JXL_DEBUG_V(2,
2264
0
                "TOC size: %" PRIuS " padding bytes after DC global: %" PRIuS,
2265
0
                toc_bytes.size(), padding_size);
2266
0
    JXL_ENSURE(output_processor->CurrentPosition() ==
2267
0
               start_pos + group_data_offset);
2268
0
    JXL_RETURN_IF_ERROR(output_processor->Seek(end_pos));
2269
0
  } else if (ooo) {
2270
    // Write TOC (in codestream order) as jxlp[jxlp_base+1]; counter +1 means
2271
    // the decoder processes it before the group sections (counters >= +2).
2272
0
    JXL_ENSURE(group_sizes.size() == permutation.size());
2273
0
    std::vector<size_t> codestream_sizes(permutation.size());
2274
0
    for (size_t canonical_idx = 0; canonical_idx < permutation.size();
2275
0
         canonical_idx++) {
2276
0
      const size_t cs_pos = group_order_perm.empty()
2277
0
                                ? canonical_idx
2278
0
                                : group_order_perm[canonical_idx];
2279
0
      codestream_sizes[cs_pos] = group_sizes[permutation[canonical_idx]];
2280
0
    }
2281
0
    BitWriter toc_writer{memory_manager};
2282
0
    JXL_RETURN_IF_ERROR(WriteTocSizes(codestream_sizes, &toc_writer, aux_out));
2283
0
    PaddedBytes toc_bytes = std::move(toc_writer).TakeBytes();
2284
0
    JXL_RETURN_IF_ERROR(
2285
0
        write_jxlp(jxlp_base + 1, /*is_last=*/false,
2286
0
                   Span<const uint8_t>(toc_bytes.data(), toc_bytes.size())));
2287
0
    if (jxlp_counter != nullptr) {
2288
0
      *jxlp_counter = jxlp_base + static_cast<uint32_t>(total_sections) + 2;
2289
0
    }
2290
0
  } else {
2291
0
    for (auto& g : global_group_codes) {
2292
0
      group_sizes.push_back(g->BitsWritten() / 8);
2293
0
    }
2294
0
    JXL_ENSURE(group_sizes.size() == permutation.size());
2295
0
    if (!group_order_perm.empty()) {
2296
0
      std::vector<std::unique_ptr<BitWriter>> reordered(
2297
0
          group_order_perm.size());
2298
0
      std::vector<size_t> reordered_sizes(group_sizes.size());
2299
0
      for (size_t i = 0; i < group_order_perm.size(); i++) {
2300
0
        reordered[group_order_perm[i]] = std::move(global_group_codes[i]);
2301
0
        reordered_sizes[group_order_perm[i]] = group_sizes[i];
2302
0
      }
2303
0
      global_group_codes.swap(reordered);
2304
0
      group_sizes.swap(reordered_sizes);
2305
0
    }
2306
0
    BitWriter combined{memory_manager};
2307
0
    JXL_RETURN_IF_ERROR(WriteFrameHeader(frame_header, &combined, aux_out));
2308
0
    JXL_RETURN_IF_ERROR(
2309
0
        WriteTocPermutation(group_order_perm, &combined, aux_out));
2310
0
    JXL_RETURN_IF_ERROR(WriteTocSizes(group_sizes, &combined, aux_out));
2311
0
    JXL_RETURN_IF_ERROR(
2312
0
        AppendData(*output_processor, std::move(combined).TakeBytes()));
2313
0
    for (auto& g : global_group_codes) {
2314
0
      JXL_RETURN_IF_ERROR(
2315
0
          AppendData(*output_processor, std::move(*g).TakeBytes()));
2316
0
    }
2317
0
  }
2318
0
  return true;
2319
0
}
2320
2321
Status EncodeFrameOneShot(JxlMemoryManager* memory_manager,
2322
                          const CompressParams& cparams,
2323
                          const FrameInfo& frame_info,
2324
                          const CodecMetadata* metadata,
2325
                          JxlEncoderChunkedFrameAdapter& frame_data,
2326
                          const JxlCmsInterface& cms, ThreadPool* pool,
2327
                          JxlEncoderOutputProcessorWrapper* output_processor,
2328
0
                          AuxOut* aux_out) {
2329
0
  auto enc_state = jxl::make_unique<PassesEncoderState>(memory_manager);
2330
0
  SetProgressiveMode(cparams, &enc_state->progressive_splitter);
2331
0
  FrameHeader frame_header(metadata);
2332
0
  std::unique_ptr<jpeg::JPEGData> jpeg_data;
2333
0
  if (frame_data.IsJPEG()) {
2334
0
    jpeg_data = frame_data.TakeJPEGData();
2335
0
    JXL_ENSURE(jpeg_data);
2336
0
  }
2337
0
  JXL_RETURN_IF_ERROR(MakeFrameHeader(frame_data.xsize, frame_data.ysize,
2338
0
                                      cparams, enc_state->progressive_splitter,
2339
0
                                      frame_info, jpeg_data.get(), false,
2340
0
                                      &frame_header));
2341
0
  const size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
2342
0
  JXL_ASSIGN_OR_RETURN(auto enc_modular,
2343
0
                       ModularFrameEncoder::Create(memory_manager, frame_header,
2344
0
                                                   cparams, false));
2345
0
  std::vector<std::unique_ptr<BitWriter>> group_codes;
2346
0
  JXL_RETURN_IF_ERROR(ComputeEncodingData(
2347
0
      cparams, frame_info, metadata, frame_data, jpeg_data.get(), 0, 0,
2348
0
      frame_data.xsize, frame_data.ysize, cms, pool, frame_header, *enc_modular,
2349
0
      *enc_state, &group_codes, aux_out));
2350
2351
0
  BitWriter writer{memory_manager};
2352
0
  JXL_RETURN_IF_ERROR(writer.AppendByteAligned(enc_state->special_frames));
2353
0
  JXL_RETURN_IF_ERROR(WriteFrameHeader(frame_header, &writer, aux_out));
2354
2355
0
  std::vector<coeff_order_t> permutation;
2356
0
  JXL_RETURN_IF_ERROR(PermuteGroups(cparams, enc_state->shared.frame_dim,
2357
0
                                    num_passes, frame_info.dc_level,
2358
0
                                    &permutation, &group_codes));
2359
2360
0
  std::vector<size_t> group_sizes;
2361
0
  group_sizes.reserve(group_codes.size());
2362
0
  for (const auto& bw : group_codes) {
2363
0
    JXL_ENSURE(bw->BitsWritten() % kBitsPerByte == 0);
2364
0
    group_sizes.push_back(bw->BitsWritten() / kBitsPerByte);
2365
0
  }
2366
0
  JXL_RETURN_IF_ERROR(WriteTocPermutation(permutation, &writer, aux_out));
2367
0
  JXL_RETURN_IF_ERROR(WriteTocSizes(group_sizes, &writer, aux_out));
2368
2369
0
  JXL_RETURN_IF_ERROR(writer.AppendByteAligned(group_codes));
2370
0
  PaddedBytes frame_bytes = std::move(writer).TakeBytes();
2371
0
  JXL_RETURN_IF_ERROR(AppendData(*output_processor, frame_bytes));
2372
2373
0
  return true;
2374
0
}
2375
2376
}  // namespace
2377
2378
std::vector<CompressParams> TectonicPlateSettingsLessPalette(
2379
0
    const CompressParams& cparams_orig) {
2380
0
  std::vector<CompressParams> all_params;
2381
0
  CompressParams cparams_attempt = cparams_orig;
2382
0
  cparams_attempt.speed_tier = SpeedTier::kGlacier;
2383
2384
0
  cparams_attempt.options.max_properties = 4;
2385
0
  cparams_attempt.options.nb_repeats = 1.0f;
2386
0
  cparams_attempt.modular_group_size_shift = 0;
2387
0
  cparams_attempt.channel_colors_percent = 0;
2388
0
  cparams_attempt.options.predictor = Predictor::Variable;
2389
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2390
0
  cparams_attempt.palette_colors = 1024;
2391
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2392
0
  cparams_attempt.patches = Override::kDefault;
2393
0
  all_params.push_back(cparams_attempt);
2394
0
  cparams_attempt.channel_colors_percent = 80.f;
2395
0
  cparams_attempt.modular_group_size_shift = 1;
2396
0
  cparams_attempt.palette_colors = 0;
2397
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2398
0
  all_params.push_back(cparams_attempt);
2399
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2400
0
  cparams_attempt.modular_group_size_shift = 2;
2401
0
  all_params.push_back(cparams_attempt);
2402
0
  cparams_attempt.modular_group_size_shift = 3;
2403
0
  cparams_attempt.patches = Override::kOff;
2404
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2405
0
  all_params.push_back(cparams_attempt);
2406
0
  cparams_attempt.palette_colors = 1024;
2407
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2408
0
  all_params.push_back(cparams_attempt);
2409
0
  cparams_attempt.patches = Override::kDefault;
2410
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2411
0
  all_params.push_back(cparams_attempt);
2412
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2413
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2414
0
  all_params.push_back(cparams_attempt);
2415
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2416
0
  cparams_attempt.options.nb_repeats = 0.9f;
2417
0
  cparams_attempt.modular_group_size_shift = 2;
2418
0
  all_params.push_back(cparams_attempt);
2419
0
  cparams_attempt.modular_group_size_shift = 3;
2420
0
  cparams_attempt.palette_colors = 0;
2421
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2422
0
  all_params.push_back(cparams_attempt);
2423
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2424
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2425
0
  all_params.push_back(cparams_attempt);
2426
0
  cparams_attempt.palette_colors = 1024;
2427
0
  cparams_attempt.options.nb_repeats = 0.95f;
2428
0
  cparams_attempt.modular_group_size_shift = 1;
2429
0
  cparams_attempt.channel_colors_percent = 0;
2430
0
  all_params.push_back(cparams_attempt);
2431
0
  cparams_attempt.modular_group_size_shift = 2;
2432
0
  cparams_attempt.palette_colors = 0;
2433
0
  all_params.push_back(cparams_attempt);
2434
0
  cparams_attempt.channel_colors_percent = 80.f;
2435
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2436
0
  all_params.push_back(cparams_attempt);
2437
0
  cparams_attempt.palette_colors = 1024;
2438
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2439
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2440
0
  cparams_attempt.modular_group_size_shift = 3;
2441
0
  all_params.push_back(cparams_attempt);
2442
0
  cparams_attempt.palette_colors = 0;
2443
0
  cparams_attempt.patches = Override::kOff;
2444
0
  all_params.push_back(cparams_attempt);
2445
0
  cparams_attempt.patches = Override::kDefault;
2446
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2447
0
  all_params.push_back(cparams_attempt);
2448
0
  cparams_attempt.palette_colors = 1024;
2449
0
  cparams_attempt.patches = Override::kOff;
2450
0
  all_params.push_back(cparams_attempt);
2451
0
  cparams_attempt.options.nb_repeats = 0.5f;
2452
0
  cparams_attempt.patches = Override::kDefault;
2453
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2454
0
  all_params.push_back(cparams_attempt);
2455
0
  cparams_attempt.options.predictor = Predictor::Zero;
2456
0
  cparams_attempt.options.nb_repeats = 0;
2457
0
  cparams_attempt.channel_colors_percent = 0;
2458
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2459
0
  cparams_attempt.patches = Override::kOff;
2460
0
  all_params.push_back(cparams_attempt);
2461
0
  cparams_attempt.channel_colors_percent = 80.f;
2462
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2463
0
  cparams_attempt.options.nb_repeats = 1.0f;
2464
0
  cparams_attempt.palette_colors = 0;
2465
0
  all_params.push_back(cparams_attempt);
2466
0
  cparams_attempt.patches = Override::kDefault;
2467
0
  cparams_attempt.options.predictor = Predictor::Best;
2468
0
  all_params.push_back(cparams_attempt);
2469
0
  cparams_attempt.options.nb_repeats = 0.9f;
2470
0
  cparams_attempt.patches = Override::kOff;
2471
0
  all_params.push_back(cparams_attempt);
2472
0
  cparams_attempt.palette_colors = 1024;
2473
0
  cparams_attempt.patches = Override::kDefault;
2474
0
  cparams_attempt.options.predictor = Predictor::Weighted;
2475
0
  cparams_attempt.options.nb_repeats = 1.0f;
2476
0
  all_params.push_back(cparams_attempt);
2477
0
  cparams_attempt.options.nb_repeats = 0.95f;
2478
0
  cparams_attempt.modular_group_size_shift = 2;
2479
0
  cparams_attempt.palette_colors = 0;
2480
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2481
0
  all_params.push_back(cparams_attempt);
2482
0
  return all_params;
2483
0
}
2484
2485
std::vector<CompressParams> TectonicPlateSettingsMorePalette(
2486
0
    const CompressParams& cparams_orig) {
2487
0
  std::vector<CompressParams> all_params;
2488
0
  CompressParams cparams_attempt = cparams_orig;
2489
0
  cparams_attempt.speed_tier = SpeedTier::kGlacier;
2490
2491
0
  cparams_attempt.options.max_properties = 4;
2492
0
  cparams_attempt.options.nb_repeats = 1.0f;
2493
0
  cparams_attempt.modular_group_size_shift = 0;
2494
0
  cparams_attempt.palette_colors = 70000;
2495
0
  cparams_attempt.options.predictor = Predictor::Variable;
2496
0
  cparams_attempt.channel_colors_percent = 80.f;
2497
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2498
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2499
0
  cparams_attempt.patches = Override::kDefault;
2500
0
  all_params.push_back(cparams_attempt);
2501
0
  cparams_attempt.modular_group_size_shift = 2;
2502
0
  cparams_attempt.channel_colors_percent = 0;
2503
0
  cparams_attempt.patches = Override::kOff;
2504
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2505
0
  all_params.push_back(cparams_attempt);
2506
0
  cparams_attempt.channel_colors_percent = 80.f;
2507
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2508
0
  cparams_attempt.modular_group_size_shift = 3;
2509
0
  all_params.push_back(cparams_attempt);
2510
0
  cparams_attempt.options.nb_repeats = 0.9f;
2511
0
  all_params.push_back(cparams_attempt);
2512
0
  cparams_attempt.patches = Override::kDefault;
2513
0
  cparams_attempt.options.nb_repeats = 0.95f;
2514
0
  cparams_attempt.modular_group_size_shift = 0;
2515
0
  all_params.push_back(cparams_attempt);
2516
0
  cparams_attempt.modular_group_size_shift = 3;
2517
0
  all_params.push_back(cparams_attempt);
2518
0
  cparams_attempt.patches = Override::kOff;
2519
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2520
0
  all_params.push_back(cparams_attempt);
2521
0
  cparams_attempt.options.nb_repeats = 0.5f;
2522
0
  all_params.push_back(cparams_attempt);
2523
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2524
0
  cparams_attempt.options.predictor = Predictor::Zero;
2525
0
  cparams_attempt.options.nb_repeats = 0;
2526
0
  all_params.push_back(cparams_attempt);
2527
0
  cparams_attempt.patches = Override::kDefault;
2528
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2529
0
  all_params.push_back(cparams_attempt);
2530
0
  cparams_attempt.options.nb_repeats = 0.01f;
2531
0
  cparams_attempt.palette_colors = 0;
2532
0
  cparams_attempt.patches = Override::kOff;
2533
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2534
0
  all_params.push_back(cparams_attempt);
2535
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2536
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2537
0
  cparams_attempt.palette_colors = 70000;
2538
0
  all_params.push_back(cparams_attempt);
2539
0
  cparams_attempt.options.nb_repeats = 1.0f;
2540
0
  cparams_attempt.modular_group_size_shift = 0;
2541
0
  cparams_attempt.channel_colors_percent = 0;
2542
0
  cparams_attempt.channel_colors_pre_transform_percent = 0;
2543
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2544
0
  all_params.push_back(cparams_attempt);
2545
0
  cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2546
0
  cparams_attempt.modular_group_size_shift = 1;
2547
0
  all_params.push_back(cparams_attempt);
2548
0
  cparams_attempt.modular_group_size_shift = 2;
2549
0
  all_params.push_back(cparams_attempt);
2550
0
  cparams_attempt.channel_colors_percent = 80.f;
2551
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2552
0
  cparams_attempt.modular_group_size_shift = 3;
2553
0
  all_params.push_back(cparams_attempt);
2554
0
  cparams_attempt.options.nb_repeats = 0.5f;
2555
0
  cparams_attempt.modular_group_size_shift = 1;
2556
0
  cparams_attempt.channel_colors_percent = 0;
2557
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2558
0
  all_params.push_back(cparams_attempt);
2559
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2560
0
  cparams_attempt.modular_group_size_shift = 2;
2561
0
  all_params.push_back(cparams_attempt);
2562
0
  cparams_attempt.channel_colors_percent = 80.f;
2563
0
  cparams_attempt.modular_group_size_shift = 3;
2564
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2565
0
  all_params.push_back(cparams_attempt);
2566
0
  cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2567
0
  cparams_attempt.options.predictor = Predictor::Select;
2568
0
  cparams_attempt.options.nb_repeats = 1.0f;
2569
0
  all_params.push_back(cparams_attempt);
2570
0
  return all_params;
2571
0
}
2572
2573
Status EncodeFrame(JxlMemoryManager* memory_manager,
2574
                   const CompressParams& cparams_orig,
2575
                   const FrameInfo& frame_info, const CodecMetadata* metadata,
2576
                   JxlEncoderChunkedFrameAdapter& frame_data,
2577
                   const JxlCmsInterface& cms, ThreadPool* pool,
2578
                   JxlEncoderOutputProcessorWrapper* output_processor,
2579
0
                   AuxOut* aux_out, uint32_t* jxlp_counter) {
2580
0
  CompressParams cparams = cparams_orig;
2581
0
  if (cparams.speed_tier == SpeedTier::kTectonicPlate &&
2582
0
      !cparams.IsLossless()) {
2583
0
    cparams.speed_tier = SpeedTier::kGlacier;
2584
0
  }
2585
  // Lightning mode is handled externally, so switch to Thunder mode to handle
2586
  // potentially weird cases.
2587
0
  if (cparams.speed_tier == SpeedTier::kLightning) {
2588
0
    cparams.speed_tier = SpeedTier::kThunder;
2589
0
  }
2590
0
  if (cparams.speed_tier == SpeedTier::kTectonicPlate) {
2591
    // Test palette performance to inform later trials.
2592
0
    std::vector<CompressParams> all_params;
2593
0
    CompressParams cparams_attempt = cparams;
2594
0
    cparams_attempt.speed_tier = SpeedTier::kGlacier;
2595
2596
0
    cparams_attempt.options.max_properties = 4;
2597
0
    cparams_attempt.options.nb_repeats = 1.0f;
2598
0
    cparams_attempt.modular_group_size_shift = 3;
2599
0
    cparams_attempt.palette_colors = 0;
2600
0
    cparams_attempt.options.predictor = Predictor::Variable;
2601
0
    cparams_attempt.channel_colors_percent = 80.f;
2602
0
    cparams_attempt.channel_colors_pre_transform_percent = 95.f;
2603
0
    cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kDefault;
2604
0
    cparams_attempt.patches = Override::kDefault;
2605
0
    all_params.push_back(cparams_attempt);
2606
0
    cparams_attempt.options.predictor = Predictor::Zero;
2607
0
    cparams_attempt.options.nb_repeats = 0.01f;
2608
0
    cparams_attempt.palette_colors = 70000;
2609
0
    cparams_attempt.patches = Override::kOff;
2610
0
    cparams_attempt.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP;
2611
0
    all_params.push_back(cparams_attempt);
2612
2613
0
    std::vector<size_t> size;
2614
0
    size.resize(all_params.size());
2615
2616
0
    const auto process_variant = [&](size_t task, size_t) -> Status {
2617
0
      JxlEncoderOutputProcessorWrapper local_output(memory_manager);
2618
0
      JXL_RETURN_IF_ERROR(EncodeFrame(
2619
0
          memory_manager, all_params[task], frame_info, metadata, frame_data,
2620
0
          cms, nullptr, &local_output, aux_out, nullptr));
2621
0
      size[task] = local_output.CurrentPosition();
2622
0
      return true;
2623
0
    };
2624
0
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, all_params.size(),
2625
0
                                  ThreadPool::NoInit, process_variant,
2626
0
                                  "Compress kTectonicPlate"));
2627
2628
0
    std::vector<CompressParams> all_params_test = all_params;
2629
0
    std::vector<size_t> size_test = size;
2630
0
    size_t best_idx_test = 0;
2631
2632
0
    if (size_test[0] <= size_test[1]) {
2633
0
      all_params = TectonicPlateSettingsLessPalette(cparams);
2634
0
    } else {
2635
0
      best_idx_test = 1;
2636
0
      all_params = TectonicPlateSettingsMorePalette(cparams);
2637
0
    }
2638
2639
0
    size.clear();
2640
0
    size.resize(all_params.size());
2641
2642
0
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, all_params.size(),
2643
0
                                  ThreadPool::NoInit, process_variant,
2644
0
                                  "Compress kTectonicPlate"));
2645
2646
0
    size_t best_idx = 0;
2647
0
    for (size_t i = 1; i < all_params.size(); i++) {
2648
0
      if (size[best_idx] > size[i]) {
2649
0
        best_idx = i;
2650
0
      }
2651
0
    }
2652
0
    if (size[best_idx] < size_test[best_idx_test]) {
2653
0
      cparams = all_params[best_idx];
2654
0
    } else {
2655
0
      cparams = all_params_test[best_idx_test];
2656
0
    }
2657
0
  }
2658
2659
0
  JXL_RETURN_IF_ERROR(ParamsPostInit(&cparams));
2660
2661
0
  if (cparams.butteraugli_distance < 0) {
2662
0
    return JXL_FAILURE("Expected non-negative distance");
2663
0
  }
2664
2665
0
  if (cparams.progressive_dc < 0) {
2666
0
    if (cparams.progressive_dc != -1) {
2667
0
      return JXL_FAILURE("Invalid progressive DC setting value (%d)",
2668
0
                         cparams.progressive_dc);
2669
0
    }
2670
0
    cparams.progressive_dc = 0;
2671
0
  }
2672
0
  if (cparams.ec_resampling < cparams.resampling) {
2673
0
    cparams.ec_resampling = cparams.resampling;
2674
0
  }
2675
0
  if (cparams.resampling > 1 ||
2676
0
      frame_info.is_preview
2677
      // LF frame extra channels not implemented yet, for images with alpha
2678
      // level 1 doesn't render and level 2 corrupts the image.
2679
0
      || metadata->m.num_extra_channels > 0) {
2680
0
    cparams.progressive_dc = 0;
2681
0
  }
2682
2683
0
  if (frame_info.dc_level + cparams.progressive_dc > 4) {
2684
0
    return JXL_FAILURE("Too many levels of progressive DC");
2685
0
  }
2686
2687
0
  if (cparams.modular_mode == false &&
2688
0
      cparams.butteraugli_distance < kMinButteraugliDistance) {
2689
0
    return JXL_FAILURE("Butteraugli distance is too low (%f)",
2690
0
                       cparams.butteraugli_distance);
2691
0
  }
2692
2693
0
  if (frame_data.IsJPEG()) {
2694
0
    cparams.gaborish = Override::kOff;
2695
0
    cparams.epf = 0;
2696
0
    cparams.modular_mode = false;
2697
0
  }
2698
2699
0
  if (frame_data.xsize == 0 || frame_data.ysize == 0) {
2700
0
    return JXL_FAILURE("Empty image");
2701
0
  }
2702
2703
  // Assert that this metadata is correctly set up for the compression params,
2704
  // this should have been done by enc_file.cc
2705
0
  JXL_ENSURE(metadata->m.xyb_encoded ==
2706
0
             (cparams.color_transform == ColorTransform::kXYB));
2707
2708
0
  if (frame_data.IsJPEG() && cparams.color_transform == ColorTransform::kXYB) {
2709
0
    return JXL_FAILURE("Can't add JPEG frame to XYB codestream");
2710
0
  }
2711
2712
0
  if (CanDoStreamingEncoding(cparams, frame_info, *metadata, frame_data)) {
2713
0
    return EncodeFrameStreaming(memory_manager, cparams, frame_info, metadata,
2714
0
                                frame_data, cms, pool, output_processor,
2715
0
                                aux_out, jxlp_counter);
2716
0
  } else {
2717
0
    if (cparams.output_mode == 2 && jxlp_counter != nullptr) {
2718
      // Leave a 12-byte gap for the jxlp box header; encode.cc fills it in.
2719
0
      JXL_RETURN_IF_ERROR(
2720
0
          output_processor->Seek(output_processor->CurrentPosition() + 12));
2721
0
    }
2722
0
    return EncodeFrameOneShot(memory_manager, cparams, frame_info, metadata,
2723
0
                              frame_data, cms, pool, output_processor, aux_out);
2724
0
  }
2725
0
}
2726
2727
Status EncodeFrame(JxlMemoryManager* memory_manager,
2728
                   const CompressParams& cparams_orig,
2729
                   const FrameInfo& frame_info, const CodecMetadata* metadata,
2730
                   ImageBundle& ib, const JxlCmsInterface& cms,
2731
0
                   ThreadPool* pool, BitWriter* writer, AuxOut* aux_out) {
2732
0
  JxlEncoderChunkedFrameAdapter frame_data(ib.xsize(), ib.ysize(),
2733
0
                                           ib.extra_channels().size());
2734
0
  std::vector<uint8_t> color;
2735
0
  if (ib.IsJPEG()) {
2736
0
    frame_data.SetJPEGData(std::move(ib.jpeg_data));
2737
0
  } else {
2738
0
    uint32_t num_channels =
2739
0
        ib.IsGray() && frame_info.ib_needs_color_transform ? 1 : 3;
2740
0
    size_t stride = ib.xsize() * num_channels * 4;
2741
0
    color.resize(ib.ysize() * stride);
2742
0
    JXL_RETURN_IF_ERROR(ConvertToExternal(
2743
0
        ib, /*bits_per_sample=*/32, /*float_out=*/true, num_channels,
2744
0
        JXL_NATIVE_ENDIAN, stride, pool, color.data(), color.size(),
2745
0
        /*out_callback=*/{}, Orientation::kIdentity));
2746
0
    JxlPixelFormat format{num_channels, JXL_TYPE_FLOAT, JXL_NATIVE_ENDIAN, 0};
2747
0
    frame_data.SetFromBuffer(0, color.data(), color.size(), format);
2748
0
  }
2749
0
  for (size_t ec = 0; ec < ib.extra_channels().size(); ++ec) {
2750
0
    JxlPixelFormat ec_format{1, JXL_TYPE_FLOAT, JXL_NATIVE_ENDIAN, 0};
2751
0
    size_t ec_stride = ib.xsize() * 4;
2752
0
    std::vector<uint8_t> ec_data(ib.ysize() * ec_stride);
2753
0
    const ImageF* channel = &ib.extra_channels()[ec];
2754
0
    JXL_RETURN_IF_ERROR(ConvertChannelsToExternal(
2755
0
        &channel, 1,
2756
0
        /*bits_per_sample=*/32,
2757
0
        /*float_out=*/true, JXL_NATIVE_ENDIAN, ec_stride, pool, ec_data.data(),
2758
0
        ec_data.size(), /*out_callback=*/{}, Orientation::kIdentity));
2759
0
    frame_data.SetFromBuffer(1 + ec, ec_data.data(), ec_data.size(), ec_format);
2760
0
  }
2761
0
  FrameInfo fi = frame_info;
2762
0
  fi.origin = ib.origin;
2763
0
  fi.blend = ib.blend;
2764
0
  fi.blendmode = ib.blendmode;
2765
0
  fi.duration = ib.duration;
2766
0
  fi.timecode = ib.timecode;
2767
0
  fi.name = ib.name;
2768
0
  JxlEncoderOutputProcessorWrapper output_processor(memory_manager);
2769
0
  JXL_RETURN_IF_ERROR(EncodeFrame(memory_manager, cparams_orig, fi, metadata,
2770
0
                                  frame_data, cms, pool, &output_processor,
2771
0
                                  aux_out, nullptr));
2772
0
  JXL_RETURN_IF_ERROR(output_processor.SetFinalizedPosition());
2773
0
  std::vector<uint8_t> output;
2774
0
  JXL_RETURN_IF_ERROR(output_processor.CopyOutput(output));
2775
0
  JXL_RETURN_IF_ERROR(writer->AppendByteAligned(Bytes(output)));
2776
0
  return true;
2777
0
}
2778
2779
}  // namespace jxl