Coverage Report

Created: 2025-11-14 07:32

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