Coverage Report

Created: 2026-12-01 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/tests/fuzzer/enc_fuzzer.cc
Line
Count
Source
1
// Copyright 2024 Google Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
////////////////////////////////////////////////////////////////////////////////
16
17
#include <cmath>
18
#include <cstddef>
19
#include <cstdint>
20
#include <cstdlib>
21
#include <iostream>
22
#include <limits>
23
#include <memory>
24
#include <string>
25
#include <string_view>
26
#include <vector>
27
28
#include "imageio/image_dec.h"
29
#include "src/dsp/cpu.h"
30
#include "tests/fuzzer/fuzz_utils.h"
31
#include "webp/decode.h"
32
#include "webp/encode.h"
33
#include "webp/types.h"
34
35
namespace {
36
37
const VP8CPUInfo default_VP8GetCPUInfo = fuzz_utils::VP8GetCPUInfo;
38
39
void EncTestImpl(WebPPicture& pic, uint32_t optimization_index, bool use_argb,
40
                 WebPConfig config,
41
11.5k
                 const fuzz_utils::CropOrScaleParams& crop_or_scale_params) {
42
11.5k
  WebPMemoryWriter memory_writer;
43
11.5k
  WebPMemoryWriterInit(&memory_writer);
44
11.5k
  std::unique_ptr<WebPMemoryWriter, fuzz_utils::UniquePtrDeleter>
45
11.5k
      memory_writer_owner(&memory_writer);
46
11.5k
  if (!fuzz_utils::CropOrScaleAndEncode(crop_or_scale_params, config, pic,
47
11.5k
                                        default_VP8GetCPUInfo,
48
11.5k
                                        optimization_index, memory_writer)) {
49
0
    return;
50
0
  }
51
52
  // Try decoding the result.
53
11.5k
  int w, h;
54
11.5k
  const uint8_t* const out_data = memory_writer.mem;
55
11.5k
  const size_t out_size = memory_writer.size;
56
11.5k
  uint8_t* const rgba = WebPDecodeBGRA(out_data, out_size, &w, &h);
57
11.5k
  if (rgba == nullptr || w != pic.width || h != pic.height) {
58
0
    std::cerr << "WebPDecodeBGRA failed.\n";
59
0
    WebPFree(rgba);
60
0
    std::abort();
61
0
  }
62
63
  // Compare the results if exact encoding.
64
11.5k
  if (pic.use_argb && config.lossless && config.near_lossless == 100) {
65
799
    const uint32_t* src1 = (const uint32_t*)rgba;
66
799
    const uint32_t* src2 = pic.argb;
67
23.9k
    for (int y = 0; y < h; ++y, src1 += w, src2 += pic.argb_stride) {
68
1.85M
      for (int x = 0; x < w; ++x) {
69
1.82M
        uint32_t v1 = src1[x], v2 = src2[x];
70
1.82M
        if (!config.exact) {
71
1.02M
          if ((v1 & 0xff000000u) == 0 || (v2 & 0xff000000u) == 0) {
72
            // Only keep alpha for comparison of fully transparent area.
73
1.08k
            v1 &= 0xff000000u;
74
1.08k
            v2 &= 0xff000000u;
75
1.08k
          }
76
1.02M
        }
77
1.82M
        if (v1 != v2) {
78
0
          std::cerr << "Lossless compression failed pixel-exactness.\n";
79
0
          WebPFree(rgba);
80
0
          std::abort();
81
0
        }
82
1.82M
      }
83
23.1k
    }
84
799
  }
85
86
11.5k
  WebPFree(rgba);
87
11.5k
}
88
89
// For open source compatibility, maybe_unused is necessary.
90
[[maybe_unused]] void EncFileTest(
91
    std::string_view file, uint32_t optimization_index, bool use_argb,
92
    WebPConfig config,
93
58
    const fuzz_utils::CropOrScaleParams& crop_or_scale_params) {
94
  // Init the source picture.
95
58
  WebPPicture pic;
96
58
  std::unique_ptr<WebPPicture, fuzz_utils::UniquePtrDeleter> pic_owner(&pic);
97
58
  if (!WebPPictureInit(&pic)) {
98
0
    std::cerr << "WebPPictureInit failed.\n";
99
0
    std::abort();
100
0
  }
101
58
  pic.use_argb = use_argb;
102
103
58
  const uint8_t* const file_data =
104
58
      reinterpret_cast<const uint8_t*>(file.data());
105
58
  if (fuzz_utils::IsImageTooBig(file_data, file.size())) return;
106
58
  WebPImageReader reader = WebPGuessImageReader(file_data, file.size());
107
58
  if (!reader(file_data, file.size(), &pic, 1, NULL)) return;
108
109
0
  EncTestImpl(pic, optimization_index, use_argb, config, crop_or_scale_params);
110
0
}
111
112
void EncArbitraryTest(
113
    const fuzz_utils::WebPPictureCpp& pic_cpp, uint32_t optimization_index,
114
    bool use_argb, const WebPConfig& config,
115
11.5k
    const fuzz_utils::CropOrScaleParams& crop_or_scale_params) {
116
11.5k
  WebPPicture& pic = pic_cpp.ref();
117
118
11.5k
  EncTestImpl(pic, optimization_index, use_argb, config, crop_or_scale_params);
119
11.5k
}
120
121
}  // namespace
122
123
FUZZ_TEST(Enc, EncFileTest)
124
    .WithDomains(fuzztest::ElementOf<std::string>(fuzz_utils::DefaultSeeds(
125
                     fuzz_utils::FuzzSeedFormat::kImageIo)),
126
                 /*optimization_index=*/
127
                 fuzztest::InRange<uint32_t>(0,
128
                                             fuzz_utils::kMaxOptimizationIndex),
129
                 /*use_argb=*/fuzztest::Arbitrary<bool>(),
130
                 fuzz_utils::ArbitraryWebPConfig(),
131
                 fuzz_utils::ArbitraryCropOrScaleParams());
