// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! WebP, against files libwebp wrote and pixels Pillow read back. //! //! The corpus holds this library against wuffs, which is the stronger claim //! and the one that found nothing here. What these add is the *shapes* wuffs //! has no file for: the same picture encoded at three different effort //! levels, so that the encoder's choice of transform varies underneath a //! fixed expectation, and the two properties `src/root.zig` can no longer //! state for a format it cannot write. const std = @import("std"); const Io = std.Io; const mem = std.mem; const testing = std.testing; const Allocator = mem.Allocator; const z2d = @import("z2d"); const z2dimg = @import("z2dimg"); const fixtures = @import("webp_fixtures.zig"); const Rgba8 = z2dimg.pixels.Rgba8; fn decodeBytes(gpa: Allocator, bytes: []const u8) !z2d.Surface { var r: Io.Reader = .fixed(bytes); return z2dimg.decode(gpa, &r, .{}); } fn at(sfc: z2d.Surface, x: i32, y: i32) Rgba8 { return .fromZ2d(sfc.getPixel(x, y).?); } fn expectPixels(sfc: z2d.Surface, expected: []const Rgba8, width: usize) !void { const height = expected.len / width; try testing.expectEqual(@as(i32, @intCast(width)), sfc.getWidth()); try testing.expectEqual(@as(i32, @intCast(height)), sfc.getHeight()); for (0..height) |y| { for (0..width) |x| { const want = expected[y * width + x]; const got = at(sfc, @intCast(x), @intCast(y)); // A z2d surface is premultiplied, so a pixel that is entirely // transparent has nowhere to keep the colour it was. libwebp // writes that colour --- `cwebp -exact` is what stops it // discarding it --- and Pillow reports it, and it cannot survive // here. What is promised for such a pixel is that it is invisible. if (want.a == 0) { testing.expectEqual(@as(u8, 0), got.a) catch |err| { std.debug.print("at ({d}, {d})\n", .{ x, y }); return err; }; continue; } testing.expectEqual(want, got) catch |err| { std.debug.print("at ({d}, {d})\n", .{ x, y }); return err; }; } } } test "the same picture at three effort levels decodes to the same pixels" { const gpa = testing.allocator; // Twelve files, four pictures, one expectation each. The effort level // changes which transforms libwebp chose and changes nothing about what // is in the image, which is exactly the property a decoder has to have. const cases = [_]struct { []const u8, []const Rgba8, []const u8 }{ .{ &fixtures.indexed_z0, &fixtures.indexed_pixels, "colour indexing, four pixels bundled" }, .{ &fixtures.indexed_z6, &fixtures.indexed_pixels, "the same, at -z 6" }, .{ &fixtures.indexed_z9, &fixtures.indexed_pixels, "the same, at -z 9" }, .{ &fixtures.bilevel_z0, &fixtures.bilevel_pixels, "two colours, eight pixels to a byte" }, .{ &fixtures.bilevel_z6, &fixtures.bilevel_pixels, "the same, at -z 6" }, .{ &fixtures.bilevel_z9, &fixtures.bilevel_pixels, "the same, at -z 9" }, .{ &fixtures.gradient_z0, &fixtures.gradient_pixels, "predictor and cross-colour" }, .{ &fixtures.gradient_z6, &fixtures.gradient_pixels, "the same, at -z 6" }, .{ &fixtures.gradient_z9, &fixtures.gradient_pixels, "the same, at -z 9" }, .{ &fixtures.alpha_z0, &fixtures.alpha_pixels, "a transparent column" }, .{ &fixtures.alpha_z6, &fixtures.alpha_pixels, "the same, at -z 6" }, .{ &fixtures.alpha_z9, &fixtures.alpha_pixels, "the same, at -z 9" }, }; for (cases) |case| { var sfc = try decodeBytes(gpa, case[0]); defer sfc.deinit(gpa); expectPixels(sfc, case[1], fixtures.width) catch |err| { std.debug.print("in: {s}\n", .{case[2]}); return err; }; } } test "a file that says it has transparency gets a surface that can hold it" { const gpa = testing.allocator; var opaque_sfc = try decodeBytes(gpa, &fixtures.gradient_z0); defer opaque_sfc.deinit(gpa); try testing.expectEqual(z2d.surface.SurfaceType.image_surface_rgb, std.meta.activeTag(opaque_sfc)); var clear = try decodeBytes(gpa, &fixtures.alpha_z0); defer clear.deinit(gpa); try testing.expectEqual(z2d.surface.SurfaceType.image_surface_rgba, std.meta.activeTag(clear)); try testing.expectEqual(@as(u8, 0), at(clear, 0, 0).a); } test "probing agrees with decoding, and says what the header said" { var r: Io.Reader = .fixed(&fixtures.gradient_z0); const info = try z2dimg.probe(&r, .{}); try testing.expectEqual(z2dimg.Format.webp, info.format); try testing.expectEqual(@as(u32, fixtures.width), info.width); try testing.expectEqual(@as(u32, fixtures.height), info.height); try testing.expect(!info.has_alpha); // A simple file does not animate, and says so before any pixels. try testing.expectEqual( @as(std.meta.Tag(z2dimg.Info.Animation), .none), std.meta.activeTag(info.animation), ); } test "an animation plays its frames with the durations it declared" { const gpa = testing.allocator; var r: Io.Reader = .fixed(&fixtures.animated); var animation = try z2dimg.decodeAnimation(gpa, &r, .{}); defer animation.deinit(gpa); try testing.expectEqual(@as(u32, fixtures.animated_loop_count), animation.info().loop_count); var count: u32 = 0; while (try animation.next(gpa)) |frame| { try testing.expectEqual(@as(u32, fixtures.animated_delay_ms), frame.delay_ms); try testing.expectEqual(count, frame.index); count += 1; } try testing.expectEqual(@as(u32, fixtures.animated_frames), count); const canvas = animation.canvasSurface().?; try testing.expectEqual(@as(i32, fixtures.animated_width), canvas.getWidth()); try testing.expectEqual(@as(i32, fixtures.animated_height), canvas.getHeight()); } test "an animated file probes as animated before any pixels" { var r: Io.Reader = .fixed(&fixtures.animated); const info = try z2dimg.probe(&r, .{}); switch (info.animation) { .declared => |a| { try testing.expectEqual(@as(u32, fixtures.animated_loop_count), a.loop_count); // Nothing in the container counts the frames, so nothing may // claim to. try testing.expectEqual(@as(?u32, null), a.frames); }, else => return error.TestUnexpectedResult, } } test "it decodes with the limits turned off" { // The property `src/root.zig` states for every format it can write, made // here instead because this one cannot be written. `Limits.unlimited` // sets every budget to the largest value of its type, and arithmetic // inside a decoder can walk off the end of that --- which is how the JPEG // decoder came to panic on every valid JPEG for a caller who asked for no // limits. const gpa = testing.allocator; var probe_reader: Io.Reader = .fixed(&fixtures.gradient_z0); const info = try z2dimg.probe(&probe_reader, .unlimited); try testing.expectEqual(@as(u32, fixtures.width), info.width); var r: Io.Reader = .fixed(&fixtures.gradient_z0); var sfc = try z2dimg.decode(gpa, &r, .{ .limits = .unlimited }); defer sfc.deinit(gpa); try testing.expectEqual(@as(i32, fixtures.width), sfc.getWidth()); } test "a lossy file decodes to what libwebp reads out of it" { // The claim a lossy decoder can make. Not "close to the picture that was // encoded" --- that is the encoder's loss and says nothing about this // --- but "the same pixels another decoder reads out of the same file", // which is exact. The expected values are Pillow's, which is libwebp's. const gpa = testing.allocator; var probe_reader: Io.Reader = .fixed(&fixtures.lossy); const info = try z2dimg.probe(&probe_reader, .{}); try testing.expectEqual(z2dimg.Format.webp, info.format); try testing.expectEqual(@as(u32, fixtures.lossy_width), info.width); try testing.expectEqual(@as(u32, fixtures.lossy_height), info.height); try testing.expect(!info.has_alpha); var r: Io.Reader = .fixed(&fixtures.lossy); var sfc = try z2dimg.decode(gpa, &r, .{}); defer sfc.deinit(gpa); try expectPixels(sfc, &fixtures.lossy_pixels, fixtures.lossy_width); } test "a lossy file's transparency comes out of the ALPH beside it" { // VP8 has no alpha channel, so a transparent lossy WebP is two images: // the frame, and a plane of alpha in a chunk of its own that is a // lossless WebP image with the values in its green channel. Getting // either half wrong shows up here. const gpa = testing.allocator; var probe_reader: Io.Reader = .fixed(&fixtures.lossy_alpha); const info = try z2dimg.probe(&probe_reader, .{}); try testing.expectEqual(@as(u32, fixtures.lossy_width), info.width); try testing.expect(info.has_alpha); var r: Io.Reader = .fixed(&fixtures.lossy_alpha); var sfc = try z2dimg.decode(gpa, &r, .{}); defer sfc.deinit(gpa); try expectPixels(sfc, &fixtures.lossy_alpha_pixels, fixtures.lossy_width); } test "what is written comes back, pixel for pixel" { // Lossless means lossless: not close, identical. Every surface here goes // out and comes back and is compared exactly, which is the only // interesting claim a lossless encoder can make. const gpa = testing.allocator; const shapes = [_]struct { u32, u32, []const u8 }{ .{ 1, 1, "one pixel, where every channel is a code of one symbol" }, .{ 11, 7, "odd in both directions" }, .{ 64, 1, "a single row" }, .{ 1, 64, "a single column" }, .{ 37, 23, "prime-ish, so nothing lines up" }, }; for (shapes) |shape| { const width = shape[0]; const height = shape[1]; var sfc: z2d.Surface = try .init(.image_surface_rgba, gpa, @intCast(width), @intCast(height)); defer sfc.deinit(gpa); for (0..height) |y| for (0..width) |x| { z2dimg.pixels.writePixel(&sfc, @intCast(x), @intCast(y), .{ .r = @truncate(x *% 37 +% y), .g = @truncate(y *% 11), .b = @truncate((x ^ y) *% 3), .a = 255, }); }; var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &sfc, &w.writer, .{ .webp = .{} }); try testing.expectEqual(@as(?z2dimg.Format, .webp), z2dimg.detect(w.written())); var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); testing.expectEqual(@as(i32, @intCast(width)), back.getWidth()) catch |err| { std.debug.print("in: {s}\n", .{shape[2]}); return err; }; for (0..height) |y| for (0..width) |x| { const want = at(sfc, @intCast(x), @intCast(y)); const got = at(back, @intCast(x), @intCast(y)); testing.expectEqual(want, got) catch |err| { std.debug.print("in: {s}, at ({d}, {d})\n", .{ shape[2], x, y }); return err; }; }; } } test "transparency survives the round trip" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgba, gpa, 8, 8); defer sfc.deinit(gpa); for (0..8) |y| for (0..8) |x| { z2dimg.pixels.writePixel(&sfc, @intCast(x), @intCast(y), .{ .r = 200, .g = @truncate(x * 30), .b = @truncate(y * 30), // Fully transparent, fully opaque, and one in between: a // premultiplied surface can carry the last two exactly and the // first only as "invisible". .a = switch (x % 3) { 0 => 0, 1 => 255, else => 128, }, }); }; var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &sfc, &w.writer, .{ .webp = .{} }); var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); try testing.expectEqual(z2d.surface.SurfaceType.image_surface_rgba, std.meta.activeTag(back)); for (0..8) |y| for (0..8) |x| { const want = at(sfc, @intCast(x), @intCast(y)); const got = at(back, @intCast(x), @intCast(y)); try testing.expectEqual(want.a, got.a); // Exact at both ends of the alpha range, and within a count or two // in between --- and that is the *surface*, not the codec. A z2d // surface stores premultiplied, so a straight colour put in and // taken out again has been through a multiply and a divide, and // doing that twice --- once writing the fixture, once decoding --- // loses a little more. `ceil(255 / a)` is how far one such trip can // move a channel. const slack: u8 = if (want.a == 0 or want.a == 255) 0 else @intCast((255 + @as(u32, want.a) - 1) / @as(u32, want.a)); if (want.a == 0) continue; for ([_][2]u8{ .{ want.r, got.r }, .{ want.g, got.g }, .{ want.b, got.b } }) |pair| { const delta = @max(pair[0], pair[1]) - @min(pair[0], pair[1]); try testing.expect(delta <= slack); } }; } test "a picture of one colour codes to almost nothing" { // Sixty-five thousand pixels, all the same: the whole image is a handful // of backward references, each naming as many pixels as one is allowed // to. What is left is the header and the five tables. const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, 256, 256); defer sfc.deinit(gpa); for (0..256) |y| for (0..256) |x| { z2dimg.pixels.writePixel(&sfc, @intCast(x), @intCast(y), .{ .r = 7, .g = 9, .b = 11, .a = 255 }); }; var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &sfc, &w.writer, .{ .webp = .{} }); // Under two hundred bytes for sixty-five thousand pixels, which is a // hundredth of a bit each. An exact number would be a test of this // encoder's current choices rather than of anything true. try testing.expect(w.written().len < 200); var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); try testing.expectEqual(Rgba8{ .r = 7, .g = 9, .b = 11, .a = 255 }, at(back, 123, 45)); } test "an image the bitstream cannot describe is refused" { const gpa = testing.allocator; // Fourteen bits a side, plus one. One more than that has nowhere to go. var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, 16385, 1); defer sfc.deinit(gpa); var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try testing.expectError( error.Unsupported, z2dimg.encode(gpa, &sfc, &w.writer, .{ .webp = .{} }), ); } test "a truncated file fails cleanly" { const gpa = testing.allocator; var length: usize = fixtures.gradient_z0.len - 1; while (length > 0) : (length -= 1) { var r: Io.Reader = .fixed(fixtures.gradient_z0[0..length]); if (z2dimg.decode(gpa, &r, .{})) |sfc| { var s = sfc; s.deinit(gpa); } else |err| switch (err) { error.InvalidData, error.EndOfStream, error.UnknownFormat, error.Unsupported => {}, else => return err, } } } test "a WebP decodes inside the sandbox" { // Worth its own test rather than resting on the sandbox's own: VP8L needs // a whole second image's worth of scratch — backward references reach // anywhere earlier in the picture, so there is no streaming form of it — // and the child decodes onto a fixed arena. Every other decoder here // allocates the surface and little else. if (!z2dimg.sandbox.available) return error.SkipZigTest; const gpa = testing.allocator; var r: Io.Reader = .fixed(&fixtures.gradient_z0); var img = z2dimg.sandbox.decode(gpa, &r, .{}) catch |err| switch (err) { error.SandboxFailed => return error.SkipZigTest, else => |e| return e, }; defer img.deinit(); try testing.expectEqual(z2dimg.Format.webp, img.info.format); try testing.expectEqual(@as(i32, fixtures.width), img.surface.getWidth()); try expectPixels(img.surface, &fixtures.gradient_pixels, fixtures.width); } test "the ICC profile comes out of the ICCP chunk" { // `webpmux -set icc` put it there, so where the chunk goes is libwebp's // answer and not this project's. It goes *before* the image data, which // is why the walk that reads the header finds it on its way past. const gpa = testing.allocator; var got: std.ArrayList(u8) = .empty; defer got.deinit(gpa); var r: Io.Reader = .fixed(&fixtures.with_icc); var sfc = try z2dimg.decode(gpa, &r, .{ .icc = &got }); defer sfc.deinit(gpa); try testing.expectEqualSlices(u8, &fixtures.icc_profile, got.items); try expectPixels(sfc, &fixtures.gradient_pixels, fixtures.width); } test "the orientation comes out of an EXIF chunk that sits after the pixels" { // This is the one that cannot be done by reading a header. WebP puts // `EXIF` after the image data, so `probe` --- which stops at the first // image chunk by design --- reports `.top_left` for a file that says // otherwise, and only a decode that was asked for the orientation walks // far enough to find it. const gpa = testing.allocator; var probe_reader: Io.Reader = .fixed(&fixtures.with_exif); const info = try z2dimg.probe(&probe_reader, .{}); try testing.expectEqual(z2dimg.exif.Orientation.top_left, info.orientation); var got: z2dimg.exif.Orientation = .top_left; var r: Io.Reader = .fixed(&fixtures.with_exif); var sfc = try z2dimg.decode(gpa, &r, .{ .orientation = &got }); defer sfc.deinit(gpa); try testing.expectEqual(z2dimg.exif.Orientation.right_top, got); // And the pixels are the ones the same picture decodes to without it: // an orientation is something to do with an image, not something done // to it. try expectPixels(sfc, &fixtures.gradient_pixels, fixtures.width); } test "a file carrying both is read on both sides of its pixels" { const gpa = testing.allocator; var profile: std.ArrayList(u8) = .empty; defer profile.deinit(gpa); var got: z2dimg.exif.Orientation = .top_left; var r: Io.Reader = .fixed(&fixtures.with_both); var sfc = try z2dimg.decode(gpa, &r, .{ .icc = &profile, .orientation = &got }); defer sfc.deinit(gpa); try testing.expectEqualSlices(u8, &fixtures.icc_profile, profile.items); try testing.expectEqual(z2dimg.exif.Orientation.bottom_right, got); } test "a profile that is not one is dropped rather than carried" { // Metadata is decoration, so a broken block is never a reason to refuse // a good picture --- but it is also never a reason to hand the caller // something to write into the next file. Both halves are asserted: the // decode succeeds and the list is still empty. const gpa = testing.allocator; var got: std.ArrayList(u8) = .empty; defer got.deinit(gpa); var r: Io.Reader = .fixed(&fixtures.with_bad_icc); var sfc = try z2dimg.decode(gpa, &r, .{ .icc = &got }); defer sfc.deinit(gpa); try testing.expectEqual(@as(usize, 0), got.items.len); try expectPixels(sfc, &fixtures.gradient_pixels, fixtures.width); // And one that is fine but larger than the caller allowed is dropped // too, for the same reason: what comes back is the profile or nothing. var small: std.ArrayList(u8) = .empty; defer small.deinit(gpa); var r2: Io.Reader = .fixed(&fixtures.with_icc); var sfc2 = try z2dimg.decode(gpa, &r2, .{ .icc = &small, .limits = .{ .max_icc_bytes = 64 }, }); defer sfc2.deinit(gpa); try testing.expectEqual(@as(usize, 0), small.items.len); } test "a caller that asks for nothing is charged for nothing" { // Metadata is read only when there is somewhere to put it, and the walk // past the pixels happens only when something out there was asked for. // What is observable from here is that the decode is unaffected either // way, which is the claim that would break if the walk went wrong. const gpa = testing.allocator; var plain = try decodeBytes(gpa, &fixtures.with_both); defer plain.deinit(gpa); try expectPixels(plain, &fixtures.gradient_pixels, fixtures.width); }