using System.Buffers.Binary; using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// /// The WebP container (RFC 9649 §2): the extended format with ALPH in every variant, ICCP, EXIF and XMP; the first /// frame of an animation on its canvas; limits; and files that are damaged or cut short. /// [TestClass] public sealed class WebPContainerTests { private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 }; [TestMethod] public void EveryAlphaVariantGivesTheSamePicture() { var reference = ReferenceImages.Get("webp-perdita-alfa-q80"); var original = reference.ReadInput(); using var expected = WebPDecoder.Decode(original); var vp8 = WebPTestFiles.Payload(original, "VP8 "); var alpha = WebPTestFiles.AlphaOf(expected); var (w, h) = (expected.Width, expected.Height); Assert.IsTrue(alpha.Distinct().Count() > 2, "il riferimento ha un'alfa vera"); for (var filter = 0; filter < 4; filter++) { var filtered = WebPTestFiles.FilterAlpha(alpha, w, h, filter); foreach (var preprocessed in (bool[])[false, true]) { var flags = (filter << 2) | (preprocessed ? 0x10 : 0); var raw = File((byte)flags, filtered); var compressed = File((byte)(flags | 1), WebPEncoder.EncodeAlphaStream(filtered, w, h, Vp8LEncoderSettings.Default)); using var fromRaw = WebPDecoder.Decode(raw); using var fromCompressed = WebPDecoder.Decode(compressed); ImageAssert.AreEqual(expected, fromRaw, $"grezza, filtro {filter}"); ImageAssert.AreEqual(expected, fromCompressed, $"compressa, filtro {filter}"); } } // A raw plane with bytes to spare is fine; a short one, an unknown method or reserved bits are not. using (var longer = WebPDecoder.Decode(File(0, [.. alpha, 1, 2, 3]))) { ImageAssert.AreEqual(expected, longer, "byte in più"); } Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0, alpha[..^1]))); Assert.ThrowsExactly(() => WebPDecoder.Decode(File(2, alpha))); Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0x40, alpha))); Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0x20, alpha))); Assert.ThrowsExactly(() => WebPDecoder.Decode(File(1, [1, 2, 3]))); Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, w, h)), ("ALPH", []), ("VP8 ", vp8)))); byte[] File(byte header, byte[] plane) => WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, w, h)), ("ALPH", [header, .. plane]), ("VP8 ", vp8)); } [TestMethod] public void TheAlphaFilterIsUndoneForEveryMethod() { var random = new Random(61); foreach (var (w, h) in new[] { (1, 1), (1, 7), (9, 1), (13, 11) }) { var alpha = new byte[w * h]; random.NextBytes(alpha); for (var filter = 0; filter < 4; filter++) { var plane = WebPTestFiles.FilterAlpha(alpha, w, h, filter); WebPAlpha.Unfilter(plane, w, h, filter); CollectionAssert.AreEqual(alpha, plane, $"{w}×{h}, filtro {filter}"); } } } [TestMethod] public void TheExtendedFormatCarriesMetadataAroundAStillPicture() { var lossy = ReferenceImages.Get("webp-perdita-q80").ReadInput(); using var expected = WebPDecoder.Decode(lossy); var vp8 = WebPTestFiles.Payload(lossy, "VP8 "); var tiff = WebPTestFiles.Tiff(8); var icc = new byte[77]; new Random(62).NextBytes(icc); var file = WebPTestFiles.Riff( ("VP8X", WebPTestFiles.Vp8X(0x20 | 0x08 | 0x04, 101, 67)), ("ICCP", icc), ("VP8 ", vp8), ("ABCD", [1, 2, 3]), ("EXIF", [.. "Exif\0\0"u8, .. tiff]), ("XMP ", ""u8.ToArray())); using var image = WebPDecoder.Decode(file, out var info); ImageAssert.AreEqual(expected, image, "VP8 dentro VP8X"); Assert.AreEqual((101, 67, 1, false), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); CollectionAssert.AreEqual(tiff, info.Metadata.Exif, "il prefisso «Exif» si toglie"); Assert.AreEqual(8, info.Metadata.Orientation); CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); Assert.AreEqual("", info.Metadata.Xmp); Assert.AreEqual(8, WebPDecoder.Identify(file).Metadata.Orientation); // Metadata beyond the budget is skipped, the picture is still read. var tight = WebPDecoder.Identify(file, ImageLimits.Default with { MaxMetadataBytes = 50 }); Assert.IsNull(tight.Metadata.IccProfile); CollectionAssert.AreEqual(tiff, tight.Metadata.Exif); // VP8L inside VP8X; a canvas of another size is refused. var lossless = ReferenceImages.Get("webp-senza-perdita").ReadInput(); var vp8l = WebPTestFiles.Payload(lossless, "VP8L"); using var simple = WebPDecoder.Decode(lossless); using var extended = WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 101, 67)), ("VP8L", vp8l))); ImageAssert.AreEqual(simple, extended, "VP8L dentro VP8X"); Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 102, 67)), ("VP8L", vp8l)))); Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0, 101, 67))))); Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", new byte[9]), ("VP8L", vp8l)))); Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("ABCD", vp8l)))); } [TestMethod] public void TheFirstFrameOfAnAnimationIsPlacedAndBlendedOnTheCanvas() { using var frame = TestImages.Random(20, 10, 63); // random alpha, some 0 and some 255 var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(frame), "VP8L"); using var second = TestImages.Random(8, 8, 64, opaque: true); var secondFrame = WebPTestFiles.Anmf(0, 0, 8, 8, 0, ("VP8L", WebPTestFiles.Payload(WebPEncoder.Encode(second), "VP8L"))); foreach (var blend in (bool[])[true, false]) { var file = WebPTestFiles.Riff( ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 40, 30)), ("ANIM", WebPTestFiles.Anim(0xFF0000FF, 0)), ("ANMF", WebPTestFiles.Anmf(4, 6, 20, 10, blend ? 0 : 2, ("VP8L", vp8l))), ("ANMF", secondFrame)); using var canvas = WebPDecoder.Decode(file, out var info); Assert.AreEqual((40, 30, 2, true), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); for (var y = 0; y < 30; y++) { for (var x = 0; x < 40; x++) { var inside = x >= 4 && x < 24 && y >= 6 && y < 16; var actual = canvas.GetPixel(x, y); if (!inside) { Assert.AreEqual(((byte)0, (byte)0, (byte)0, (byte)0), actual, $"fuori dal fotogramma ({x}, {y})"); continue; } var source = frame.GetPixel(x - 4, y - 6); // On a transparent canvas blending gives the source, and transparent black where it is transparent. var expected = blend && source.A == 0 ? ((byte)0, (byte)0, (byte)0, (byte)0) : source; Assert.AreEqual(expected, actual, $"fondere {blend}, ({x}, {y})"); } } Assert.AreEqual(2, ImageDecoder.Identify(file).FrameCount); } // A lossy frame with alpha that covers the canvas reads as the still picture. var lossy = ReferenceImages.Get("webp-perdita-alfa-q80").ReadInput(); using var still = WebPDecoder.Decode(lossy); var animated = WebPTestFiles.Riff( ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 101, 67)), ("ANIM", WebPTestFiles.Anim()), ("ANMF", WebPTestFiles.Anmf(0, 0, 101, 67, 2, ("ALPH", WebPTestFiles.Payload(lossy, "ALPH")), ("VP8 ", WebPTestFiles.Payload(lossy, "VP8 "))))); using var first = WebPDecoder.Decode(animated); ImageAssert.AreEqual(still, first, "fotogramma VP8 con ALPH"); } [TestMethod] public void BrokenAnimationsAreRefused() { using var frame = TestImages.Random(20, 10, 65); var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(frame), "VP8L"); byte[] Animation(params (string, byte[])[] chunks) => WebPTestFiles.Riff([("VP8X", WebPTestFiles.Vp8X(0x02, 40, 30)), ("ANIM", WebPTestFiles.Anim()), .. chunks]); Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(22, 0, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela"); Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 22, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela in basso"); Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 21, 10, 0, ("VP8L", vp8l))))), "misura diversa dall'immagine"); Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 20, 10, 0)))), "senza immagine"); Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", new byte[15]))), "ANMF corto"); Assert.ThrowsExactly(() => WebPDecoder.Identify(Animation()), "nessun fotogramma"); } [TestMethod] public void BlendingFollowsTheFormulaOfTheSpecification() { // A = As + Ad·(1 − As), RGB = (RGBs·As + RGBd·Ad·(1 − As)) / A. var destination = new byte[] { 200, 100, 0, 128 }; WebPDecoder.Blend([0, 50, 250, 64], destination); var sa = 64 / 255.0; var da = 128 / 255.0 * (1 - sa); var a = sa + da; Assert.AreEqual((int)Math.Round(a * 255), destination[3]); Assert.AreEqual((int)Math.Round(((0 * sa) + (200 * da)) / a), destination[0]); Assert.AreEqual((int)Math.Round(((50 * sa) + (100 * da)) / a), destination[1]); Assert.AreEqual((int)Math.Round(((250 * sa) + (0 * da)) / a), destination[2]); var opaque = new byte[] { 1, 2, 3, 4 }; WebPDecoder.Blend([9, 8, 7, 255], opaque); CollectionAssert.AreEqual(new byte[] { 9, 8, 7, 255 }, opaque); var keep = new byte[] { 1, 2, 3, 40 }; WebPDecoder.Blend([9, 8, 7, 0], keep); CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 40 }, keep); } [TestMethod] public void LimitsAreCheckedBeforeDecoding() { using var image = TestImages.Random(4, 4, 66); var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(image), "VP8L"); // A canvas of 16384×16384 announced by VP8X for an animation: Identify tells its size, Decode refuses it. var big = WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x02, 16384, 16384)), ("ANIM", WebPTestFiles.Anim()), ("ANMF", WebPTestFiles.Anmf(0, 0, 4, 4, 0, ("VP8L", vp8l)))); var info = WebPDecoder.Identify(big, Small); Assert.AreEqual((16384, 16384), (info.Width, info.Height)); Assert.ThrowsExactly(() => WebPDecoder.Decode(big, Small)); // A VP8L header claiming 4000×4000 with nothing behind it: over the small limits it is refused for its // size, within the default ones for the missing data. var writer = new Vp8LBitWriter(); writer.WriteBits(0x2F, 8); writer.WriteBits(3999, 14); writer.WriteBits(3999, 14); writer.WriteBits(0, 4); writer.WriteBits(0, 16); var empty = WebPTestFiles.Riff(("VP8L", writer.ToArray())); Assert.AreEqual((4000, 4000), (WebPDecoder.Identify(empty, Small).Width, WebPDecoder.Identify(empty, Small).Height)); Assert.ThrowsExactly(() => WebPDecoder.Decode(empty, Small)); Assert.ThrowsExactly(() => WebPDecoder.Decode(empty)); } [TestMethod] public void DamagedHeadersAreRefused() { var lossy = ReferenceImages.Get("webp-perdita-q30").ReadInput(); var vp8 = WebPTestFiles.Payload(lossy, "VP8 "); Assert.ThrowsExactly(() => WebPDecoder.Decode("RIFF\0\0\0\0WEBQ"u8.ToArray())); Assert.ThrowsExactly(() => WebPDecoder.Decode((byte[])[.. "RIFF"u8, 3, 0, 0, 0, .. "WEBP"u8])); Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff())); // RIFF size beyond the file; a chunk beyond the RIFF size. var longer = lossy.ToArray(); BinaryPrimitives.WriteUInt32LittleEndian(longer.AsSpan(4), (uint)(lossy.Length - 8 + 2)); Assert.ThrowsExactly(() => WebPDecoder.Decode(longer)); var chunk = lossy.ToArray(); BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(16), (uint)(vp8.Length + 3)); Assert.ThrowsExactly(() => WebPDecoder.Decode(chunk)); // Trailing bytes after the RIFF size are ignored. using (var trailing = WebPDecoder.Decode((byte[])[.. lossy, 1, 2, 3, 4, 5])) using (var plain = WebPDecoder.Decode(lossy)) { ImageAssert.AreEqual(plain, trailing, "byte dopo il RIFF"); } // VP8 frame header: inter frame, unknown version, not shown, start code, zero size, first partition too long. foreach (var (at, value, what) in new[] { (0, vp8[0] | 1, "interfotogramma"), (0, (vp8[0] & 0xF1) | 0x08, "versione 4"), (0, vp8[0] & 0xEF, "da non mostrare"), (3, 0x9C, "codice d'inizio"), (6, 0, "larghezza nulla") }) { var bad = vp8.ToArray(); bad[at] = (byte)value; if (what == "larghezza nulla") { bad[7] &= 0xC0; } Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", bad))), what); } var huge = vp8.ToArray(); huge[2] = 0xFF; Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", huge))), "prima partizione troppo lunga"); Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", vp8[..9])))); // VP8L header: signature, version. var vp8l = WebPTestFiles.Payload(ReferenceImages.Get("webp-senza-perdita").ReadInput(), "VP8L"); var signature = vp8l.ToArray(); signature[0] = 0x2E; Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", signature)))); var version = vp8l.ToArray(); version[4] |= 0x20; Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", version)))); } [TestMethod] public void DamagedLosslessStreamsAreRefused() { // Built bit by bit: header of a 4×4 image, then what follows. byte[] Stream(Action body) { var writer = new Vp8LBitWriter(); writer.WriteBits(0x2F, 8); writer.WriteBits(3, 14); writer.WriteBits(3, 14); writer.WriteBits(0, 4); body(writer); writer.WriteBits(0, 32); return WebPTestFiles.Riff(("VP8L", writer.ToArray())); } void SimpleCode(Vp8LBitWriter w, int symbol) { w.WriteBits(1, 1); // simple w.WriteBits(0, 1); // one symbol w.WriteBits(1, 1); // eight bits w.WriteBits((uint)symbol, 8); } void NoTransformNoCache(Vp8LBitWriter w) { w.WriteBits(0, 1); // no transform w.WriteBits(0, 1); // no colour cache w.WriteBits(0, 1); // no meta codes } // A valid stream: every pixel the literal (green 7, red 1, blue 2, alpha 3). var valid = Stream(w => { NoTransformNoCache(w); SimpleCode(w, 7); SimpleCode(w, 1); SimpleCode(w, 2); SimpleCode(w, 3); SimpleCode(w, 0); }); using (var image = WebPDecoder.Decode(valid)) { Assert.AreEqual(((byte)1, (byte)7, (byte)2, (byte)3), image.GetPixel(3, 3)); } // The same transform twice. Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => { w.WriteBits(1, 1); w.WriteBits(2, 2); w.WriteBits(1, 1); w.WriteBits(2, 2); }))); // Colour cache of 0 and 12 bits. foreach (var bits in (uint[])[0, 12]) { Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => { w.WriteBits(0, 1); w.WriteBits(1, 1); w.WriteBits(bits, 4); })), $"cache {bits}"); } // An incomplete normal code: code length code with two lengths of 2 (half the space unused). Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => { NoTransformNoCache(w); w.WriteBits(0, 1); w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 w.WriteBits(0, 3); w.WriteBits(0, 3); w.WriteBits(2, 3); w.WriteBits(2, 3); }))); // A simple code naming a symbol outside a distance alphabet of 40. Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => { NoTransformNoCache(w); SimpleCode(w, 7); SimpleCode(w, 1); SimpleCode(w, 2); SimpleCode(w, 3); SimpleCode(w, 45); }))); // A backward reference before the first pixel: the green code has only symbol 256 + 0 (length 1)... which // needs a normal code since it is above 255; here a two-symbol simple code cannot reach it, so use the cache // index instead: a cache symbol with no cache is damage. Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => { w.WriteBits(0, 1); w.WriteBits(1, 1); w.WriteBits(1, 4); // cache of 2 entries: green alphabet 282 w.WriteBits(0, 1); Normal(w, 282, 256); SimpleCode(w, 0); SimpleCode(w, 0); SimpleCode(w, 0); SimpleCode(w, 0); }))); // A distance past the start of the image. Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => { NoTransformNoCache(w); Normal(w, 280, 256 + 3); // only length symbol 3: length 4 SimpleCode(w, 0); SimpleCode(w, 0); SimpleCode(w, 0); SimpleCode(w, 39); // the largest distance w.WriteBits(0, 18); }))); } [TestMethod] public void StreamsCutShortAreRefusedOrReadWhole() { foreach (var name in (string[])["webp-senza-perdita", "webp-senza-perdita-rapido", "webp-perdita-q30", "webp-perdita-alfa-q80"]) { var input = ReferenceImages.Get(name).ReadInput(); using var whole = WebPDecoder.Decode(input); var chunks = WebPTestFiles.Chunks(input); var last = chunks[^1]; var lossless = last.Type == "VP8L"; for (var cut = 1; cut < last.Payload.Length - 1; cut++) { // Cut the image chunk, and keep the RIFF consistent so only the bitstream is short. var shorter = last.Payload[..^cut]; var file = WebPTestFiles.Riff([.. chunks.Take(chunks.Count - 1), (last.Type, shorter)]); RgbaImage? image = null; try { image = WebPDecoder.Decode(file); } catch (ImageDecodeException) { } using (image) { if (image is null) { continue; } // What is read is read whole. The boolean coder ends with flush bytes the decoder may never // need (measured: up to 3 on these files), so a lossy stream can lose only those. ImageAssert.AreEqual(whole, image, $"{name} senza gli ultimi {cut} byte"); if (!lossless) { Assert.IsLessThanOrEqualTo(4, cut, $"{name}: senza gli ultimi {cut} byte la lettura doveva fermarsi"); } } } // Plainly cut files (RIFF size beyond the end) are refused at every length. for (var length = 0; length < input.Length; length += Math.Max(1, input.Length / 200)) { Assert.ThrowsExactly(() => WebPDecoder.Decode(input[..length]), $"{name} tagliato a {length}"); } } } // A normal code over `alphabet` symbols in which only `symbol` has a length (a code of zero bits): code length // code with the single symbol 1 (zero bits too), then max_symbol so only the lengths up to `symbol` are read. private static void Normal(Vp8LBitWriter w, int alphabet, int symbol) { w.WriteBits(0, 1); w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 w.WriteBits(0, 3); w.WriteBits(0, 3); w.WriteBits(1, 3); // length code 0 has length 1 w.WriteBits(1, 3); // length code 1 has length 1 w.WriteBits(1, 1); // max_symbol present w.WriteBits(4, 3); // length_nbits = 2 + 2·4 = 10 w.WriteBits((uint)(symbol + 1 - 2), 10); for (var s = 0; s < symbol; s++) { w.WriteBits(0, 1); // length 0 (code 0) } w.WriteBits(1, 1); // length 1 (code 1) Assert.IsGreaterThan(symbol, alphabet); } }