Immagini di riferimento per i codec di casa (C1, passo 1)
SkiaSharp esce da Febe: prima di toglierlo serve un termine di confronto per i lettori PNG, JPEG, WebP, GIF e BMP scritti in casa, e dopo non si potrà più generarlo. In tests/Febe.Tests/Imaging/Riferimenti ci sono 57 casi (ingresso più .atteso.png, la lettura RGBA a 8 bit non premoltiplicata di SkiaSharp 4.153.1), generati una volta sola con il permesso di Alberto da un programma usa e getta fuori dal repository; contenuto solo sintetico. Le immagini attese sono PNG scritti a mano (filtro 0, un solo IDAT), così le leggerà il lettore PNG di casa del passo 2. LEGGIMI.md dice come sono fatte, quali casi sono costruiti a mano dalle specifiche e che cosa manca (JPEG progressivo, intervalli di ripristino, CMYK/Adobe: codificatori di prova nostri dalla T.81). ReferenceImages carica l'elenco; ReferenceSetTests controlla l'integrità dell'insieme (nessun file in più o in meno, firme, misure, orientamento EXIF, CRC dei blocchi PNG, JPEG solo base) senza leggere i pixel. Le estensioni delle immagini sono binarie in .gitattributes; una riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No files matched your search
@@ -19,5 +19,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="campioni\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
<!-- Immagini di riferimento dei codec di casa (Imaging/Riferimenti/LEGGIMI.md). -->
|
||||
<None Include="Imaging\Riferimenti\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,170 @@
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>The format of a reference case's input file, from its extension.</summary>
|
||||
public enum ReferenceFormat
|
||||
{
|
||||
Png,
|
||||
Jpeg,
|
||||
WebP,
|
||||
Gif,
|
||||
Bmp,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One case of the reference set in Imaging/Riferimenti (see LEGGIMI.md there): an input file and, beside it,
|
||||
/// «<see cref="Name"/>.atteso.png», SkiaSharp's straight (unpremultiplied) RGBA8 decode of it, upright.
|
||||
/// </summary>
|
||||
/// <param name="Folder">The folder of the set.</param>
|
||||
/// <param name="Name">The case name, as elenco.txt lists it.</param>
|
||||
/// <param name="Format">The format of the input file.</param>
|
||||
/// <param name="InputFileName">The input file name, inside <paramref name="Folder"/>.</param>
|
||||
/// <param name="Width">Width of the expected image (after the EXIF orientation, for a JPEG that has one).</param>
|
||||
/// <param name="Height">Height of the expected image (after the EXIF orientation, for a JPEG that has one).</param>
|
||||
public sealed record ReferenceCase(string Folder, string Name, ReferenceFormat Format, string InputFileName, int Width, int Height)
|
||||
{
|
||||
/// <summary>Full path of the input file.</summary>
|
||||
public string InputPath => Path.Combine(Folder, InputFileName);
|
||||
|
||||
/// <summary>Full path of the expected image («.atteso.png»).</summary>
|
||||
public string ExpectedPath => Path.Combine(Folder, Name + ReferenceImages.ExpectedSuffix);
|
||||
|
||||
/// <summary>
|
||||
/// The EXIF orientation (1-8) the input carries by construction: only the «jpeg-orientamento-N» cases have one.
|
||||
/// The integrity test checks it against the file.
|
||||
/// </summary>
|
||||
public int Orientation =>
|
||||
Name.StartsWith(ReferenceImages.OrientationPrefix, StringComparison.Ordinal)
|
||||
? int.Parse(Name.AsSpan(ReferenceImages.OrientationPrefix.Length), System.Globalization.CultureInfo.InvariantCulture)
|
||||
: 1;
|
||||
|
||||
/// <summary>Width of the image as stored in the input file (orientations 5-8 swap the two sides).</summary>
|
||||
public int StoredWidth => Orientation >= 5 ? Height : Width;
|
||||
|
||||
/// <summary>Height of the image as stored in the input file (orientations 5-8 swap the two sides).</summary>
|
||||
public int StoredHeight => Orientation >= 5 ? Width : Height;
|
||||
|
||||
/// <summary>The bytes of the input file.</summary>
|
||||
public byte[] ReadInput() => File.ReadAllBytes(InputPath);
|
||||
|
||||
/// <summary>
|
||||
/// The bytes of the expected image: an 8-bit RGBA PNG (colour type 6), one filter-0 row after the other in a single
|
||||
/// zlib stream. From step 2 of track C1 Febe's own PNG decoder reads it; SkiaSharp is no longer needed for that.
|
||||
/// </summary>
|
||||
public byte[] ReadExpectedPng() => File.ReadAllBytes(ExpectedPath);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
/// <summary>Loads the reference set of the in-house image codecs from the test output folder.</summary>
|
||||
public static class ReferenceImages
|
||||
{
|
||||
/// <summary>Suffix of the expected images.</summary>
|
||||
public const string ExpectedSuffix = ".atteso.png";
|
||||
|
||||
/// <summary>The list of the cases, one «name WxH» per line.</summary>
|
||||
public const string ListFileName = "elenco.txt";
|
||||
|
||||
/// <summary>The description of the set.</summary>
|
||||
public const string ReadmeFileName = "LEGGIMI.md";
|
||||
|
||||
/// <summary>Name prefix of the JPEG cases with an EXIF orientation.</summary>
|
||||
public const string OrientationPrefix = "jpeg-orientamento-";
|
||||
|
||||
private static readonly (string Extension, ReferenceFormat Format)[] InputExtensions =
|
||||
[
|
||||
(".png", ReferenceFormat.Png),
|
||||
(".jpg", ReferenceFormat.Jpeg),
|
||||
(".webp", ReferenceFormat.WebP),
|
||||
(".gif", ReferenceFormat.Gif),
|
||||
(".bmp", ReferenceFormat.Bmp),
|
||||
];
|
||||
|
||||
/// <summary>The folder of the set in the test output (copied there by Febe.Tests.csproj).</summary>
|
||||
public static string Folder { get; } = Path.Combine(AppContext.BaseDirectory, "Imaging", "Riferimenti");
|
||||
|
||||
private static readonly Lazy<IReadOnlyList<ReferenceCase>> Cases = new(() => Load(Folder));
|
||||
|
||||
/// <summary>Every case, in the order of elenco.txt.</summary>
|
||||
public static IReadOnlyList<ReferenceCase> All => Cases.Value;
|
||||
|
||||
/// <summary>The case with that name.</summary>
|
||||
public static ReferenceCase Get(string name)
|
||||
{
|
||||
foreach (var reference in All)
|
||||
{
|
||||
if (reference.Name == name)
|
||||
{
|
||||
return reference;
|
||||
}
|
||||
}
|
||||
|
||||
throw new KeyNotFoundException($"No reference case named '{name}' in {ListFileName}.");
|
||||
}
|
||||
|
||||
/// <summary>The cases whose input has that format.</summary>
|
||||
public static IEnumerable<ReferenceCase> Of(ReferenceFormat format) => All.Where(c => c.Format == format);
|
||||
|
||||
/// <summary>
|
||||
/// The case names of a format, for <c>[DynamicData]</c>: the test receives the name and calls <see cref="Get"/>,
|
||||
/// so each case shows up as its own row in the results.
|
||||
/// </summary>
|
||||
public static IEnumerable<object[]> NamesOf(ReferenceFormat format) => Of(format).Select(c => new object[] { c.Name });
|
||||
|
||||
/// <summary>The input formats, with their extensions.</summary>
|
||||
public static IReadOnlyList<(string Extension, ReferenceFormat Format)> Extensions => InputExtensions;
|
||||
|
||||
/// <summary>Reads elenco.txt in <paramref name="folder"/> and finds the input file of every case.</summary>
|
||||
public static IReadOnlyList<ReferenceCase> Load(string folder)
|
||||
{
|
||||
var list = new List<ReferenceCase>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var lineNumber = 0;
|
||||
foreach (var rawLine in File.ReadLines(Path.Combine(folder, ListFileName)))
|
||||
{
|
||||
lineNumber++;
|
||||
var line = rawLine.Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var parts = line.Split(' ');
|
||||
var size = parts.Length == 2 ? parts[1].Split('x') : [];
|
||||
if (size.Length != 2
|
||||
|| !int.TryParse(size[0], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var width)
|
||||
|| !int.TryParse(size[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var height)
|
||||
|| width <= 0
|
||||
|| height <= 0)
|
||||
{
|
||||
throw new InvalidDataException($"{ListFileName}, line {lineNumber}: expected 'name WxH', found '{line}'.");
|
||||
}
|
||||
|
||||
var name = parts[0];
|
||||
if (!seen.Add(name))
|
||||
{
|
||||
throw new InvalidDataException($"{ListFileName}, line {lineNumber}: '{name}' is listed twice.");
|
||||
}
|
||||
|
||||
ReferenceCase? found = null;
|
||||
foreach (var (extension, format) in InputExtensions)
|
||||
{
|
||||
if (!File.Exists(Path.Combine(folder, name + extension)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (found is not null)
|
||||
{
|
||||
throw new InvalidDataException($"'{name}' has more than one input file.");
|
||||
}
|
||||
|
||||
found = new ReferenceCase(folder, name, format, name + extension, width, height);
|
||||
}
|
||||
|
||||
list.Add(found ?? throw new FileNotFoundException($"'{name}' has no input file in {folder}."));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>
|
||||
/// Integrity of the reference set in Imaging/Riferimenti: every listed file is there and nothing else, each input starts
|
||||
/// with the magic of its format and has the listed size, each expected image is a well-formed straight RGBA8 PNG of the
|
||||
/// listed size. The pixels are not read here: Febe's own PNG decoder (step 2 of track C1) will read them, without
|
||||
/// SkiaSharp.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ReferenceSetTests
|
||||
{
|
||||
/// <summary>The number of cases SkiaSharp's references were made for (LEGGIMI.md lists them).</summary>
|
||||
private const int CaseCount = 57;
|
||||
|
||||
[TestMethod]
|
||||
public void TheListNamesEveryFileOfTheFolderAndNothingElse()
|
||||
{
|
||||
var cases = ReferenceImages.All;
|
||||
Assert.HasCount(CaseCount, cases);
|
||||
|
||||
var expectedFiles = new HashSet<string>(StringComparer.Ordinal) { ReferenceImages.ListFileName, ReferenceImages.ReadmeFileName };
|
||||
foreach (var reference in cases)
|
||||
{
|
||||
Assert.IsTrue(expectedFiles.Add(reference.InputFileName), $"{reference.Name}: input listed twice.");
|
||||
Assert.IsTrue(expectedFiles.Add(reference.Name + ReferenceImages.ExpectedSuffix), $"{reference.Name}: expected image listed twice.");
|
||||
Assert.IsTrue(File.Exists(reference.ExpectedPath), $"{reference.Name}: the expected image is missing.");
|
||||
}
|
||||
|
||||
var actualFiles = Directory.EnumerateFiles(ReferenceImages.Folder, "*", SearchOption.AllDirectories)
|
||||
.Select(path => Path.GetRelativePath(ReferenceImages.Folder, path))
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
CollectionAssert.AreEquivalent(expectedFiles.Order(StringComparer.Ordinal).ToList(), actualFiles.Order(StringComparer.Ordinal).ToList());
|
||||
|
||||
foreach (var (_, format) in ReferenceImages.Extensions)
|
||||
{
|
||||
Assert.IsTrue(ReferenceImages.Of(format).Any(), $"No case for {format}.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheListIsReadTheSameWithWindowsLineEnds()
|
||||
{
|
||||
// A checkout with core.autocrlf must not change what the list says (.gitattributes also keeps it LF).
|
||||
var folder = Path.Combine(Path.GetTempPath(), "febe-riferimenti-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(folder);
|
||||
try
|
||||
{
|
||||
var listed = File.ReadAllText(Path.Combine(ReferenceImages.Folder, ReferenceImages.ListFileName));
|
||||
File.WriteAllText(Path.Combine(folder, ReferenceImages.ListFileName), listed.ReplaceLineEndings("\r\n"));
|
||||
foreach (var reference in ReferenceImages.All)
|
||||
{
|
||||
File.WriteAllBytes(Path.Combine(folder, reference.InputFileName), []);
|
||||
}
|
||||
|
||||
var again = ReferenceImages.Load(folder);
|
||||
CollectionAssert.AreEqual(
|
||||
ReferenceImages.All.Select(c => (c.Name, c.Format, c.Width, c.Height)).ToList(),
|
||||
again.Select(c => (c.Name, c.Format, c.Width, c.Height)).ToList());
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryInputStartsWithTheMagicOfItsFormatAndHasTheListedSize()
|
||||
{
|
||||
foreach (var reference in ReferenceImages.All)
|
||||
{
|
||||
var bytes = reference.ReadInput();
|
||||
var (width, height) = reference.Format switch
|
||||
{
|
||||
ReferenceFormat.Png => PngSize(reference.Name, bytes),
|
||||
ReferenceFormat.Jpeg => JpegSize(reference, bytes),
|
||||
ReferenceFormat.WebP => WebPSize(reference.Name, bytes),
|
||||
ReferenceFormat.Gif => GifSize(reference.Name, bytes),
|
||||
ReferenceFormat.Bmp => BmpSize(reference.Name, bytes),
|
||||
_ => throw new AssertFailedException($"{reference.Name}: unknown format."),
|
||||
};
|
||||
Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (width, height), $"{reference.Name}: size of the input.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryExpectedImageIsAStraightRgba8PngWithTheListedSize()
|
||||
{
|
||||
foreach (var reference in ReferenceImages.All)
|
||||
{
|
||||
var bytes = reference.ReadExpectedPng();
|
||||
var chunks = PngChunks(reference.Name + ReferenceImages.ExpectedSuffix, bytes);
|
||||
var types = chunks.Select(c => c.Type).Distinct().ToList();
|
||||
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "IEND" }, types, $"{reference.Name}: only IHDR, IDAT and IEND, in this order.");
|
||||
|
||||
var ihdr = bytes.AsSpan(chunks[0].Offset, chunks[0].Length);
|
||||
Assert.AreEqual(13, ihdr.Length, $"{reference.Name}: IHDR length.");
|
||||
Assert.AreEqual(reference.Width, BinaryPrimitives.ReadInt32BigEndian(ihdr), $"{reference.Name}: width.");
|
||||
Assert.AreEqual(reference.Height, BinaryPrimitives.ReadInt32BigEndian(ihdr[4..]), $"{reference.Name}: height.");
|
||||
Assert.AreEqual(8, ihdr[8], $"{reference.Name}: bit depth.");
|
||||
Assert.AreEqual(6, ihdr[9], $"{reference.Name}: colour type (RGBA).");
|
||||
Assert.AreEqual(0, ihdr[10] | ihdr[11] | ihdr[12], $"{reference.Name}: compression, filter method and interlace.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheJpegInputsAreBaselineWithoutRestartIntervalsOrAdobeColour()
|
||||
{
|
||||
// LEGGIMI.md says progressive JPEG, restart intervals and CMYK/Adobe have no SkiaSharp reference: they are covered
|
||||
// by our own encoders in the JPEG tests. This keeps that sentence true if the set is ever regenerated.
|
||||
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
|
||||
{
|
||||
foreach (var (marker, _, _) in JpegSegments(reference.Name, reference.ReadInput()))
|
||||
{
|
||||
Assert.IsFalse(marker is >= 0xC1 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC, $"{reference.Name}: SOF marker FF{marker:X2}, not baseline.");
|
||||
Assert.AreNotEqual(0xDD, marker, $"{reference.Name}: restart interval (DRI).");
|
||||
Assert.AreNotEqual(0xEE, marker, $"{reference.Name}: Adobe segment (APP14).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSetStaysSmall()
|
||||
{
|
||||
long total = 0;
|
||||
foreach (var path in Directory.EnumerateFiles(ReferenceImages.Folder))
|
||||
{
|
||||
var length = new FileInfo(path).Length;
|
||||
Assert.IsGreaterThan(0L, length, $"{Path.GetFileName(path)} is empty.");
|
||||
Assert.IsLessThan(512L * 1024, length, $"{Path.GetFileName(path)} is larger than 512 KiB.");
|
||||
total += length;
|
||||
}
|
||||
|
||||
Assert.IsLessThan(4L * 1024 * 1024, total, "The whole set should stay under 4 MiB.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCrcOfTheChecksIsTheOneOfThePngSpecification()
|
||||
{
|
||||
// PNG specification, annex D: the CRC of "IEND" with no data.
|
||||
Assert.AreEqual(0xAE426082u, Crc32("IEND"u8, []));
|
||||
}
|
||||
|
||||
private static (int Width, int Height) PngSize(string name, byte[] bytes)
|
||||
{
|
||||
var chunks = PngChunks(name, bytes);
|
||||
Assert.AreEqual("IHDR", chunks[0].Type, $"{name}: the first chunk.");
|
||||
var ihdr = bytes.AsSpan(chunks[0].Offset, chunks[0].Length);
|
||||
return (BinaryPrimitives.ReadInt32BigEndian(ihdr), BinaryPrimitives.ReadInt32BigEndian(ihdr[4..]));
|
||||
}
|
||||
|
||||
/// <summary>Walks the chunks of a PNG, checking signature, lengths, CRCs and that IEND ends the file.</summary>
|
||||
private static List<(string Type, int Offset, int Length)> PngChunks(string name, byte[] bytes)
|
||||
{
|
||||
ReadOnlySpan<byte> signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
Assert.IsTrue(bytes.AsSpan().StartsWith(signature), $"{name}: PNG signature.");
|
||||
var chunks = new List<(string, int, int)>();
|
||||
var position = signature.Length;
|
||||
while (true)
|
||||
{
|
||||
Assert.IsLessThanOrEqualTo(bytes.Length, position + 12, $"{name}: truncated chunk at {position}.");
|
||||
var length = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(position));
|
||||
Assert.IsTrue(length >= 0 && position + 12 + (long)length <= bytes.Length, $"{name}: chunk length at {position}.");
|
||||
var type = bytes.AsSpan(position + 4, 4);
|
||||
var data = bytes.AsSpan(position + 8, length);
|
||||
var crc = BinaryPrimitives.ReadUInt32BigEndian(bytes.AsSpan(position + 8 + length));
|
||||
var typeName = Encoding.ASCII.GetString(type);
|
||||
Assert.AreEqual(Crc32(type, data), crc, $"{name}: CRC of {typeName} at {position}.");
|
||||
chunks.Add((typeName, position + 8, length));
|
||||
position += 12 + length;
|
||||
if (typeName == "IEND")
|
||||
{
|
||||
Assert.AreEqual(0, length, $"{name}: IEND has no data.");
|
||||
Assert.AreEqual(bytes.Length, position, $"{name}: bytes after IEND.");
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static (int Width, int Height) JpegSize(ReferenceCase reference, byte[] bytes)
|
||||
{
|
||||
var name = reference.Name;
|
||||
Assert.IsTrue(bytes is [0xFF, 0xD8, ..] && bytes[^2] == 0xFF && bytes[^1] == 0xD9, $"{name}: SOI at the start and EOI at the end.");
|
||||
(int, int)? size = null;
|
||||
var orientation = 1;
|
||||
foreach (var (marker, offset, length) in JpegSegments(name, bytes))
|
||||
{
|
||||
var segment = bytes.AsSpan(offset, length);
|
||||
if (marker == 0xC0)
|
||||
{
|
||||
Assert.IsNull(size, $"{name}: more than one SOF.");
|
||||
size = (BinaryPrimitives.ReadUInt16BigEndian(segment[3..]), BinaryPrimitives.ReadUInt16BigEndian(segment[1..]));
|
||||
}
|
||||
else if (marker == 0xE1 && segment.StartsWith("Exif\0\0"u8))
|
||||
{
|
||||
orientation = ExifOrientation(name, segment[6..]);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(reference.Orientation, orientation, $"{name}: EXIF orientation.");
|
||||
return size ?? throw new AssertFailedException($"{name}: no baseline SOF.");
|
||||
}
|
||||
|
||||
/// <summary>The marker segments of a JPEG up to the start of scan: marker, offset and length of the payload.</summary>
|
||||
private static List<(byte Marker, int Offset, int Length)> JpegSegments(string name, byte[] bytes)
|
||||
{
|
||||
var segments = new List<(byte, int, int)>();
|
||||
var position = 2;
|
||||
while (true)
|
||||
{
|
||||
Assert.IsLessThanOrEqualTo(bytes.Length, position + 4, $"{name}: truncated before the start of scan.");
|
||||
Assert.AreEqual(0xFF, bytes[position], $"{name}: marker expected at {position}.");
|
||||
var marker = bytes[position + 1];
|
||||
var length = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(position + 2));
|
||||
Assert.IsTrue(length >= 2 && position + 2 + length <= bytes.Length, $"{name}: segment length at {position}.");
|
||||
segments.Add((marker, position + 4, length - 2));
|
||||
if (marker == 0xDA)
|
||||
{
|
||||
return segments;
|
||||
}
|
||||
|
||||
position += 2 + length;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Orientation tag (0x0112) of IFD0 of an EXIF TIFF block, 1 when absent.</summary>
|
||||
private static int ExifOrientation(string name, ReadOnlySpan<byte> tiff)
|
||||
{
|
||||
var bigEndian = tiff.StartsWith("MM"u8);
|
||||
Assert.IsTrue(bigEndian || tiff.StartsWith("II"u8), $"{name}: TIFF byte order.");
|
||||
int U16(ReadOnlySpan<byte> s) => bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s);
|
||||
var ifd = (int)(bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(tiff[4..]) : BinaryPrimitives.ReadUInt32LittleEndian(tiff[4..]));
|
||||
Assert.AreEqual(42, U16(tiff[2..]), $"{name}: TIFF magic.");
|
||||
var count = U16(tiff[ifd..]);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var entry = tiff.Slice(ifd + 2 + (i * 12), 12);
|
||||
if (U16(entry) == 0x0112)
|
||||
{
|
||||
Assert.AreEqual(3, U16(entry[2..]), $"{name}: Orientation is a SHORT.");
|
||||
return U16(entry[8..]);
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static (int Width, int Height) WebPSize(string name, byte[] bytes)
|
||||
{
|
||||
Assert.IsTrue(bytes.AsSpan().StartsWith("RIFF"u8) && bytes.AsSpan(8).StartsWith("WEBP"u8), $"{name}: RIFF/WEBP header.");
|
||||
Assert.AreEqual(bytes.Length - 8, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(4)), $"{name}: RIFF size.");
|
||||
var chunk = Encoding.ASCII.GetString(bytes, 12, 4);
|
||||
var data = bytes.AsSpan(20);
|
||||
switch (chunk)
|
||||
{
|
||||
case "VP8 ":
|
||||
// RFC 9649 §2.5 and RFC 6386 §9.1: 3-byte frame tag, start code, then 14-bit width and height.
|
||||
Assert.IsTrue(data[3..].StartsWith((ReadOnlySpan<byte>)[0x9D, 0x01, 0x2A]), $"{name}: VP8 start code.");
|
||||
return (BinaryPrimitives.ReadUInt16LittleEndian(data[6..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(data[8..]) & 0x3FFF);
|
||||
case "VP8L":
|
||||
// RFC 9649 §3.2: signature 0x2F, then 14 bits of width - 1 and 14 bits of height - 1.
|
||||
Assert.AreEqual(0x2F, data[0], $"{name}: VP8L signature.");
|
||||
var bits = BinaryPrimitives.ReadUInt32LittleEndian(data[1..]);
|
||||
return ((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1);
|
||||
case "VP8X":
|
||||
// RFC 9649 §2.7: flags, 3 reserved bytes, 24-bit canvas width - 1 and height - 1.
|
||||
return (U24(data[4..]) + 1, U24(data[7..]) + 1);
|
||||
default:
|
||||
throw new AssertFailedException($"{name}: unknown first chunk '{chunk}'.");
|
||||
}
|
||||
|
||||
static int U24(ReadOnlySpan<byte> s) => s[0] | (s[1] << 8) | (s[2] << 16);
|
||||
}
|
||||
|
||||
private static (int Width, int Height) GifSize(string name, byte[] bytes)
|
||||
{
|
||||
Assert.IsTrue(bytes.AsSpan().StartsWith("GIF89a"u8), $"{name}: GIF89a signature.");
|
||||
Assert.AreEqual(0x3B, bytes[^1], $"{name}: trailer.");
|
||||
return (BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(6)), BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(8)));
|
||||
}
|
||||
|
||||
private static (int Width, int Height) BmpSize(string name, byte[] bytes)
|
||||
{
|
||||
Assert.IsTrue(bytes is [(byte)'B', (byte)'M', ..], $"{name}: BM signature.");
|
||||
Assert.AreEqual(bytes.Length, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(2)), $"{name}: file size in the header.");
|
||||
var offset = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(10));
|
||||
Assert.IsTrue(offset > 14 && offset < bytes.Length, $"{name}: offset of the pixels.");
|
||||
var height = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(22));
|
||||
return (BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(18)), Math.Abs(height));
|
||||
}
|
||||
|
||||
private static readonly uint[] CrcTable = BuildCrcTable();
|
||||
|
||||
private static uint[] BuildCrcTable()
|
||||
{
|
||||
// PNG specification, annex D (ISO 3309 polynomial, reflected).
|
||||
var table = new uint[256];
|
||||
for (uint n = 0; n < 256; n++)
|
||||
{
|
||||
var c = n;
|
||||
for (var k = 0; k < 8; k++)
|
||||
{
|
||||
c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
|
||||
}
|
||||
|
||||
table[n] = c;
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private static uint Crc32(ReadOnlySpan<byte> type, ReadOnlySpan<byte> data)
|
||||
{
|
||||
var crc = 0xFFFFFFFFu;
|
||||
foreach (var b in type)
|
||||
{
|
||||
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||
}
|
||||
|
||||
foreach (var b in data)
|
||||
{
|
||||
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||
}
|
||||
|
||||
return crc ^ 0xFFFFFFFFu;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Immagini di riferimento dei codec di casa
|
||||
|
||||
Insieme fisso di immagini con cui si provano i lettori di immagini scritti in casa (tappa C1: SkiaSharp esce da
|
||||
Febe). Ogni caso è una coppia:
|
||||
|
||||
- il **file d'ingresso** (`nome.png`, `.jpg`, `.webp`, `.gif`, `.bmp`);
|
||||
- `nome.atteso.png`, **l'immagine attesa**: ciò che SkiaSharp ha letto da quel file, in RGBA a 8 bit per canale con
|
||||
l'alfa non premoltiplicata, già raddrizzata secondo l'orientamento EXIF quando c'è.
|
||||
|
||||
`elenco.txt` nomina ogni caso con la misura dell'immagine attesa (`nome LxA`, una riga per caso, righe Unix).
|
||||
|
||||
## Come sono state fatte
|
||||
|
||||
Una volta sola, il 18 novembre 2026, con il permesso di Alberto, da un programma usa e getta con SkiaSharp 4.153.1
|
||||
(lo stesso di `Directory.Packages.props` in quel momento) che **non è nel repository**: nel repository c'è solo ciò che
|
||||
ha prodotto. Non si rigenerano: quando SkiaSharp sarà tolto non si potrà, ed è voluto. Un caso nuovo si costruisce con
|
||||
il nostro codice, non si aggiunge qui.
|
||||
|
||||
- **Contenuto solo sintetico.** Le scene sono calcolate: sfumature, un disco, righe a colori invertiti, una zona di
|
||||
rumore da un generatore congruenziale con seme fisso, alfa a rampa con una banda trasparente e una opaca. Nessuna
|
||||
fotografia, nessun dato di terzi, nessun campione della sonda.
|
||||
- **Lettura di riferimento.** `SKCodec.GetPixels` in `Rgba8888` con alfa `Unpremul`, prima immagine soltanto.
|
||||
- **Orientamento.** Per i casi `jpeg-orientamento-N` il programma ha raddrizzato a mano i pixel letti e li ha
|
||||
confrontati, uguali, con il disegno con matrice di SkiaSharp (quello che faceva `ImageDecoding`).
|
||||
- **L'immagine attesa** non è scritta dal codificatore di SkiaSharp ma da uno scritto a mano nel programma: PNG RGBA a
|
||||
8 bit (tipo di colore 6), senza interlacciamento, ogni riga con il filtro 0, un solo `IDAT` (zlib della BCL), nessun
|
||||
altro blocco oltre a `IHDR`, `IDAT`, `IEND`. Così il lettore PNG di casa (tappa C1, passo 2) la legge senza SkiaSharp;
|
||||
fino ad allora la prova d'integrità ne controlla solo la struttura.
|
||||
|
||||
## I casi
|
||||
|
||||
Misura 101×67 se non detto altrimenti (dispari, per provare i bordi dei blocchi e il sottocampionamento).
|
||||
|
||||
### Costruiti a mano dalle specifiche
|
||||
|
||||
Byte scritti dal programma seguendo la specifica del formato; SkiaSharp li ha solo letti.
|
||||
|
||||
| Gruppo | Casi | Che cosa provano |
|
||||
| --- | --- | --- |
|
||||
| PNG a tavolozza | `png-tav-1`, `png-tav-2`, `png-tav-4-trns`, `png-tav-8-trns`, `png-tav-4-adam7` | profondità 1–8, `tRNS` più corto della tavolozza, Adam7 |
|
||||
| PNG grigio | `png-grigio-1`, `-2`, `-4`, `-8`, `-16`, `png-grigio-16-adam7`, `png-grigio-8-trns` | tutte le profondità, 16 bit, Adam7, colore trasparente |
|
||||
| PNG grigio con alfa | `png-grigioalfa-8`, `png-grigioalfa-16` | 8 e 16 bit |
|
||||
| PNG RGB / RGBA | `png-rgb-8`, `png-rgb-8-trns`, `png-rgb-16`, `png-rgba-8`, `png-rgba-16`, `png-rgba-8-adam7` | 16 bit (l'atteso è a 8), colore trasparente, Adam7 |
|
||||
| GIF | `gif-globale`, `gif-locale-interlacciata`, `gif-animata`, `gif-2-colori` | tavolozza globale e locale, indice trasparente, interlacciamento, riquadro più piccolo della tela, LZW con codici fino a 12 bit e, in `gif-animata`, il dizionario pieno e azzerato; blocchi di commento e NETSCAPE2.0 da saltare |
|
||||
| BMP | `bmp-24`, `bmp-24-dall-alto`, `bmp-32-campi-v5`, `bmp-32-senza-alfa`, `bmp-16-565` (`BI_BITFIELDS`), `bmp-16-555`, `bmp-8`, `bmp-4`, `bmp-1`, `bmp-rle8`, `bmp-rle4` | dal basso e dall'alto, intestazione V5 con maschere e alfa, 32 bit con il quarto byte a zero, 16 bit 565 e 555, tavolozze, RLE8 e RLE4 con tratti assoluti |
|
||||
|
||||
Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up, Average, Paeth), divide i dati in due
|
||||
`IDAT` e ha un `tEXt` da saltare.
|
||||
|
||||
### Codificati da SkiaSharp
|
||||
|
||||
| Gruppo | Casi | Che cosa provano |
|
||||
| --- | --- | --- |
|
||||
| PNG | `png-skia-rgba`, `png-skia-rgb` | il codificatore di SkiaSharp, con tutti i filtri |
|
||||
| JPEG | `jpeg-420-q90`, `jpeg-422-q75`, `jpeg-444-q95`, `jpeg-420-q40`, `jpeg-grigio-q85` | base (SOF0, Huffman), 4:2:0, 4:2:2, 4:4:4, una sola componente |
|
||||
| JPEG grande | `jpeg-grande-420-q85` (333×250) | più blocchi, bordi non multipli di 16 |
|
||||
| JPEG con orientamento | `jpeg-orientamento-2`, `-3`, `-5`, `-6`, `-7`, `-8` | un `APP1` EXIF con il solo tag Orientation, inserito a mano dopo `SOI` in un JPEG di SkiaSharp; da 5 a 8 l'immagine attesa è 67×101 |
|
||||
| WebP con perdita | `webp-perdita-q80`, `webp-perdita-q30`, `webp-perdita-alfa-q80` | VP8, e VP8X con `ALPH` |
|
||||
| WebP senza perdita | `webp-senza-perdita`, `webp-senza-perdita-opaco`, `webp-senza-perdita-rapido` | VP8L con alfa, opaco, con lo sforzo minimo |
|
||||
| WebP grandi | `webp-grande-perdita-q75`, `webp-grande-senza-perdita` (333×250) | più macroblocchi; nel senza perdita, più spazio per trasformate e gruppi di Huffman |
|
||||
|
||||
### Che cosa dice l'immagine attesa, dove serve saperlo
|
||||
|
||||
- `gif-animata`: solo il primo fotogramma.
|
||||
- `gif-locale-interlacciata`: il fotogramma è 80×50 in (7, 9) su una tela 101×67 senza tavolozza globale; fuori dal
|
||||
fotogramma l'immagine attesa è trasparente (0, 0, 0, 0).
|
||||
- Alfa non premoltiplicata: per i PNG il colore sotto un'alfa 0 resta quello del file.
|
||||
- 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 potrà differire di poco: la tolleranza
|
||||
la fissano le prove di quei lettori. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte.
|
||||
|
||||
## Che cosa qui non c'è
|
||||
|
||||
Nessuno di questi casi ha un riferimento di SkiaSharp, e la prova d'integrità controlla che i JPEG dell'insieme restino
|
||||
così (SOF0, nessun `DRI`, nessun `APP14`):
|
||||
|
||||
- **JPEG progressivo** (T.81, allegato G);
|
||||
- **intervalli di ripristino** (`DRI`, marcatori `RSTn`);
|
||||
- **CMYK e YCCK con il segmento Adobe** (`APP14`).
|
||||
|
||||
Si provano con codificatori di prova nostri, scritti dalla specifica T.81 (allegato F per il sequenziale, allegato G
|
||||
per il progressivo): il codificatore scrive coefficienti noti e la prova confronta, esatti, i coefficienti che il
|
||||
lettore ricava prima della trasformata inversa, poi i pixel di un'immagine semplice.
|
||||
|
||||
## Le prove
|
||||
|
||||
- `Imaging/ReferenceImages.cs`: carica `elenco.txt` e dà i casi (`ReferenceImages.All`, `Get`, `Of`, `NamesOf` per
|
||||
`[DynamicData]`).
|
||||
- `Imaging/ReferenceSetTests.cs`: integrità dell'insieme. Ogni file elencato c'è e non c'è altro; ogni ingresso
|
||||
comincia con la firma del suo formato e ha la misura elencata (ruotata per l'orientamento EXIF 5–8); ogni immagine
|
||||
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
|
||||
- `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.
|
||||
|
After Width: | Height: | Size: 383 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
@@ -0,0 +1,57 @@
|
||||
png-tav-1 101x67
|
||||
png-tav-2 101x67
|
||||
png-tav-4-trns 101x67
|
||||
png-tav-8-trns 101x67
|
||||
png-tav-4-adam7 101x67
|
||||
png-grigio-1 101x67
|
||||
png-grigio-2 101x67
|
||||
png-grigio-4 101x67
|
||||
png-grigio-8 101x67
|
||||
png-grigio-16 101x67
|
||||
png-grigio-16-adam7 101x67
|
||||
png-grigio-8-trns 101x67
|
||||
png-grigioalfa-8 101x67
|
||||
png-grigioalfa-16 101x67
|
||||
png-rgb-8 101x67
|
||||
png-rgb-8-trns 101x67
|
||||
png-rgb-16 101x67
|
||||
png-rgba-8 101x67
|
||||
png-rgba-16 101x67
|
||||
png-rgba-8-adam7 101x67
|
||||
png-skia-rgba 101x67
|
||||
png-skia-rgb 101x67
|
||||
jpeg-420-q90 101x67
|
||||
jpeg-422-q75 101x67
|
||||
jpeg-444-q95 101x67
|
||||
jpeg-420-q40 101x67
|
||||
jpeg-grigio-q85 101x67
|
||||
webp-perdita-q80 101x67
|
||||
webp-perdita-q30 101x67
|
||||
webp-perdita-alfa-q80 101x67
|
||||
webp-senza-perdita 101x67
|
||||
webp-senza-perdita-opaco 101x67
|
||||
webp-senza-perdita-rapido 101x67
|
||||
jpeg-grande-420-q85 333x250
|
||||
webp-grande-perdita-q75 333x250
|
||||
webp-grande-senza-perdita 333x250
|
||||
jpeg-orientamento-2 101x67
|
||||
jpeg-orientamento-3 101x67
|
||||
jpeg-orientamento-5 67x101
|
||||
jpeg-orientamento-6 67x101
|
||||
jpeg-orientamento-7 67x101
|
||||
jpeg-orientamento-8 67x101
|
||||
gif-globale 101x67
|
||||
gif-locale-interlacciata 101x67
|
||||
gif-animata 101x67
|
||||
gif-2-colori 101x67
|
||||
bmp-24 101x67
|
||||
bmp-24-dall-alto 101x67
|
||||
bmp-32-campi-v5 101x67
|
||||
bmp-32-senza-alfa 101x67
|
||||
bmp-16-565 101x67
|
||||
bmp-16-555 101x67
|
||||
bmp-8 101x67
|
||||
bmp-4 101x67
|
||||
bmp-1 101x67
|
||||
bmp-rle8 101x67
|
||||
bmp-rle4 101x67
|
||||
|
After Width: | Height: | Size: 319 B |
|
After Width: | Height: | Size: 881 B |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 245 B |
|
After Width: | Height: | Size: 258 B |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 658 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 238 B |
|
After Width: | Height: | Size: 280 B |
|
After Width: | Height: | Size: 313 B |
|
After Width: | Height: | Size: 415 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 1.1 KiB |