Coverage Report

Created: 2025-11-16 07:22

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
1.73k
                               bool* uses_extra_channels) {
34
1.73k
  positions_.clear();
35
1.73k
  blendings_stride_ = num_extra_channels + 1;
36
1.73k
  std::vector<uint8_t> context_map;
37
1.73k
  ANSCode code;
38
1.73k
  JXL_RETURN_IF_ERROR(DecodeHistograms(
39
1.73k
      memory_manager, br, kNumPatchDictionaryContexts, &code, &context_map));
40
3.17k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader decoder,
41
3.17k
                       ANSSymbolReader::Create(&code, br));
42
43
3.38M
  auto read_num = [&](size_t context) -> size_t {
44
3.38M
    size_t r = decoder.ReadHybridUint(context, br, context_map);
45
3.38M
    return r;
46
3.38M
  };
47
48
3.17k
  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
3.17k
  const size_t num_pixels = xsize * ysize;
52
3.17k
  const size_t max_ref_patches = 1024 + num_pixels / 4;
53
3.17k
  const size_t max_patches = max_ref_patches * 4;
54
3.17k
  const size_t max_blending_infos = max_patches * 4;
55
3.17k
  if (num_ref_patch > max_ref_patches) {
56
6
    return JXL_FAILURE("Too many patches in dictionary");
57
6
  }
58
59
1.57k
  size_t total_patches = 0;
60
1.57k
  size_t next_size = 1;
