Coverage Report

Created: 2025-08-11 08:01

/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
1.08k
                                      AuxOut* aux_out) {
58
1.08k
  JXL_ENSURE(pdic.HasAny());
59
1.08k
  JxlMemoryManager* memory_manager = writer->memory_manager();
60
1.08k
  std::vector<std::vector<Token>> tokens(1);
61
62
4.95M
  auto add_num = [&](int context, size_t num) {
63
4.95M
    tokens[0].emplace_back(context, num);
64
4.95M
  };
65
1.08k
  size_t num_ref_patch = 0;
66
99.0k
  for (size_t i = 0; i < pdic.positions_.size();) {
67
98.0k
    size_t ref_pos_idx = pdic.positions_[i].ref_pos_idx;
68
1.55M
    while (i < pdic.positions_.size() &&
69
1.55M
           pdic.positions_[i].ref_pos_idx == ref_pos_idx) {
70
1.45M
      i++;
71
1.45M
    }
72
98.0k
    num_ref_patch++;
73
98.0k
  }
74
1.08k
  add_num(kNumRefPatchContext, num_ref_patch);
75
1.08k
  size_t blend_pos = 0;
76
1.08k
  size_t blending_stride = pdic.blendings_stride_;
77
  // blending_stride == num_ec + 1; num_ec > 1 =>
78
1.08k
  bool choose_alpha = (blending_stride > 1 + 1);
79
99.0k
  for (size_t i = 0; i < pdic.positions_.size();) {
80
98.0k
    size_t i_start = i;
81
98.0k
    size_t ref_pos_idx = pdic.positions_[i].ref_pos_idx;
82
98.0k
    const auto& ref_pos = pdic.ref_positions_[ref_pos_idx];
83
1.55M
    while (i < pdic.positions_.size() &&
84
1.55M
           pdic.positions_[i].ref_pos_idx == ref_pos_idx) {
85
1.45M
      i++;
86
1.45M
    }
87
98.0k
    size_t num = i - i_start;
88
98.0k
    JXL_ENSURE(num > 0);
89
98.0k
    add_num(kReferenceFrameContext, ref_pos.ref);
90
98.0k
    add_num(kPatchReferencePositionContext, ref_pos.x0);
91
98.0k
    add_num(kPatchReferencePositionContext, ref_pos.y0);
92
98.0k
    add_num(kPatchSizeContext, ref_pos.xsize - 1);
93
98.0k
    add_num(kPatchSizeContext, ref_pos.ysize - 1);
94
98.0k
    add_num(kPatchCountContext, num - 1);
95
1.55M
    for (size_t j = i_start; j < i; j++) {
96
1.45M
      const PatchPosition& pos = pdic.positions_[j];
97
1.45M
      if (j == i_start) {
98
98.0k
        add_num(kPatchPositionContext, pos.x);
99
98.0k
        add_num(kPatchPositionContext, pos.y);
100
1.35M
      } else {
101
1.35M
        add_num(kPatchOffsetContext,
102
1.35M
                PackSigned(pos.x - pdic.positions_[j - 1].x));
103
1.35M
        add_num(kPatchOffsetContext,
104
1.35M
                PackSigned(pos.y - pdic.positions_[j - 1].y));
105
1.35M
      }
106
2.90M
      for (size_t k = 0; k < blending_stride; ++k, ++blend_pos) {
107
1.45M
        const PatchBlending& info = pdic.blendings_[blend_pos];
108
1.45M
        add_num(kPatchBlendModeContext, static_cast<uint32_t>(info.mode));
109
1.45M
        if (UsesAlpha(info.mode) && choose_alpha) {
110
0
          add_num(kPatchAlphaChannelContext, info.alpha_channel);
111
0
        }
112
1.45M
        if (UsesClamp(info.mode)) {
113
0
          add_num(kPatchClampContext, TO_JXL_BOOL(info.clamp));
114
0
        }
115
1.45M
      }
116
1.45M
    }
117
98.0k
  }
118
119
1.08k
  EntropyEncodingData codes;
120
1.08k
  JXL_ASSIGN_OR_RETURN(
121
1.08k
      size_t cost, BuildAndEncodeHistograms(memory_manager, HistogramParams(),
122
1.08k
                                            kNumPatchDictionaryContexts, tokens,
123
1.08k
                                            &codes, writer, layer, aux_out));
124
1.08k
  (void)cost;
125
1.08k
  JXL_RETURN_IF_ERROR(WriteTokens(tokens[0], codes, 0, writer, layer, aux_out));
126
1.08k
  return true;
127
1.08k
}
128
129
// static
130
Status PatchDictionaryEncoder::SubtractFrom(const PatchDictionary& pdic,
131
3.37k
                                            Image3F* opsin) {
132
  // TODO(veluca): this can likely be optimized knowing it runs on full images.
133
637k
  for (size_t y = 0; y < opsin->ysize(); y++) {
134
634k
    float* JXL_RESTRICT rows[3] = {
135
634k
        opsin->PlaneRow(0, y),
136
634k
        opsin->PlaneRow(1, y),
137
634k
        opsin->PlaneRow(2, y),
138
634k
    };
139
634k
    size_t blending_stride = pdic.blendings_stride_;
140
3.62M
    for (size_t pos_idx : pdic.GetPatchesForRow(y)) {
141
3.62M
      const size_t blending_idx = pos_idx * blending_stride;
142
3.62M
      const PatchPosition& pos = pdic.positions_[pos_idx];
143
3.62M
      const PatchReferencePosition& ref_pos =
144
3.62M
          pdic.ref_positions_[pos.ref_pos_idx];
145
3.62M
      const PatchBlendMode mode = pdic.blendings_[blending_idx].mode;
146
3.62M
      size_t by = pos.y;
147
3.62M
      size_t bx = pos.x;
148
3.62M
      size_t xsize = ref_pos.xsize;
149
3.62M
      JXL_ENSURE(y >= by);
150
3.62M
      JXL_ENSURE(y < by + ref_pos.ysize);
151
3.62M
      size_t iy = y - by;
152
3.62M
      size_t ref = ref_pos.ref;
153
3.62M
      const float* JXL_RESTRICT ref_rows[3] = {
154
3.62M
          pdic.reference_frames_->at(ref).frame->color()->ConstPlaneRow(
155
3.62M
              0, ref_pos.y0 + iy) +
156
3.62M
              ref_pos.x0,
157
3.62M
          pdic.reference_frames_->at(ref).frame->color()->ConstPlaneRow(
158
3.62M
              1, ref_pos.y0 + iy) +
159
3.62M
              ref_pos.x0,
160
3.62M
          pdic.reference_frames_->at(ref).frame->color()->ConstPlaneRow(
161
3.62M
              2, ref_pos.y0 + iy) +
162
3.62M
              ref_pos.x0,
163
3.62M
      };
164
30.0M
      for (size_t ix = 0; ix < xsize; ix++) {
165
105M
        for (size_t c = 0; c < 3; c++) {
166
79.3M
          if (mode == PatchBlendMode::kAdd) {
167
79.3M
            rows[c][bx + ix] -= ref_rows[c][ix];
168
79.3M
          } 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
79.3M
        }
177
26.4M
      }
178
3.62M
    }
179
634k
  }
180
3.37k
  return true;
181
3.37k
}
182
183
namespace {
184
185
struct PatchColorspaceInfo {
186
  float kChannelDequant[3];
187
  float kChannelWeights[3];
188
189
2.29k
  explicit PatchColorspaceInfo(bool is_xyb) {
190
2.29k
    if (is_xyb) {
191
2.29k
      kChannelDequant[0] = 0.01615;
192
2.29k
      kChannelDequant[1] = 0.08875;
193
2.29k
      kChannelDequant[2] = 0.1922;
194
2.29k
      kChannelWeights[0] = 30.0;
195
2.29k
      kChannelWeights[1] = 3.0;
196
2.29k
      kChannelWeights[2] = 1.0;
197
2.29k
    } 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
2.29k
  }
206
207
132M
  float ScaleForQuantization(float val, size_t c) {
208
132M
    return val / kChannelDequant[c];
209
132M
  }
210
211
132M
  int Quantize(float val, size_t c) {
212
132M
    return std::trunc(ScaleForQuantization(val, c));
213
132M
  }
214
215
317M
  bool is_similar_v(const Color& v1, const Color& v2, float threshold) {
216
317M
    float distance = 0;
217
1.27G
    for (size_t c = 0; c < 3; c++) {
218
953M
      distance += std::abs(v1[c] - v2[c]) * kChannelWeights[c];
219
953M
    }
220
317M
    return distance <= threshold;
221
317M
  }
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
3.37k
    AuxOut* aux_out, bool is_xyb) {
231
3.37k
  std::vector<PatchInfo> info;
232
3.37k
  if (state->cparams.patches == Override::kOff) return info;
233
2.29k
  const auto& frame_dim = state->shared.frame_dim;
234
2.29k
  JxlMemoryManager* memory_manager = opsin.memory_manager();
235
236
2.29k
  PatchColorspaceInfo pci(is_xyb);
237
2.29k
  float kSimilarThreshold = 0.8f;
238
239
2.29k
  auto is_similar_impl = [&pci](const XY& p1, const XY& p2,
240
2.29k
                                const float* JXL_RESTRICT rows[3],
241
209M
                                size_t stride, float threshold) {
242
209M
    size_t offset1 = p1.second * stride + p1.first;
243
209M
    Color v1{rows[0][offset1], rows[1][offset1], rows[2][offset1]};
244
209M
    size_t offset2 = p2.second * stride + p2.first;
245
209M
    Color v2{rows[0][offset2], rows[1][offset2], rows[2][offset2]};
246
209M
    return pci.is_similar_v(v1, v2, threshold);
247
209M
  };
248
249
2.29k
  std::atomic<uint32_t> screenshot_area_seeds{0};
250
2.29k
  const size_t opsin_stride = opsin.PixelsPerRow();
251
2.29k
  const float* JXL_RESTRICT opsin_rows[3] = {opsin.ConstPlaneRow(0, 0),
252
2.29k
                                             opsin.ConstPlaneRow(1, 0),
253
2.29k
                                             opsin.ConstPlaneRow(2, 0)};
254
11.8M
  const auto pick = [&opsin_rows, opsin_stride](const XY& p) -> Color {
255
11.8M
    size_t offset = p.second * opsin_stride + p.first;
256
11.8M
    return {opsin_rows[0][offset], opsin_rows[1][offset],
257
11.8M
            opsin_rows[2][offset]};
258
11.8M
  };
259
2.29k
  const auto is_same_color = [&opsin_rows, opsin_stride](
260
157M
                                 const XY& p, const Color& c) -> size_t {
261
157M
    const size_t offset = p.second * opsin_stride + p.first;
262
598M
    for (size_t i = 0; i < c.size(); ++i) {
263
452M
      if (std::fabs(c[i] - opsin_rows[i][offset]) > 1e-4) {
264
11.0M
        return 0;
265
11.0M
      }
266
452M
    }
267
146M
    return 1;
268
157M
  };
269
270
143M
  auto is_similar = [&](const XY& p1, const XY& p2) {
271
143M
    return is_similar_impl(p1, p2, opsin_rows, opsin_stride, kSimilarThreshold);
272
143M
  };
273
274
  // Look for kPatchSide size squares, naturally aligned, that all have the same
275
  // pixel values.
276
2.29k
  JXL_ASSIGN_OR_RETURN(
277
2.29k
      ImageB is_screenshot_like,
278
2.29k
      ImageB::Create(memory_manager, DivCeil(frame_dim.xsize, kPatchSide),
279
2.29k
                     DivCeil(frame_dim.ysize, kPatchSide)));
280
2.29k
  ZeroFillImage(&is_screenshot_like);
281
2.29k
  const size_t pw = frame_dim.xsize / kPatchSide;
282
2.29k
  const size_t ph = frame_dim.ysize / kPatchSide;
283
284
11.8M
  const auto flat_patch = [&](const XY& o, const Color& base) -> bool {
285
35.6M
    for (size_t iy = 0; iy < kPatchSide; iy++) {
286
134M
      for (size_t ix = 0; ix < kPatchSide; ix++) {
287
110M
        if (!is_same_color({o.first + ix, o.second + iy}, base)) {
288
6.68M
          return false;
289
6.68M
        }
290
110M
      }
291
30.5M
    }
292
5.14M
    return true;
293
11.8M
  };
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
2.29k
  const auto process_row = [&](const uint32_t py,
300
126k
                               size_t /* thread */) -> Status {
301
126k
    uint32_t found = 0;
302
11.9M
    for (size_t px = 1; px <= pw - 2; px++) {
303
11.8M
      XY o = {px * kPatchSide, py * kPatchSide};
304
11.8M
      Color base = pick(o);
305
11.8M
      if (!flat_patch(o, base)) continue;
306
5.14M
      size_t num_same = 0;
307
20.5M
      for (size_t y = (py - 1) * kPatchSide; y <= (py + 1) * kPatchSide;
308
15.4M
           y += kPatchSide) {
309
61.7M
        for (size_t x = (px - 1) * kPatchSide; x <= (px + 1) * kPatchSide;
310
46.3M
             x += kPatchSide) {
311
46.3M
          num_same += is_same_color({x, y}, base);
312
46.3M
        }
313
15.4M
      }
314
      // Too few equal pixels nearby.
315
5.14M
      if (num_same < 8) continue;
316
3.92M
      is_screenshot_like.Row(py)[px] = 1;
317
3.92M
      found++;
318
3.92M
    }
319
126k
    screenshot_area_seeds.fetch_add(found);
320
126k
    return true;
321
126k
  };
322
2.29k
  bool can_have_seeds = ((pw >= 3) && (ph >= 3));
323
2.29k
  if (can_have_seeds) {
324
2.04k
    JXL_RETURN_IF_ERROR(RunOnPool(pool, 1, ph - 2, ThreadPool::NoInit,
325
2.04k
                                  process_row, "IsScreenshotLike"));
326
2.04k
  }
327
328
  // TODO(veluca): also parallelize the rest of this function.
329
2.29k
  if (WantDebugOutput(cparams)) {
330
0
    JXL_RETURN_IF_ERROR(
331
0
        DumpPlaneNormalized(cparams, "screenshot_like", is_screenshot_like));
332
0
  }
333
334
2.29k
  constexpr int kSearchRadius = 1;
335
336
2.29k
  size_t num_seeds = screenshot_area_seeds.load();
337
2.29k
  if (!ApplyOverride(state->cparams.patches, (num_seeds > 0))) {
338
652
    return info;
339
652
  }
340
341
  // Search for "similar enough" pixels near the screenshot-like areas.
342
3.28k
  JXL_ASSIGN_OR_RETURN(
343
3.28k
      ImageB is_background,
344
3.28k
      ImageB::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
345
3.28k
  ZeroFillImage(&is_background);
346
3.28k
  JXL_ASSIGN_OR_RETURN(
347
1.64k
      Image3F background,
348
1.64k
      Image3F::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
349
1.64k
  ZeroFillImage(&background);
350
1.64k
  constexpr size_t kDistanceLimit = 50;
351
1.64k
  float* JXL_RESTRICT background_rows[3] = {
352
1.64k
      background.PlaneRow(0, 0),
353
1.64k
      background.PlaneRow(1, 0),
354
1.64k
      background.PlaneRow(2, 0),
355
1.64k
  };
356
1.64k
  const size_t background_stride = background.PixelsPerRow();
357
1.64k
  uint8_t* JXL_RESTRICT is_background_row = is_background.Row(0);
358
1.64k
  const size_t is_background_stride = is_background.PixelsPerRow();
359
1.29G
  const auto is_bg = [&](const XY& p) -> uint8_t& {
360
1.29G
    return is_background_row[p.second * is_background_stride + p.first];
361
1.29G
  };
362
1.64k
  std::vector<std::pair<XY, XY>> queue;
363
1.64k
  queue.reserve(2 * num_seeds * kPatchSide * kPatchSide);
364
1.64k
  size_t queue_front = 0;
365
  // TODO(eustas): coalesce neighbours, leave only border.
366
1.64k
  if (can_have_seeds) {
367
115k
    for (size_t py = 1; py < ph - 1; py++) {
368
113k
      uint8_t* JXL_RESTRICT screenshot_row = is_screenshot_like.Row(py);
369
10.9M
      for (size_t px = 1; px < pw - 1; px++) {
370
10.8M
        if (!screenshot_row[px]) continue;
371
19.6M
        for (size_t y = py * kPatchSide; y < (py + 1) * kPatchSide; ++y) {
372
78.4M
          for (size_t x = px * kPatchSide; x < (px + 1) * kPatchSide; ++x) {
373
62.7M
            XY p = {x, y};
374
62.7M
            queue.emplace_back(p, p);
375
62.7M
            is_bg(p) = 1;
376
62.7M
          }
377
15.6M
        }
378
3.92M
      }
379
113k
    }
380
1.64k
  }
381
137M
  while (queue_front < queue.size()) {
382
137M
    XY cur = queue[queue_front].first;
383
137M
    XY src = queue[queue_front].second;
384
137M
    queue_front++;
385
137M
    Color src_color;
386
550M
    for (size_t c = 0; c < 3; c++) {
387
412M
      float clr = opsin_rows[c][src.second * opsin_stride + src.first];
388
412M
      src_color[c] = clr;
389
412M
      background_rows[c][cur.second * background_stride + cur.first] = clr;
390
412M
    }
391
550M
    for (int dx = -kSearchRadius; dx <= kSearchRadius; dx++) {
392
1.65G
      for (int dy = -kSearchRadius; dy <= kSearchRadius; dy++) {
393
1.23G
        XY next{cur.first + dx, cur.second + dy};
394
1.23G
        if (next.first < 0 || next.second < 0 ||
395
1.23G
            static_cast<uint32_t>(next.first) >= frame_dim.xsize ||
396
1.23G
            static_cast<uint32_t>(next.second) >= frame_dim.ysize) {
397
4.03M
          continue;
398
4.03M
        }
399
1.23G
        uint8_t& bg = is_bg(next);
400
1.23G
        if (bg) continue;
401
144M
        if (static_cast<uint32_t>(
402
144M
                std::abs(next.first - static_cast<int>(src.first)) +
403
144M
                std::abs(next.second - static_cast<int>(src.second))) >
404
144M
            kDistanceLimit) {
405
775k
          continue;
406
775k
        }
407
143M
        if (is_similar(src, next)) {
408
74.7M
          queue.emplace_back(next, src);
409
74.7M
          bg = 1;
410
74.7M
        }
411
143M
      }
412
412M
    }
413
137M
  }
414
1.64k
  queue.clear();
415
416
1.64k
  ImageF ccs;
417
1.64k
  Rng rng(0);
418
1.64k
  bool paint_ccs = false;
419
1.64k
  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
1.64k
  constexpr float kVerySimilarThreshold = 0.03f;
434
1.64k
  constexpr float kHasSimilarThreshold = 0.03f;
435
436
1.64k
  const float* JXL_RESTRICT const_background_rows[3] = {
437
1.64k
      background_rows[0], background_rows[1], background_rows[2]};
438
65.7M
  auto is_similar_b = [&](std::pair<int, int> p1, std::pair<int, int> p2) {
439
65.7M
    return is_similar_impl(p1, p2, const_background_rows, background_stride,
440
65.7M
                           kVerySimilarThreshold);
441
65.7M
  };
442
443
1.64k
  constexpr int kMinPeak = 2;
444
1.64k
  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
1.64k
  JXL_ASSIGN_OR_RETURN(
449
1.64k
      ImageB visited,
450
1.64k
      ImageB::Create(memory_manager, frame_dim.xsize, frame_dim.ysize));
451
1.64k
  ZeroFillImage(&visited);
452
1.64k
  uint8_t* JXL_RESTRICT visited_row = visited.Row(0);
453
1.64k
  const size_t visited_stride = visited.PixelsPerRow();
454
1.64k
  std::vector<std::pair<uint32_t, uint32_t>> cc;
455
1.64k
  std::vector<std::pair<uint32_t, uint32_t>> stack;
456
472k
  for (size_t y = 0; y < frame_dim.ysize; y++) {
457
182M
    for (size_t x = 0; x < frame_dim.xsize; x++) {
458
182M
      if (is_background_row[y * is_background_stride + x]) continue;
459
44.6M
      cc.clear();
460
44.6M
      stack.clear();
461
44.6M
      stack.emplace_back(x, y);
462
44.6M
      size_t min_x = x;
463
44.6M
      size_t max_x = x;
464
44.6M
      size_t min_y = y;
465
44.6M
      size_t max_y = y;
466
44.6M
      std::pair<uint32_t, uint32_t> reference;
467
44.6M
      bool found_border = false;
468
44.6M
      bool all_similar = true;
469
377M
      while (!stack.empty()) {
470
332M
        std::pair<uint32_t, uint32_t> cur = stack.back();
471
332M
        stack.pop_back();
472
332M
        if (visited_row[cur.second * visited_stride + cur.first]) continue;
473
44.6M
        visited_row[cur.second * visited_stride + cur.first] = 1;
474
44.6M
        if (cur.first < min_x) min_x = cur.first;
475
44.6M
        if (cur.first > max_x) max_x = cur.first;
476
44.6M
        if (cur.second < min_y) min_y = cur.second;
477
44.6M
        if (cur.second > max_y) max_y = cur.second;
478
44.6M
        if (paint_ccs) {
479
0
          cc.push_back(cur);
480
0
        }
481
178M
        for (int dx = -kSearchRadius; dx <= kSearchRadius; dx++) {
482
536M
          for (int dy = -kSearchRadius; dy <= kSearchRadius; dy++) {
483
402M
            if (dx == 0 && dy == 0) continue;
484
357M
            int next_first = static_cast<int32_t>(cur.first) + dx;
485
357M
            int next_second = static_cast<int32_t>(cur.second) + dy;
486
357M
            if (next_first < 0 || next_second < 0 ||
487
357M
                static_cast<uint32_t>(next_first) >= frame_dim.xsize ||
488
357M
                static_cast<uint32_t>(next_second) >= frame_dim.ysize) {
489
1.90M
              continue;
490
1.90M
            }
491
355M
            std::pair<uint32_t, uint32_t> next{next_first, next_second};
492
355M
            if (!is_background_row[next.second * is_background_stride +
493
355M
                                   next.first]) {
494
288M
              stack.push_back(next);
495
288M
            } else {
496
67.4M
              if (!found_border) {
497
1.69M
                reference = next;
498
1.69M
                found_border = true;
499
65.7M
              } else {
500
65.7M
                if (!is_similar_b(next, reference)) all_similar = false;
501
65.7M
              }
502
67.4M
            }
503
355M
          }
504
134M
        }
505
44.6M
      }
506
44.6M
      if (!found_border || !all_similar || max_x - min_x >= kMaxPatchSize ||
507
44.6M
          max_y - min_y >= kMaxPatchSize) {
508
43.0M
        continue;
509
43.0M
      }
510
1.62M
      size_t bpos = background_stride * reference.second + reference.first;
511
1.62M
      Color ref = {background_rows[0][bpos], background_rows[1][bpos],
512
1.62M
                   background_rows[2][bpos]};
513
1.62M
      bool has_similar = false;
514
1.62M
      for (size_t iy = std::max<int>(
515
1.62M
               static_cast<int32_t>(min_y) - kHasSimilarRadius, 0);
516
13.0M
           iy < std::min(max_y + kHasSimilarRadius + 1, frame_dim.ysize);
517
11.3M
           iy++) {
518
11.3M
        for (size_t ix = std::max<int>(
519
11.3M
                 static_cast<int32_t>(min_x) - kHasSimilarRadius, 0);
520
119M
             ix < std::min(max_x + kHasSimilarRadius + 1, frame_dim.xsize);
521
108M
             ix++) {
522
108M
          size_t opos = opsin_stride * iy + ix;
523
108M
          Color px = {opsin_rows[0][opos], opsin_rows[1][opos],
524
108M
                      opsin_rows[2][opos]};
525
108M
          if (pci.is_similar_v(ref, px, kHasSimilarThreshold)) {
526
73.0M
            has_similar = true;
527
73.0M
          }
528
108M
        }
529
11.3M
      }
530
1.62M
      if (!has_similar) continue;
531
1.62M
      info.emplace_back();
532
1.62M
      info.back().second.emplace_back(min_x, min_y);
533
1.62M
      QuantizedPatch& patch = info.back().first;
534
1.62M
      patch.xsize = max_x - min_x + 1;
535
1.62M
      patch.ysize = max_y - min_y + 1;
536
1.62M
      int max_value = 0;
537
4.86M
      for (size_t c : {1, 0, 2}) {
538
19.6M
        for (size_t iy = min_y; iy <= max_y; iy++) {
539
146M
          for (size_t ix = min_x; ix <= max_x; ix++) {
540
132M
            size_t offset = (iy - min_y) * patch.xsize + ix - min_x;
541
132M
            patch.fpixels[c][offset] =
542
132M
                opsin_rows[c][iy * opsin_stride + ix] - ref[c];
543
132M
            int val = pci.Quantize(patch.fpixels[c][offset], c);
544
132M
            patch.pixels[c][offset] = val;
545
132M
            if (std::abs(val) > max_value) max_value = std::abs(val);
546
132M
          }
547
14.7M
        }
548
4.86M
      }
549
1.62M
      if (max_value < kMinPeak) {
550
11.3k
        info.pop_back();
551
11.3k
        continue;
552
11.3k
      }
553
1.60M
      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
1.60M
    }
560
470k
  }
561
562
1.64k
  if (paint_ccs) {
563
0
    JXL_ENSURE(WantDebugOutput(cparams));
564
0
    JXL_RETURN_IF_ERROR(DumpPlaneNormalized(cparams, "ccs", ccs));
565
0
  }
566
1.64k
  if (info.empty()) {
567
333
    return info;
568
333
  }
569
570
  // Remove duplicates.
571
1.30k
  constexpr size_t kMinPatchOccurrences = 2;
572
1.30k
  std::sort(info.begin(), info.end());
573
1.30k
  size_t unique = 0;
574
1.60M
  for (size_t i = 1; i < info.size(); i++) {
575
1.60M
    if (info[i].first == info[unique].first) {
576
1.36M
      info[unique].second.insert(info[unique].second.end(),
577
1.36M
                                 info[i].second.begin(), info[i].second.end());
578
1.36M
    } else {
579
246k
      if (info[unique].second.size() >= kMinPatchOccurrences) {
580
97.9k
        unique++;
581
97.9k
      }
582
246k
      info[unique] = info[i];
583
246k
    }
584
1.60M
  }
585
1.30k
  if (info[unique].second.size() >= kMinPatchOccurrences) {
586
381
    unique++;
587
381
  }
588
1.30k
  info.resize(unique);
589
590
1.30k
  size_t max_patch_size = 0;
591
592
98.3k
  for (const auto& patch : info) {
593
98.3k
    size_t pixels = patch.first.xsize * patch.first.ysize;
594
98.3k
    if (pixels > max_patch_size) max_patch_size = pixels;
595
98.3k
  }
596
597
  // don't use patches if all patches are smaller than this
598
1.30k
  constexpr size_t kMinMaxPatchSize = 20;
599
1.30k
  if (max_patch_size < kMinMaxPatchSize) {
600
224
    info.clear();
601
224
  }
602
603
1.30k
  return info;
604
1.64k
}
605
606
}  // namespace
607
608
Status FindBestPatchDictionary(const Image3F& opsin,
609
                               PassesEncoderState* JXL_RESTRICT state,
610
                               const JxlCmsInterface& cms, ThreadPool* pool,
611
3.37k
                               AuxOut* aux_out, bool is_xyb) {
612
3.37k
  JXL_ASSIGN_OR_RETURN(
613
3.37k
      std::vector<PatchInfo> info,
614
3.37k
      FindTextLikePatches(state->cparams, opsin, state, pool, aux_out, is_xyb));
615
3.37k
  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
3.37k
  if (info.empty() &&
621
3.37k
      ApplyOverride(
622
2.28k
          state->cparams.dots,
623
2.28k
          state->cparams.speed_tier <= SpeedTier::kSquirrel &&
624
2.28k
              state->cparams.butteraugli_distance >= kMinButteraugliForDots &&
625
2.28k
              !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
3.37k
  if (info.empty()) return true;
634
635
1.08k
  std::sort(
636
564k
      info.begin(), info.end(), [&](const PatchInfo& a, const PatchInfo& b) {
637
564k
        return a.first.xsize * a.first.ysize > b.first.xsize * b.first.ysize;
638
564k
      });
639
640
1.08k
  size_t max_x_size = 0;
641
1.08k
  size_t max_y_size = 0;
642
1.08k
  size_t total_pixels = 0;
643
644
98.0k
  for (const auto& patch : info) {
645
98.0k
    size_t pixels = patch.first.xsize * patch.first.ysize;
646
98.0k
    if (max_x_size < patch.first.xsize) max_x_size = patch.first.xsize;
647
98.0k
    if (max_y_size < patch.first.ysize) max_y_size = patch.first.ysize;
648
98.0k
    total_pixels += pixels;
649
98.0k
  }
650
651
  // Bin-packing & conversion of patches.
652
1.08k
  constexpr float kBinPackingSlackness = 1.05f;
653
1.08k
  size_t ref_xsize = std::max<float>(max_x_size, std::sqrt(total_pixels));
654
1.08k
  size_t ref_ysize = std::max<float>(max_y_size, std::sqrt(total_pixels));
655
1.08k
  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
1.08k
  size_t max_y = 0;
658
1.65k
  do {
659
1.65k
    max_y = 0;
660
    // Increase packed image size.
661
1.65k
    ref_xsize = ref_xsize * kBinPackingSlackness + 1;
662
1.65k
    ref_ysize = ref_ysize * kBinPackingSlackness + 1;
663
664
1.65k
    JXL_ASSIGN_OR_RETURN(ImageB occupied,
665
1.65k
                         ImageB::Create(memory_manager, ref_xsize, ref_ysize));
666
1.65k
    ZeroFillImage(&occupied);
667
1.65k
    uint8_t* JXL_RESTRICT occupied_rows = occupied.Row(0);
668
1.65k
    size_t occupied_stride = occupied.PixelsPerRow();
669
670
1.65k
    bool success = true;
671
    // For every patch...
672
102k
    for (size_t patch = 0; patch < info.size(); patch++) {
673
101k
      size_t x0 = 0;
674
101k
      size_t y0 = 0;
675
101k
      size_t xsize = info[patch].first.xsize;
676
101k
      size_t ysize = info[patch].first.ysize;
677
101k
      bool found = false;
678
      // For every possible start position ...
679
7.35M
      for (; y0 + ysize <= ref_ysize; y0++) {
680
7.35M
        x0 = 0;
681
955M
        for (; x0 + xsize <= ref_xsize; x0++) {
682
947M
          bool has_occupied_pixel = false;
683
947M
          size_t x = x0;
684
          // Check if it is possible to place the patch in this position in the
685
          // reference frame.
686
7.75G
          for (size_t y = y0; y < y0 + ysize; y++) {
687
6.81G
            x = x0;
688
7.60G
            for (; x < x0 + xsize; x++) {
689
7.56G
              if (occupied_rows[y * occupied_stride + x]) {
690
6.77G
                has_occupied_pixel = true;
691
6.77G
                break;
692
6.77G
              }
693
7.56G
            }
694
6.81G
          }  // end of positioning check
695
947M
          if (!has_occupied_pixel) {
696
100k
            found = true;
697
100k
            break;
698
100k
          }
699
947M
          x0 = x;  // Jump to next pixel after the occupied one.
700
947M
        }
701
7.35M
        if (found) break;
702
7.35M
      }  // 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
101k
      if (!found) {
707
569
        success = false;
708
569
        break;
709
569
      }
710
711
      // We found a position: mark the corresponding positions in the reference
712
      // image as used.
713
100k
      ref_positions[patch] = {x0, y0};
714
795k
      for (size_t y = y0; y < y0 + ysize; y++) {
715
9.72M
        for (size_t x = x0; x < x0 + xsize; x++) {
716
9.03M
          occupied_rows[y * occupied_stride + x] = JXL_TRUE;
717
9.03M
        }
718
694k
      }
719
100k
      max_y = std::max(max_y, y0 + ysize);
720
100k
    }
721
722
1.65k
    if (success) break;
723
1.65k
  } while (true);
724
725
1.08k
  JXL_ENSURE(ref_ysize >= max_y);
726
727
1.08k
  ref_ysize = max_y;
728
729
1.08k
  JXL_ASSIGN_OR_RETURN(Image3F reference_frame,
730
1.08k
                       Image3F::Create(memory_manager, ref_xsize, ref_ysize));
731
  // TODO(veluca): figure out a better way to fill the image.
732
1.08k
  ZeroFillImage(&reference_frame);
733
1.08k
  std::vector<PatchPosition> positions;
734
1.08k
  std::vector<PatchReferencePosition> pref_positions;
735
1.08k
  std::vector<PatchBlending> blendings;
736
1.08k
  float* JXL_RESTRICT ref_rows[3] = {
737
1.08k
      reference_frame.PlaneRow(0, 0),
738
1.08k
      reference_frame.PlaneRow(1, 0),
739
1.08k
      reference_frame.PlaneRow(2, 0),
740
1.08k
  };
741
1.08k
  size_t ref_stride = reference_frame.PixelsPerRow();
742
1.08k
  size_t num_ec = state->shared.metadata->m.num_extra_channels;
743
744
99.0k
  for (size_t i = 0; i < info.size(); i++) {
745
98.0k
    PatchReferencePosition ref_pos;
746
98.0k
    ref_pos.xsize = info[i].first.xsize;
747
98.0k
    ref_pos.ysize = info[i].first.ysize;
748
98.0k
    ref_pos.x0 = ref_positions[i].first;
749
98.0k
    ref_pos.y0 = ref_positions[i].second;
750
98.0k
    ref_pos.ref = kPatchFrameReferenceId;
751
753k
    for (size_t y = 0; y < ref_pos.ysize; y++) {
752
9.12M
      for (size_t x = 0; x < ref_pos.xsize; x++) {
753
33.8M
        for (size_t c = 0; c < 3; c++) {
754
25.4M
          ref_rows[c][(y + ref_pos.y0) * ref_stride + x + ref_pos.x0] =
755
25.4M
              info[i].first.fpixels[c][y * ref_pos.xsize + x];
756
25.4M
        }
757
8.47M
      }
758
655k
    }
759
1.45M
    for (const auto& pos : info[i].second) {
760
1.45M
      JXL_DEBUG_V(4, "Patch %" PRIuS "x%" PRIuS " at position %u,%u",
761
1.45M
                  ref_pos.xsize, ref_pos.ysize, pos.first, pos.second);
762
1.45M
      positions.emplace_back(
763
1.45M
          PatchPosition{pos.first, pos.second, pref_positions.size()});
764
      // Add blending for color channels, ignore other channels.
765
1.45M
      blendings.push_back({PatchBlendMode::kAdd, 0, false});
766
1.45M
      for (size_t j = 0; j < num_ec; ++j) {
767
0
        blendings.push_back({PatchBlendMode::kNone, 0, false});
768
0
      }
769
1.45M
    }
770
98.0k
    pref_positions.emplace_back(ref_pos);
771
98.0k
  }
772
773
1.08k
  CompressParams cparams = state->cparams;
774
  // Recursive application of patches could create very weird issues.
775
1.08k
  cparams.patches = Override::kOff;
776
777
1.08k
  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
1.08k
  JXL_RETURN_IF_ERROR(RoundtripPatchFrame(&reference_frame, state,
788
1.08k
                                          kPatchFrameReferenceId, cparams, cms,
789
1.08k
                                          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
1.08k
  PatchDictionaryEncoder::SetPositions(
795
1.08k
      &state->shared.image_features.patches, std::move(positions),
796
1.08k
      std::move(pref_positions), std::move(blendings), num_ec + 1);
797
1.08k
  return true;
798
1.08k
}
799
800
Status RoundtripPatchFrame(Image3F* reference_frame,
801
                           PassesEncoderState* JXL_RESTRICT state, int idx,
802
                           CompressParams& cparams, const JxlCmsInterface& cms,
803
1.08k
                           ThreadPool* pool, AuxOut* aux_out, bool subtract) {
804
1.08k
  JxlMemoryManager* memory_manager = state->memory_manager();
805
1.08k
  FrameInfo patch_frame_info;
806
1.08k
  cparams.resampling = 1;
807
1.08k
  cparams.ec_resampling = 1;
808
1.08k
  cparams.dots = Override::kOff;
809
1.08k
  cparams.noise = Override::kOff;
810
1.08k
  cparams.modular_mode = true;
811
1.08k
  cparams.responsive = 0;
812
1.08k
  cparams.progressive_dc = 0;
813
1.08k
  cparams.progressive_mode = Override::kOff;
814
1.08k
  cparams.qprogressive_mode = Override::kOff;
815
  // Use gradient predictor and not Predictor::Best.
816
1.08k
  cparams.options.predictor = Predictor::Gradient;
817
1.08k
  patch_frame_info.save_as_reference = idx;  // always saved.
818
1.08k
  patch_frame_info.frame_type = FrameType::kReferenceOnly;
819
1.08k
  patch_frame_info.save_before_color_transform = true;
820
1.08k
  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
1.08k
  patch_frame_info.ib_needs_color_transform = false;
824
1.08k
  JXL_RETURN_IF_ERROR(ib.SetFromImage(
825
1.08k
      std::move(*reference_frame), state->shared.metadata->m.color_encoding));
826
1.08k
  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
1.08k
  auto special_frame = jxl::make_unique<BitWriter>(memory_manager);
844
1.08k
  AuxOut patch_aux_out;
845
1.08k
  JXL_RETURN_IF_ERROR(EncodeFrame(
846
1.08k
      memory_manager, cparams, patch_frame_info, state->shared.metadata, ib,
847
1.08k
      cms, pool, special_frame.get(), aux_out ? &patch_aux_out : nullptr));
848
1.08k
  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
1.08k
  const Span<const uint8_t> encoded = special_frame->GetSpan();
854
1.08k
  state->special_frames.emplace_back(std::move(special_frame));
855
1.08k
  if (subtract) {
856
1.08k
    ImageBundle decoded(memory_manager, &state->shared.metadata->m);
857
1.08k
    auto dec_state = jxl::make_unique<PassesDecoderState>(memory_manager);
858
1.08k
    JXL_RETURN_IF_ERROR(dec_state->output_encoding_info.SetFromMetadata(
859
1.08k
        *state->shared.metadata));
860
1.08k
    const uint8_t* frame_start = encoded.data();
861
1.08k
    size_t encoded_size = encoded.size();
862
1.08k
    JXL_RETURN_IF_ERROR(DecodeFrame(
863
1.08k
        dec_state.get(), pool, frame_start, encoded_size,
864
1.08k
        /*frame_header=*/nullptr, &decoded, *state->shared.metadata));
865
1.08k
    frame_start += decoded.decoded_bytes();
866
1.08k
    encoded_size -= decoded.decoded_bytes();
867
1.08k
    size_t ref_xsize =
868
1.08k
        dec_state->shared_storage.reference_frames[idx].frame->color()->xsize();
869
    // if the frame itself uses patches, we need to decode another frame
870
1.08k
    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
1.08k
    JXL_ENSURE(encoded_size == 0);
876
1.08k
    state->shared.reference_frames[idx] =
877
1.08k
        std::move(dec_state->shared_storage.reference_frames[idx]);
878
1.08k
  } else {
879
0
    *state->shared.reference_frames[idx].frame = std::move(ib);
880
0
  }
881
1.08k
  return true;
882
1.08k
}
883
884
}  // namespace jxl