Files
Febe/tests/Febe.Tests/Imaging/WebPEncoderTests.cs
T
Alby96andClaude Opus 5.5 b4383a6110 Lettore e scrittore WebP di casa (C1, passo 4)
Il lettore WebP, scritto dalla RFC 9649 e dalla RFC 6386, prende il posto di
SkiaSharp per i WebP: VP8 con perdita, VP8L senza perdita, ALPH grezzo e
compresso con ogni filtro, VP8X con ICCP, EXIF e XMP, e di un'animazione il
primo fotogramma fuso sulla tela, con il numero dei fotogrammi. La facciata
ImageDecoder ora legge i WebP.

Contro i riferimenti di SkiaSharp i quattro WebP senza perdita coincidono byte
per byte; i quattro con perdita stanno fra 68,7 e 74,4 dB per canale, scarto
massimo 1, alfa esatta. File danneggiati, tagliati o fuori dai limiti si
rifiutano; i limiti si controllano prima di allocare.

Lo scrittore fa WebP senza perdita (tavolozza, sottrazione del verde,
predittore, trasformata del colore, LZ77, cache dei colori, Huffman) e il
formato esteso solo quando ci sono metadati: i 57 riferimenti tornano esatti e
pesano l'88% del PNG di casa. Niente componenti esterni.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:01:47 +01:00