132
133
FUZZ_TEST(Enc, EncArbitraryTest)
134
    .WithDomains(fuzz_utils::ArbitraryWebPPicture(),
135
                 /*optimization_index=*/
136
                 fuzztest::InRange<uint32_t>(0,
137
                                             fuzz_utils::kMaxOptimizationIndex),
138
                 /*use_argb=*/fuzztest::Arbitrary<bool>(),
139
                 fuzz_utils::ArbitraryWebPConfig(),
140
                 fuzz_utils::ArbitraryCropOrScaleParams());
141
142
// NaN compares false with everything, so it used to pass the range checks of
143
// WebPValidateConfig() and reach float to int casts.
144
0
TEST(Enc, ValidateConfigRejectsNaN) {
145
0
  const float kNaN = std::numeric_limits<float>::quiet_NaN();
146
0
  WebPConfig config;
147
0
  ASSERT_TRUE(WebPConfigInit(&config));
148
0
  EXPECT_TRUE(WebPValidateConfig(&config));
149
0
  config.quality = kNaN;
150
0
  EXPECT_FALSE(WebPValidateConfig(&config));
151
0
  ASSERT_TRUE(WebPConfigInit(&config));
152
0
  config.target_PSNR = kNaN;
153
0
  EXPECT_FALSE(WebPValidateConfig(&config));
154
155
0
  for (const int lossless : {0, 1}) {
156
0
    ASSERT_TRUE(WebPConfigInit(&config));
157
0
    config.lossless = lossless;
158
0
    config.quality = kNaN;
159
0
    WebPPicture pic;
160
0
    ASSERT_TRUE(WebPPictureInit(&pic));
161
0
    pic.use_argb = lossless;
162
0
    pic.width = 32;
163
0
    pic.height = 32;
164
0
    ASSERT_TRUE(WebPPictureAlloc(&pic));
165
0
    WebPMemoryWriter writer;
166
0
    WebPMemoryWriterInit(&writer);
167
0
    pic.writer = WebPMemoryWrite;
168
0
    pic.custom_ptr = &writer;
169
0
    EXPECT_FALSE(WebPEncode(&config, &pic));
170
0
    EXPECT_EQ(pic.error_code, VP8_ENC_ERROR_INVALID_CONFIGURATION);
171
0
    WebPMemoryWriterClear(&writer);
172
0
    WebPPictureFree(&pic);
173
0
  }
174
0
}
175
176
namespace {
177
178
#if !(defined(WEBP_DISABLE_STATS) || defined(WEBP_REDUCE_SIZE))
179
180
// Fuzzes WebPPlaneDistortion across valid padded strides, pixel steps
181
// (`x_step`), and metric types (0 = PSNR, 1 = SSIM, 2 = LSIM), checking finite
182
// results and bit-exact C-vs-SIMD parity.
183
void PlaneDistortionValidTest(int width, int height, size_t src_pad,
184
                              size_t ref_pad, size_t x_step, int type,
185
                              const std::vector<uint8_t>& src_pattern,
186
                              const std::vector<uint8_t>& ref_pattern,
187
0
                              uint32_t optimization_index) {
188
0
  if (src_pattern.empty() || ref_pattern.empty()) return;
189
0
  const size_t src_stride = static_cast<size_t>(width) * x_step + src_pad;
190
0
  const size_t ref_stride = static_cast<size_t>(width) * x_step + ref_pad;
191
  // Allocate only through the last accessed sample (no trailing slack past the
192
  // final pixel) so sanitizers catch any out-of-bounds read into row padding.
193
0
  const size_t src_size = static_cast<size_t>(height - 1) * src_stride +
194
0
                          static_cast<size_t>(width - 1) * x_step + 1;
195
0
  const size_t ref_size = static_cast<size_t>(height - 1) * ref_stride +
196
0
                          static_cast<size_t>(width - 1) * x_step + 1;
197
198
0
  std::vector<uint8_t> src(src_size);
199
0
  std::vector<uint8_t> ref(ref_size);
200
0
  for (size_t i = 0; i < src_size; ++i) {
201
0
    src[i] = src_pattern[i % src_pattern.size()];
202
0
  }
203
0
  for (size_t i = 0; i < ref_size; ++i) {
204
0
    ref[i] = ref_pattern[i % ref_pattern.size()];
205
0
  }
206
207
  // Run pure C (index == 0) vs. the fuzzed SIMD tier, then restore default CPU
208
  // dispatch for subsequent tests.
209
0
  float dist_c = 0.f;
210
0
  float res_c = 0.f;
211
0
  fuzz_utils::SetOptimization(default_VP8GetCPUInfo, /*index=*/0);
212
0
  ASSERT_EQ(WebPPlaneDistortion(src.data(), src_stride, ref.data(), ref_stride,
213
0
                                width, height, x_step, type, &dist_c, &res_c),
214
0
            1);
215
216
0
  float dist_simd = 0.f;
217
0
  float res_simd = 0.f;
218
0
  fuzz_utils::SetOptimization(default_VP8GetCPUInfo, optimization_index);
219
0
  ASSERT_EQ(
220
0
      WebPPlaneDistortion(src.data(), src_stride, ref.data(), ref_stride, width,
221
0
                          height, x_step, type, &dist_simd, &res_simd),
222
0
      1);
223
0
  fuzz_utils::SetOptimization(default_VP8GetCPUInfo,
224
0
                              fuzz_utils::kMaxOptimizationIndex);
225
226
0
  EXPECT_TRUE(std::isfinite(dist_c));
227
0
  EXPECT_TRUE(std::isfinite(res_c));
228
0
  EXPECT_EQ(dist_simd, dist_c);
229
0
  EXPECT_EQ(res_simd, res_c);
230
0
}
231
232
#endif  // !(defined(WEBP_DISABLE_STATS) || defined(WEBP_REDUCE_SIZE))
233
234
// Fuzzes WebPPictureHasTransparency on valid ARGB and YUVA alpha planes with
235
// row padding and positive or negative strides, checking exact detection
236
// against a ground-truth oracle, C-vs-SIMD parity, and const safety.
237
void PictureHasTransparencyValidTest(bool use_argb, int width, int height,
238
                                     int pad, bool negative_stride,
239
                                     bool has_transparent_pixel, int tx, int ty,
240
                                     uint8_t alpha_val,
241
0
                                     uint32_t optimization_index) {
242
0
  const int abs_stride = width + pad;
243
  // Tight allocation through the last pixel of the final row (no slack past
244
  // `width` on the last row) so sanitizers flag any over-read.
245
0
  const size_t total =
246
0
      static_cast<size_t>(height - 1) * abs_stride + static_cast<size_t>(width);
247
248
  // Fill padding pixels with alpha == 0 so any out-of-bounds read into row
249
  // padding produces a false positive. Active pixels start fully opaque (0xff)
250
  // and optionally get one pixel set to `alpha_val` at (px, py).
251
0
  std::vector<uint32_t> argb;
252
0
  std::vector<uint8_t> alpha;
253
0
  WebPPicture pic;
254
0
  ASSERT_TRUE(WebPPictureInit(&pic));
255
0
  pic.use_argb = use_argb ? 1 : 0;
256
0
  pic.width = width;
257
0
  pic.height = height;
258
259
0
  const int px = tx % width;
260
0
  const int py = ty % height;
261
0
  const int expected = (has_transparent_pixel && alpha_val != 0xffu) ? 1 : 0;
262
263
0
  if (use_argb) {
264
0
    argb.assign(total, 0x00112233u);
265
0
    for (int y = 0; y < height; ++y) {
266
0
      for (int x = 0; x < width; ++x) {
267
0
        argb[static_cast<size_t>(y) * abs_stride + x] = 0xff112233u;
268
0
      }
269
0
    }
270
0
    if (has_transparent_pixel) {
271
0
      argb[static_cast<size_t>(py) * abs_stride + px] =
272
0
          (static_cast<uint32_t>(alpha_val) << 24) | 0x00112233u;
273
0
    }
274
    // For bottom-up buffers, start at the last row and step backwards.
275
0
    pic.argb = negative_stride
276
0
                   ? argb.data() + static_cast<size_t>(height - 1) * abs_stride
277
0
                   : argb.data();
278
0
    pic.argb_stride = negative_stride ? -abs_stride : abs_stride;
279
0
  } else {
280
0
    alpha.assign(total, 0x00u);
281
0
    for (int y = 0; y < height; ++y) {
282
0
      for (int x = 0; x < width; ++x) {
283
0
        alpha[static_cast<size_t>(y) * abs_stride + x] = 0xffu;
284
0
      }
285
0
    }
286
0
    if (has_transparent_pixel) {
287
0
      alpha[static_cast<size_t>(py) * abs_stride + px] = alpha_val;
288
0
    }
289
0
    pic.a = negative_stride
290
0
                ? alpha.data() + static_cast<size_t>(height - 1) * abs_stride
291
0
                : alpha.data();
292
0
    pic.a_stride = negative_stride ? -abs_stride : abs_stride;
293
0
  }
294
295
  // Compare pure C against SIMD and confirm the const WebPPicture* parameter's
296
  // error_code is never mutated.
297
0
  fuzz_utils::SetOptimization(default_VP8GetCPUInfo, /*index=*/0);
298
0
  const int res_c = WebPPictureHasTransparency(&pic);
299
0
  fuzz_utils::SetOptimization(default_VP8GetCPUInfo, optimization_index);
300
0
  const int res_simd = WebPPictureHasTransparency(&pic);
301
0
  fuzz_utils::SetOptimization(default_VP8GetCPUInfo,
302
0
                              fuzz_utils::kMaxOptimizationIndex);
303
304
0
  EXPECT_EQ(res_c, expected);
305
0
  EXPECT_EQ(res_simd, expected);
306
0
  EXPECT_EQ(pic.error_code, VP8_ENC_OK);
307
0
}
308
309
}  // namespace
310
311
#if !(defined(WEBP_DISABLE_STATS) || defined(WEBP_REDUCE_SIZE))
312
313
FUZZ_TEST(Enc, PlaneDistortionValidTest)
314
    .WithDomains(
315
        /*width=*/fuzztest::InRange(1, 64),
316
        /*height=*/fuzztest::InRange(1, 64),
317
        /*src_pad=*/fuzztest::InRange<size_t>(0, 64),
318
        /*ref_pad=*/fuzztest::InRange<size_t>(0, 64),
319
        /*x_step=*/fuzztest::InRange<size_t>(1, 4),
320
        /*type=*/fuzztest::InRange(0, 2),
321
        /*src_pattern=*/
322
        fuzztest::VectorOf(fuzztest::Arbitrary<uint8_t>())
323
            .WithMinSize(1)
324
            .WithMaxSize(32),
325
        /*ref_pattern=*/
326
        fuzztest::VectorOf(fuzztest::Arbitrary<uint8_t>())
327
            .WithMinSize(1)
328
            .WithMaxSize(32),
329
        /*optimization_index=*/
330
        fuzztest::InRange<uint32_t>(1, fuzz_utils::kMaxOptimizationIndex));
331
332
#endif  // !(defined(WEBP_DISABLE_STATS) || defined(WEBP_REDUCE_SIZE))
333
334
FUZZ_TEST(Enc, PictureHasTransparencyValidTest)
335
    .WithDomains(
336
        /*use_argb=*/fuzztest::Arbitrary<bool>(),
337
        /*width=*/fuzztest::InRange(1, 128),
338
        /*height=*/fuzztest::InRange(1, 64),
339
        /*pad=*/fuzztest::InRange(0, 32),
340
        /*negative_stride=*/fuzztest::Arbitrary<bool>(),
341
        /*has_transparent_pixel=*/fuzztest::Arbitrary<bool>(),
342
        /*tx=*/fuzztest::InRange(0, 127),
343
        /*ty=*/fuzztest::InRange(0, 63),
344
        /*alpha_val=*/fuzztest::Arbitrary<uint8_t>(),
345
        /*optimization_index=*/
346
        fuzztest::InRange<uint32_t>(1, fuzz_utils::kMaxOptimizationIndex));