Correzioni della revisione dei codec di casa (C1)
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>
This commit is contained in:
1 parent
d6a6a68496
commit
7e8296e790
32 files changed
+1120
-132
No files matched your search
@@ -43,6 +43,23 @@ public sealed class BmpDecoderTests
|
||||
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(2, 0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ACoreHeaderHeightIsUnsignedAndBottomUp()
|
||||
{
|
||||
// bcHeight 40000 is 0x9C40, which a signed read takes for −25536 (top-down, wrong size). One-bit pixels,
|
||||
// rows of 4 bytes: the first row in the file is the bottom of the picture and the only one with index 1.
|
||||
const int height = 40_000;
|
||||
byte[] palette = [10, 20, 30, 40, 50, 60];
|
||||
var pixels = new byte[height * 4];
|
||||
pixels[0] = 0b1000_0000;
|
||||
var bmp = Bmp(12, 1, height, 1, BiRgb, palette, pixels);
|
||||
Assert.AreEqual((1, height), (BmpDecoder.Identify(bmp).Width, BmpDecoder.Identify(bmp).Height));
|
||||
using var image = BmpDecoder.Decode(bmp);
|
||||
Assert.AreEqual((1, height), (image.Width, image.Height));
|
||||
Assert.AreEqual((60, 50, 40, 255), image.GetPixel(0, height - 1), "la prima riga del file è in fondo");
|
||||
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(0, 0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SixteenBitsWithFourMasksAfterAnInformationHeader()
|
||||
{
|
||||
|
||||
@@ -205,6 +205,74 @@ public sealed class ImageProcessingTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheReducedTransformIsTheMeanOfTheFullOne()
|
||||
{
|
||||
// InverseReduced computes the means of 2×2 and 4×4 squares of the full inverse straight from the
|
||||
// coefficients; checked against the T.81 definition in double precision, averaged, then rounded and clamped.
|
||||
var random = new Random(91);
|
||||
var quantization = new ushort[64];
|
||||
var block = new short[64];
|
||||
Span<byte> output = stackalloc byte[16];
|
||||
for (var round = 0; round < 400; round++)
|
||||
{
|
||||
for (var i = 0; i < 64; i++)
|
||||
{
|
||||
quantization[i] = (ushort)random.Next(1, 24);
|
||||
|
||||
// Mostly small coefficients, some zero rows and columns, now and then a large one.
|
||||
var zero = random.Next(4) == 0 || (round % 5 == 0 && i >= 8);
|
||||
block[i] = zero ? (short)0 : (short)random.Next(-40, 41);
|
||||
}
|
||||
|
||||
block[0] = (short)random.Next(-60, 61);
|
||||
var full = new double[64];
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
for (var x = 0; x < 8; x++)
|
||||
{
|
||||
double sum = 0;
|
||||
for (var v = 0; v < 8; v++)
|
||||
{
|
||||
for (var u = 0; u < 8; u++)
|
||||
{
|
||||
var cu = u == 0 ? 1 / Math.Sqrt(2) : 1;
|
||||
var cv = v == 0 ? 1 / Math.Sqrt(2) : 1;
|
||||
sum += cu * cv * block[(v * 8) + u] * quantization[(v * 8) + u]
|
||||
* Math.Cos(((2 * x) + 1) * u * Math.PI / 16) * Math.Cos(((2 * y) + 1) * v * Math.PI / 16);
|
||||
}
|
||||
}
|
||||
|
||||
full[(y * 8) + x] = (sum / 4) + 128;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var shift in new[] { 1, 2 })
|
||||
{
|
||||
var n = 8 >> shift;
|
||||
var side = 1 << shift;
|
||||
JpegDct.InverseReduced(block, quantization, output, n, 8, [], shift);
|
||||
for (var y = 0; y < n; y++)
|
||||
{
|
||||
for (var x = 0; x < n; x++)
|
||||
{
|
||||
double mean = 0;
|
||||
for (var dy = 0; dy < side; dy++)
|
||||
{
|
||||
for (var dx = 0; dx < side; dx++)
|
||||
{
|
||||
mean += full[(((y * side) + dy) * 8) + (x * side) + dx];
|
||||
}
|
||||
}
|
||||
|
||||
var expected = Math.Clamp((int)Math.Floor((mean / (side * side)) + 0.5), 0, 255);
|
||||
Assert.IsLessThanOrEqualTo(1, Math.Abs(expected - output[(y * n) + x]), $"giro {round}, 1/{side}, ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeAtLeastShrinksOnlyWhileTheLongSideIsEnough()
|
||||
{
|
||||
@@ -294,6 +362,84 @@ public sealed class ImageProcessingTests
|
||||
Assert.IsLessThanOrEqualTo(6, Math.Abs(back.GetPixel(63, 10).R - expected));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AProfileThatDoesNotDescribeRgbIsLeftBehind()
|
||||
{
|
||||
// Adobe CMYK, every pixel the same inks: the decoder writes RGB, so a CMYK profile no longer fits.
|
||||
const int width = 16;
|
||||
const int height = 8;
|
||||
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||
int[] Plane(int value) => Enumerable.Repeat(value, width * height).ToArray();
|
||||
var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, Plane(200)), (2, 1, 1, 0, Plane(120)), (3, 1, 1, 0, Plane(60)), (4, 1, 1, 0, Plane(230))], [fine], 0xC1);
|
||||
var cmykFile = WithIcc(JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 }), Profile(400, "CMYK"));
|
||||
Assert.AreEqual("CMYK", ImageConverter.IccColorSpace(JpegDecoder.Identify(cmykFile).Metadata.IccProfile));
|
||||
|
||||
// A grey JPEG with a grey profile: the encoders write RGB.
|
||||
using var scene = Scenes.Scene(8, 48, 32);
|
||||
var greyFile = JpegEncoder.Encode(scene, new JpegEncoderOptions { Grayscale = true, IccProfile = Profile(300, "GRAY") });
|
||||
|
||||
foreach (var (file, space) in new[] { (cmykFile, "CMYK"), (greyFile, "grigi") })
|
||||
{
|
||||
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP, ImageFormat.Jpeg })
|
||||
{
|
||||
var result = ImageConverter.Convert(file, target);
|
||||
var said = string.Join("; ", result.NotCarried);
|
||||
Assert.IsNull(result.Metadata.IccProfile, $"{space} in {target}");
|
||||
Assert.IsNull(result.Metadata.IccProfileName, $"{space} in {target}");
|
||||
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal) && n.Contains(space, StringComparison.Ordinal)), $"{space} in {target}: {said}");
|
||||
Assert.IsNull(ImageDecoder.Identify(result.Data).Metadata.IccProfile, $"{space} in {target}: il file scritto non ha il profilo");
|
||||
}
|
||||
}
|
||||
|
||||
// An RGB profile travels (the other converter tests check it byte for byte); one too short to have a
|
||||
// colour space does not.
|
||||
Assert.AreEqual("RGB ", ImageConverter.IccColorSpace(Profile(200)));
|
||||
Assert.IsNull(ImageConverter.IccColorSpace(new byte[12]));
|
||||
var garbled = JpegEncoder.Encode(scene, new JpegEncoderOptions { IccProfile = new byte[12] });
|
||||
var dropped = ImageConverter.Convert(garbled, ImageFormat.Png);
|
||||
Assert.IsNull(dropped.Metadata.IccProfile);
|
||||
Assert.IsTrue(dropped.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SixteenBitSamplesAndPngColourChunksAreReported()
|
||||
{
|
||||
// A 2×2 16-bit RGB PNG with gAMA and sRGB: decoded to 8 bits, so not lossless, and the colour chunks stay
|
||||
// behind; both are said.
|
||||
var raw = new byte[2 * (1 + (2 * 6))];
|
||||
for (var i = 0; i < raw.Length; i++)
|
||||
{
|
||||
raw[i] = i % 13 == 0 ? (byte)0 : (byte)(i * 37);
|
||||
}
|
||||
|
||||
var gamma = new byte[4];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(gamma, 45455);
|
||||
var png = TestImages.Png(("IHDR", TestImages.Ihdr(2, 2, 16, 2)), ("gAMA", gamma), ("sRGB", [0]), ("IDAT", TestImages.Zlib(raw)), ("IEND", []));
|
||||
var info = PngDecoder.Identify(png);
|
||||
Assert.AreEqual(16, info.BitsPerSample);
|
||||
CollectionAssert.AreEqual(new[] { "gAMA", "sRGB" }, info.Metadata.ColorChunks.ToArray());
|
||||
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP })
|
||||
{
|
||||
var result = ImageConverter.Convert(png, target);
|
||||
var said = string.Join("; ", result.NotCarried);
|
||||
Assert.IsTrue(result.Lossy, $"{target}: 16 bit diventano 8");
|
||||
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("16 bit", StringComparison.Ordinal)), said);
|
||||
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("gAMA", StringComparison.Ordinal)), said);
|
||||
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("sRGB", StringComparison.Ordinal)), said);
|
||||
}
|
||||
|
||||
// An 8-bit PNG without colour chunks converts losslessly and says nothing.
|
||||
var plain = PngEncoder.Encode(TestImages.Random(5, 4, 2, opaque: true));
|
||||
Assert.AreEqual(8, PngDecoder.Identify(plain).BitsPerSample);
|
||||
var clean = ImageConverter.Convert(plain, ImageFormat.WebP);
|
||||
Assert.IsFalse(clean.Lossy);
|
||||
Assert.IsEmpty(clean.NotCarried);
|
||||
|
||||
// The precision of a 12-bit JPEG is reported too.
|
||||
var twelve = JpegEncoder.TransformPlanes(8, 8, 12, [(1, 1, 1, 0, new int[64])], [Enumerable.Repeat((ushort)1, 64).ToArray()], 0xC1);
|
||||
Assert.AreEqual(12, JpegDecoder.Identify(JpegTestEncoder.Write(twelve, new JpegTestOptions())).BitsPerSample);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyJpegPngAndWebPAreWritten()
|
||||
{
|
||||
@@ -515,7 +661,8 @@ public sealed class ImageProcessingTests
|
||||
}
|
||||
|
||||
/// <summary>Bytes standing in for an ICC profile (the codecs carry it without reading it).</summary>
|
||||
private static byte[] Profile(int length)
|
||||
/// <summary>A stand-in ICC profile: arbitrary bytes with the data colour space of its header (bytes 16-19) set.</summary>
|
||||
private static byte[] Profile(int length, string colorSpace = "RGB ")
|
||||
{
|
||||
var bytes = new byte[length];
|
||||
for (var i = 0; i < length; i++)
|
||||
@@ -523,6 +670,19 @@ public sealed class ImageProcessingTests
|
||||
bytes[i] = (byte)((i * 7) + (i >> 3));
|
||||
}
|
||||
|
||||
Encoding.ASCII.GetBytes(colorSpace, bytes.AsSpan(16, 4));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI.</summary>
|
||||
private static byte[] WithIcc(byte[] jpeg, byte[] profile)
|
||||
{
|
||||
byte[] payload = [.. Encoding.ASCII.GetBytes("ICC_PROFILE"), 0, 1, 1, .. profile];
|
||||
var segment = new byte[4 + payload.Length];
|
||||
segment[0] = 0xFF;
|
||||
segment[1] = 0xE2;
|
||||
BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), (ushort)(payload.Length + 2));
|
||||
payload.CopyTo(segment, 4);
|
||||
return [.. jpeg.AsSpan(0, 2), .. segment, .. jpeg.AsSpan(2)];
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,42 @@ public sealed class ImagingBaseTests
|
||||
var owned = new RgbaImage(1, 1);
|
||||
owned.Dispose();
|
||||
Assert.AreEqual(4, owned.Pixels.Length);
|
||||
|
||||
// A picture above 16 MiB is rented as a plain array, not from the pool, and still starts clear.
|
||||
var large = RgbaImage.Rent(2100, 2100);
|
||||
Assert.IsTrue(large.IsPooled);
|
||||
Assert.IsTrue(large.Pixels.IndexOfAnyExcept((byte)0) < 0);
|
||||
large.Dispose();
|
||||
Assert.ThrowsExactly<ObjectDisposedException>(() => large.GetRow(0).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LargeWorkingArraysDoNotStayInTheSharedPool()
|
||||
{
|
||||
// Up to 16 MiB the shared pool, rounded up to a power of two; above, an array of exactly the size asked,
|
||||
// which the pool would otherwise round to the next power of two and keep after it was given back.
|
||||
var small = ImageBuffers.Rent<byte>(1000);
|
||||
Assert.AreEqual(1024, small.Length);
|
||||
Assert.IsTrue(ImageBuffers.IsPooled(small));
|
||||
ImageBuffers.Return(small);
|
||||
|
||||
var limit = ImageBuffers.Rent<byte>(ImageBuffers.PooledBytes);
|
||||
Assert.AreEqual(ImageBuffers.PooledBytes, limit.Length);
|
||||
Assert.IsTrue(ImageBuffers.IsPooled(limit));
|
||||
ImageBuffers.Return(limit);
|
||||
|
||||
var large = ImageBuffers.Rent<byte>(ImageBuffers.PooledBytes + 1);
|
||||
Assert.AreEqual(ImageBuffers.PooledBytes + 1, large.Length, "non arrotondato a 32 MiB: non viene dal pool");
|
||||
Assert.IsFalse(ImageBuffers.IsPooled(large));
|
||||
ImageBuffers.Return(large); // left to the collector: the pool would refuse an array it did not give
|
||||
|
||||
// The threshold is in bytes, whatever the element.
|
||||
var shorts = ImageBuffers.Rent<short>((ImageBuffers.PooledBytes / 2) + 1);
|
||||
Assert.AreEqual((ImageBuffers.PooledBytes / 2) + 1, shorts.Length);
|
||||
ImageBuffers.Return(shorts);
|
||||
var words = ImageBuffers.Rent<uint>(1000);
|
||||
Assert.AreEqual(1024, words.Length);
|
||||
ImageBuffers.Return(words);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -40,6 +40,30 @@ public sealed class JpegMalformedTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AFileCutAfterItsHeadersFailsAtTheFirstMcuRow()
|
||||
{
|
||||
// Headers of 8192×8192 (64 megapixels, within the default limits) and not one byte of the scan. The reader
|
||||
// gives zero bits past the end, which are valid codes of the Annex K tables, so before the check per MCU row
|
||||
// the decoder went through all 262,144 MCUs (seconds of IDCT) before failing; now it stops after one row.
|
||||
foreach (var lossless in new[] { false, true })
|
||||
{
|
||||
var file = lossless ? JpegTestEncoder.WriteLossless(16, 16, 8, [(1, 1, 1, new int[256])], 1, 0, new JpegTestOptions()) : Baseline(16, 16);
|
||||
var sof = SegmentOffset(file, lossless ? 0xC3 : 0xC0);
|
||||
var sos = SegmentOffset(file, 0xDA);
|
||||
var headers = file[..(sos + 2 + ((file[sos + 2] << 8) | file[sos + 3]))];
|
||||
headers[sof + 5] = headers[sof + 7] = 0x20;
|
||||
headers[sof + 6] = headers[sof + 8] = 0x00;
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(headers), lossless ? "senza perdita" : "base");
|
||||
clock.Stop();
|
||||
StringAssert.Contains(error.Message, "troncato");
|
||||
|
||||
// Planes of 64 MB are still allocated; decoding every MCU took several seconds even in Release.
|
||||
Assert.IsLessThan(2000, clock.ElapsedMilliseconds, $"{(lossless ? "senza perdita" : "base")}: {clock.ElapsedMilliseconds} ms");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BytesAfterTheEndAreIgnored()
|
||||
{
|
||||
@@ -141,11 +165,15 @@ public sealed class JpegMalformedTests
|
||||
// No quantization table.
|
||||
AssertDamaged(RemoveSegments(file, 0xDB), "senza DQT");
|
||||
|
||||
// A Huffman table with more codes than its lengths allow (two codes of length 1, then more).
|
||||
// A Huffman table with more codes than its lengths allow; the total stays that of the segment's values, so
|
||||
// the error is the oversubscription itself and not a truncated segment.
|
||||
var dht = SegmentOffset(file, 0xC4);
|
||||
var badTable = file.ToArray();
|
||||
// The luminance DC table counts 0,1,5,1,1,...: three codes of length 1, none of length 2, three of length 3.
|
||||
badTable[dht + 5] = 3;
|
||||
AssertDamaged(badTable, "tabella di Huffman impossibile");
|
||||
badTable[dht + 6] = 0;
|
||||
badTable[dht + 7] = 3;
|
||||
AssertOversubscribed(badTable, "tabella di Huffman impossibile");
|
||||
|
||||
// A segment length that runs past the end.
|
||||
var longSegment = file.ToArray();
|
||||
@@ -158,6 +186,63 @@ public sealed class JpegMalformedTests
|
||||
AssertDamaged(file[..sos], "senza scansioni");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OversubscribedHuffmanTablesAreRefusedAtEveryLength()
|
||||
{
|
||||
// One code of each length below L leaves room for two codes of length L; three overflow it. The symbols
|
||||
// match the counts, so only the oversubscription can be at fault. Lengths up to 9 used to index past the
|
||||
// lookup table and threw ArgumentOutOfRangeException.
|
||||
for (var length = 1; length <= 16; length++)
|
||||
{
|
||||
var counts = new byte[16];
|
||||
for (var shorter = 1; shorter < length; shorter++)
|
||||
{
|
||||
counts[shorter - 1] = 1;
|
||||
}
|
||||
|
||||
counts[length - 1] = 3;
|
||||
Assert.IsTrue(Oversubscribed(counts), $"lunghezza {length}");
|
||||
var values = new byte[length + 2];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
values[i] = (byte)i;
|
||||
}
|
||||
|
||||
var error = Assert.ThrowsExactly<ImageDecodeException>(() => JpegHuffmanTable.Build(counts, values), $"lunghezza {length}");
|
||||
StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", $"lunghezza {length}");
|
||||
|
||||
// Two codes of length L fill the code space exactly and are valid.
|
||||
counts[length - 1] = 2;
|
||||
_ = JpegHuffmanTable.Build(counts, values.AsSpan(0, length + 1));
|
||||
}
|
||||
|
||||
// Three codes of length 1 (the case of the review) and a full table that is still valid.
|
||||
var three = new byte[16];
|
||||
three[0] = 3;
|
||||
Assert.ThrowsExactly<ImageDecodeException>(() => JpegHuffmanTable.Build(three, [0, 1, 2]));
|
||||
var full = new byte[16];
|
||||
full[0] = 1;
|
||||
full[1] = 2;
|
||||
_ = JpegHuffmanTable.Build(full, [0, 1, 2]);
|
||||
}
|
||||
|
||||
private static bool Oversubscribed(byte[] counts)
|
||||
{
|
||||
long code = 0;
|
||||
for (var length = 1; length <= 16; length++)
|
||||
{
|
||||
code += counts[length - 1];
|
||||
if (code > 1L << length)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
code <<= 1;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLimitsAreEnforcedBeforeDecoding()
|
||||
{
|
||||
@@ -306,6 +391,12 @@ public sealed class JpegMalformedTests
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what);
|
||||
}
|
||||
|
||||
private static void AssertOversubscribed(byte[] file, string what)
|
||||
{
|
||||
var error = Assert.ThrowsExactly<ImageDecodeException>(() => JpegDecoder.Decode(file), what);
|
||||
StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", what);
|
||||
}
|
||||
|
||||
/// <summary>Offset of the first marker segment of type <paramref name="marker"/> (the 0xFF byte).</summary>
|
||||
private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0];
|
||||
|
||||
|
||||
@@ -152,6 +152,46 @@ public sealed class Vp8BitstreamTests
|
||||
Assert.IsFalse(plain.Y.AsSpan().SequenceEqual(different.Y));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AFrameLevelOfZeroTurnsTheFilterOffWhateverSegmentsAndDeltasSay()
|
||||
{
|
||||
var mbs = Vp8TestWriter.Random(5 * 4, seed: 36);
|
||||
var none = Planes(new Vp8TestWriter { Width = 80, Height = 64 }.Write(mbs));
|
||||
|
||||
// Absolute segment strengths above zero, relative ones above zero, and positive ref/mode deltas: with
|
||||
// loop_filter_level 0 the reference decoders filter nothing.
|
||||
var absolute = new Vp8TestWriter
|
||||
{
|
||||
Width = 80,
|
||||
Height = 64,
|
||||
Segmentation = true,
|
||||
UpdateMap = true,
|
||||
AbsoluteDeltas = true,
|
||||
SegmentQuant = [40, 40, 40, 40], // the base quantizer, as absolute values
|
||||
SegmentFilter = [20, 35, 50, 63],
|
||||
};
|
||||
var relative = new Vp8TestWriter { Width = 80, Height = 64, Segmentation = true, UpdateMap = true, SegmentFilter = [20, 35, 50, 63] };
|
||||
var deltas = new Vp8TestWriter { Width = 80, Height = 64, RefLfDelta = [30, 0, 0, 0], ModeLfDelta = [30, 0, 0, 0] };
|
||||
foreach (var (writer, what) in new[] { (absolute, "segmenti assoluti"), (relative, "segmenti relativi"), (deltas, "differenze") })
|
||||
{
|
||||
AssertSamePlanes(none, Planes(writer.Write(mbs)), what);
|
||||
}
|
||||
|
||||
// The same segment strengths with a frame level above zero do filter.
|
||||
var filtered = Planes(new Vp8TestWriter
|
||||
{
|
||||
Width = 80,
|
||||
Height = 64,
|
||||
FilterLevel = 1,
|
||||
Segmentation = true,
|
||||
UpdateMap = true,
|
||||
AbsoluteDeltas = true,
|
||||
SegmentQuant = [40, 40, 40, 40],
|
||||
SegmentFilter = [20, 35, 50, 63],
|
||||
}.Write(mbs));
|
||||
Assert.IsFalse(none.Y.AsSpan().SequenceEqual(filtered.Y), "con un livello del fotogramma il filtro lavora");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FilterDeltasMoveTheLevel()
|
||||
{
|
||||
|
||||
@@ -398,6 +398,131 @@ public sealed class WebPContainerTests
|
||||
})));
|
||||
}
|
||||
|
||||
[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()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user