Coverage Report

Created: 2026-02-14 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/dec_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/dec_patch_dictionary.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <cstdint>
12
#include <cstdlib>
13
#include <utility>
14
#include <vector>
15
16
#include "lib/jxl/base/printf_macros.h"
17
#include "lib/jxl/base/status.h"
18
#include "lib/jxl/blending.h"
19
#include "lib/jxl/common.h"  // kMaxNumReferenceFrames
20
#include "lib/jxl/dec_ans.h"
21
#include "lib/jxl/dec_bit_reader.h"
22
#include "lib/jxl/image.h"
23
#include "lib/jxl/image_bundle.h"
24
#include "lib/jxl/image_metadata.h"
25
#include "lib/jxl/pack_signed.h"
26
#include "lib/jxl/patch_dictionary_internal.h"
27
28
namespace jxl {
29
30
Status PatchDictionary::Decode(JxlMemoryManager* memory_manager, BitReader* br,
31
                               size_t xsize, size_t ysize,
32
                               size_t num_extra_channels,
33
534
                               bool* uses_extra_channels) {
34
534
  positions_.clear();
35
534
  blendings_stride_ = num_extra_channels + 1;
36
534
  std::vector<uint8_t> context_map;
37
534
  ANSCode code;
38
534
  JXL_RETURN_IF_ERROR(DecodeHistograms(
39
534
      memory_manager, br, kNumPatchDictionaryContexts, &code, &context_map));
40
1.06k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader decoder,
41
1.06k
                       ANSSymbolReader::Create(&code, br));
42
43
1.12M
  auto read_num = [&](size_t context) -> size_t {
44
1.12M
    size_t r = decoder.ReadHybridUint(context, br, context_map);
45
1.12M
    return r;
46
1.12M
  };
47
48
1.06k
  size_t num_ref_patch = read_num(kNumRefPatchContext);
49
  // Limit max memory usage of patches to about 66 bytes per pixel (assuming 8
50
  // bytes per size_t)
51
1.06k
  const size_t num_pixels = xsize * ysize;
52
1.06k
  const size_t max_ref_patches = 1024 + num_pixels / 4;
53
1.06k
  const size_t max_patches = max_ref_patches * 4;
54
1.06k
  const size_t max_blending_infos = max_patches * 4;
55
1.06k
  if (num_ref_patch > max_ref_patches) {
56
0
    return JXL_FAILURE("Too many patches in dictionary");
57
0
  }
58
59
533
  size_t total_patches = 0;
60
533
  size_t next_size = 1;
61
62
9.59k
  for (size_t id = 0; id < num_ref_patch; id++) {
63
9.06k
    PatchReferencePosition ref_pos;
64
9.06k
    ref_pos.ref = read_num(kReferenceFrameContext);
65
9.06k
    if (ref_pos.ref >= kMaxNumReferenceFrames ||
66
9.06k
        reference_frames_->at(ref_pos.ref).frame->xsize() == 0) {
67
0
      return JXL_FAILURE("Invalid reference frame ID");
68
0
    }
69
9.06k
    if (!reference_frames_->at(ref_pos.ref).ib_is_in_xyb) {
70
0
      return JXL_FAILURE(
71
0
          "Patches cannot use frames saved post color transforms");
72
0
    }
73
9.06k
    const ImageBundle& ib = *reference_frames_->at(ref_pos.ref).frame;
74
9.06k
    ref_pos.x0 = read_num(kPatchReferencePositionContext);
75
9.06k
    ref_pos.y0 = read_num(kPatchReferencePositionContext);
76
9.06k
    ref_pos.xsize = read_num(kPatchSizeContext) + 1;
77
9.06k
    ref_pos.ysize = read_num(kPatchSizeContext) + 1;
78
9.06k
    if (ref_pos.x0 + ref_pos.xsize > ib.xsize()) {
79
0
      return JXL_FAILURE("Invalid position specified in reference frame");
80
0
    }
81
9.06k
    if (ref_pos.y0 + ref_pos.ysize > ib.ysize()) {
82
0
      return JXL_FAILURE("Invalid position specified in reference frame");
83
0
    }
84
9.06k
    size_t id_count = read_num(kPatchCountContext);
85
9.06k
    if (id_count > max_patches) {
86
0
      return JXL_FAILURE("Too many patches in dictionary");
87
0
    }
88
9.06k
    id_count++;
89
9.06k
    total_patches += id_count;
90
9.06k
    if (total_patches > max_patches) {
91
0
      return JXL_FAILURE("Too many patches in dictionary");
92
0
    }
93
9.06k
    if (next_size < total_patches) {
94
2.05k
      next_size *= 2;
95
2.05k
      next_size = std::min<size_t>(next_size, max_patches);
96
2.05k
    }
97
9.06k
    if (next_size * blendings_stride_ > max_blending_infos) {
98
0
      return JXL_FAILURE("Too many patches in dictionary");
99
0
    }
100
9.06k
    positions_.reserve(next_size);
101
9.06k
    blendings_.reserve(next_size * blendings_stride_);
102
9.06k
    bool choose_alpha = (num_extra_channels > 1);
103
362k
    for (size_t i = 0; i < id_count; i++) {
104
353k
      PatchPosition pos;
105
353k
      pos.ref_pos_idx = ref_positions_.size();
106
353k
      if (i == 0) {
107
9.06k
        pos.x = read_num(kPatchPositionContext);
108
9.06k
        pos.y = read_num(kPatchPositionContext);
109
344k
      } else {
110
344k
        ptrdiff_t deltax = UnpackSigned(read_num(kPatchOffsetContext));
111
344k
        if (deltax < 0 && static_cast<size_t>(-deltax) > positions_.back().x) {
112
0
          return JXL_FAILURE("Invalid patch: negative x coordinate (%" PRIuS
113
0
                             " base x %" PRIdS " delta x)",
114
0
                             positions_.back().x, deltax);
115
0
        }
116
344k
        pos.x = positions_.back().x + deltax;
117
344k
        ptrdiff_t deltay = UnpackSigned(read_num(kPatchOffsetContext));
118
344k
        if (deltay < 0 && static_cast<size_t>(-deltay) > positions_.back().y) {
119
0
          return JXL_FAILURE("Invalid patch: negative y coordinate (%" PRIuS
120
0
                             " base y %" PRIdS " delta y)",
121
0
                             positions_.back().y, deltay);
122
0
        }
123
344k
        pos.y = positions_.back().y + deltay;
124
344k
      }
125
353k
      if (pos.x + ref_pos.xsize > xsize) {
126
0
        return JXL_FAILURE("Invalid patch x: at %" PRIuS " + %" PRIuS
127
0
                           " > %" PRIuS,
128
0
                           pos.x, ref_pos.xsize, xsize);
129
0
      }
130
353k
      if (pos.y + ref_pos.ysize > ysize) {
131
0
        return JXL_FAILURE("Invalid patch y: at %" PRIuS " + %" PRIuS
132
0
                           " > %" PRIuS,
133
0
                           pos.y, ref_pos.ysize, ysize);
134
0
      }
135
712k
      for (size_t j = 0; j < blendings_stride_; j++) {
136
359k
        uint32_t blend_mode = read_num(kPatchBlendModeContext);
137
359k
        if (blend_mode >= kNumPatchBlendModes) {
138
0
          return JXL_FAILURE("Invalid patch blend mode: %u", blend_mode);
139
0
        }
140
359k
        PatchBlending info;
141
359k
        info.mode = static_cast<PatchBlendMode>(blend_mode);
142
359k
        if (UsesAlpha(info.mode)) {
143
0
          *uses_extra_channels = true;
144
0
        }
145
359k
        if (info.mode != PatchBlendMode::kNone && j > 0) {
146
1.12k
          *uses_extra_channels = true;
147
1.12k
        }
148
359k
        if (UsesAlpha(info.mode) && choose_alpha) {
149
0
          info.alpha_channel = read_num(kPatchAlphaChannelContext);
150
0
          if (info.alpha_channel >= num_extra_channels) {
151
0
            return JXL_FAILURE(
152
0
                "Invalid alpha channel for blending: %u out of %u\n",
153
0
                info.alpha_channel, static_cast<uint32_t>(num_extra_channels));
154
0
          }
155
359k
        } else {
156
359k
          info.alpha_channel = 0;
157
359k
        }
158
359k
        if (UsesClamp(info.mode)) {
159
0
          info.clamp = static_cast<bool>(read_num(kPatchClampContext));
160
359k
        } else {
161
359k
          info.clamp = false;
162
359k
        }
163
359k
        blendings_.push_back(info);
164
359k
      }
165
353k
      positions_.emplace_back(pos);
166
353k
    }
167
9.06k
    ref_positions_.emplace_back(ref_pos);
168
9.06k
  }
169
533
  positions_.shrink_to_fit();
170
171
533
  if (!decoder.CheckANSFinalState()) {
172
0
    return JXL_FAILURE("ANS checksum failure.");
173
0
  }
174
175
533
  ComputePatchTree();
176
533
  return true;
177
533
}
178
179
520
int PatchDictionary::GetReferences() const {
180
520
  int result = 0;
181
49.1k
  for (const auto& ref_pos : ref_positions_) {
182
49.1k
    result |= (1 << static_cast<int>(ref_pos.ref));
183
49.1k
  }
184
520
  return result;
185
520
}
186
187
namespace {
188
struct PatchInterval {
189
  size_t idx;
190
  size_t y0, y1;
191
};
192
}  // namespace
193
194
9.11k
void PatchDictionary::ComputePatchTree() {
195
9.11k
  patch_tree_.clear();
196
9.11k
  num_patches_.clear();
197
9.11k
  sorted_patches_y0_.clear();
198
9.11k
  sorted_patches_y1_.clear();
199
9.11k
  if (positions_.empty()) {
200
8.71k
    return;
201
8.71k
  }
202
  // Create a y-interval for each patch.
203
397
  std::vector<PatchInterval> intervals(positions_.size());
204
353k
  for (size_t i = 0; i < positions_.size(); ++i) {
205
353k
    const auto& pos = positions_[i];
206
353k
    intervals[i].idx = i;
207
353k
    intervals[i].y0 = pos.y;
208
353k
    intervals[i].y1 = pos.y + ref_positions_[pos.ref_pos_idx].ysize;
209
353k
  }
210
31.3k
  auto sort_by_y0 = [&intervals](size_t start, size_t end) {
211
31.3k
    std::sort(intervals.data() + start, intervals.data() + end,
212
8.84M
              [](const PatchInterval& i0, const PatchInterval& i1) {
213
8.84M
                return i0.y0 < i1.y0;
214
8.84M
              });
215
31.3k
  };
216
16.0k
  auto sort_by_y1 = [&intervals](size_t start, size_t end) {
217
16.0k
    std::sort(intervals.data() + start, intervals.data() + end,
218
7.50M
              [](const PatchInterval& i0, const PatchInterval& i1) {
219
7.50M
                return i0.y1 < i1.y1;
220
7.50M
              });
221
16.0k
  };
222
  // Count the number of patches for each row.
223
397
  sort_by_y1(0, intervals.size());
224
397
  num_patches_.resize(intervals.back().y1);
225
353k
  for (auto iv : intervals) {
226
10.1M
    for (size_t y = iv.y0; y < iv.y1; ++y) num_patches_[y]++;
227
353k
  }
228
397
  PatchTreeNode root;
229
397
  root.start = 0;
230
397
  root.num = intervals.size();
231
397
  patch_tree_.push_back(root);
232
397
  size_t next = 0;
233
16.0k
  while (next < patch_tree_.size()) {
234
15.6k
    auto& node = patch_tree_[next];
235
15.6k
    size_t start = node.start;
236
15.6k
    size_t end = node.start + node.num;
237
    // Choose the y_center for this node to be the median of interval starts.
238
15.6k
    sort_by_y0(start, end);
239
15.6k
    size_t middle_idx = start + node.num / 2;
240
15.6k
    node.y_center = intervals[middle_idx].y0;
241
    // Divide the intervals in [start, end) into three groups:
242
    //   * those completely to the right of y_center: [right_start, end)
243
    //   * those overlapping y_center: [left_end, right_start)
244
    //   * those completely to the left of y_center: [start, left_end)
245
15.6k
    size_t right_start = middle_idx;
246
65.3k
    while (right_start < end && intervals[right_start].y0 == node.y_center) {
247
49.6k
      ++right_start;
248
49.6k
    }
249
15.6k
    sort_by_y1(start, right_start);
250
15.6k
    size_t left_end = right_start;
251
369k
    while (left_end > start && intervals[left_end - 1].y1 > node.y_center) {
252
353k
      --left_end;
253
353k
    }
254
    // Fill in sorted_patches_y0_ and sorted_patches_y1_ for the current node.
255
15.6k
    node.num = right_start - left_end;
256
15.6k
    node.start = sorted_patches_y0_.size();
257
15.6k
    for (ptrdiff_t i = static_cast<ptrdiff_t>(right_start) - 1;
258
369k
         i >= static_cast<ptrdiff_t>(left_end); --i) {
259
353k
      sorted_patches_y1_.emplace_back(intervals[i].y1, intervals[i].idx);
260
353k
    }
261
15.6k
    sort_by_y0(left_end, right_start);
262
369k
    for (size_t i = left_end; i < right_start; ++i) {
263
353k
      sorted_patches_y0_.emplace_back(intervals[i].y0, intervals[i].idx);
264
353k
    }
265
    // Create the left and right nodes (if not empty).
266
15.6k
    node.left_child = node.right_child = -1;
267
15.6k
    if (left_end > start) {
268
7.52k
      PatchTreeNode left;
269
7.52k
      left.start = start;
270
7.52k
      left.num = left_end - left.start;
271
7.52k
      patch_tree_[next].left_child = patch_tree_.size();
272
7.52k
      patch_tree_.push_back(left);
273
7.52k
    }
274
15.6k
    if (right_start < end) {
275
7.75k
      PatchTreeNode right;
276
7.75k
      right.start = right_start;
277
7.75k
      right.num = end - right.start;
278
7.75k
      patch_tree_[next].right_child = patch_tree_.size();
279
7.75k
      patch_tree_.push_back(right);
280
7.75k
    }
281
15.6k
    ++next;
282
15.6k
  }
283
397
}
284
285
89.1k
std::vector<size_t> PatchDictionary::GetPatchesForRow(size_t y) const {
286
89.1k
  std::vector<size_t> result;
287
89.1k
  if (y < num_patches_.size() && num_patches_[y] > 0) {
288
47.4k
    result.reserve(num_patches_[y]);
289
299k
    for (ptrdiff_t tree_idx = 0; tree_idx != -1;) {
290
252k
      JXL_DASSERT(tree_idx < static_cast<ptrdiff_t>(patch_tree_.size()));
291
252k
      const auto& node = patch_tree_[tree_idx];
292
252k
      if (y <= node.y_center) {
293
2.89M
        for (size_t i = 0; i < node.num; ++i) {
294
2.88M
          const auto& p = sorted_patches_y0_[node.start + i];
295
2.88M
          if (y < p.first) break;
296
2.79M
          result.push_back(p.second);
297
2.79M
        }
298
99.3k
        tree_idx = y < node.y_center ? node.left_child : -1;
299
153k
      } else {
300
6.33M
        for (size_t i = 0; i < node.num; ++i) {
301
6.30M
          const auto& p = sorted_patches_y1_[node.start + i];
302
6.30M
          if (y >= p.first) break;
303
6.18M
          result.push_back(p.second);
304
6.18M
        }
305
153k
        tree_idx = node.right_child;
306
153k
      }
307
252k
    }
308
    // Ensure that he relative order of patches that affect the same pixels is
309
    // preserved. This is important for patches that have a blend mode
310
    // different from kAdd.
311
47.4k
    std::sort(result.begin(), result.end());
312
47.4k
  }
313
89.1k
  return result;
314
89.1k
}
315
316
// Adds patches to a segment of `xsize` pixels, starting at `inout`, assumed
317
// to be located at position (x0, y) in the frame.
318
Status PatchDictionary::AddOneRow(
319
    float* const* inout, size_t y, size_t x0, size_t xsize,
320
89.1k
    const std::vector<ExtraChannelInfo>& extra_channel_info) const {
321
89.1k
  size_t num_ec = extra_channel_info.size();
322
89.1k
  JXL_ENSURE(num_ec + 1 <= blendings_stride_);
323
89.1k
  std::vector<const float*> fg_ptrs(3 + num_ec);
324
8.97M
  for (size_t pos_idx : GetPatchesForRow(y)) {
325
8.97M
    const size_t blending_idx = pos_idx * blendings_stride_;
326
8.97M
    const PatchPosition& pos = positions_[pos_idx];
327
8.97M
    const PatchReferencePosition& ref_pos = ref_positions_[pos.ref_pos_idx];
328
8.97M
    size_t by = pos.y;
329
8.97M
    size_t bx = pos.x;
330
8.97M
    size_t patch_xsize = ref_pos.xsize;
331
8.97M
    JXL_ENSURE(y >= by);
332
8.97M
    JXL_ENSURE(y < by + ref_pos.ysize);
333
8.97M
    size_t iy = y - by;
334
8.97M
    size_t ref = ref_pos.ref;
335
8.97M
    if (bx >= x0 + xsize) continue;
336
8.97M
    if (bx + patch_xsize < x0) continue;
337
8.97M
    size_t patch_x0 = std::max(bx, x0);
338
8.97M
    size_t patch_x1 = std::min(bx + patch_xsize, x0 + xsize);
339
35.9M
    for (size_t c = 0; c < 3; c++) {
340
26.9M
      fg_ptrs[c] = reference_frames_->at(ref).frame->color()->ConstPlaneRow(
341
26.9M
                       c, ref_pos.y0 + iy) +
342
26.9M
                   ref_pos.x0 + x0 - bx;
343
26.9M
    }
344
9.04M
    for (size_t i = 0; i < num_ec; i++) {
345
61.0k
      fg_ptrs[3 + i] =
346
61.0k
          reference_frames_->at(ref).frame->extra_channels()[i].ConstRow(
347
61.0k
              ref_pos.y0 + iy) +
348
61.0k
          ref_pos.x0 + x0 - bx;
349
61.0k
    }
350
8.97M
    JXL_RETURN_IF_ERROR(PerformBlending(
351
8.97M
        memory_manager_, inout, fg_ptrs.data(), inout, patch_x0 - x0,
352
8.97M
        patch_x1 - patch_x0, blendings_[blending_idx],
353
8.97M
        blendings_.data() + blending_idx + 1, extra_channel_info));
354
8.97M
  }
355
89.1k
  return true;
356
89.1k
}
357
}  // namespace jxl