Correggo i difetti confermati dalla revisione di funzione/codec-immagini e aggiungo le prove che li avrebbero trovati. - JPEG: una tabella di Huffman con troppi codici corti dava ArgumentOutOfRangeException invece di ImageDecodeException, e un file rovinato faceva fallire importazione e ricostruzione; ora il controllo si fa prima di scrivere le voci. La prova che diceva di coprirlo cadeva invece su «tabella troncata»: ora tiene il totale giusto e controlla il messaggio. - JPEG: il troncamento delle scansioni di Huffman si vede a ogni riga di MCU, non dopo l'ultimo MCU (un file tagliato dopo le intestazioni costava 6,7 s). - JPEG: IDCT ridotta a 1/2 e 1/4 calcolata dai coefficienti; miniatura di una foto 4000x3000 da 126 a 59 ms in Release. Il predittore senza perdita non cerca più l'indice della componente a ogni campione. - WebP: con livello del filtro del fotogramma 0 il filtro è spento, come nei decodificatori di riferimento; VP8L costruisce solo i gruppi nominati dai meta codici (prima fino a 335 MB di tabelle da 160 KB di file). - BMP OS/2: altezza senza segno e sempre dal basso. - Array di lavoro dei codec oltre 16 MiB fuori dal pool condiviso, che li avrebbe tenuti dopo l'uso. - Conversione: profilo ICC copiato solo se RGB, profondità oltre 8 bit e blocchi gAMA/cHRM/sRGB dichiarati in NotCarried, Lossy vero quando si perde precisione. - Impronta e misure di una foto da una sola lettura e decodifica; ReadSize legge solo l'inizio di JPEG, GIF e BMP. - docs: decisioni (righe aggiunte, con la correzione dei 2,0 MB del set di riferimento) e windows.md (Febe.exe rimisurato: 85,6 MB, a capo sistemato). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
597 lines
27 KiB
C#
597 lines
27 KiB
C#
using System.Buffers.Binary;
|
||
using Febe.Core.Codecs.Images;
|
||
|
||
namespace Febe.Tests.Imaging;
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
[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<ImageDecodeException>(() => WebPDecoder.Decode(File(0, alpha[..^1])));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(File(2, alpha)));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(File(0x40, alpha)));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(File(0x20, alpha)));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(File(1, [1, 2, 3])));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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 ", "<x:xmpmeta/>"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("<x:xmpmeta/>", 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<ImageDecodeException>(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 102, 67)), ("VP8L", vp8l))));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0, 101, 67)))));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", new byte[9]), ("VP8L", vp8l))));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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<ImageDecodeException>(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(22, 0, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 22, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela in basso");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 21, 10, 0, ("VP8L", vp8l))))), "misura diversa dall'immagine");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 20, 10, 0)))), "senza immagine");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(Animation(("ANMF", new byte[15]))), "ANMF corto");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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<ImageLimitException>(() => 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<ImageLimitException>(() => WebPDecoder.Decode(empty, Small));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(empty));
|
||
}
|
||
|
||
[TestMethod]
|
||
public void DamagedHeadersAreRefused()
|
||
{
|
||
var lossy = ReferenceImages.Get("webp-perdita-q30").ReadInput();
|
||
var vp8 = WebPTestFiles.Payload(lossy, "VP8 ");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode("RIFF\0\0\0\0WEBQ"u8.ToArray()));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode((byte[])[.. "RIFF"u8, 3, 0, 0, 0, .. "WEBP"u8]));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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<ImageDecodeException>(() => WebPDecoder.Decode(longer));
|
||
var chunk = lossy.ToArray();
|
||
BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(16), (uint)(vp8.Length + 3));
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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<ImageDecodeException>(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", bad))), what);
|
||
}
|
||
|
||
var huge = vp8.ToArray();
|
||
huge[2] = 0xFF;
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", huge))), "prima partizione troppo lunga");
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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<ImageDecodeException>(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", signature))));
|
||
var version = vp8l.ToArray();
|
||
version[4] |= 0x20;
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => 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<Vp8LBitWriter> 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<ImageDecodeException>(() => 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<ImageDecodeException>(() => 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<ImageDecodeException>(() => 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<ImageDecodeException>(() => 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<ImageDecodeException>(() => 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<ImageDecodeException>(() => 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 OnlyTheGroupsTheMetaImageNamesAreBuilt()
|
||
{
|
||
// An 8×8 image with meta codes of 4×4 blocks: a 2×2 meta image whose pixels name groups 5, 2, 2 and 5 (in
|
||
// green; red 0). The stream holds the codes of groups 0 to 5; only 2 and 5 paint.
|
||
static byte[] Stream(int groups, (int Meta0, int Meta1) names, Action<Vp8LBitWriter, int> unused)
|
||
{
|
||
var w = new Vp8LBitWriter();
|
||
w.WriteBits(0x2F, 8);
|
||
w.WriteBits(7, 14);
|
||
w.WriteBits(7, 14);
|
||
w.WriteBits(0, 4);
|
||
w.WriteBits(0, 1); // no transform
|
||
w.WriteBits(0, 1); // no colour cache
|
||
w.WriteBits(1, 1); // meta codes
|
||
w.WriteBits(0, 3); // meta bits 2: blocks of 4×4, a 2×2 meta image
|
||
|
||
// The meta image: no cache, green a two-symbol code (bit 0 → the smaller name, 1 → the larger), the rest
|
||
// single symbols; the pixel bits pick larger, smaller, smaller, larger.
|
||
w.WriteBits(0, 1);
|
||
var (small, large) = names;
|
||
w.WriteBits(1, 1);
|
||
w.WriteBits(small == large ? 0u : 1u, 1);
|
||
w.WriteBits(1, 1);
|
||
w.WriteBits((uint)(small & 0xFF), 8);
|
||
if (small != large)
|
||
{
|
||
w.WriteBits((uint)(large & 0xFF), 8);
|
||
}
|
||
|
||
Single(w, small >> 8); // red: the high byte of the group
|
||
Single(w, 0);
|
||
Single(w, 0);
|
||
Single(w, 0);
|
||
foreach (var bit in (uint[])[1, 0, 0, 1])
|
||
{
|
||
if (small != large)
|
||
{
|
||
w.WriteBits(bit, 1);
|
||
}
|
||
}
|
||
|
||
for (var g = 0; g < groups; g++)
|
||
{
|
||
if (g == small || g == large)
|
||
{
|
||
// Green g + 1, red g, blue 2·g, alpha 255.
|
||
Single(w, g + 1);
|
||
Single(w, g);
|
||
Single(w, 2 * g);
|
||
Single(w, 255);
|
||
Single(w, 0);
|
||
}
|
||
else
|
||
{
|
||
unused(w, g);
|
||
}
|
||
}
|
||
|
||
w.WriteBits(0, 32);
|
||
return WebPTestFiles.Riff(("VP8L", w.ToArray()));
|
||
}
|
||
|
||
static void Single(Vp8LBitWriter w, int symbol)
|
||
{
|
||
w.WriteBits(1, 1);
|
||
w.WriteBits(0, 1);
|
||
w.WriteBits(1, 1);
|
||
w.WriteBits((uint)(symbol & 0xFF), 8);
|
||
}
|
||
|
||
static void Cheap(Vp8LBitWriter w, int g)
|
||
{
|
||
for (var k = 0; k < 5; k++)
|
||
{
|
||
w.WriteBits(1, 1); // simple
|
||
w.WriteBits(0, 1); // one symbol
|
||
w.WriteBits(0, 1); // of one bit
|
||
w.WriteBits(0, 1); // symbol 0
|
||
}
|
||
}
|
||
|
||
using (var image = WebPDecoder.Decode(Stream(6, (2, 5), Cheap)))
|
||
{
|
||
Assert.AreEqual(((byte)5, (byte)6, (byte)10, (byte)255), image.GetPixel(1, 1), "gruppo 5 in alto a sinistra");
|
||
Assert.AreEqual(((byte)2, (byte)3, (byte)4, (byte)255), image.GetPixel(6, 1), "gruppo 2 in alto a destra");
|
||
Assert.AreEqual(((byte)2, (byte)3, (byte)4, (byte)255), image.GetPixel(1, 6), "gruppo 2 in basso a sinistra");
|
||
Assert.AreEqual(((byte)5, (byte)6, (byte)10, (byte)255), image.GetPixel(7, 7), "gruppo 5 in basso a destra");
|
||
}
|
||
|
||
// A single meta pixel naming group 65535: 65,536 groups in the stream (about 160 KB of codes). Building all
|
||
// of them took about 335 MB of tables; only one is built now, so a working budget of 4 MiB is enough.
|
||
var huge = Stream(65536, (65535, 65535), Cheap);
|
||
Assert.IsLessThan(200_000, huge.Length);
|
||
using (var image = WebPDecoder.Decode(huge, new ImageLimits { MaxWorkingBytes = 4 * 1024 * 1024 }))
|
||
{
|
||
Assert.AreEqual(((byte)255, (byte)0, (byte)254, (byte)255), image.GetPixel(4, 4));
|
||
}
|
||
|
||
// The codes of unused groups are still read and checked: three symbols of length 1 are no prefix code.
|
||
Assert.ThrowsExactly<ImageDecodeException>(() => WebPDecoder.Decode(Stream(6, (2, 5), (w, g) =>
|
||
{
|
||
if (g != 3)
|
||
{
|
||
Cheap(w, g);
|
||
return;
|
||
}
|
||
|
||
w.WriteBits(0, 1); // normal code
|
||
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(0, 3); // length_nbits = 2
|
||
w.WriteBits(1, 2); // max_symbol = 3
|
||
w.WriteBits(7, 3); // three lengths of 1
|
||
for (var k = 1; k < 5; k++)
|
||
{
|
||
Single(w, 0);
|
||
}
|
||
})));
|
||
}
|
||
|
||
[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<ImageDecodeException>(() => 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);
|
||
}
|
||
}
|