228 lines
9.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// The in-house lossless WebP encoder: every image comes back exactly with each tool alone and with all of them,
/// metadata goes into a VP8X file in the order of RFC 9649, and what cannot be written is refused.
/// </summary>
[TestClass]
public sealed class WebPEncoderTests
{
private static readonly Vp8LEncoderSettings Nothing = new()
{
Palette = false,
SubtractGreen = false,
Predictor = false,
ColorTransform = false,
Lz77 = false,
ColorCacheBits = 0,
};
public TestContext TestContext { get; set; } = null!;
public static IEnumerable<object[]> Tools =>
[
["nessuno"],
["tavolozza"],
["verde"],
["predittore"],
["colore"],
["lz77"],
["cache"],
["tutti"],
["predittore-piccolo"],
["predittore-grande"],
];
[TestMethod]
[DynamicData(nameof(Tools))]
public void EveryImageComesBackExactly(string tool)
{
var settings = Settings(tool);
var sizes = new (int Width, int Height)[] { (1, 1), (2, 1), (1, 3), (5, 4), (17, 13), (64, 1), (1, 40), (101, 67) };
var seed = 10;
foreach (var (width, height) in sizes)
{
foreach (var image in Images(width, height, seed++))
{
using (image)
{
var file = WebPEncoder.Encode(image, new WebPEncoderOptions { Lossless = settings });
using var back = WebPDecoder.Decode(file);
ImageAssert.AreEqual(image, back, $"{tool}, {width}×{height}");
}
}
}
}
[TestMethod]
public void TheReferencesComeBackExactly()
{
long ours = 0;
long png = 0;
foreach (var reference in ReferenceImages.All)
{
using var image = PngDecoder.Decode(reference.ReadExpectedPng());
var file = WebPEncoder.Encode(image);
using var back = WebPDecoder.Decode(file);
ImageAssert.AreEqual(image, back, reference.Name);
ours += file.Length;
png += PngEncoder.Encode(image).Length;
}
TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"57 riferimenti: WebP senza perdita {ours} byte, PNG di casa {png} byte ({100.0 * ours / png:F1}%)."));
Assert.IsLessThan(png, ours, "il WebP senza perdita deve stare sotto il PNG di casa");
}
[TestMethod]
public void TheToolsMakeTheFilesSmaller()
{
// On the large lossless reference the default tools beat plain Huffman coding by a wide margin, and stay
// within reach of libwebp's own file.
var reference = ReferenceImages.Get("webp-grande-senza-perdita");
using var image = PngDecoder.Decode(reference.ReadExpectedPng());
var plain = WebPEncoder.Encode(image, new WebPEncoderOptions { Lossless = Nothing }).Length;
var full = WebPEncoder.Encode(image).Length;
var skia = reference.ReadInput().Length;
TestContext.WriteLine($"{reference.Name}: solo Huffman {plain} byte, tutti gli strumenti {full} byte, libwebp {skia} byte.");
Assert.IsLessThan(plain * 3 / 4, full);
Assert.IsLessThan(skia * 2, full);
using var flat = new RgbaImage(300, 200);
flat.Pixels.Fill(0x80);
Assert.IsLessThan(100, WebPEncoder.Encode(flat).Length);
}
[TestMethod]
public void WithoutMetadataTheFileIsTheSimpleFormat()
{
using var opaque = TestImages.Random(9, 7, 3, opaque: true);
var file = WebPEncoder.Encode(opaque);
var chunks = WebPTestFiles.Chunks(file);
Assert.AreEqual("VP8L", chunks.Single().Type);
var info = WebPDecoder.Identify(file);
Assert.AreEqual((9, 7, 1, false), (info.Width, info.Height, info.FrameCount, info.HasAlpha));
using var transparent = TestImages.Random(9, 7, 3);
Assert.IsTrue(WebPDecoder.Identify(WebPEncoder.Encode(transparent)).HasAlpha);
}
[TestMethod]
public void MetadataGoesIntoAnExtendedFileInOrder()
{
using var image = TestImages.Random(11, 5, 4);
var tiff = WebPTestFiles.Tiff(6);
var icc = new byte[301];
new Random(5).NextBytes(icc);
const string Xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">città</x:xmpmeta>";
var file = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = [.. "Exif\0\0"u8, .. tiff], IccProfile = icc, Xmp = Xmp });
var chunks = WebPTestFiles.Chunks(file);
CollectionAssert.AreEqual(new[] { "VP8X", "ICCP", "VP8L", "EXIF", "XMP " }, chunks.Select(c => c.Type).ToArray());
var vp8x = chunks[0].Payload;
Assert.AreEqual(0x20 | 0x10 | 0x08 | 0x04, vp8x[0]);
Assert.AreEqual((10, 4), (vp8x[4] | (vp8x[5] << 8) | (vp8x[6] << 16), vp8x[7] | (vp8x[8] << 8) | (vp8x[9] << 16)));
CollectionAssert.AreEqual(tiff, chunks[3].Payload, "il prefisso «Exif» di JPEG si toglie");
Assert.AreEqual(file.Length, 8 + (int)System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4)));
Assert.AreEqual(0, file.Length % 2);
using var back = WebPDecoder.Decode(file, out var info);
ImageAssert.AreEqual(image, back, "con i metadati");
CollectionAssert.AreEqual(tiff, info.Metadata.Exif);
Assert.AreEqual(6, info.Metadata.Orientation);
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
Assert.AreEqual(Xmp, info.Metadata.Xmp);
Assert.IsTrue(info.HasAlpha);
// Only one kind of metadata: only its flag; an opaque image has no alpha flag.
using var opaque = TestImages.Random(4, 4, 6, opaque: true);
var onlyXmp = WebPEncoder.Encode(opaque, new WebPEncoderOptions { Xmp = "x" });
Assert.AreEqual(0x04, WebPTestFiles.Payload(onlyXmp, "VP8X")[0]);
Assert.AreEqual("x", WebPDecoder.Identify(onlyXmp).Metadata.Xmp);
}
[TestMethod]
public void WhatCannotBeWrittenIsRefused()
{
using var image = TestImages.Random(3, 3, 7);
Assert.Throws<ArgumentException>(() => WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = "non TIFF"u8.ToArray() }));
Assert.Throws<ArgumentException>(() => WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = [.. "Exif\0\0"u8, 1, 2] }));
Assert.Throws<ArgumentNullException>(() => WebPEncoder.Encode(null!));
using var wide = new RgbaImage(WebPEncoder.MaxDimension + 1, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => WebPEncoder.Encode(wide));
using var tall = new RgbaImage(1, WebPEncoder.MaxDimension + 1);
Assert.Throws<ArgumentOutOfRangeException>(() => WebPEncoder.Encode(tall));
}
[TestMethod]
public void TheLargestSideIsWritten()
{
using var image = TestImages.Random(WebPEncoder.MaxDimension, 2, 8);
var file = WebPEncoder.Encode(image);
using var back = WebPDecoder.Decode(file);
ImageAssert.AreEqual(image, back, "16384×2");
}
[TestMethod]
public void ThePrefixCodesOfLengthsAndDistancesInvertTheDecoder()
{
for (var value = 1; value <= (1 << 20); value += value < 5000 ? 1 : 997)
{
var (symbol, bits, extra) = Vp8LEncoder.Prefix(value);
Assert.IsLessThan(40, symbol);
var decoded = symbol < 4 ? symbol + 1 : ((2 + (symbol & 1)) << ((symbol - 2) >> 1)) + extra + 1;
Assert.AreEqual(value, decoded, $"valore {value}");
Assert.AreEqual(symbol < 4 ? 0 : (symbol - 2) >> 1, bits);
}
// The 120 short codes cover the neighbours exactly once.
for (var code = 1; code <= 120; code++)
{
var (dx, dy) = Vp8LDecoder.ShortDistance(code);
Assert.AreEqual(code, Vp8LEncoder.DistanceCode(dx + (dy * 1000), 1000), $"codice {code}");
}
Assert.AreEqual(9000 + 120, Vp8LEncoder.DistanceCode(9000, 1000)); // eight rows up: no short code
}
private static Vp8LEncoderSettings Settings(string tool) => tool switch
{
"nessuno" => Nothing,
"tavolozza" => Nothing with { Palette = true },
"verde" => Nothing with { SubtractGreen = true },
"predittore" => Nothing with { Predictor = true },
"colore" => Nothing with { ColorTransform = true },
"lz77" => Nothing with { Lz77 = true },
"cache" => Nothing with { ColorCacheBits = 6 },
"predittore-piccolo" => Vp8LEncoderSettings.Default with { Palette = false, PredictorBits = 2, ColorTransformBits = 2 },
"predittore-grande" => Vp8LEncoderSettings.Default with { Palette = false, PredictorBits = 9, ColorTransformBits = 9 },
_ => Vp8LEncoderSettings.Default,
};
private static IEnumerable<RgbaImage> Images(int width, int height, int seed)
{
yield return TestImages.Random(width, height, seed);
yield return TestImages.Random(width, height, seed, opaque: true);
yield return TestImages.Gradient(width, height, seed);
foreach (var colors in (int[])[1, 2, 3, 4, 5, 16, 17, 256])
{
yield return WebPTestFiles.FewColors(width, height, colors, seed + colors);
}
// Transparent pixels that keep their colour, and long runs.
var runs = new RgbaImage(width, height);
var pixels = runs.Pixels;
for (var i = 0; i < width * height; i++)
{
pixels[i * 4] = (byte)(i / 7);
pixels[(i * 4) + 1] = 200;
pixels[(i * 4) + 2] = (byte)(i % 3);
pixels[(i * 4) + 3] = (byte)((i / 5) % 2 == 0 ? 0 : 255);
}
yield return runs;
}
}