Coverage Report

Created: 2025-08-12 07:37

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