Coverage Report

Created: 2025-10-12 07:48

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