Coverage Report

Created: 2025-11-16 07:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/enc_patch_dictionary.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_patch_dictionary.h"
7
8
#include <jxl/cms_interface.h>
9
#include <jxl/memory_manager.h>
10
#include <jxl/types.h>
11
12
#include <algorithm>
13
#include <atomic>
14
#include <cmath>
15
#include <cstdint>
16
#include <cstdlib>
17
#include <utility>
18
#include <vector>
19
20
#include "lib/jxl/base/common.h"
21
#include "lib/jxl/base/compiler_specific.h"
22
#include "lib/jxl/base/data_parallel.h"
23
#include "lib/jxl/base/override.h"
24
#include "lib/jxl/base/printf_macros.h"
25
#include "lib/jxl/base/random.h"
26
#include "lib/jxl/base/rect.h"
27
#include "lib/jxl/base/span.h"
28
#include "lib/jxl/base/status.h"
29
#include "lib/jxl/common.h"
30
#include "lib/jxl/dec_cache.h"
31
#include "lib/jxl/dec_frame.h"
32
#include "lib/jxl/dec_patch_dictionary.h"
33
#include "lib/jxl/enc_ans.h"
34
#include "lib/jxl/enc_ans_params.h"
35
#include "lib/jxl/enc_aux_out.h"
36
#include "lib/jxl/enc_bit_writer.h"
37
#include "lib/jxl/enc_cache.h"
38
#include "lib/jxl/enc_debug_image.h"
39
#include "lib/jxl/enc_dot_dictionary.h"
40
#include "lib/jxl/enc_frame.h"
41
#include "lib/jxl/enc_params.h"
42
#include "lib/jxl/frame_header.h"
43
#include "lib/jxl/image.h"
44
#include "lib/jxl/image_bundle.h"
45
#include "lib/jxl/image_ops.h"
46
#include "lib/jxl/modular/options.h"
47
#include "lib/jxl/pack_signed.h"
48
#include "lib/jxl/patch_dictionary_internal.h"
49
50
namespace jxl {
51
52
static constexpr size_t kPatchFrameReferenceId = 3;
53
54
// static
55
Status PatchDictionaryEncoder::Encode(const PatchDictionary& pdic,
56
                                      BitWriter* writer, LayerType layer,
57
1.44k
                                      AuxOut* aux_out) {
58
1.44k
  JXL_ENSURE(pdic.HasAny());
59
1.44k
  JxlMemoryManager* memory_manager = writer->memory_manager();
60
1.44k
  std::vector<std::vector<Token>> tokens(1);
61
62
5.67M
  auto add_num = [&](int context, size_t num) {
63
5.67M
    tokens[0].emplace_back(context, static_cast<uint32_t>(num));
64
5.67M
  };
65
1.44k
  size_t num_ref_patch = 0;
66
114k
  for (size_t i = 0; i < pdic.positions_.size();) {
67
113k
    size_t ref_pos_idx = pdic.positions_[i].ref_pos_idx;
68
1.77M
    while (i < pdic.positions_.size() &&
69
1.77M
           pdic.positions_[i].ref_pos_idx == ref_pos_idx) {
70
1.66M
      i++;
71
1.66M
    }
72
113k
    num_ref_patch++;
73
113k
  }
74
1.44k
  add_num(kNumRefPatchContext, num_ref_patch);
75
1.44k
  size_t blend_pos = 0;
76
1.44k
  size_t blending_stride = pdic.blendings_stride_;
77
  // blending_stride == num_ec + 1; num_ec > 1 =>
78
1.44k
  bool choose_alpha = (blending_stride > 1 + 1);
79
114k
  for (size_t i = 0; i < pdic.positions_.size();) {
80
113k
    size_t i_start = i;
81
113k
    size_t ref_pos_idx = pdic.positions_[i].ref_pos_idx;
82
113k
    const auto& ref_pos = pdic.ref_positions_[ref_pos_idx];
83
1.77M
    while (i < pdic.positions_.size() &&
84
1.77M
           pdic.positions_[i].ref_pos_idx == ref_pos_idx) {
85
1.66M
      i++;
86
1.66M
    }
87
113k
    size_t num = i - i_start;
88
113k
    JXL_ENSURE(num > 0);
89
113k
    add_num(kReferenceFrameContext, ref_pos.ref);
90
113k
    add_num(kPatchReferencePositionContext, ref_pos.x0);
91
113k
    add_num(kPatchReferencePositionContext, ref_pos.y0);
92
113k
    add_num(kPatchSizeContext, ref_pos.xsize - 1);
93
113k
    add_num(kPatchSizeContext, ref_pos.ysize - 1);
94
113k
    add_num(kPatchCountContext, num - 1);
95
1.77M
    for (size_t j = i_start; j < i; j++) {
96
1.66M
      const PatchPosition& pos = pdic.positions_[j];
97
1.66M
      if (j == i_start) {
98
113k
        add_num(kPatchPositionContext, pos.x);
99
113k
        add_num(kPatchPositionContext, pos.y);
100
1.55M
      } else {
101
1.55M
        add_num(kPatchOffsetContext,
102
1.55M
                PackSigned(pos.x - pdic.positions_[j - 1].x));
103
1.55M
        add_num(kPatchOffsetContext,
104
1.55M
                PackSigned(pos.y - pdic.positions_[j - 1].y));
105
1.55M
      }
106
3.32M
      for (size_t k = 0; k < blending_stride; ++k, ++blend_pos) {
107
1.66M
        const PatchBlending& info = pdic.blendings_[blend_pos];
108
1.66M
        add_num(kPatchBlendModeContext, static_cast<uint32_t>(info.mode));
109
1.66M
        if (UsesAlpha(info.mode) && choose_alpha) {
110
0
          add_num(kPatchAlphaChannelContext, info.alpha_channel);
111
0
        }
112
1.66M
        if (UsesClamp(info.mode)) {
113
0
          add_num(kPatchClampContext, TO_JXL_BOOL(info.clamp));
114
0
        }
115
1.66M
      }
116
1.66M
    }
117
113k
  }
118
119
1.44k
  EntropyEncodingData codes;
120
1.44k
  JXL_ASSIGN_OR_RETURN(
121
1.44k
      size_t cost, BuildAndEncodeHistograms(memory_manager, HistogramParams(),
122
1.44k
                                            kNumPatchDictionaryContexts, tokens,
123
1.44k
                                            &codes, writer, layer, aux_out));
124
1.44k
  (void)cost;
125
1.44k
  JXL_RETURN_IF_ERROR(WriteTokens(tokens[0], codes, 0, writer, layer, aux_out));
126
1.44k
  return true;
127
1.44k
}
128
129
// static
130
Status PatchDictionaryEncoder::SubtractFrom(const PatchDictionary& pdic,
131
4.92k
                                            Image3F* opsin) {
132
  // TODO(veluca): this can likely be optimized knowing it runs on full images.
133
932k
  for (size_t y = 0; y < opsin->ysize(); y++) {
134
927k
    float* JXL_RESTRICT rows[3] = {
135
927k
        opsin->PlaneRow(0, y),
136
927k
        opsin->PlaneRow(1, y),
137
927k
        opsin->PlaneRow(2, y),
138
927k
    };
139
927k
    size_t blending_stride = pdic.blendings_stride_;
140
4.01M
    for (size_t pos_idx : pdic.GetPatchesForRow(y)) {
141
4.01M
      const size_t blending_idx = pos_idx * blending_stride;
142
4.01M
      const PatchPosition& pos = pdic.positions_[pos_idx];
143
4.01M
      const PatchReferencePosition& ref_pos =
144
4.01M
          pdic.ref_positions_[pos.ref_pos_idx];
145
4.01M
      const PatchBlendMode mode = pdic.blendings_[blending_idx].mode;
146
4.01M
      size_t by = pos.y;
147
4.01M
      size_t bx = pos.x;
148
4.01M
      size_t xsize = ref_pos.xsize;
149
4.01M
      JXL_ENSURE(y >= by);
150
4.01M
      JXL_ENSURE(y < by + ref_pos.ysize);
151
4.01M
      size_t iy = y - by;
152
4.01M
      size_t ref = ref_pos.ref;
153
4.01M
      const float* JXL_RESTRICT ref_rows[3] = {
154
4.01M
          pdic.reference_frames_->at(ref).frame->color()->ConstPlaneRow(
155
4.01M
              0, ref_pos.y0 + iy) +
156
4.01M
              ref_pos.x0,
157
4.01M
          pdic.reference_frames_->at(ref).frame->color()->ConstPlaneRow(
158
4.01M
              1, ref_pos.y0 + iy) +
159
4.01M
              ref_pos.x0,
160
4.01M
          pdic.reference_frames_->at(ref).frame->color()->ConstPlaneRow(
161
4.01M
              2, ref_pos.y0 + iy) +
162
4.01M
              ref_pos.x0,
163
4.01M
      };
164
31.6M
      for (size_t ix = 0; ix < xsize; ix++) {
165
110M
        for (size_t c = 0; c < 3; c++) {
166
82.8M
          if (mode == PatchBlendMode::kAdd) {
167
82.8M
            rows[c][bx + ix] -= ref_rows[c][ix];
168
82.8M
          } else if (mode == PatchBlendMode::kReplace) {
169
0
            rows[c][bx + ix] = 0;
170
0
          } else if (mode == PatchBlendMode::kNone) {
171
            // Nothing to do.
172
0
          } else {
173
0
            return JXL_UNREACHABLE("blending mode %u not yet implemented",
174
0
                                   static_cast<uint32_t>(mode));
175
0
          }
176
82.8M
        }
177
27.6M
      }
178
4.01M
    }
179
927k
  }
180
4.92k
  return true;
181
4.92k
}
182
183
namespace {
184
185
struct PatchColorspaceInfo {
186
  float kChannelDequant[3];
187
  float kChannelWeights[3];
188
189
3.48k
  explicit PatchColorspaceInfo(bool is_xyb) {
190
3.48k
    if (is_xyb) {
191
3.48k
      kChannelDequant[0] = 0.01615;
192
3.48k
      kChannelDequant[1] = 0.08875;
193
3.48k
      kChannelDequant[2] = 0.1922;
194
3.48k
      kChannelWeights[0] = 30.0;
195
3.48k
      kChannelWeights[1] = 3.0;
196
3.48k
      kChannelWeights[2] = 1.0;
197
3.48k
    } else {
198
0
      kChannelDequant[0] = 20.0f / 255;
199
0
      kChannelDequant[1] = 22.0f / 255;
200
0
      kChannelDequant[2] = 20.0f / 255;
201
0
      kChannelWeights[0] = 0.017 * 255;
202
0
      kChannelWeights[1] = 0.02 * 255;
203
0
      kChannelWeights[2] = 0.017 * 255;
204
0
    }
205
3.48k
  }
206
207
153M
  float ScaleForQuantization(float val, size_t c) {
208
153M
    return val / kChannelDequant[c];
209
153M
  }
210
211
153M
  int Quantize(float val, size_t c) {
212
153M
    return std::trunc(ScaleForQuantization(val, c));
213
153M
  }
214
215
394M
  bool is_similar_v(const Color& v1, const Color& v2, float threshold) {
216
394M
    float distance = 0;
217
1.57G
    for (size_t c = 0; c < 3; c++) {
218
1.18G
      distance += std::abs(v1[c] - v2[c]) * kChannelWeights[c];
219
1.18G
    }
220
394M
    return distance <= threshold;
221
394M
  }
222
};
223
224
using XY = std::pair<int32_t, int32_t>;
225
constexpr const size_t kPatchSide = 4;
226
227
StatusOr<std::vector<PatchInfo>> FindTextLikePatches(
228
    const CompressParams& cparams, const Image3F& opsin,
229
    const PassesEncoderState* JXL_RESTRICT state, ThreadPool* pool,
230
4.92k
    AuxOut* aux_out, bool is_xyb) {
231
4.92k
  std::vector<PatchInfo> info;
232
4.92k
  if (state->cparams.patches == Override::kOff) return info;
233
3.48k
  const auto& frame_dim = state->shared.frame_dim;
234
3.48k
  JxlMemoryManager* memory_manager = opsin.memory_manager();
235
236
3.48k
  PatchColorspaceInfo pci(is_xyb);
237
3.48k
  float kSimilarThreshold = 0.8f;
238
239
3.48k
  auto is_similar_impl = [&pci](const XY& p1, const XY& p2,
240
3.48k
                                const float* JXL_RESTRICT rows[3],
241
261M
                                size_t stride, float threshold) {
242
261M
    size_t offset1 = p1.second * stride + p1.first;
243
261M
    Color v1{rows[0][offset1], rows[1][offset1], rows[2][offset1]};
244
261M
    size_t offset2 = p2.second * stride + p2.first;
245
261M
    Color v2{rows[0][offset2], rows[1][offset2], rows[2][offset2]};
246
261M
    return pci.is_similar_v(v1, v2, threshold);
247
261M
  };
248
249
3.48k
  std::atomic<uint32_t> screenshot_area_seeds{0};
250
3.48k
  const size_t opsin_stride = opsin.PixelsPerRow();
251
3.48k
  const float* JXL_RESTRICT opsin_rows[3] = {opsin.ConstPlaneRow(0, 0),
252
3.48k
                                             opsin.ConstPlaneRow(1, 0),
253
3.48k
                                             opsin.ConstPlaneRow(2, 0)};
254
18.1M
  const auto pick = [&opsin_rows, opsin_stride](const XY& p) -> Color {
255
18.1M
    size_t offset = p.second * opsin_stride + p.first;
256
18.1M
    return {opsin_rows[0][offset], opsin_rows[1][offset],
257
18.1M
            opsin_rows[2][offset]};
258
18.1M
  };
259
3.48k
  const auto is_same_color = [&opsin_rows, opsin_stride](
260
208M
                                 const XY& p, const Color& c) -> size_t {
261
208M
    const size_t offset = p.second * opsin_stride + p.first;
262
788M
    for (size_t i = 0; i < c.size(); ++i) {
263
596M
      if (std::fabs(c[i] - opsin_rows[i][offset]) > 1e-4) {
264
16.5M
        return 0;
265
16.5M
      }
266
596M
    }
267
192M
    return 1;
268
208M
  };
269
270
181M
  auto is_similar = [&](const XY& p1, const XY& p2) {
271
181M
    return is_similar_impl(p1, p2, opsin_rows, opsin_stride, kSimilarThreshold);
272
181M
  };
273
274
  // Look for kPatchSide size squares, naturally aligned, that all have the same
275
  // pixel values.
276
3.48k
  JXL_ASSIGN_OR_RETURN(
277
3.48k
      ImageB is_screenshot_like,
278
3.48k
      ImageB::Create(memory_manager, DivCeil(frame_dim.xsize, kPatchSide),
279
3.48k
                     DivCeil(frame_dim.ysize, kPatchSide)));
280
3.48k
  ZeroFillImage(&is_screenshot_like);
281
3.48k
  const size_t pw = frame_dim.xsize / kPatchSide;
282
3.48k
  const size_t ph = frame_dim.ysize / kPatchSide;
283
284
18.1M
  const auto flat_patch = [&](const XY& o, const Color& base) -> bool {
285
48.7M
    for (size_t iy = 0; iy < kPatchSide; iy++) {
286
180M
      for (size_t ix = 0; ix < kPatchSide; ix++) {
287
149M
        XY p = {static_cast<int32_t>(o.first + ix),
288
149M
                static_cast<int32_t>(o.second + iy)};
289
149M
        if (!is_same_color(p, base)) {
290
11.5M
          return false;
291
11.5M
        }
292
149M
      }
293
42.2M
    }
294
6.59M
    return true;
295
18.1M
  };
296
297
  // TODO(eustas): should do this in 2 phases:
298
  //   1) if patches are not enabled do sampling run for has_screenshot_areas
299
  //   2) if patches forced or not disables + has_screenshot_areas do
300
  //      SIMDified full scan for is_screenshot_like
301
3.48k
  const auto process_row = [&](const uint32_t py,
302
192k
                               size_t /* thread */) -> Status {
303
192k
    uint32_t found = 0;
304
18.3M
    for (size_t px = 1; px <= pw - 2; px++) {
305
18.1M
      XY o = {static_cast<uint32_t>(px * kPatchSide),
306
18.1M
              static_cast<uint32_t>(py * kPatchSide)};
307
18.1M
      Color base = pick(o);
308
18.1M
      if (!flat_patch(o, base)) continue;
309
6.59M
      size_t num_same = 0;
310
26.3M
      for (size_t y = (py - 1) * kPatchSide; y <= (py + 1) * kPatchSide;
311
19.7M
           y += kPatchSide) {
312
79.0M
        for (size_t x = (px - 1) * kPatchSide; x <= (px + 1) * kPatchSide;
313
59.3M
             x += kPatchSide) {
314
59.3M
          XY p = {static_cast<uint32_t>(x), static_cast<uint32_t>(y)};
315
59.3M
          num_same += is_same_color(p, base);
316
59.3M
        }
317
19.7M
      }
318
      // Too few equal pixels nearby.
319
6.59M
      if (num_same < 8) continue;
320
5.18M
      is_screenshot_like.Row(py)[px] = 1;
321
5.18M
      found++;
322
5.18M
    }
323
192k
    screenshot_area_seeds.fetch_add(found);
324
192k
    return true;
325
192k
  };
326
3.48k
  bool can_have_seeds = ((pw >= 3) && (ph >= 3));
327
3.48k
  if (can_have_seeds) {
328
3.14k
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 1, ph - 2, ThreadPool::NoInit,
329
3.14k
                                  process_row, "IsScreenshotLike"));
330
3.14k
  }
331
332
  // TODO(veluca): also parallelize the rest of this function.
333
3.48k
  if (WantDebugOutput(cparams)) {
334
0
    JXL_RETURN_IF_ERROR(
335
0
        DumpPlaneNormalized(cparams, "screenshot_like", is_screenshot_like));
336
0
  }
337
338
3.48k
  constexpr int kSearchRadius = 1;
339
340
3.48k
  size_t num_seeds = screenshot_area_seeds.load();
341
3.48k
  if (!ApplyOverride(state->cparams.patches, (num_seeds > 0))) {
342
1.23k
    return info;
343
1.23k
  }
344
345
  // Search for "similar enough" pixels near the screenshot-like areas.
346
4.51k
  JXL_ASSIGN_OR_RETURN(
347
4.51k
      ImageB is_background,
348
4.51k
      ImageB::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
349
4.51k
  ZeroFillImage(&is_background);
350
4.51k
  JXL_ASSIGN_OR_RETURN(
351
2.25k
      Image3F background,
352
2.25k
      Image3F::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
353
2.25k
  ZeroFillImage(&background);
354
2.25k
  constexpr size_t kDistanceLimit = 50;
355
2.25k
  float* JXL_RESTRICT background_rows[3] = {
356
2.25k
      background.PlaneRow(0, 0),
357
2.25k
      background.PlaneRow(1, 0),
358
2.25k
      background.PlaneRow(2, 0),
359
2.25k
  };
360
2.25k
  const size_t background_stride = background.PixelsPerRow();
361
2.25k
  uint8_t* JXL_RESTRICT is_background_row = is_background.Row(0);
362
2.25k
  const size_t is_background_stride = is_background.PixelsPerRow();
363
1.70G
  const auto is_bg = [&](const XY& p) -> uint8_t& {
364
1.70G
    return is_background_row[p.second * is_background_stride + p.first];
365
1.70G
  };
366
2.25k
  std::vector<std::pair<XY, XY>> queue;
367
2.25k
  queue.reserve(2 * num_seeds * kPatchSide * kPatchSide);
368
2.25k
  size_t queue_front = 0;
369
  // TODO(eustas): coalesce neighbours, leave only border.
370
2.25k
  if (can_have_seeds) {
371
155k
    for (size_t py = 1; py < ph - 1; py++) {
372
153k
      uint8_t* JXL_RESTRICT screenshot_row = is_screenshot_like.Row(py);
373
14.1M
      for (size_t px = 1; px < pw - 1; px++) {
374
14.0M
        if (!screenshot_row[px]) continue;
375
25.9M
        for (size_t y = py * kPatchSide; y < (py + 1) * kPatchSide; ++y) {
376
103M
          for (size_t x = px * kPatchSide; x < (px + 1) * kPatchSide; ++x) {
377
83.0M
            XY p = {static_cast<uint32_t>(x), static_cast<uint32_t>(y)};
378
83.0M
            queue.emplace_back(p, p);
379
83.0M
            is_bg(p) = 1;
380
83.0M
          }
381
20.7M
        }
382
5.18M
      }
383
153k
    }
384
2.25k
  }
385
180M
  while (queue_front < queue.size()) {
386
180M
    XY cur = queue[queue_front].first;
387
180M
    XY src = queue[queue_front].second;
388
180M
    queue_front++;
389
180M
    Color src_color;
390
722M
    for (size_t c = 0; c < 3; c++) {
391
541M
      float clr = opsin_rows[c][src.second * opsin_stride + src.first];
392
541M
      src_color[c] = clr;
393
541M
      background_rows[c][cur.second * background_stride + cur.first] = clr;
394
541M
    }
395
722M
    for (int dx = -kSearchRadius; dx <= kSearchRadius; dx++) {
396
2.16G
      for (int dy = -kSearchRadius; dy <= kSearchRadius; dy++) {
397
1.62G
        XY next{cur.first + dx, cur.second + dy};
398
1.62G
        if (next.first < 0 || next.second < 0 ||
399
1.62G
            static_cast<uint32_t>(next.first) >= frame_dim.xsize ||
400
1.62G
            static_cast<uint32_t>(next.second) >= frame_dim.ysize) {
401
5.56M
          continue;
402
5.56M
        }
403
1.61G
        uint8_t& bg = is_bg(next);
404
1.61G
        if (bg) continue;
405
182M
        if (static_cast<uint32_t>(
406
182M
                std::abs(next.first - static_cast<int>(src.first)) +
407
182M
                std::abs(next.second - static_cast<int>(src.second))) >
408
182M
            kDistanceLimit) {
409
911k
          continue;
410
911k
        }
411
181M
        if (is_similar(src, next)) {
412
97.5M
          queue.emplace_back(next, src);
413
97.5M
          bg = 1;
414
97.5M
        }
415
181M
      }
416
541M
    }
417
180M
  }
418
2.25k
  queue.clear();
419
420
2.25k
  ImageF ccs;
421
2.25k
  Rng rng(0);
422
2.25k
  bool paint_ccs = false;
423
2.25k
  if (WantDebugOutput(cparams)) {
424
0
    JXL_RETURN_IF_ERROR(
425
0
        DumpPlaneNormalized(cparams, "is_background", is_background));
426
0
    if (is_xyb) {
427
0
      JXL_RETURN_IF_ERROR(DumpXybImage(cparams, "background", background));
428
0
    } else {
429
0
      JXL_RETURN_IF_ERROR(DumpImage(cparams, "background", background));
430
0
    }
431
0
    JXL_ASSIGN_OR_RETURN(
432
0
        ccs, ImageF::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
433
0
    ZeroFillImage(&ccs);
434
0
    paint_ccs = true;
435
0
  }
436
437
2.25k
  constexpr float kVerySimilarThreshold = 0.03f;
438
2.25k
  constexpr float kHasSimilarThreshold = 0.03f;
439
440
2.25k
  const float* JXL_RESTRICT const_background_rows[3] = {
441
2.25k
      background_rows[0], background_rows[1], background_rows[2]};
442
80.0M
  auto is_similar_b = [&](std::pair<int, int> p1, std::pair<int, int> p2) {
443
80.0M
    return is_similar_impl(p1, p2, const_background_rows, background_stride,
444
80.0M
                           kVerySimilarThreshold);
445
80.0M
  };
446
447
2.25k
  constexpr int kMinPeak = 2;
448
2.25k
  constexpr int kHasSimilarRadius = 2;
449
450
  // Find small CC outside the "similar enough" areas, compute bounding boxes,
451
  // and run heuristics to exclude some patches.
452
2.25k
  JXL_ASSIGN_OR_RETURN(
453
2.25k
      ImageB visited,
454
2.25k
      ImageB::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
455
2.25k
  ZeroFillImage(&visited);
456
2.25k
  uint8_t* JXL_RESTRICT visited_row = visited.Row(0);
457
2.25k
  const size_t visited_stride = visited.PixelsPerRow();
458
2.25k
  std::vector<std::pair<uint32_t, uint32_t>> cc;
459
2.25k
  std::vector<std::pair<uint32_t, uint32_t>> stack;
460
637k
  for (size_t y = 0; y < frame_dim.ysize; y++) {
461
237M
    for (size_t x = 0; x < frame_dim.xsize; x++) {
462
237M
      if (is_background_row[y * is_background_stride + x]) continue;
463
56.7M
      cc.clear();
464
56.7M
      stack.clear();
465
56.7M
      stack.emplace_back(static_cast<uint32_t>(x), static_cast<uint32_t>(y));
466
56.7M
      size_t min_x = x;
467
56.7M
      size_t max_x = x;
468
56.7M
      size_t min_y = y;
469
56.7M
      size_t max_y = y;
470
56.7M
      std::pair<uint32_t, uint32_t> reference;
471
56.7M
      bool found_border = false;
472
56.7M
      bool all_similar = true;
473
482M
      while (!stack.empty()) {
474
425M
        std::pair<uint32_t, uint32_t> cur = stack.back();
475
425M
        stack.pop_back();
476
425M
        if (visited_row[cur.second * visited_stride + cur.first]) continue;
477
56.7M
        visited_row[cur.second * visited_stride + cur.first] = 1;
478
56.7M
        if (cur.first < min_x) min_x = cur.first;
479
56.7M
        if (cur.first > max_x) max_x = cur.first;
480
56.7M
        if (cur.second < min_y) min_y = cur.second;
481
56.7M
        if (cur.second > max_y) max_y = cur.second;
482
56.7M
        if (paint_ccs) {
483
0
          cc.push_back(cur);
484
0
        }
485
226M
        for (int dx = -kSearchRadius; dx <= kSearchRadius; dx++) {
486
680M
          for (int dy = -kSearchRadius; dy <= kSearchRadius; dy++) {
487
510M
            if (dx == 0 && dy == 0) continue;
488
453M
            int next_first = static_cast<int32_t>(cur.first) + dx;
489
453M
            int next_second = static_cast<int32_t>(cur.second) + dy;
490
453M
            if (next_first < 0 || next_second < 0 ||
491
452M
                static_cast<uint32_t>(next_first) >= frame_dim.xsize ||
492
452M
                static_cast<uint32_t>(next_second) >= frame_dim.ysize) {
493
2.66M
              continue;
494
2.66M
            }
495
451M
            std::pair<uint32_t, uint32_t> next{next_first, next_second};
496
451M
            if (!is_background_row[next.second * is_background_stride +
497
451M
                                   next.first]) {
498
369M
              stack.push_back(next);
499
369M
            } else {
500
82.1M
              if (!found_border) {
501
2.14M
                reference = next;
502
2.14M
                found_border = true;
503
80.0M
              } else {
504
80.0M
                if (!is_similar_b(next, reference)) all_similar = false;
505
80.0M
              }
506
82.1M
            }
507
451M
          }
508
170M
        }
509
56.7M
      }
510
56.7M
      if (!found_border || !all_similar || max_x - min_x >= kMaxPatchSize ||
511
54.6M
          max_y - min_y >= kMaxPatchSize) {
512
54.6M
        continue;
513
54.6M
      }
514
2.05M
      size_t bpos = background_stride * reference.second + reference.first;
515
2.05M
      Color ref = {background_rows[0][bpos], background_rows[1][bpos],
516
2.05M
                   background_rows[2][bpos]};
517
2.05M
      bool has_similar = false;
518
2.05M
      for (size_t iy = std::max<int>(
519
2.05M
               static_cast<int32_t>(min_y) - kHasSimilarRadius, 0);
520
16.3M
           iy < std::min(max_y + kHasSimilarRadius + 1, frame_dim.ysize);
521
14.3M
           iy++) {
522
14.3M
        for (size_t ix = std::max<int>(
523
14.3M
                 static_cast<int32_t>(min_x) - kHasSimilarRadius, 0);
524
146M
             ix < std::min(max_x + kHasSimilarRadius + 1, frame_dim.xsize);
525
132M
             ix++) {
526
132M
          size_t opos = opsin_stride * iy + ix;
527
132M
          Color px = {opsin_rows[0][opos], opsin_rows[1][opos],
528
132M
                      opsin_rows[2][opos]};
529
132M
          if (pci.is_similar_v(ref, px, kHasSimilarThreshold)) {
530
87.6M
            has_similar = true;
531
87.6M
          }
532
132M
        }
533
14.3M
      }
534
2.05M
      if (!has_similar) continue;
535
2.05M
      info.emplace_back();
536
2.05M
      info.back().second.emplace_back(static_cast<uint32_t>(min_x),
537
2.05M
                                      static_cast<uint32_t>(min_y));
538
2.05M
      QuantizedPatch& patch = info.back().first;
539
2.05M
      patch.xsize = max_x - min_x + 1;
540
2.05M
      patch.ysize = max_y - min_y + 1;
541
2.05M
      int max_value = 0;
542
6.15M
      for (size_t c : {1, 0, 2}) {
543
24.5M
        for (size_t iy = min_y; iy <= max_y; iy++) {
544
172M
          for (size_t ix = min_x; ix <= max_x; ix++) {
545
153M
            size_t offset = (iy - min_y) * patch.xsize + ix - min_x;
546
153M
            patch.fpixels[c][offset] =
547
153M
                opsin_rows[c][iy * opsin_stride + ix] - ref[c];
548
153M
            int val = pci.Quantize(patch.fpixels[c][offset], c);
549
153M
            patch.pixels[c][offset] = val;
550
153M
            max_value = std::max(max_value, std::abs(val));
551
153M
          }
552
18.3M
        }
553
6.15M
      }
554
2.05M
      if (max_value < kMinPeak) {
555
22.1k
        info.pop_back();
556
22.1k
        continue;
557
22.1k
      }
558
2.02M
      if (paint_ccs) {
559
0
        float cc_color = rng.UniformF(0.5, 1.0);
560
0
        for (std::pair<uint32_t, uint32_t> p : cc) {
561
0
          ccs.Row(p.second)[p.first] = cc_color;
562
0
        }
563
0
      }
564
2.02M
    }
565
634k
  }
566
567
2.25k
  if (paint_ccs) {
568
0
    JXL_ENSURE(WantDebugOutput(cparams));
569
0
    JXL_RETURN_IF_ERROR(DumpPlaneNormalized(cparams, "ccs", ccs));
570
0
  }
571
2.25k
  if (info.empty()) {
572
414
    return info;
573
414
  }
574
575
  // Remove duplicates.
576
1.84k
  constexpr size_t kMinPatchOccurrences = 2;
577
1.84k
  std::sort(info.begin(), info.end());
578
1.84k
  size_t unique = 0;
579
2.02M
  for (size_t i = 1; i < info.size(); i++) {
580
2.02M
    if (info[i].first == info[unique].first) {
581
1.61M
      info[unique].second.insert(info[unique].second.end(),
582
1.61M
                                 info[i].second.begin(), info[i].second.end());
583
1.61M
    } else {
584
410k
      if (info[unique].second.size() >= kMinPatchOccurrences) {
585
117k
        unique++;
586
117k
      }
587
410k
      info[unique] = info[i];
588
410k
    }
589
2.02M
  }
590
1.84k
  if (info[unique].second.size() >= kMinPatchOccurrences) {
591
482
    unique++;
592
482
  }
593
1.84k
  info.resize(unique);
594
595
1.84k
  size_t max_patch_size = 0;
596
597
117k
  for (const auto& patch : info) {
598
117k
    size_t pixels = patch.first.xsize * patch.first.ysize;
599
117k
    if (pixels > max_patch_size) max_patch_size = pixels;
600
117k
  }
601
602
  // don't use patches if all patches are smaller than this
603
1.84k
  constexpr size_t kMinMaxPatchSize = 20;
604
1.84k
  if (max_patch_size < kMinMaxPatchSize) {
605
397
    info.clear();
606
397
  }
607
608
1.84k
  return info;
609
2.25k
}
610
611
}  // namespace
612
613
Status FindBestPatchDictionary(const Image3F& opsin,
614
                               PassesEncoderState* JXL_RESTRICT state,
615
                               const JxlCmsInterface& cms, ThreadPool* pool,
616
4.92k
                               AuxOut* aux_out, bool is_xyb) {
617
4.92k
  JXL_ASSIGN_OR_RETURN(
618
4.92k
      std::vector<PatchInfo> info,
619
4.92k
      FindTextLikePatches(state->cparams, opsin, state, pool, aux_out, is_xyb));
620
4.92k
  JxlMemoryManager* memory_manager = opsin.memory_manager();
621
622
  // TODO(veluca): this doesn't work if both dots and patches are enabled.
623
  // For now, since dots and patches are not likely to occur in the same kind of
624
  // images, disable dots if some patches were found.
625
4.92k
  if (info.empty() &&
626
3.48k
      ApplyOverride(
627
3.48k
          state->cparams.dots,
628
3.48k
          state->cparams.speed_tier <= SpeedTier::kSquirrel &&
629
3.48k
              state->cparams.butteraugli_distance >= kMinButteraugliForDots &&
630
0
              !state->cparams.disable_perceptual_optimizations)) {
631
0
    Rect rect(0, 0, state->shared.frame_dim.xsize,
632
0
              state->shared.frame_dim.ysize);
633
0
    JXL_ASSIGN_OR_RETURN(info,
634
0
                         FindDotDictionary(state->cparams, opsin, rect,
635
0
                                           state->shared.cmap.base(), pool));
636
0
  }
637
638
4.92k
  if (info.empty()) return true;
639
640
1.44k
  std::sort(
641
610k
      info.begin(), info.end(), [&](const PatchInfo& a, const PatchInfo& b) {
642
610k
        return a.first.xsize * a.first.ysize > b.first.xsize * b.first.ysize;
643
610k
      });
644
645
1.44k
  size_t max_x_size = 0;
646
1.44k
  size_t max_y_size = 0;
647
1.44k
  size_t total_pixels = 0;
648
649
113k
  for (const auto& patch : info) {
650
113k
    size_t pixels = patch.first.xsize * patch.first.ysize;
651
113k
    if (max_x_size < patch.first.xsize) max_x_size = patch.first.xsize;
652
113k
    if (max_y_size < patch.first.ysize) max_y_size = patch.first.ysize;
653
113k
    total_pixels += pixels;
654
113k
  }
655
656
  // Bin-packing & conversion of patches.
657
1.44k
  constexpr float kBinPackingSlackness = 1.05f;
658
1.44k
  size_t ref_xsize = std::max<float>(max_x_size, std::sqrt(total_pixels));
659
1.44k
  size_t ref_ysize = std::max<float>(max_y_size, std::sqrt(total_pixels));
660
1.44k
  std::vector<std::pair<size_t, size_t>> ref_positions(info.size());
661
  // TODO(veluca): allow partial overlaps of patches that have the same pixels.
662
1.44k
  size_t max_y = 0;
663
2.12k
  do {
664
2.12k
    max_y = 0;
665
    // Increase packed image size.
666
2.12k
    ref_xsize = ref_xsize * kBinPackingSlackness + 1;
667
2.12k
    ref_ysize = ref_ysize * kBinPackingSlackness + 1;
668
669
2.12k
    JXL_ASSIGN_OR_RETURN(ImageB occupied,
670
2.12k
                         ImageB::Create(memory_manager, ref_xsize, ref_ysize));
671
2.12k
    ZeroFillImage(&occupied);
672
2.12k
    uint8_t* JXL_RESTRICT occupied_rows = occupied.Row(0);
673
2.12k
    size_t occupied_stride = occupied.PixelsPerRow();
674
675
2.12k
    bool success = true;
676
    // For every patch...
677
120k
    for (size_t patch = 0; patch < info.size(); patch++) {
678
118k
      size_t x0 = 0;
679
118k
      size_t y0 = 0;
680
118k
      size_t xsize = info[patch].first.xsize;
681
118k
      size_t ysize = info[patch].first.ysize;
682
118k
      bool found = false;
683
      // For every possible start position ...
684
7.42M
      for (; y0 + ysize <= ref_ysize; y0++) {
685
7.42M
        x0 = 0;
686
914M
        for (; x0 + xsize <= ref_xsize; x0++) {
687
907M
          bool has_occupied_pixel = false;
688
907M
          size_t x = x0;
689
          // Check if it is possible to place the patch in this position in the
690
          // reference frame.
691
7.40G
          for (size_t y = y0; y < y0 + ysize; y++) {
692
6.49G
            x = x0;
693
7.25G
            for (; x < x0 + xsize; x++) {
694
7.21G
              if (occupied_rows[y * occupied_stride + x]) {
695
6.46G
                has_occupied_pixel = true;
696
6.46G
                break;
697
6.46G
              }
698
7.21G
            }
699
6.49G
          }  // end of positioning check
700
907M
          if (!has_occupied_pixel) {
701
117k
            found = true;
702
117k
            break;
703
117k
          }
704
906M
          x0 = x;  // Jump to next pixel after the occupied one.
705
906M
        }
706
7.42M
        if (found) break;
707
7.42M
      }  // end of start position checking
708
709
      // We didn't find a possible position: repeat from the beginning with a
710
      // larger reference frame size.
711
118k
      if (!found) {
712
683
        success = false;
713
683
        break;
714
683
      }
715
716
      // We found a position: mark the corresponding positions in the reference
717
      // image as used.
718
117k
      ref_positions[patch] = {x0, y0};
719
868k
      for (size_t y = y0; y < y0 + ysize; y++) {
720
10.1M
        for (size_t x = x0; x < x0 + xsize; x++) {
721
9.39M
          occupied_rows[y * occupied_stride + x] = JXL_TRUE;
722
9.39M
        }
723
750k
      }
724
117k
      max_y = std::max(max_y, y0 + ysize);
725
117k
    }
726
727
2.12k
    if (success) break;
728
2.12k
  } while (true);
729
730
1.44k
  JXL_ENSURE(ref_ysize >= max_y);
731
732
1.44k
  ref_ysize = max_y;
733
734
1.44k
  JXL_ASSIGN_OR_RETURN(Image3F reference_frame,
735
1.44k
                       Image3F::Create(memory_manager, ref_xsize, ref_ysize));
736
  // TODO(veluca): figure out a better way to fill the image.
737
1.44k
  ZeroFillImage(&reference_frame);
738
1.44k
  std::vector<PatchPosition> positions;
739
1.44k
  std::vector<PatchReferencePosition> pref_positions;
740
1.44k
  std::vector<PatchBlending> blendings;
741
1.44k
  float* JXL_RESTRICT ref_rows[3] = {
742
1.44k
      reference_frame.PlaneRow(0, 0),
743
1.44k
      reference_frame.PlaneRow(1, 0),
744
1.44k
      reference_frame.PlaneRow(2, 0),
745
1.44k
  };
746
1.44k
  size_t ref_stride = reference_frame.PixelsPerRow();
747
1.44k
  size_t num_ec = state->shared.metadata->m.num_extra_channels;
748
749
114k
  for (size_t i = 0; i < info.size(); i++) {
750
113k
    PatchReferencePosition ref_pos;
751
113k
    ref_pos.xsize = info[i].first.xsize;
752
113k
    ref_pos.ysize = info[i].first.ysize;
753
113k
    ref_pos.x0 = ref_positions[i].first;
754
113k
    ref_pos.y0 = ref_positions[i].second;
755
113k
    ref_pos.ref = kPatchFrameReferenceId;
756
816k
    for (size_t y = 0; y < ref_pos.ysize; y++) {
757
9.47M
      for (size_t x = 0; x < ref_pos.xsize; x++) {
758
35.0M
        for (size_t c = 0; c < 3; c++) {
759
26.3M
          ref_rows[c][(y + ref_pos.y0) * ref_stride + x + ref_pos.x0] =
760
26.3M
              info[i].first.fpixels[c][y * ref_pos.xsize + x];
761
26.3M
        }
762
8.77M
      }
763
703k
    }
764
1.66M
    for (const auto& pos : info[i].second) {
765
1.66M
      JXL_DEBUG_V(4, "Patch %" PRIuS "x%" PRIuS " at position %u,%u",
766
1.66M
                  ref_pos.xsize, ref_pos.ysize, pos.first, pos.second);
767
1.66M
      positions.emplace_back(
768
1.66M
          PatchPosition{pos.first, pos.second, pref_positions.size()});
769
      // Add blending for color channels, ignore other channels.
770
1.66M
      blendings.push_back({PatchBlendMode::kAdd, 0, false});
771
1.66M
      for (size_t j = 0; j < num_ec; ++j) {
772
0
        blendings.push_back({PatchBlendMode::kNone, 0, false});
773
0
      }
774
1.66M
    }
775
113k
    pref_positions.emplace_back(ref_pos);
776
113k
  }
777
778
1.44k
  CompressParams cparams = state->cparams;
779
  // Recursive application of patches could create very weird issues.
780
1.44k
  cparams.patches = Override::kOff;
781
782
1.44k
  if (WantDebugOutput(cparams)) {
783
0
    if (is_xyb) {
784
0
      JXL_RETURN_IF_ERROR(
785
0
          DumpXybImage(cparams, "patch_reference", reference_frame));
786
0
    } else {
787
0
      JXL_RETURN_IF_ERROR(
788
0
          DumpImage(cparams, "patch_reference", reference_frame));
789
0
    }
790
0
  }
791
792
1.44k
  JXL_RETURN_IF_ERROR(RoundtripPatchFrame(&reference_frame, state,
793
1.44k
                                          kPatchFrameReferenceId, cparams, cms,
794
1.44k
                                          pool, aux_out, /*subtract=*/true));
795
796
  // TODO(veluca): this assumes that applying patches is commutative, which is
797
  // not true for all blending modes. This code only produces kAdd patches, so
798
  // this works out.
799
1.44k
  PatchDictionaryEncoder::SetPositions(
800
1.44k
      &state->shared.image_features.patches, std::move(positions),
801
1.44k
      std::move(pref_positions), std::move(blendings), num_ec + 1);
802
1.44k
  return true;
803
1.44k
}
804
805
Status RoundtripPatchFrame(Image3F* reference_frame,
806
                           PassesEncoderState* JXL_RESTRICT state, int idx,
807
                           CompressParams& cparams, const JxlCmsInterface& cms,
808
1.44k
                           ThreadPool* pool, AuxOut* aux_out, bool subtract) {
809
1.44k
  JxlMemoryManager* memory_manager = state->memory_manager();
810
1.44k
  FrameInfo patch_frame_info;
811
1.44k
  cparams.resampling = 1;
812
1.44k
  cparams.ec_resampling = 1;
813
1.44k
  cparams.dots = Override::kOff;
814
1.44k
  cparams.noise = Override::kOff;
815
1.44k
  cparams.modular_mode = true;
816
1.44k
  cparams.responsive = 0;
817
1.44k
  cparams.progressive_dc = 0;
818
1.44k
  cparams.progressive_mode = Override::kOff;
819
1.44k
  cparams.qprogressive_mode = Override::kOff;
820
  // Use gradient predictor and not Predictor::Best.
821
1.44k
  cparams.options.predictor = Predictor::Gradient;
822
1.44k
  patch_frame_info.save_as_reference = idx;  // always saved.
823
1.44k
  patch_frame_info.frame_type = FrameType::kReferenceOnly;
824
1.44k
  patch_frame_info.save_before_color_transform = true;
825
1.44k
  ImageBundle ib(memory_manager, &state->shared.metadata->m);
826
  // TODO(veluca): metadata.color_encoding is a lie: ib is in XYB, but there is
827
  // no simple way to express that yet.
828
1.44k
  patch_frame_info.ib_needs_color_transform = false;
829
1.44k
  JXL_RETURN_IF_ERROR(ib.SetFromImage(
830
1.44k
      std::move(*reference_frame), state->shared.metadata->m.color_encoding));
831
1.44k
  if (!ib.metadata()->extra_channel_info.empty()) {
832
    // Add placeholder extra channels to the patch image: patch encoding does
833
    // not yet support extra channels, but the codec expects that the amount of
834
    // extra channels in frames matches that in the metadata of the codestream.
835
0
    std::vector<ImageF> extra_channels;
836
0
    extra_channels.reserve(ib.metadata()->extra_channel_info.size());
837
0
    for (size_t i = 0; i < ib.metadata()->extra_channel_info.size(); i++) {
838
0
      JXL_ASSIGN_OR_RETURN(
839
0
          ImageF ch, ImageF::Create(memory_manager, ib.xsize(), ib.ysize()));
840
0
      extra_channels.emplace_back(std::move(ch));
841
      // Must initialize the image with data to not affect blending with
842
      // uninitialized memory.
843
      // TODO(lode): patches must copy and use the real extra channels instead.
844
0
      ZeroFillImage(&extra_channels.back());
845
0
    }
846
0
    JXL_RETURN_IF_ERROR(ib.SetExtraChannels(std::move(extra_channels)));
847
0
  }
848
1.44k
  auto special_frame = jxl::make_unique<BitWriter>(memory_manager);
849
1.44k
  AuxOut patch_aux_out;
850
1.44k
  JXL_RETURN_IF_ERROR(EncodeFrame(
851
1.44k
      memory_manager, cparams, patch_frame_info, state->shared.metadata, ib,
852
1.44k
      cms, pool, special_frame.get(), aux_out ? &patch_aux_out : nullptr));
853
1.44k
  if (aux_out) {
854
0
    for (const auto& l : patch_aux_out.layers) {
855
0
      aux_out->layer(LayerType::Dictionary).Assimilate(l);
856
0
    }
857
0
  }
858
1.44k
  const Span<const uint8_t> encoded = special_frame->GetSpan();
859
1.44k
  state->special_frames.emplace_back(std::move(special_frame));
860
1.44k
  if (subtract) {
861
1.44k
    ImageBundle decoded(memory_manager, &state->shared.metadata->m);
862
1.44k
    auto dec_state = jxl::make_unique<PassesDecoderState>(memory_manager);
863
1.44k
    JXL_RETURN_IF_ERROR(dec_state->output_encoding_info.SetFromMetadata(
864
1.44k
        *state->shared.metadata));
865
1.44k
    const uint8_t* frame_start = encoded.data();
866
1.44k
    size_t encoded_size = encoded.size();
867
1.44k
    JXL_RETURN_IF_ERROR(DecodeFrame(
868
1.44k
        dec_state.get(), pool, frame_start, encoded_size,
869
1.44k
        /*frame_header=*/nullptr, &decoded, *state->shared.metadata));
870
1.44k
    frame_start += decoded.decoded_bytes();
871
1.44k
    encoded_size -= decoded.decoded_bytes();
872
1.44k
    size_t ref_xsize =
873
1.44k
        dec_state->shared_storage.reference_frames[idx].frame->color()->xsize();
874
    // if the frame itself uses patches, we need to decode another frame
875
1.44k
    if (!ref_xsize) {
876
0
      JXL_RETURN_IF_ERROR(DecodeFrame(
877
0
          dec_state.get(), pool, frame_start, encoded_size,
878
0
          /*frame_header=*/nullptr, &decoded, *state->shared.metadata));
879
0
    }
880
1.44k
    JXL_ENSURE(encoded_size == 0);
881
1.44k
    state->shared.reference_frames[idx] =
882
1.44k
        std::move(dec_state->shared_storage.reference_frames[idx]);
883
1.44k
  } else {
884
0
    *state->shared.reference_frames[idx].frame = std::move(ib);
885
0
  }
886
1.44k
  return true;
887
1.44k
}
888
889
}  // namespace jxl