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>
This commit is contained in:
1 parent
36196526bb
commit
b4383a6110
21 files changed
+6637
-13
No files matched your search
@@ -19,6 +19,7 @@ public sealed class ImageFuzzTests
|
||||
[ReferenceFormat.Gif],
|
||||
[ReferenceFormat.Bmp],
|
||||
[ReferenceFormat.Jpeg],
|
||||
[ReferenceFormat.WebP],
|
||||
];
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -85,11 +85,11 @@ public sealed class ImagingBaseTests
|
||||
[TestMethod]
|
||||
public void TheFacadeSaysWhichFormatsItCannotReadYet()
|
||||
{
|
||||
var webp = ReferenceImages.Of(ReferenceFormat.WebP).First().ReadInput();
|
||||
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(webp));
|
||||
Assert.Contains("WEBP", error.Message);
|
||||
var tiff = "II*\0\u0008\0\0\0\0\0"u8.ToArray();
|
||||
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(tiff));
|
||||
Assert.Contains("TIFF", error.Message);
|
||||
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi")));
|
||||
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg));
|
||||
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown));
|
||||
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg) && ImageDecoder.CanDecode(ImageFormat.WebP));
|
||||
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Tiff) || ImageDecoder.CanDecode(ImageFormat.Heif) || ImageDecoder.CanDecode(ImageFormat.Unknown));
|
||||
}
|
||||
}
|
||||
@@ -64,9 +64,10 @@ public sealed class ReferenceDecodeTests
|
||||
continue;
|
||||
}
|
||||
|
||||
if (reference.Format == ReferenceFormat.Jpeg)
|
||||
if (reference.Format == ReferenceFormat.Jpeg || (reference.Format == ReferenceFormat.WebP && !reference.Name.Contains("senza-perdita", StringComparison.Ordinal)))
|
||||
{
|
||||
// Lossy: JpegReferenceTests compares it with thresholds, and with the EXIF orientation applied.
|
||||
// Lossy: JpegReferenceTests and WebPReferenceTests compare it with thresholds (JPEG with the EXIF
|
||||
// orientation applied).
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -68,8 +68,9 @@ Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up,
|
||||
- JPEG e WebP con perdita: l'immagine attesa è la lettura di libjpeg-turbo e libwebp dentro SkiaSharp (IDCT,
|
||||
ricampionamento della crominanza, conversione dei colori). Il nostro lettore può differire di poco: per JPEG la
|
||||
tolleranza è almeno 40 dB di PSNR per canale e al più lo 0,1% dei pixel con uno scarto oltre 16 (il lettore di casa
|
||||
sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). PNG, GIF, BMP e WebP senza perdita devono coincidere
|
||||
byte per byte.
|
||||
sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). Per WebP con perdita la tolleranza è la stessa e l'alfa
|
||||
deve coincidere: il lettore di casa (passo 4) sta fra 68,7 e 74,4 dB, scarto massimo 1, nessun pixel oltre 16, alfa
|
||||
esatta. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte.
|
||||
|
||||
## Che cosa qui non c'è
|
||||
|
||||
@@ -93,12 +94,19 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl
|
||||
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
|
||||
- `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG
|
||||
di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato,
|
||||
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per WebP
|
||||
dice che non lo legge ancora; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal
|
||||
passo 3), che applica anche l'orientamento EXIF riportato dal lettore.
|
||||
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e i WebP
|
||||
senza perdita devono coincidere; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal
|
||||
passo 3), che applica anche l'orientamento EXIF riportato dal lettore, e i WebP con perdita
|
||||
`Imaging/WebPReferenceTests.cs` (dal passo 4).
|
||||
- `Imaging/JpegCodingTests.cs`, `JpegEncoderTests.cs`, `JpegMalformedTests.cs` (dal passo 3): i casi qui assenti
|
||||
(progressivo, ripristino, codifica aritmetica, 12 bit, senza perdita, CMYK e YCCK, campionamenti insoliti) scritti
|
||||
dal codificatore di prova `JpegTestEncoder.cs` e confrontati coefficiente per coefficiente con la codifica di base
|
||||
delle stesse immagini; il codificatore di casa; i file danneggiati.
|
||||
- `Imaging/WebPReferenceTests.cs`, `WebPEncoderTests.cs`, `WebPContainerTests.cs`, `Vp8BitstreamTests.cs` (dal passo
|
||||
4): i WebP dell'insieme contro l'immagine attesa (senza perdita esatti, con perdita con la tolleranza sopra); lo
|
||||
scrittore senza perdita di casa, che rilegge esatti tutti i 57 riferimenti; le varianti che qui mancano, costruite
|
||||
dalle prove a partire dai file dell'insieme (`ALPH` grezzo e compresso con ogni filtro, VP8X con ICCP, EXIF e XMP,
|
||||
animazioni con scostamento e fusione) o scritte bit per bit (`Vp8TestWriter.cs`: segmenti, delta del filtro, più
|
||||
partizioni, filtro semplice); i file danneggiati o tagliati.
|
||||
- `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini
|
||||
come binarie e tiene `elenco.txt` con le righe Unix.
|
||||
@@ -0,0 +1,338 @@
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>
|
||||
/// The VP8 decoder on frames written by <see cref="Vp8TestWriter"/>, for what the libwebp references do not reach:
|
||||
/// the border rules of intra prediction, the token categories, several partitions, the skip flag, segment maps,
|
||||
/// filter deltas and the simple loop filter (checked against a separate implementation of RFC 6386 §15.2).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class Vp8BitstreamTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TheBooleanCoderRoundTrips()
|
||||
{
|
||||
var random = new Random(21);
|
||||
for (var round = 0; round < 20; round++)
|
||||
{
|
||||
var count = random.Next(1, 4000);
|
||||
var probs = new int[count];
|
||||
var bits = new bool[count];
|
||||
var encoder = new Vp8BoolEncoder();
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
probs[i] = random.Next(1, 256);
|
||||
bits[i] = random.Next(256) >= probs[i];
|
||||
encoder.Write(probs[i], bits[i]);
|
||||
}
|
||||
|
||||
var data = encoder.Finish();
|
||||
var decoder = new Vp8BoolDecoder(data, 0, data.Length);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
Assert.AreEqual(bits[i] ? 1 : 0, decoder.GetBit(probs[i]), $"giro {round}, bit {i}");
|
||||
}
|
||||
|
||||
Assert.IsFalse(decoder.Overrun);
|
||||
}
|
||||
|
||||
// Reading on past the end is noticed.
|
||||
var empty = new Vp8BoolDecoder([], 0, 0);
|
||||
for (var i = 0; i < 40; i++)
|
||||
{
|
||||
empty.GetBit(128);
|
||||
}
|
||||
|
||||
Assert.IsTrue(empty.Overrun);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PredictionFollowsTheBorderRules()
|
||||
{
|
||||
// 3×2 macroblocks, no residual, no loop filter: the pixels are the prediction alone.
|
||||
Assert.AreEqual(128, Uniform(Vp8Tables.DcPred, Vp8Tables.DcPred).Y.Distinct().Single(), "DC senza vicini");
|
||||
Assert.AreEqual(127, Uniform(Vp8Tables.VPred, Vp8Tables.VPred).Y.Distinct().Single(), "sopra il fotogramma 127");
|
||||
Assert.AreEqual(129, Uniform(Vp8Tables.HPred, Vp8Tables.HPred).Y.Distinct().Single(), "a sinistra del fotogramma 129");
|
||||
Assert.AreEqual(129, Uniform(Vp8Tables.TmPred, Vp8Tables.TmPred).Y.Distinct().Single(), "TM: 129 + 127 − 127");
|
||||
var vertical = Uniform(Vp8Tables.VPred, Vp8Tables.VPred);
|
||||
Assert.AreEqual(127, vertical.U.Distinct().Single());
|
||||
|
||||
// B_VE smooths the row above with the pixel above-left, which is 127 above the frame and 129 left of it:
|
||||
// column 0 is avg3(127, 127, 127) in the first four rows and avg3(129, 127, 127) = 128 below.
|
||||
var subVertical = Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BVe);
|
||||
for (var y = 0; y < 32; y++)
|
||||
{
|
||||
Assert.AreEqual(y < 4 ? 127 : 128, subVertical.Y[y * 48], $"riga {y}");
|
||||
Assert.AreEqual(127, subVertical.Y[(y * 48) + 1], $"riga {y}");
|
||||
}
|
||||
|
||||
// B_DC of the first subblock: (4·127 + 4·129 + 4) >> 3; B_HE and B_TM next to the left border: 129.
|
||||
Assert.AreEqual(128, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BDc).Y[0]);
|
||||
Assert.AreEqual(129, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BHe).Y[0]);
|
||||
Assert.AreEqual(129, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BTm).Y[0]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TokenCategoriesCarryTheirValues()
|
||||
{
|
||||
// Base quantizer 0: Y DC step 4, Y2 DC step 8. A DC-only block adds (level·4 + 4) >> 3 to the prediction 128.
|
||||
foreach (var level in (int[])[1, -1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 18, 19, 34, 35, 66, 67, 300, -2114, 2114])
|
||||
{
|
||||
var mbs = Vp8TestWriter.Uniform(1, Vp8Tables.BPred, Vp8Tables.DcPred);
|
||||
mbs[0].Skip = false;
|
||||
mbs[0].Levels[0][0] = level;
|
||||
var planes = Planes(new Vp8TestWriter { Width = 16, Height = 16, BaseQ = 0 }.Write(mbs));
|
||||
var expected = Math.Clamp(128 + (((level * 4) + 4) >> 3), 0, 255);
|
||||
Assert.AreEqual(expected, planes.Y[0], $"livello {level}");
|
||||
Assert.AreEqual(expected, planes.Y[(3 * 16) + 3], $"livello {level}");
|
||||
}
|
||||
|
||||
// Y2: the inverse WHT of a DC of 8·16 gives 16 to every luma block, which adds (16 + 4) >> 3 = 2.
|
||||
var whole = Vp8TestWriter.Uniform(1, Vp8Tables.DcPred, Vp8Tables.DcPred);
|
||||
whole[0].Skip = false;
|
||||
whole[0].Levels[24][0] = 16;
|
||||
Assert.AreEqual(130, Planes(new Vp8TestWriter { Width = 16, Height = 16, BaseQ = 0 }.Write(whole)).Y.Distinct().Single());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PartitionsDoNotChangeThePicture()
|
||||
{
|
||||
var mbs = Vp8TestWriter.Random(7 * 5, seed: 31);
|
||||
var expected = Planes(new Vp8TestWriter { Width = 100, Height = 70, FilterLevel = 20, Sharpness = 2 }.Write(mbs));
|
||||
for (var log2 = 1; log2 <= 3; log2++)
|
||||
{
|
||||
var actual = Planes(new Vp8TestWriter { Width = 100, Height = 70, FilterLevel = 20, Sharpness = 2, Log2Partitions = log2 }.Write(mbs));
|
||||
AssertSamePlanes(expected, actual, $"{1 << log2} partizioni");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSkipFlagAndEmptyBlocksAgree()
|
||||
{
|
||||
var mbs = Vp8TestWriter.Random(6 * 4, seed: 32, skips: false);
|
||||
for (var i = 0; i < mbs.Length; i += 3)
|
||||
{
|
||||
foreach (var block in mbs[i].Levels)
|
||||
{
|
||||
Array.Clear(block);
|
||||
}
|
||||
|
||||
mbs[i].Skip = true;
|
||||
}
|
||||
|
||||
var skipped = Planes(new Vp8TestWriter { Width = 90, Height = 60, FilterLevel = 30 }.Write(mbs));
|
||||
var explicitEmpty = Planes(new Vp8TestWriter { Width = 90, Height = 60, FilterLevel = 30, UseSkipProb = false }.Write(mbs));
|
||||
AssertSamePlanes(skipped, explicitEmpty, "salto contro blocchi vuoti");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SegmentsWithTheBaseValuesChangeNothing()
|
||||
{
|
||||
var mbs = Vp8TestWriter.Random(5 * 5, seed: 33);
|
||||
var plain = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50 }.Write(mbs));
|
||||
var deltas = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50, Segmentation = true, UpdateMap = true, SegmentProbs = [90, 140, 200] }.Write(mbs));
|
||||
AssertSamePlanes(plain, deltas, "segmenti con differenze nulle");
|
||||
var absolute = Planes(new Vp8TestWriter
|
||||
{
|
||||
Width = 80,
|
||||
Height = 80,
|
||||
FilterLevel = 25,
|
||||
BaseQ = 50,
|
||||
Segmentation = true,
|
||||
UpdateMap = true,
|
||||
AbsoluteDeltas = true,
|
||||
SegmentQuant = [50, 50, 50, 50],
|
||||
SegmentFilter = [25, 25, 25, 25],
|
||||
}.Write(mbs));
|
||||
AssertSamePlanes(plain, absolute, "segmenti con valori assoluti uguali");
|
||||
|
||||
// Different quantizers per segment do change the picture.
|
||||
var different = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50, Segmentation = true, UpdateMap = true, SegmentQuant = [0, 10, -20, 30] }.Write(mbs));
|
||||
Assert.IsFalse(plain.Y.AsSpan().SequenceEqual(different.Y));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FilterDeltasMoveTheLevel()
|
||||
{
|
||||
var unfiltered = Vp8TestWriter.Random(4 * 3, seed: 34);
|
||||
var none = Planes(new Vp8TestWriter { Width = 64, Height = 48 }.Write(unfiltered));
|
||||
var cancelled = Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, RefLfDelta = [-30, 5, 5, 5] }.Write(unfiltered));
|
||||
AssertSamePlanes(none, cancelled, "livello annullato dalla differenza del riferimento intra");
|
||||
|
||||
// The mode delta of B_PRED: on a frame of B_PRED macroblocks it cancels the level, on 16×16 ones it does not.
|
||||
var subblocks = Vp8TestWriter.Random(4 * 3, seed: 35);
|
||||
var sixteen = Vp8TestWriter.Random(4 * 3, seed: 35);
|
||||
foreach (var mb in subblocks)
|
||||
{
|
||||
mb.YMode = Vp8Tables.BPred;
|
||||
}
|
||||
|
||||
foreach (var mb in sixteen)
|
||||
{
|
||||
mb.YMode = Vp8Tables.TmPred;
|
||||
}
|
||||
|
||||
AssertSamePlanes(
|
||||
Planes(new Vp8TestWriter { Width = 64, Height = 48 }.Write(subblocks)),
|
||||
Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, ModeLfDelta = [-30, 0, 0, 0] }.Write(subblocks)),
|
||||
"B_PRED");
|
||||
AssertSamePlanes(
|
||||
Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30 }.Write(sixteen)),
|
||||
Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, ModeLfDelta = [-30, 0, 0, 0] }.Write(sixteen)),
|
||||
"16×16");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSimpleFilterMatchesASeparateImplementation()
|
||||
{
|
||||
foreach (var (level, sharpness, seed) in new[] { (10, 0, 40), (32, 3, 41), (63, 7, 42), (45, 5, 43) })
|
||||
{
|
||||
var mbs = Vp8TestWriter.Random(6 * 4, seed);
|
||||
var raw = Planes(new Vp8TestWriter { Width = 96, Height = 64 }.Write(mbs));
|
||||
var filtered = Planes(new Vp8TestWriter { Width = 96, Height = 64, SimpleFilter = true, FilterLevel = level, Sharpness = sharpness }.Write(mbs));
|
||||
var expected = raw.Y.ToArray();
|
||||
SimpleFilter(expected, raw.YStride, 6, 4, mbs, level, sharpness);
|
||||
CollectionAssert.AreEqual(expected, filtered.Y, $"livello {level}, nitidezza {sharpness}");
|
||||
CollectionAssert.AreEqual(raw.U, filtered.U, "il filtro semplice non tocca la crominanza");
|
||||
CollectionAssert.AreEqual(raw.V, filtered.V);
|
||||
Assert.IsFalse(raw.Y.AsSpan().SequenceEqual(filtered.Y), "il filtro deve aver cambiato qualcosa");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RandomFramesDecodeThroughTheContainer()
|
||||
{
|
||||
for (var seed = 50; seed < 60; seed++)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var width = random.Next(1, 120);
|
||||
var height = random.Next(1, 90);
|
||||
var writer = new Vp8TestWriter
|
||||
{
|
||||
Width = width,
|
||||
Height = height,
|
||||
FilterLevel = random.Next(64),
|
||||
Sharpness = random.Next(8),
|
||||
SimpleFilter = random.Next(2) == 0,
|
||||
Log2Partitions = random.Next(4),
|
||||
BaseQ = random.Next(128),
|
||||
QDeltas = [random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16)],
|
||||
Segmentation = random.Next(2) == 0,
|
||||
UpdateMap = true,
|
||||
SegmentQuant = [random.Next(-30, 30), random.Next(-30, 30), random.Next(-30, 30), random.Next(-30, 30)],
|
||||
SegmentFilter = [random.Next(-20, 20), random.Next(-20, 20), random.Next(-20, 20), random.Next(-20, 20)],
|
||||
};
|
||||
var frame = writer.Write(Vp8TestWriter.Random(writer.MbWidth * writer.MbHeight, seed, maxLevel: 2114));
|
||||
var file = WebPTestFiles.Riff(("VP8 ", frame));
|
||||
using var image = WebPDecoder.Decode(file);
|
||||
Assert.AreEqual((width, height), (image.Width, image.Height));
|
||||
Assert.IsTrue(image.IsOpaque());
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 6386 §15.2 and §15.1, written apart from the decoder: the simple filter over the luma plane, macroblock
|
||||
// after macroblock, left edge, inner vertical edges, top edge, inner horizontal edges.
|
||||
private static void SimpleFilter(byte[] y, int stride, int mbWidth, int mbHeight, Vp8TestMacroblock[] mbs, int level, int sharpness)
|
||||
{
|
||||
var interior = level;
|
||||
if (sharpness > 0)
|
||||
{
|
||||
interior >>= sharpness > 4 ? 2 : 1;
|
||||
interior = Math.Min(interior, 9 - sharpness);
|
||||
}
|
||||
|
||||
interior = Math.Max(interior, 1);
|
||||
var mbLimit = ((level + 2) * 2) + interior;
|
||||
var subLimit = (level * 2) + interior;
|
||||
for (var mbY = 0; mbY < mbHeight; mbY++)
|
||||
{
|
||||
for (var mbX = 0; mbX < mbWidth; mbX++)
|
||||
{
|
||||
var mb = mbs[(mbY * mbWidth) + mbX];
|
||||
var inner = mb.YMode == Vp8Tables.BPred || HasCoefficients(mb);
|
||||
var x0 = mbX * 16;
|
||||
var y0 = mbY * 16;
|
||||
for (var edge = 0; edge < 16; edge += 4)
|
||||
{
|
||||
if ((edge == 0 && mbX > 0) || (edge > 0 && inner))
|
||||
{
|
||||
for (var r = 0; r < 16; r++)
|
||||
{
|
||||
Segment(y, ((y0 + r) * stride) + x0 + edge, 1, edge == 0 ? mbLimit : subLimit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var edge = 0; edge < 16; edge += 4)
|
||||
{
|
||||
if ((edge == 0 && mbY > 0) || (edge > 0 && inner))
|
||||
{
|
||||
for (var c = 0; c < 16; c++)
|
||||
{
|
||||
Segment(y, ((y0 + edge) * stride) + x0 + c, stride, edge == 0 ? mbLimit : subLimit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Segment(byte[] y, int q0At, int step, int edgeLimit)
|
||||
{
|
||||
int p1 = y[q0At - (2 * step)] - 128, p0 = y[q0At - step] - 128, q0 = y[q0At] - 128, q1 = y[q0At + step] - 128;
|
||||
if ((Math.Abs(p0 - q0) * 2) + (Math.Abs(p1 - q1) >> 1) > edgeLimit)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
static int C(int v) => Math.Clamp(v, -128, 127);
|
||||
var a = C(C(p1 - q1) + (3 * (q0 - p0)));
|
||||
var b = C(a + 3) >> 3;
|
||||
a = C(a + 4) >> 3;
|
||||
y[q0At] = (byte)(C(q0 - a) + 128);
|
||||
y[q0At - step] = (byte)(C(p0 + b) + 128);
|
||||
}
|
||||
|
||||
private static bool HasCoefficients(Vp8TestMacroblock mb)
|
||||
{
|
||||
if (mb.Skip)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var i16 = mb.YMode != Vp8Tables.BPred;
|
||||
for (var b = 0; b < 25; b++)
|
||||
{
|
||||
var levels = mb.Levels[b];
|
||||
var first = i16 && b < 16 ? 1 : 0;
|
||||
if (b == 24 && !i16)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var n = first; n < 16; n++)
|
||||
{
|
||||
if (levels[n] != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) Uniform(int yMode, int uvMode, int bMode = Vp8Tables.BDc) =>
|
||||
Planes(new Vp8TestWriter { Width = 48, Height = 32 }.Write(Vp8TestWriter.Uniform(6, yMode, uvMode, bMode)));
|
||||
|
||||
private static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) Planes(byte[] frame) =>
|
||||
Vp8Decoder.DecodePlanes(frame, 0, frame.Length, ImageLimits.Default);
|
||||
|
||||
private static void AssertSamePlanes((byte[] Y, byte[] U, byte[] V, int, int) expected, (byte[] Y, byte[] U, byte[] V, int, int) actual, string what)
|
||||
{
|
||||
CollectionAssert.AreEqual(expected.Y, actual.Y, $"{what}: Y");
|
||||
CollectionAssert.AreEqual(expected.U, actual.U, $"{what}: U");
|
||||
CollectionAssert.AreEqual(expected.V, actual.V, $"{what}: V");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>
|
||||
/// The boolean entropy encoder of RFC 6386 §7.3 (write_bool, add_one_to_output, flush_bool_encoder), for the tests.
|
||||
/// </summary>
|
||||
internal sealed class Vp8BoolEncoder
|
||||
{
|
||||
private readonly List<byte> _output = [];
|
||||
private uint _range = 255;
|
||||
private uint _bottom;
|
||||
private int _bitCount = 24;
|
||||
|
||||
public void Write(int prob, bool value)
|
||||
{
|
||||
var split = 1 + (((_range - 1) * (uint)prob) >> 8);
|
||||
if (value)
|
||||
{
|
||||
_bottom += split;
|
||||
_range -= split;
|
||||
}
|
||||
else
|
||||
{
|
||||
_range = split;
|
||||
}
|
||||
|
||||
while (_range < 128)
|
||||
{
|
||||
_range <<= 1;
|
||||
if ((_bottom & (1u << 31)) != 0)
|
||||
{
|
||||
AddOne();
|
||||
}
|
||||
|
||||
_bottom <<= 1;
|
||||
if (--_bitCount == 0)
|
||||
{
|
||||
_output.Add((byte)(_bottom >> 24));
|
||||
_bottom &= (1 << 24) - 1;
|
||||
_bitCount = 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Write(int prob, int value) => Write(prob, value != 0);
|
||||
|
||||
public void Literal(int value, int bits)
|
||||
{
|
||||
for (var b = bits - 1; b >= 0; b--)
|
||||
{
|
||||
Write(128, (value >> b) & 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A flag, then (when the value is not 0) magnitude and sign, as the frame header writes deltas.</summary>
|
||||
public void OptionalSigned(int value, int bits)
|
||||
{
|
||||
Write(128, value != 0);
|
||||
if (value != 0)
|
||||
{
|
||||
Literal(Math.Abs(value), bits);
|
||||
Write(128, value < 0);
|
||||
}
|
||||
}
|
||||
|
||||
public void Tree(ReadOnlySpan<sbyte> tree, ReadOnlySpan<byte> probs, int offset, int leaf)
|
||||
{
|
||||
Span<int> path = stackalloc int[16];
|
||||
var depth = FindPath(tree, 0, leaf, path, 0);
|
||||
Assert.IsGreaterThan(0, depth, $"foglia {leaf} assente");
|
||||
var node = 0;
|
||||
for (var i = 0; i < depth; i++)
|
||||
{
|
||||
Write(probs[offset + (node >> 1)], path[i]);
|
||||
node = tree[node + path[i]];
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] Finish()
|
||||
{
|
||||
var c = _bitCount;
|
||||
var v = _bottom;
|
||||
if ((v & (1u << (32 - c))) != 0)
|
||||
{
|
||||
AddOne();
|
||||
}
|
||||
|
||||
v <<= c & 7;
|
||||
c >>= 3;
|
||||
while (--c >= 0)
|
||||
{
|
||||
v <<= 8;
|
||||
}
|
||||
|
||||
for (c = 0; c < 4; c++)
|
||||
{
|
||||
_output.Add((byte)(v >> 24));
|
||||
v <<= 8;
|
||||
}
|
||||
|
||||
return [.. _output];
|
||||
}
|
||||
|
||||
private static int FindPath(ReadOnlySpan<sbyte> tree, int node, int leaf, Span<int> path, int depth)
|
||||
{
|
||||
for (var bit = 0; bit < 2; bit++)
|
||||
{
|
||||
var child = tree[node + bit];
|
||||
path[depth] = bit;
|
||||
if (child <= 0)
|
||||
{
|
||||
if (-child == leaf)
|
||||
{
|
||||
return depth + 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var found = FindPath(tree, child, leaf, path, depth + 1);
|
||||
if (found > 0)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private void AddOne()
|
||||
{
|
||||
var i = _output.Count - 1;
|
||||
while (_output[i] == 255)
|
||||
{
|
||||
_output[i] = 0;
|
||||
i--;
|
||||
}
|
||||
|
||||
_output[i]++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a test macroblock holds.</summary>
|
||||
internal sealed class Vp8TestMacroblock
|
||||
{
|
||||
public int Segment { get; set; }
|
||||
|
||||
public bool Skip { get; set; }
|
||||
|
||||
/// <summary>DC_PRED, V_PRED, H_PRED, TM_PRED or B_PRED (Vp8Tables).</summary>
|
||||
public int YMode { get; set; }
|
||||
|
||||
/// <summary>The sixteen subblock modes for B_PRED.</summary>
|
||||
public int[] BModes { get; } = new int[16];
|
||||
|
||||
public int UvMode { get; set; }
|
||||
|
||||
/// <summary>Quantized levels of the 25 blocks (16 Y, 4 U, 4 V, Y2), in zigzag order.</summary>
|
||||
public int[][] Levels { get; } = [.. Enumerable.Range(0, 25).Select(_ => new int[16])];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A VP8 key frame writer for the tests (RFC 6386 §9, §19): any header the decoder reads, given modes and quantized
|
||||
/// levels of every macroblock, tokens with the same contexts and default probabilities as the decoder.
|
||||
/// </summary>
|
||||
internal sealed class Vp8TestWriter
|
||||
{
|
||||
public int Width { get; init; }
|
||||
|
||||
public int Height { get; init; }
|
||||
|
||||
public bool Segmentation { get; init; }
|
||||
|
||||
public bool UpdateMap { get; init; }
|
||||
|
||||
public bool AbsoluteDeltas { get; init; }
|
||||
|
||||
public int[] SegmentQuant { get; init; } = new int[4];
|
||||
|
||||
public int[] SegmentFilter { get; init; } = new int[4];
|
||||
|
||||
public byte[] SegmentProbs { get; init; } = [128, 128, 128];
|
||||
|
||||
public bool SimpleFilter { get; init; }
|
||||
|
||||
public int FilterLevel { get; init; }
|
||||
|
||||
public int Sharpness { get; init; }
|
||||
|
||||
public int[]? RefLfDelta { get; init; }
|
||||
|
||||
public int[]? ModeLfDelta { get; init; }
|
||||
|
||||
public int Log2Partitions { get; init; }
|
||||
|
||||
public int BaseQ { get; init; } = 40;
|
||||
|
||||
public int[] QDeltas { get; init; } = new int[5];
|
||||
|
||||
public bool UseSkipProb { get; init; } = true;
|
||||
|
||||
public int SkipProb { get; init; } = 100;
|
||||
|
||||
public int MbWidth => (Width + 15) / 16;
|
||||
|
||||
public int MbHeight => (Height + 15) / 16;
|
||||
|
||||
/// <summary>The VP8 frame (the payload of a «VP8 » chunk).</summary>
|
||||
public byte[] Write(Vp8TestMacroblock[] macroblocks)
|
||||
{
|
||||
Assert.HasCount(MbWidth * MbHeight, macroblocks);
|
||||
var first = new Vp8BoolEncoder();
|
||||
WriteHeader(first);
|
||||
var partitions = Enumerable.Range(0, 1 << Log2Partitions).Select(_ => new Vp8BoolEncoder()).ToArray();
|
||||
var intraTop = Enumerable.Repeat(Vp8Tables.BDc, MbWidth * 4).ToArray();
|
||||
var nzTop = new int[MbWidth * 9];
|
||||
for (var mbY = 0; mbY < MbHeight; mbY++)
|
||||
{
|
||||
var intraLeft = new int[] { Vp8Tables.BDc, Vp8Tables.BDc, Vp8Tables.BDc, Vp8Tables.BDc };
|
||||
var nzLeft = new int[9];
|
||||
var tokens = partitions[mbY % partitions.Length];
|
||||
for (var mbX = 0; mbX < MbWidth; mbX++)
|
||||
{
|
||||
var mb = macroblocks[(mbY * MbWidth) + mbX];
|
||||
WriteModes(first, mb, intraTop.AsSpan(mbX * 4, 4), intraLeft);
|
||||
var top = nzTop.AsSpan(mbX * 9, 9);
|
||||
if (UseSkipProb && mb.Skip)
|
||||
{
|
||||
top[..8].Clear();
|
||||
nzLeft.AsSpan(0, 8).Clear();
|
||||
if (mb.YMode != Vp8Tables.BPred)
|
||||
{
|
||||
top[8] = nzLeft[8] = 0;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
WriteResiduals(tokens, mb, top, nzLeft);
|
||||
}
|
||||
}
|
||||
|
||||
var firstBytes = first.Finish();
|
||||
var partitionBytes = partitions.Select(p => p.Finish()).ToArray();
|
||||
using var frame = new MemoryStream();
|
||||
var tag = (firstBytes.Length << 5) | (1 << 4); // key frame, version 0, shown
|
||||
frame.Write([(byte)tag, (byte)(tag >> 8), (byte)(tag >> 16), 0x9D, 0x01, 0x2A, (byte)Width, (byte)(Width >> 8), (byte)Height, (byte)(Height >> 8)]);
|
||||
frame.Write(firstBytes);
|
||||
for (var i = 0; i < partitionBytes.Length - 1; i++)
|
||||
{
|
||||
var size = partitionBytes[i].Length;
|
||||
frame.Write([(byte)size, (byte)(size >> 8), (byte)(size >> 16)]);
|
||||
}
|
||||
|
||||
foreach (var p in partitionBytes)
|
||||
{
|
||||
frame.Write(p);
|
||||
}
|
||||
|
||||
return frame.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>A frame of empty macroblocks with the given modes (skip set, so no tokens).</summary>
|
||||
public static Vp8TestMacroblock[] Uniform(int count, int yMode, int uvMode, int bMode = Vp8Tables.BDc)
|
||||
{
|
||||
var mbs = new Vp8TestMacroblock[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
mbs[i] = new Vp8TestMacroblock { YMode = yMode, UvMode = uvMode, Skip = true };
|
||||
Array.Fill(mbs[i].BModes, bMode);
|
||||
}
|
||||
|
||||
return mbs;
|
||||
}
|
||||
|
||||
/// <summary>Random modes, segments and levels from a fixed seed; about a third of the blocks empty.</summary>
|
||||
public static Vp8TestMacroblock[] Random(int count, int seed, int maxLevel = 40, bool skips = true)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var mbs = new Vp8TestMacroblock[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var mb = new Vp8TestMacroblock
|
||||
{
|
||||
Segment = random.Next(4),
|
||||
YMode = random.Next(5),
|
||||
UvMode = random.Next(4),
|
||||
Skip = skips && random.Next(6) == 0,
|
||||
};
|
||||
for (var b = 0; b < 16; b++)
|
||||
{
|
||||
mb.BModes[b] = random.Next(Vp8Tables.NumBModes);
|
||||
}
|
||||
|
||||
foreach (var block in mb.Levels)
|
||||
{
|
||||
if (random.Next(3) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var count2 = random.Next(1, 17);
|
||||
for (var k = 0; k < count2; k++)
|
||||
{
|
||||
var position = random.Next(k < 3 ? 4 : 16);
|
||||
var magnitude = random.Next(8) == 0 ? random.Next(1, maxLevel + 1) : random.Next(1, 4);
|
||||
block[position] = random.Next(2) == 0 ? magnitude : -magnitude;
|
||||
}
|
||||
}
|
||||
|
||||
mbs[i] = mb;
|
||||
}
|
||||
|
||||
return mbs;
|
||||
}
|
||||
|
||||
private void WriteHeader(Vp8BoolEncoder e)
|
||||
{
|
||||
e.Literal(0, 1); // colour space
|
||||
e.Literal(0, 1); // clamping type
|
||||
e.Write(128, Segmentation);
|
||||
if (Segmentation)
|
||||
{
|
||||
e.Write(128, UpdateMap);
|
||||
e.Write(128, true); // update segment feature data
|
||||
e.Write(128, AbsoluteDeltas);
|
||||
foreach (var q in SegmentQuant)
|
||||
{
|
||||
e.OptionalSigned(q, 7);
|
||||
}
|
||||
|
||||
foreach (var f in SegmentFilter)
|
||||
{
|
||||
e.OptionalSigned(f, 6);
|
||||
}
|
||||
|
||||
if (UpdateMap)
|
||||
{
|
||||
foreach (var p in SegmentProbs)
|
||||
{
|
||||
e.Write(128, true);
|
||||
e.Literal(p, 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
e.Write(128, SimpleFilter);
|
||||
e.Literal(FilterLevel, 6);
|
||||
e.Literal(Sharpness, 3);
|
||||
var deltas = RefLfDelta is not null || ModeLfDelta is not null;
|
||||
e.Write(128, deltas);
|
||||
if (deltas)
|
||||
{
|
||||
e.Write(128, true);
|
||||
foreach (var d in RefLfDelta ?? new int[4])
|
||||
{
|
||||
e.OptionalSigned(d, 6);
|
||||
}
|
||||
|
||||
foreach (var d in ModeLfDelta ?? new int[4])
|
||||
{
|
||||
e.OptionalSigned(d, 6);
|
||||
}
|
||||
}
|
||||
|
||||
e.Literal(Log2Partitions, 2);
|
||||
e.Literal(BaseQ, 7);
|
||||
foreach (var d in QDeltas)
|
||||
{
|
||||
e.OptionalSigned(d, 4);
|
||||
}
|
||||
|
||||
e.Write(128, false); // refresh entropy probs
|
||||
foreach (var p in Vp8Tables.CoefficientUpdateProbs)
|
||||
{
|
||||
e.Write(p, false); // no probability updated
|
||||
}
|
||||
|
||||
e.Write(128, UseSkipProb);
|
||||
if (UseSkipProb)
|
||||
{
|
||||
e.Literal(SkipProb, 8);
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteModes(Vp8BoolEncoder e, Vp8TestMacroblock mb, Span<int> top, int[] left)
|
||||
{
|
||||
if (UpdateMap)
|
||||
{
|
||||
var s = mb.Segment;
|
||||
e.Write(SegmentProbs[0], s >= 2);
|
||||
e.Write(SegmentProbs[s >= 2 ? 2 : 1], s & 1);
|
||||
}
|
||||
|
||||
if (UseSkipProb)
|
||||
{
|
||||
e.Write(SkipProb, mb.Skip);
|
||||
}
|
||||
|
||||
if (mb.YMode == Vp8Tables.BPred)
|
||||
{
|
||||
e.Write(145, false);
|
||||
for (var row = 0; row < 4; row++)
|
||||
{
|
||||
for (var col = 0; col < 4; col++)
|
||||
{
|
||||
var mode = mb.BModes[(row * 4) + col];
|
||||
e.Tree(Vp8Tables.BModeTree, Vp8Tables.KeyFrameBModeProbs, ((top[col] * Vp8Tables.NumBModes) + left[row]) * 9, mode);
|
||||
top[col] = left[row] = mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Write(145, true);
|
||||
var y = mb.YMode;
|
||||
e.Write(156, y is Vp8Tables.HPred or Vp8Tables.TmPred);
|
||||
if (y is Vp8Tables.HPred or Vp8Tables.TmPred)
|
||||
{
|
||||
e.Write(128, y == Vp8Tables.TmPred);
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Write(163, y == Vp8Tables.VPred);
|
||||
}
|
||||
|
||||
var implied = y switch { Vp8Tables.VPred => Vp8Tables.BVe, Vp8Tables.HPred => Vp8Tables.BHe, Vp8Tables.TmPred => Vp8Tables.BTm, _ => Vp8Tables.BDc };
|
||||
top.Fill(implied);
|
||||
Array.Fill(left, implied);
|
||||
}
|
||||
|
||||
var uv = mb.UvMode;
|
||||
e.Write(142, uv != Vp8Tables.DcPred);
|
||||
if (uv != Vp8Tables.DcPred)
|
||||
{
|
||||
e.Write(114, uv != Vp8Tables.VPred);
|
||||
if (uv != Vp8Tables.VPred)
|
||||
{
|
||||
e.Write(183, uv == Vp8Tables.TmPred);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteResiduals(Vp8BoolEncoder e, Vp8TestMacroblock mb, Span<int> top, int[] left)
|
||||
{
|
||||
int first;
|
||||
int yType;
|
||||
if (mb.YMode != Vp8Tables.BPred)
|
||||
{
|
||||
var flag = WriteBlock(e, 1, top[8] + left[8], 0, mb.Levels[24]);
|
||||
top[8] = left[8] = flag;
|
||||
first = 1;
|
||||
yType = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
first = 0;
|
||||
yType = 3;
|
||||
}
|
||||
|
||||
for (var row = 0; row < 4; row++)
|
||||
{
|
||||
for (var col = 0; col < 4; col++)
|
||||
{
|
||||
var flag = WriteBlock(e, yType, top[col] + left[row], first, mb.Levels[(row * 4) + col]);
|
||||
top[col] = left[row] = flag;
|
||||
}
|
||||
}
|
||||
|
||||
for (var plane = 0; plane < 2; plane++)
|
||||
{
|
||||
for (var row = 0; row < 2; row++)
|
||||
{
|
||||
for (var col = 0; col < 2; col++)
|
||||
{
|
||||
var t = 4 + (plane * 2) + col;
|
||||
var l = 4 + (plane * 2) + row;
|
||||
var flag = WriteBlock(e, 2, top[t] + left[l], 0, mb.Levels[16 + (plane * 4) + (row * 2) + col]);
|
||||
top[t] = left[l] = flag;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 6386 §13: the tokens of one block from position `first`; returns the context flag (any token not EOB).
|
||||
private static int WriteBlock(Vp8BoolEncoder e, int type, int context, int first, int[] levels)
|
||||
{
|
||||
var probs = Vp8Tables.DefaultCoefficientProbs;
|
||||
var bands = Vp8Tables.Bands;
|
||||
var last = -1;
|
||||
for (var n = first; n < 16; n++)
|
||||
{
|
||||
if (levels[n] != 0)
|
||||
{
|
||||
last = n;
|
||||
}
|
||||
}
|
||||
|
||||
var p = Index(type, bands[first], context);
|
||||
if (last < 0)
|
||||
{
|
||||
e.Write(probs[p], false);
|
||||
return 0;
|
||||
}
|
||||
|
||||
var afterZero = false;
|
||||
for (var n = first; n <= last; n++)
|
||||
{
|
||||
if (!afterZero)
|
||||
{
|
||||
e.Write(probs[p], true); // not the end of the block
|
||||
}
|
||||
|
||||
var v = Math.Abs(levels[n]);
|
||||
if (v == 0)
|
||||
{
|
||||
e.Write(probs[p + 1], false);
|
||||
p = Index(type, bands[n + 1], 0);
|
||||
afterZero = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
e.Write(probs[p + 1], true);
|
||||
int context2;
|
||||
if (v == 1)
|
||||
{
|
||||
e.Write(probs[p + 2], false);
|
||||
context2 = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Write(probs[p + 2], true);
|
||||
WriteLarge(e, probs.Slice(p, 11), v);
|
||||
context2 = 2;
|
||||
}
|
||||
|
||||
e.Write(128, levels[n] < 0);
|
||||
p = Index(type, bands[n + 1], context2);
|
||||
afterZero = false;
|
||||
}
|
||||
|
||||
if (last < 15)
|
||||
{
|
||||
e.Write(probs[p], false); // end of block
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void WriteLarge(Vp8BoolEncoder e, ReadOnlySpan<byte> p, int v)
|
||||
{
|
||||
if (v <= 4)
|
||||
{
|
||||
e.Write(p[3], false);
|
||||
e.Write(p[4], v != 2);
|
||||
if (v != 2)
|
||||
{
|
||||
e.Write(p[5], v == 4);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
e.Write(p[3], true);
|
||||
if (v <= 10)
|
||||
{
|
||||
e.Write(p[6], false);
|
||||
e.Write(p[7], v > 6);
|
||||
if (v <= 6)
|
||||
{
|
||||
e.Write(159, v - 5);
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Write(165, (v - 7) >> 1);
|
||||
e.Write(145, (v - 7) & 1);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
e.Write(p[6], true);
|
||||
var category = v <= 18 ? 0 : v <= 34 ? 1 : v <= 66 ? 2 : 3;
|
||||
e.Write(p[8], category >> 1);
|
||||
e.Write(p[9 + (category >> 1)], category & 1);
|
||||
var extra = category switch { 0 => Vp8Tables.Cat3, 1 => Vp8Tables.Cat4, 2 => Vp8Tables.Cat5, _ => Vp8Tables.Cat6 };
|
||||
var value = v - 3 - (8 << category);
|
||||
for (var i = 0; i < extra.Length; i++)
|
||||
{
|
||||
e.Write(extra[i], (value >> (extra.Length - 1 - i)) & 1);
|
||||
}
|
||||
}
|
||||
|
||||
private static int Index(int type, int band, int context) => (((type * 8) + band) * 3 + context) * 11;
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>
|
||||
/// The in-house WebP decoder against the SkiaSharp (libwebp) reads of the reference set: lossless files must match
|
||||
/// byte for byte, alpha included; lossy files are compared with the thresholds of <see cref="ImageQuality"/>, and their
|
||||
/// alpha (stored losslessly in ALPH) must match exactly.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebPReferenceTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
public static IEnumerable<object[]> LosslessCases => ReferenceImages.Of(ReferenceFormat.WebP).Where(c => !IsLossy(c)).Select(c => new object[] { c.Name });
|
||||
|
||||
public static IEnumerable<object[]> LossyCases => ReferenceImages.Of(ReferenceFormat.WebP).Where(IsLossy).Select(c => new object[] { c.Name });
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(LosslessCases))]
|
||||
public void TheLosslessDecoderReadsTheReferenceExactly(string name)
|
||||
{
|
||||
var reference = ReferenceImages.Get(name);
|
||||
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
|
||||
using var actual = WebPDecoder.Decode(reference.ReadInput());
|
||||
ImageAssert.AreEqual(expected, actual, name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(LossyCases))]
|
||||
public void TheLossyDecoderIsCloseToTheReference(string name)
|
||||
{
|
||||
var reference = ReferenceImages.Get(name);
|
||||
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
|
||||
using var actual = WebPDecoder.Decode(reference.ReadInput(), out var info);
|
||||
var result = ImageQuality.Compare(expected, actual);
|
||||
TestContext.WriteLine($"{name}: {result}");
|
||||
ImageQuality.AssertClose(result, name);
|
||||
|
||||
// Alpha is lossless even in a lossy file.
|
||||
var e = expected.Pixels;
|
||||
var a = actual.Pixels;
|
||||
for (var i = 3; i < e.Length; i += 4)
|
||||
{
|
||||
Assert.AreEqual(e[i], a[i], $"{name}: alfa del pixel {i / 4}");
|
||||
}
|
||||
|
||||
Assert.AreEqual(name.Contains("alfa", StringComparison.Ordinal), info.HasAlpha, name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheFacadeReadsWebPAndIdentifyAgreesWithDecode()
|
||||
{
|
||||
foreach (var reference in ReferenceImages.Of(ReferenceFormat.WebP))
|
||||
{
|
||||
var input = reference.ReadInput();
|
||||
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.WebP));
|
||||
using var viaFacade = ImageDecoder.Decode(input);
|
||||
using var direct = WebPDecoder.Decode(input, pooled: true);
|
||||
Assert.IsTrue(direct.IsPooled);
|
||||
ImageAssert.AreEqual(direct, viaFacade, reference.Name);
|
||||
|
||||
var info = ImageDecoder.Identify(input);
|
||||
Assert.AreEqual((ImageFormat.WebP, reference.Width, reference.Height, 1), (info.Format, info.Width, info.Height, info.FrameCount), reference.Name);
|
||||
Assert.AreSame(ImageMetadata.Empty, info.Metadata, reference.Name);
|
||||
if (!info.HasAlpha)
|
||||
{
|
||||
Assert.IsTrue(direct.IsOpaque(), reference.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsLossy(ReferenceCase c) => !c.Name.Contains("senza-perdita", StringComparison.Ordinal);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using System.Buffers.Binary;
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>WebP files put together by the tests from RIFF chunks (RFC 9649 §2), to reach what the reference set lacks.</summary>
|
||||
internal static class WebPTestFiles
|
||||
{
|
||||
/// <summary>The chunks of a WebP file: FourCC and payload, in order.</summary>
|
||||
public static List<(string Type, byte[] Payload)> Chunks(byte[] file)
|
||||
{
|
||||
var chunks = new List<(string, byte[])>();
|
||||
var end = 8 + (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4));
|
||||
var pos = 12;
|
||||
while (pos + 8 <= end)
|
||||
{
|
||||
var size = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos + 4));
|
||||
chunks.Add((System.Text.Encoding.ASCII.GetString(file, pos, 4), file.AsSpan(pos + 8, size).ToArray()));
|
||||
pos += 8 + size + (size & 1);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/// <summary>The payload of the first chunk of that type.</summary>
|
||||
public static byte[] Payload(byte[] file, string type) => Chunks(file).First(c => c.Type == type).Payload;
|
||||
|
||||
/// <summary>A RIFF/WEBP file of the given chunks (padded to even sizes).</summary>
|
||||
public static byte[] Riff(params (string Type, byte[] Payload)[] chunks)
|
||||
{
|
||||
using var body = new MemoryStream();
|
||||
body.Write("WEBP"u8);
|
||||
foreach (var (type, payload) in chunks)
|
||||
{
|
||||
body.Write(Chunk(type, payload));
|
||||
}
|
||||
|
||||
var file = new byte[8 + body.Length];
|
||||
"RIFF"u8.CopyTo(file);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(4), (uint)body.Length);
|
||||
body.ToArray().CopyTo(file, 8);
|
||||
return file;
|
||||
}
|
||||
|
||||
public static byte[] Chunk(string type, byte[] payload)
|
||||
{
|
||||
var chunk = new byte[8 + payload.Length + (payload.Length & 1)];
|
||||
System.Text.Encoding.ASCII.GetBytes(type).CopyTo(chunk, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(4), (uint)payload.Length);
|
||||
payload.CopyTo(chunk, 8);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
/// <summary>A VP8X payload: the flags byte and the canvas size.</summary>
|
||||
public static byte[] Vp8X(int flags, int width, int height)
|
||||
{
|
||||
var payload = new byte[10];
|
||||
payload[0] = (byte)flags;
|
||||
Uint24(payload.AsSpan(4), width - 1);
|
||||
Uint24(payload.AsSpan(7), height - 1);
|
||||
return payload;
|
||||
}
|
||||
|
||||
/// <summary>An ANIM payload: background colour (B, G, R, A) and loop count.</summary>
|
||||
public static byte[] Anim(uint backgroundBgra = 0, int loops = 0)
|
||||
{
|
||||
var payload = new byte[6];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(payload, backgroundBgra);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(4), (ushort)loops);
|
||||
return payload;
|
||||
}
|
||||
|
||||
/// <summary>An ANMF payload: offset (even), size, duration, flags (2 = do not blend, 1 = dispose) and frame chunks.</summary>
|
||||
public static byte[] Anmf(int x, int y, int width, int height, int flags, params (string Type, byte[] Payload)[] chunks)
|
||||
{
|
||||
using var payload = new MemoryStream();
|
||||
var header = new byte[16];
|
||||
Uint24(header, x / 2);
|
||||
Uint24(header.AsSpan(3), y / 2);
|
||||
Uint24(header.AsSpan(6), width - 1);
|
||||
Uint24(header.AsSpan(9), height - 1);
|
||||
Uint24(header.AsSpan(12), 100);
|
||||
header[15] = (byte)flags;
|
||||
payload.Write(header);
|
||||
foreach (var (type, data) in chunks)
|
||||
{
|
||||
payload.Write(Chunk(type, data));
|
||||
}
|
||||
|
||||
return payload.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The forward alpha filter of RFC 9649 §2.7.1.2 (1 horizontal, 2 vertical, 3 gradient), written from the
|
||||
/// predictor definitions, independent of the decoder's inverse.
|
||||
/// </summary>
|
||||
public static byte[] FilterAlpha(ReadOnlySpan<byte> alpha, int width, int height, int filter)
|
||||
{
|
||||
var output = new byte[alpha.Length];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
int predictor;
|
||||
if (filter == 0 || (x == 0 && y == 0))
|
||||
{
|
||||
predictor = 0;
|
||||
}
|
||||
else if (y == 0)
|
||||
{
|
||||
predictor = alpha[x - 1];
|
||||
}
|
||||
else if (x == 0)
|
||||
{
|
||||
predictor = alpha[(y - 1) * width];
|
||||
}
|
||||
else
|
||||
{
|
||||
int left = alpha[(y * width) + x - 1], top = alpha[((y - 1) * width) + x], topLeft = alpha[((y - 1) * width) + x - 1];
|
||||
predictor = filter switch
|
||||
{
|
||||
1 => left,
|
||||
2 => top,
|
||||
_ => Math.Clamp(left + top - topLeft, 0, 255),
|
||||
};
|
||||
}
|
||||
|
||||
output[(y * width) + x] = (byte)(alpha[(y * width) + x] - predictor);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>The alpha bytes of an image.</summary>
|
||||
public static byte[] AlphaOf(RgbaImage image)
|
||||
{
|
||||
var alpha = new byte[image.Width * image.Height];
|
||||
for (var i = 0; i < alpha.Length; i++)
|
||||
{
|
||||
alpha[i] = image.Pixels[(i * 4) + 3];
|
||||
}
|
||||
|
||||
return alpha;
|
||||
}
|
||||
|
||||
/// <summary>A little-endian TIFF with an IFD0 holding only the Orientation tag.</summary>
|
||||
public static byte[] Tiff(int orientation)
|
||||
{
|
||||
var tiff = new byte[8 + 2 + 12 + 4];
|
||||
"II*\0"u8.CopyTo(tiff);
|
||||
tiff[4] = 8;
|
||||
tiff[8] = 1;
|
||||
tiff[10] = 0x12;
|
||||
tiff[11] = 0x01;
|
||||
tiff[12] = 3;
|
||||
tiff[14] = 1;
|
||||
tiff[18] = (byte)orientation;
|
||||
return tiff;
|
||||
}
|
||||
|
||||
/// <summary>An image with only <paramref name="colors"/> distinct colours (some transparent), from a fixed seed.</summary>
|
||||
public static RgbaImage FewColors(int width, int height, int colors, int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var palette = new byte[colors * 4];
|
||||
random.NextBytes(palette);
|
||||
var image = new RgbaImage(width, height);
|
||||
var pixels = image.Pixels;
|
||||
for (var i = 0; i < width * height; i++)
|
||||
{
|
||||
var c = (((i % width) / 3) + ((i / width) / 2) + random.Next(2)) % colors;
|
||||
palette.AsSpan(c * 4, 4).CopyTo(pixels[(i * 4)..]);
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
private static void Uint24(Span<byte> destination, int value)
|
||||
{
|
||||
destination[0] = (byte)value;
|
||||
destination[1] = (byte)(value >> 8);
|
||||
destination[2] = (byte)(value >> 16);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user