61
62
117k
  for (size_t id = 0; id < num_ref_patch; id++) {
63
116k
    PatchReferencePosition ref_pos;
64
116k
    ref_pos.ref = read_num(kReferenceFrameContext);
65
116k
    if (ref_pos.ref >= kMaxNumReferenceFrames ||
66
116k
        reference_frames_->at(ref_pos.ref).frame->xsize() == 0) {
67
40
      return JXL_FAILURE("Invalid reference frame ID");
68
40
    }
69
116k
    if (!reference_frames_->at(ref_pos.ref).ib_is_in_xyb) {
70
3
      return JXL_FAILURE(
71
3
          "Patches cannot use frames saved post color transforms");
72
3
    }
73
116k
    const ImageBundle& ib = *reference_frames_->at(ref_pos.ref).frame;
74
116k
    ref_pos.x0 = read_num(kPatchReferencePositionContext);
75
116k
    ref_pos.y0 = read_num(kPatchReferencePositionContext);
76
116k
    ref_pos.xsize = read_num(kPatchSizeContext) + 1;
77
116k
    ref_pos.ysize = read_num(kPatchSizeContext) + 1;
78
116k
    if (ref_pos.x0 + ref_pos.xsize > ib.xsize()) {
79
6
      return JXL_FAILURE("Invalid position specified in reference frame");
80
6
    }
81
116k
    if (ref_pos.y0 + ref_pos.ysize > ib.ysize()) {
82
2
      return JXL_FAILURE("Invalid position specified in reference frame");
83
2
    }
84
116k
    size_t id_count = read_num(kPatchCountContext);
85
116k
    if (id_count > max_patches) {
86
4
      return JXL_FAILURE("Too many patches in dictionary");
87
4
    }
88
116k
    id_count++;
89
116k
    total_patches += id_count;
90
116k
    if (total_patches > max_patches) {
91
3
      return JXL_FAILURE("Too many patches in dictionary");
92
3
    }
93
116k
    if (next_size < total_patches) {
94
9.02k
      next_size *= 2;
95
9.02k
      next_size = std::min<size_t>(next_size, max_patches);
96
9.02k
    }
97
116k
    if (next_size * blendings_stride_ > max_blending_infos) {
98
0
      return JXL_FAILURE("Too many patches in dictionary");
99
0
    }
100
116k
    positions_.reserve(next_size);
101
116k
    blendings_.reserve(next_size * blendings_stride_);
102
116k
    bool choose_alpha = (num_extra_channels > 1);
103
1.00M
    for (size_t i = 0; i < id_count; i++) {
104
885k
      PatchPosition pos;
105
885k
      pos.ref_pos_idx = ref_positions_.size();
106
885k
      if (i == 0) {
107
116k
        pos.x = read_num(kPatchPositionContext);
108
116k
        pos.y = read_num(kPatchPositionContext);
109
769k
      } else {
110
769k
        ptrdiff_t deltax = UnpackSigned(read_num(kPatchOffsetContext));
111
769k
        if (deltax < 0 && static_cast<size_t>(-deltax) > positions_.back().x) {
112
5
          return JXL_FAILURE("Invalid patch: negative x coordinate (%" PRIuS
113
5
                             " base x %" PRIdS " delta x)",
114
5
                             positions_.back().x, deltax);
115
5
        }
116
769k
        pos.x = positions_.back().x + deltax;
117
769k
        ptrdiff_t deltay = UnpackSigned(read_num(kPatchOffsetContext));
118
769k
        if (deltay < 0 && static_cast<size_t>(-deltay) > positions_.back().y) {
119
8
          return JXL_FAILURE("Invalid patch: negative y coordinate (%" PRIuS
120
8
                             " base y %" PRIdS " delta y)",
121
8
                             positions_.back().y, deltay);
122
8
        }
123
769k
        pos.y = positions_.back().y + deltay;
124
769k
      }
125
885k
      if (pos.x + ref_pos.xsize > xsize) {
126
2
        return JXL_FAILURE("Invalid patch x: at %" PRIuS " + %" PRIuS
127
2
                           " > %" PRIuS,
128
2
                           pos.x, ref_pos.xsize, xsize);
129
2
      }
130
885k
      if (pos.y + ref_pos.ysize > ysize) {
131
9
        return JXL_FAILURE("Invalid patch y: at %" PRIuS " + %" PRIuS
132
9
                           " > %" PRIuS,
133
9
                           pos.y, ref_pos.ysize, ysize);
134
9
      }
135
1.78M
      for (size_t j = 0; j < blendings_stride_; j++) {
136
902k
        uint32_t blend_mode = read_num(kPatchBlendModeContext);
137
902k
        if (blend_mode >= kNumPatchBlendModes) {
138
8
          return JXL_FAILURE("Invalid patch blend mode: %u", blend_mode);
139
8
        }
140
902k
        PatchBlending info;
141
902k
        info.mode = static_cast<PatchBlendMode>(blend_mode);
142
902k
        if (UsesAlpha(info.mode)) {
143
13.5k
          *uses_extra_channels = true;
144
13.5k
        }
145
902k
        if (info.mode != PatchBlendMode::kNone && j > 0) {
146
7
          *uses_extra_channels = true;
147
7
        }
148
902k
        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
902k
        } else {
156
902k
          info.alpha_channel = 0;
157
902k
        }
158
902k
        if (UsesClamp(info.mode)) {
159
15.7k
          info.clamp = static_cast<bool>(read_num(kPatchClampContext));
160
886k
        } else {
161
886k
          info.clamp = false;
162
886k
        }
163
902k
        blendings_.push_back(info);
164
902k
      }
165
885k
      positions_.emplace_back(pos);
166
885k
    }
167
116k
    ref_positions_.emplace_back(ref_pos);
168
116k
  }
169
1.48k
  positions_.shrink_to_fit();
170
171
1.48k
  if (!decoder.CheckANSFinalState()) {
172
0
    return JXL_FAILURE("ANS checksum failure.");
173
0
  }
174
175
1.48k
  ComputePatchTree();
176
1.48k
  return true;
