Files
Febe/tests/Febe.Tests/Imaging/ImageFuzzTests.cs
T
Alby96andClaude Opus 5.5 36196526bb Lettore e scrittore JPEG di casa (C1, passo 3)
Febe deve leggere e scrivere JPEG senza SkiaSharp né altri componenti
esterni (decisione del 18 novembre 2026), quindi il codec è scritto dalla
specifica ITU-T T.81.

Lettore (JpegDecoder): sequenziale di base ed esteso, progressivo (selezione
spettrale e approssimazioni successive), senza perdita (predittori 1-7),
ognuno con Huffman e con codifica aritmetica; 8 e 12 bit (senza perdita da 2
a 16); qualunque campionamento, ripristino, DNL; grigio, YCbCr, RGB, CMYK e
YCCK con il segmento Adobe. IDCT esatta e crominanza con il filtro
triangolare. EXIF, ICC a pezzi, XMP e commenti; l'orientamento EXIF va in
ImageMetadata.Orientation (anche per PNG) e non si applica ai pixel. I file
gerarchici e quelli a 2 componenti si rifiutano come formato non letto; i
dati troncati dentro una scansione sono un file danneggiato.

Scrittore (JpegEncoder): sequenziale di base, qualità 1-100 sulle tabelle
dell'allegato K, 4:2:0, 4:4:4 e grigio, intervallo di ripristino, EXIF, ICC,
XMP e commenti.

Prove: contro le letture di SkiaSharp i JPEG dell'insieme di riferimento
stanno fra 59 e 67 dB di PSNR per canale, scarto massimo 3 (soglia 40 dB e
0,1% di pixel oltre 16). Un codificatore di prova scrive gli stessi
coefficienti in progressivo, aritmetico, 12 bit, con ripristino, scansioni
separate e DNL, e il lettore deve ridarli identici; senza perdita si
confronta campione per campione. Più andata e ritorno dello scrittore, file
danneggiati e mutazioni casuali con seme fisso. La facciata ImageDecoder
ora legge i JPEG.

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

129 lines
3.9 KiB
C#

using Febe.Core.Codecs.Images;
namespace Febe.Tests.Imaging;
/// <summary>
/// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws
/// <see cref="ImageDecodeException"/>, never anything else (no index out of range, no overflow, no huge allocation).
/// </summary>
[TestClass]
public sealed class ImageFuzzTests
{
private const int MutationsPerFile = 120;
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
public static IEnumerable<object[]> Formats =>
[
[ReferenceFormat.Png],
[ReferenceFormat.Gif],
[ReferenceFormat.Bmp],
[ReferenceFormat.Jpeg],
];
[TestMethod]
[DynamicData(nameof(Formats))]
public void ChangedBytesNeverBreakTheDecoder(ReferenceFormat format)
{
var seed = 1000 + (int)format;
foreach (var reference in ReferenceImages.Of(format))
{
var original = reference.ReadInput();
var random = new Random(seed++);
for (var i = 0; i < MutationsPerFile; i++)
{
var mutated = Mutate(original, random);
if (format == ReferenceFormat.Png && random.Next(3) > 0)
{
// Most changes to a PNG only meet a wrong CRC: fixing it lets them reach the pixels.
TestImages.FixPngCrcs(mutated);
}
TryDecode(mutated, $"{reference.Name}, modifica {i}");
}
}
}
[TestMethod]
public void ChangedBytesNeverBreakTheFacade()
{
var random = new Random(77);
foreach (var reference in ReferenceImages.All)
{
var mutated = Mutate(reference.ReadInput(), random);
try
{
using var image = ImageDecoder.Decode(mutated, Small);
ImageDecoder.Identify(mutated, Small);
}
catch (ImageDecodeException)
{
}
}
}
private static void TryDecode(byte[] bytes, string what)
{
try
{
using var image = ImageDecoder.Decode(bytes, Small);
Assert.IsGreaterThan(0, image.Width, what);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
try
{
ImageDecoder.Identify(bytes, Small);
}
catch (ImageDecodeException)
{
}
catch (Exception ex)
{
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
}
private static byte[] Mutate(byte[] original, Random random)
{
var bytes = original.ToArray();
switch (random.Next(4))
{
case 0:
// A few random bytes anywhere after the signature.
for (var k = random.Next(1, 9); k > 0; k--)
{
bytes[random.Next(Math.Min(8, bytes.Length - 1), bytes.Length)] = (byte)random.Next(256);
}
return bytes;
case 1:
// A byte of the headers set to an extreme.
bytes[random.Next(Math.Min(8, bytes.Length - 1), Math.Min(bytes.Length, 80))] = random.Next(2) == 0 ? (byte)0 : (byte)0xFF;
return bytes;
case 2:
// Cut short.
return bytes[..random.Next(1, bytes.Length)];
default:
// A run of bytes flipped.
var start = random.Next(8, bytes.Length);
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
for (var k = 0; k < length; k++)
{
bytes[start + k] ^= 0x5A;
}
return bytes;
}
}
}