Coverage Report

Created: 2025-12-13 07:57

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