177
1.48k
}
178
179
535
int PatchDictionary::GetReferences() const {
180
535
  int result = 0;
181
9.24k
  for (const auto& ref_pos : ref_positions_) {
182
9.24k
    result |= (1 << static_cast<int>(ref_pos.ref));
183
9.24k
  }
184
535
  return result;
185
535
}
186
187
namespace {
188
struct PatchInterval {
189
  size_t idx;
190
  size_t y0, y1;
191
};
192
}  // namespace
193
194
106k
void PatchDictionary::ComputePatchTree() {
195
106k
  patch_tree_.clear();
196
106k
  num_patches_.clear();
197
106k
  sorted_patches_y0_.clear();
198
106k
  sorted_patches_y1_.clear();
199
106k
  if (positions_.empty()) {
200
104k
    return;
201
104k
  }
202
  // Create a y-interval for each patch.
203
2.62k
  std::vector<PatchInterval> intervals(positions_.size());
204
2.46M
  for (size_t i = 0; i < positions_.size(); ++i) {
205
2.46M
    const auto& pos = positions_[i];
206
2.46M
    intervals[i].idx = i;
207
2.46M
    intervals[i].y0 = pos.y;
208
2.46M
    intervals[i].y1 = pos.y + ref_positions_[pos.ref_pos_idx].ysize;
209
2.46M
  }
210
325k
  auto sort_by_y0 = [&intervals](size_t start, size_t end) {
211
325k
    std::sort(intervals.data() + start, intervals.data() + end,
212
78.6M
              [](const PatchInterval& i0, const PatchInterval& i1) {
213
78.6M
                return i0.y0 < i1.y0;
214
78.6M
              });
215
325k
  };
216
165k
  auto sort_by_y1 = [&intervals](size_t start, size_t end) {
217
165k
    std::sort(intervals.data() + start, intervals.data() + end,
218
64.0M
              [](const PatchInterval& i0, const PatchInterval& i1) {
219
64.0M
                return i0.y1 < i1.y1;
220
64.0M
              });
221
165k
  };
222
  // Count the number of patches for each row.
223
2.62k
  sort_by_y1(0, intervals.size());
224
2.62k
  num_patches_.resize(intervals.back().y1);
225
2.46M
  for (auto iv : intervals) {
226
16.1M
    for (size_t y = iv.y0; y < iv.y1; ++y) num_patches_[y]++;
227
2.46M
  }
228
2.62k
  PatchTreeNode root;
229
2.62k
  root.start = 0;
230
2.62k
  root.num = intervals.size();
231
2.62k
  patch_tree_.push_back(root);
232
2.62k
  size_t next = 0;
233
165k
  while (next < patch_tree_.size()) {
234
162k
    auto& node = patch_tree_[next];
235
162k
    size_t start = node.start;
236
162k
    size_t end = node.start + node.num;
237
    // Choose the y_center for this node to be the median of interval starts.
238
162k
    sort_by_y0(start, end);
239
162k
    size_t middle_idx = start + node.num / 2;
240
162k
    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
162k
    size_t right_start = middle_idx;
246
1.20M
    while (right_start < end && intervals[right_start].y0 == node.y_center) {
247
1.04M
      ++right_start;
248
1.04M
    }
249
162k
    sort_by_y1(start, right_start);
250
162k
    size_t left_end = right_start;
251
2.62M
    while (left_end > start && intervals[left_end - 1].y1 > node.y_center) {
252
2.46M
      --left_end;
253
2.46M
    }
254
    // Fill in sorted_patches_y0_ and sorted_patches_y1_ for the current node.
255
162k
    node.num = right_start - left_end;
256
162k
    node.start = sorted_patches_y0_.size();
257
162k
    for (ptrdiff_t i = static_cast<ptrdiff_t>(right_start) - 1;
258
2.62M
         i >= static_cast<ptrdiff_t>(left_end); --i) {
259
2.46M
      sorted_patches_y1_.emplace_back(intervals[i].y1, intervals[i].idx);
260
2.46M
    }
261
162k
    sort_by_y0(left_end, right_start);
262
2.62M
    for (size_t i = left_end; i < right_start; ++i) {
263
2.46M
      sorted_patches_y0_.emplace_back(intervals[i].y0, intervals[i].idx);
264
2.46M
    }
265
    // Create the left and right nodes (if not empty).
266
162k
    node.left_child = node.right_child = -1;
267
162k
    if (left_end > start) {
268
76.8k
      PatchTreeNode left;
269
76.8k
      left.start = start;
270
76.8k
      left.num = left_end - left.start;
271
76.8k
      patch_tree_[next].left_child = patch_tree_.size();
272
76.8k
      patch_tree_.push_back(left);
273
76.8k
    }
274
162k
    if (right_start < end) {
275
83.1k
      PatchTreeNode right;
276
83.1k
      right.start = right_start;
277
83.1k
      right.num = end - right.start;
278
83.1k
      patch_tree_[next].right_child = patch_tree_.size();
279
83.1k
      patch_tree_.push_back(right);
280
83.1k
    }
281
162k
    ++next;
282
162k
  }
283
2.62k
}
284
285
3.49M
std::vector<size_t> PatchDictionary::GetPatchesForRow(size_t y) const {
286
3.49M
  std::vector<size_t> result;
287
3.49M
  if (y < num_patches_.size() && num_patches_[y] > 0) {
288
1.85M
    result.reserve(num_patches_[y]);
289
13.4M
    for (ptrdiff_t tree_idx = 0; tree_idx != -1;) {
290
11.6M
      JXL_DASSERT(tree_idx < static_cast<ptrdiff_t>(patch_tree_.size()));
291
11.6M
      const auto& node = patch_tree_[tree_idx];
292
11.6M
      if (y <= node.y_center) {
293
21.4M
        for (size_t i = 0; i < node.num; ++i) {
294
20.6M
          const auto& p = sorted_patches_y0_[node.start + i];
295
20.6M
          if (y < p.first) break;
296
15.6M
          result.push_back(p.second);
297
15.6M
        }
298
5.85M
        tree_idx = y < node.y_center ? node.left_child : -1;
299
5.85M
      } else {
300
17.7M
        for (size_t i = 0; i < node.num; ++i) {
301
17.0M
          const auto& p = sorted_patches_y1_[node.start + i];
302
17.0M
          if (y >= p.first) break;
303
12.0M
          result.push_back(p.second);
304
12.0M
        }
305
5.77M
        tree_idx = node.right_child;
306
5.77M
      }
307
11.6M
    }
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
1.85M
    std::sort(result.begin(), result.end());
312
1.85M
  }
313
3.49M
  return result;
314
3.49M
}
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
2.56M
    const std::vector<ExtraChannelInfo>& extra_channel_info) const {
321
2.56M
  size_t num_ec = extra_channel_info.size();
322
2.56M
  JXL_ENSURE(num_ec + 1 <= blendings_stride_);
323
2.56M
  std::vector<const float*> fg_ptrs(3 + num_ec);
324
23.6M
  for (size_t pos_idx : GetPatchesForRow(y)) {
325
23.6M
    const size_t blending_idx = pos_idx * blendings_stride_;
326
23.6M
    const PatchPosition& pos = positions_[pos_idx];
327
23.6M
    const PatchReferencePosition& ref_pos = ref_positions_[pos.ref_pos_idx];
328
23.6M
    size_t by = pos.y;
329
23.6M
    size_t bx = pos.x;
330
23.6M
    size_t patch_xsize = ref_pos.xsize;
331
23.6M
    JXL_ENSURE(y >= by);
332
23.6M
    JXL_ENSURE(y < by + ref_pos.ysize);
333
23.6M
    size_t iy = y - by;
334
23.6M
    size_t ref = ref_pos.ref;
335
23.6M
    if (bx >= x0 + xsize) continue;
336
18.2M
    if (bx + patch_xsize < x0) continue;
337
12.3M
    size_t patch_x0 = std::max(bx, x0);
338
12.3M
    size_t patch_x1 = std::min(bx + patch_xsize, x0 + xsize);
339
49.5M
    for (size_t c = 0; c < 3; c++) {
340
37.1M
      fg_ptrs[c] = reference_frames_->at(ref).frame->color()->ConstPlaneRow(
341
37.1M
                       c, ref_pos.y0 + iy) +
342
37.1M
                   ref_pos.x0 + x0 - bx;
343
37.1M
    }
344
12.3M
    for (size_t i = 0; i < num_ec; i++) {
345
0
      fg_ptrs[3 + i] =
346
0
          reference_frames_->at(ref).frame->extra_channels()[i].ConstRow(
347
0
              ref_pos.y0 + iy) +
348
0
          ref_pos.x0 + x0 - bx;
349
0
    }
350
12.3M
    JXL_RETURN_IF_ERROR(PerformBlending(
351
12.3M
        memory_manager_, inout, fg_ptrs.data(), inout, patch_x0 - x0,
352
12.3M
        patch_x1 - patch_x0, blendings_[blending_idx],
353
12.3M
        blendings_.data() + blending_idx + 1, extra_channel_info));
354
12.3M
  }
355
2.56M
  return true;
356
2.56M
}
357
}  // namespace jxl