Unione di funzione/codec-immagini in funzione/decoder-h264 (catena della 0.3.0)

Porta nel decodificatore H.264 le regole senza componenti esterni, la sessione S4b e i codec
di immagini di casa (C1), così la richiesta di unione di questo ramo contiene già tutta la
catena. Conflitti risolti tenendo le due parti: in decisioni.md tutte le righe, prima quelle
della catena e poi quelle del decodificatore; in docker.md, processo.md e Sviluppo.md né
ffmpeg (uscito con questo ramo) né SkiaSharp (uscito con C1), con l'eccezione «da fare» delle
prove di conformità; nelle prove di Febe.Tests entrambe le cartelle di file copiati e, nelle
prove delle miniature, sia i video sia le immagini di riferimento.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 11:16:26 +01:00
commit 8bcc86e496
279 files changed
+25617 -816

No files matched your search

@@ -0,0 +1,81 @@
using System.Security.Cryptography;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Library;
/// <summary>
/// «File danneggiato o incompleto» (spec §4.6, §8.4; Alberto's answer of 25 November 2026): a truncated PNG or JPEG
/// is refused and said so, with no thumbnail and no perceptual hash, and the file stays in the library as it came.
/// </summary>
[TestClass]
public sealed class DamagedImageTests
{
[TestMethod]
public void ATruncatedPngOrJpegIsDamagedAndWhatFebeDoesNotReadIsNot()
{
using var scene = TestImages.Scene(4, 320, 240);
var jpeg = TestImages.Jpeg(scene, 85);
var png = TestImages.Png(scene);
Assert.IsFalse(DamagedImage.IsDamaged(jpeg), "un JPEG intero");
Assert.IsFalse(DamagedImage.IsDamaged(png), "un PNG intero");
Assert.IsTrue(DamagedImage.IsDamaged(jpeg[..(jpeg.Length / 2)]), "un JPEG che finisce a metà della scansione");
Assert.IsTrue(DamagedImage.IsDamaged(png[..(png.Length / 2)]), "un PNG che finisce a metà dei dati");
Assert.IsTrue(DamagedImage.IsDamaged(png[..40]), "un PNG che finisce dentro l'intestazione");
// Not damaged: Febe just has no picture of them.
Assert.IsFalse(DamagedImage.IsDamaged(ReadOnlyMemory<byte>.Empty));
Assert.IsFalse(DamagedImage.IsDamaged(new byte[100]), "un formato sconosciuto");
byte[] heic = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. new byte[64]];
Assert.IsFalse(DamagedImage.IsDamaged(heic), "HEIC: Febe non lo legge, ma non è rovinato");
}
[TestMethod]
public void AFileOnDiskIsReadOnceAndLeftAsItIs()
{
using var temp = new TempFolder();
using var scene = TestImages.Scene(5, 200, 150);
var cut = TestImages.Jpeg(scene)[..900];
var path = temp.Combine("foto.jpg");
File.WriteAllBytes(path, cut);
var written = File.GetLastWriteTimeUtc(path);
Assert.IsTrue(DamagedImage.IsFileDamaged(path));
CollectionAssert.AreEqual(cut, File.ReadAllBytes(path), "il file resta com'è");
Assert.AreEqual(written, File.GetLastWriteTimeUtc(path));
Assert.IsFalse(DamagedImage.IsFileDamaged(temp.Combine("non-c-e.jpg")), "un file che non c'è non è danneggiato");
}
[TestMethod]
public async Task ADamagedPhotoIsStoredWithItsShaButNoThumbnailOrHashAndStays()
{
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
using var scene = TestImages.Scene(6, 640, 480);
var whole = TestImages.Jpeg(scene, 88);
var cutJpeg = whole[..(whole.Length * 2 / 3)];
var png = TestImages.Png(scene);
var cutPng = png[..(png.Length / 2)];
var saved = await library.SaveAsync(account, Make.Entry(account.Id, "701", Make.T0), [new TestFile(Make.Photo(1), cutJpeg, ".jpg"), new TestFile(Make.Photo(2), cutPng, ".png")]);
var intact = await library.SaveAsync(account, Make.Entry(account.Id, "702", Make.T0 + TimeSpan.FromHours(1)), [new TestFile(Make.Photo(1), whole, ".jpg")]);
Assert.AreEqual(EntryState.Downloaded, saved.Entry.State, "scaricato come gli altri: niente si riscarica da sé");
foreach (var (media, bytes) in saved.Media.Zip([cutJpeg, cutPng]))
{
Assert.AreEqual(MediaState.Downloaded, media.State);
Assert.IsNull(media.PerceptualHash, "nessuna impronta visiva: mai doppione probabile per impronta");
Assert.IsFalse(media.HasThumbnail, "la tessera neutra");
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), media.Sha256, "lo SHA-256 sì");
var path = library.Layout.FullPath(account, media.RelativePath!);
CollectionAssert.AreEqual(bytes, await File.ReadAllBytesAsync(path), "il file resta in libreria com'è arrivato");
Assert.IsTrue(DamagedImage.IsFileDamaged(path));
}
Assert.IsNotNull(intact.Media[0].PerceptualHash, "la stessa foto intera ha la sua impronta");
Assert.IsTrue(intact.Media[0].HasThumbnail);
}
}
@@ -0,0 +1,138 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Images;
using Febe.Core.Library;
using ImagingTestImages = Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Library;
/// <summary>
/// How much of a file the library reads for the size and the perceptual hash of a photo: the size from the headers
/// alone where the format allows, and hash and size from one read and one decode.
/// </summary>
[TestClass]
public sealed class ImageDecodingTests
{
[TestMethod]
public void TheSizeOfALargeJpegComesFromItsHeaders()
{
// Noise does not compress: a JPEG well over the prefix, turned by its EXIF tag (orientation 6: shown 600×900).
using var noise = ImagingTestImages.Random(900, 600, 5, opaque: true);
var jpeg = JpegEncoder.Encode(noise, new JpegEncoderOptions { Quality = 98, Exif = Orientation(6) });
Assert.IsGreaterThan(2 * ImageDecoding.HeaderBytes, jpeg.Length);
using var stream = new CountingStream(jpeg);
Assert.AreEqual((600, 900), ImageDecoding.ReadSize(stream));
Assert.AreEqual(ImageDecoding.HeaderBytes, stream.BytesRead, "solo l'inizio del file");
// Headers that do not fit the prefix (an ICC profile of 300 KB before the frame): the rest is read too.
var withProfile = JpegEncoder.Encode(noise, new JpegEncoderOptions { Quality = 98, Exif = Orientation(6), IccProfile = Profile(300_000) });
using var whole = new CountingStream(withProfile);
Assert.AreEqual((600, 900), ImageDecoding.ReadSize(whole));
Assert.AreEqual(withProfile.Length, whole.BytesRead);
// PNG is always read whole (every chunk is checked, eXIf may come late); so is a stream that cannot seek.
var png = PngEncoder.Encode(noise);
Assert.IsGreaterThan(ImageDecoding.HeaderBytes, png.Length);
using var pngStream = new CountingStream(png);
Assert.AreEqual((900, 600), ImageDecoding.ReadSize(pngStream));
Assert.AreEqual(png.Length, pngStream.BytesRead);
using var forward = new CountingStream(jpeg, seekable: false);
Assert.AreEqual((600, 900), ImageDecoding.ReadSize(forward));
// Small files, and what is not an image.
Assert.AreEqual((30, 20), ImageDecoding.ReadSize(new MemoryStream(PngEncoder.Encode(ImagingTestImages.Random(30, 20, 1)))));
Assert.IsNull(ImageDecoding.ReadSize(new MemoryStream(new byte[ImageDecoding.HeaderBytes + 10])));
Assert.IsNull(ImageDecoding.ReadSize(new MemoryStream()));
}
[TestMethod]
public void HashAndSizeComeFromOneDecodeOfTheSameBytes()
{
using var scene = Support.TestImages.Scene(3, 640, 480);
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 85, Exif = Orientation(8) });
var png = PngEncoder.Encode(scene);
foreach (var (name, file) in new[] { ("JPEG", jpeg), ("PNG", png) })
{
var (hash, size) = PerceptualHash.ComputeWithSize(file);
Assert.AreEqual(PerceptualHash.Compute(new MemoryStream(file)), hash, name);
Assert.AreEqual(ImageDecoding.ReadSize(file), size, name);
}
Assert.AreEqual((480, 640), PerceptualHash.ComputeWithSize(jpeg).Size, "le misure come si vede, intere anche se decodificato ridotto");
// A file cut inside its scan has no hash, but its headers still give the size, as ReadSize did.
var cut = jpeg[..(jpeg.Length / 2)];
var (noHash, stillSized) = PerceptualHash.ComputeWithSize(cut);
Assert.IsNull(noHash);
Assert.AreEqual((480, 640), stillSized);
var nothing = PerceptualHash.ComputeWithSize(new byte[100]);
Assert.IsNull(nothing.Hash);
Assert.IsNull(nothing.Size);
// From a file: read once, the same answer.
var path = Path.Combine(Path.GetTempPath(), $"febe-prova-{Guid.NewGuid():N}.jpg");
try
{
File.WriteAllBytes(path, jpeg);
Assert.AreEqual(PerceptualHash.ComputeWithSize(jpeg), PerceptualHash.ComputeWithSizeFromFile(path));
File.WriteAllBytes(path, []);
var empty = PerceptualHash.ComputeWithSizeFromFile(path);
Assert.IsNull(empty.Hash);
Assert.IsNull(empty.Size);
}
finally
{
File.Delete(path);
}
}
/// <summary>A big-endian TIFF with only the Orientation tag.</summary>
private static byte[] Orientation(ushort value)
{
var tiff = new byte[8 + 2 + 12 + 4];
"MM\0*"u8.CopyTo(tiff);
BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(4), 8);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(8), 1);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(10), 0x0112);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(12), 3);
BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(14), 1);
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(18), value);
return tiff;
}
private static byte[] Profile(int length)
{
var bytes = new byte[length];
for (var i = 0; i < length; i++)
{
bytes[i] = (byte)((i * 13) + (i >> 5));
}
"RGB "u8.CopyTo(bytes.AsSpan(16));
return bytes;
}
/// <summary>A stream over bytes that counts what was read.</summary>
private sealed class CountingStream(byte[] data, bool seekable = true) : MemoryStream(data, writable: false)
{
public long BytesRead { get; private set; }
public override bool CanSeek => seekable && base.CanSeek;
public override long Length => seekable ? base.Length : throw new NotSupportedException();
public override long Position
{
get => seekable ? base.Position : throw new NotSupportedException();
set => base.Position = seekable ? value : throw new NotSupportedException();
}
// A derived MemoryStream sends Read(Span) through Stream.Read(Span), which calls this one: counted once.
public override int Read(byte[] buffer, int offset, int count)
{
var read = base.Read(buffer, offset, count);
BytesRead += read;
return read;
}
}
}
+12 -12
View File
@@ -1,8 +1,8 @@
using System.Diagnostics;
using Febe.Core.Codecs.Images;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Support;
using SkiaSharp;
namespace Febe.Tests.Library;
@@ -15,7 +15,7 @@ public sealed class PerceptualHashTests
private static ulong Hash(byte[] encoded) => PerceptualHash.Compute(new MemoryStream(encoded)) ?? throw new AssertFailedException("Immagine non decodificata.");
private static ulong Hash(SKBitmap bitmap) => Hash(TestImages.Png(bitmap));
private static ulong Hash(RgbaImage image) => Hash(TestImages.Png(image));
/// <summary>
/// Calibration of <see cref="PerceptualHash.DuplicateThreshold"/> (spec §9.3, §14.1): resized and recompressed
@@ -63,20 +63,20 @@ public sealed class PerceptualHashTests
}
var side = Math.Min(width, height);
var crops = new (string Name, SKRectI Area)[]
var crops = new (string Name, (int Left, int Top, int Width, int Height) Area)[]
{
("centrale 80%", SKRectI.Create(width / 10, height / 10, width * 8 / 10, height * 8 / 10)),
("centrale 75%", SKRectI.Create(width / 8, height / 8, width * 3 / 4, height * 3 / 4)),
("centrale 60%", SKRectI.Create(width / 5, height / 5, width * 3 / 5, height * 3 / 5)),
("lato sinistro tolto 10%", SKRectI.Create(width / 10, 0, width * 9 / 10, height)),
("lato sinistro tolto 25%", SKRectI.Create(width / 4, 0, width * 3 / 4, height)),
("in alto tolto 33%", SKRectI.Create(0, height / 3, width, height * 2 / 3)),
("quadrato", SKRectI.Create((width - side) / 2, (height - side) / 2, side, side)),
("quarto in basso a destra", SKRectI.Create(width / 2, height / 2, width / 2, height / 2)),
("centrale 80%", (width / 10, height / 10, width * 8 / 10, height * 8 / 10)),
("centrale 75%", (width / 8, height / 8, width * 3 / 4, height * 3 / 4)),
("centrale 60%", (width / 5, height / 5, width * 3 / 5, height * 3 / 5)),
("lato sinistro tolto 10%", (width / 10, 0, width * 9 / 10, height)),
("lato sinistro tolto 25%", (width / 4, 0, width * 3 / 4, height)),
("in alto tolto 33%", (0, height / 3, width, height * 2 / 3)),
("quadrato", ((width - side) / 2, (height - side) / 2, side, side)),
("quarto in basso a destra", (width / 2, height / 2, width / 2, height / 2)),
};
foreach (var (name, area) in crops)
{
using var cropped = TestImages.Crop(scene, area);
using var cropped = TestImages.Crop(scene, area.Left, area.Top, area.Width, area.Height);
var distance = PerceptualHash.Distance(original, Hash(TestImages.Jpeg(cropped, 90)));
cropMin = Math.Min(cropMin, distance);
Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, ritaglio {name}: distanza {distance}");
+129 -10
View File
@@ -1,20 +1,25 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Images;
using Febe.Core.Library;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Imaging;
using Febe.Tests.Support;
using SkiaSharp;
using TestImages = Febe.Tests.Support.TestImages;
namespace Febe.Tests.Library;
[TestClass]
public sealed class ThumbnailStoreTests
{
private static SKImageInfo InfoOf(string path)
private static ImageInfo InfoOf(string path)
{
using var codec = SKCodec.Create(path) ?? throw new AssertFailedException("Miniatura non leggibile.");
Assert.AreEqual(SKEncodedImageFormat.Jpeg, codec.EncodedFormat);
return codec.Info;
var info = ImageDecoder.Identify(File.ReadAllBytes(path));
Assert.AreEqual(ImageFormat.Jpeg, info.Format);
return info;
}
private static RgbaImage Read(string path) => ImageDecoder.Decode(File.ReadAllBytes(path));
[TestMethod]
public void ThumbnailsAre480PixelsOnTheLongSideStoredOnceAndSharded()
{
@@ -69,17 +74,90 @@ public sealed class ThumbnailStoreTests
Assert.AreEqual(360, info.Height);
}
[TestMethod]
public void UprightAndTaggedSidewaysGiveTheSameThumbnail()
{
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var scene = TestImages.Scene(4, 1200, 900);
using var sideways = TestImages.RotateCounterClockwise(scene);
Assert.IsTrue(store.Create(Make.Sha(9), new MemoryStream(TestImages.Png(scene))));
Assert.IsTrue(store.Create(Make.Sha(10), new MemoryStream(TestImages.WithExifOrientation(TestImages.Jpeg(sideways, 95), 6))));
using var upright = Read(store.PathFor(Make.Sha(9)));
using var turned = Read(store.PathFor(Make.Sha(10)));
var quality = ImageQuality.Compare(upright, turned);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void TransparentImagesBecomeJpegOnWhite()
{
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var transparent = new SKBitmap(new SKImageInfo(600, 600, SKColorType.Rgba8888, SKAlphaType.Premul));
transparent.Erase(SKColors.Transparent);
using var transparent = new RgbaImage(600, 600);
Assert.IsTrue(store.Create(Make.Sha(4), new MemoryStream(TestImages.Png(transparent))));
using var thumbnail = SKBitmap.Decode(store.PathFor(Make.Sha(4)));
using var thumbnail = Read(store.PathFor(Make.Sha(4)));
var pixel = thumbnail.GetPixel(10, 10);
Assert.IsGreaterThan((byte)240, pixel.Red);
Assert.IsGreaterThan((byte)240, pixel.R);
}
[TestMethod]
public void TheThumbnailShowsThePictureReducedFaithfully()
{
// Compared with the source reduced by area averaging (the most neutral reduction), what differs is only the
// JPEG compression and the filter.
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var scene = TestImages.Scene(8, 2400, 1800);
Assert.IsTrue(store.Create(Make.Sha(7), new MemoryStream(TestImages.Png(scene))));
using var thumbnail = Read(store.PathFor(Make.Sha(7)));
using var expected = ImageResampler.Resize(scene, 480, 360, new ResampleOptions { Filter = ResampleFilter.Area });
var quality = ImageQuality.Compare(expected, thumbnail);
Assert.IsGreaterThan(28.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void AJpegShrunkWhileDecodingGivesTheSameThumbnailAsAFullDecode()
{
// 4000 × 3000 is decoded at a quarter (1000 × 750) and then reduced to 480: compared with the full-size path.
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var scene = TestImages.Scene(9, 4000, 3000);
var jpeg = TestImages.Jpeg(scene, 92);
Assert.IsTrue(store.Create(Make.Sha(8), new MemoryStream(jpeg)));
using var thumbnail = Read(store.PathFor(Make.Sha(8)));
Assert.AreEqual((480, 360), (thumbnail.Width, thumbnail.Height));
using var full = ImageDecoder.Decode(jpeg);
using var reference = ImageResampler.Resize(full, 480, 360);
var quality = ImageQuality.Compare(reference, thumbnail);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void VideoFramesAsBmpBecomeThumbnails()
{
// The in-house video decoder (branch funzione/decoder-h264) hands frames over as 24-bit BMP, rows bottom up.
using var temp = new TempFolder();
var store = new ThumbnailStore(temp.Path);
using var frame = TestImages.Scene(11, 1280, 720);
Assert.IsTrue(store.Create(Make.Sha(11), new MemoryStream(Bmp24(frame))));
var info = InfoOf(store.PathFor(Make.Sha(11)));
Assert.AreEqual((480, 270), (info.Width, info.Height));
using var thumbnail = Read(store.PathFor(Make.Sha(11)));
using var expected = ImageResampler.Resize(frame, 480, 270);
var quality = ImageQuality.Compare(expected, thumbnail);
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
}
[TestMethod]
public void ThePhotoOfASearchIsASmallJpeg()
{
using var scene = TestImages.Scene(12, 1080, 1080);
var small = ThumbnailStore.EncodeSmallJpeg(new MemoryStream(TestImages.Jpeg(scene)), 160);
Assert.IsNotNull(small);
var info = ImageDecoder.Identify(small);
Assert.AreEqual((ImageFormat.Jpeg, 160, 160), (info.Format, info.Width, info.Height));
Assert.IsNull(ThumbnailStore.EncodeSmallJpeg(new MemoryStream([1, 2, 3]), 160));
}
[TestMethod]
@@ -101,8 +179,14 @@ public sealed class ThumbnailStoreTests
var tile = store.NeutralVideoTile();
Assert.AreEqual(Path.Combine(temp.Path, ThumbnailStore.NeutralVideoTileName), tile);
var info = InfoOf(tile);
Assert.AreEqual(480, info.Height);
Assert.AreEqual((270, 480), (info.Width, info.Height));
Assert.AreEqual(tile, store.NeutralVideoTile());
// Light grey, a darker disc in the middle, the play sign in the light grey again.
using var image = Read(tile);
AssertGrey(image.GetPixel(10, 10), 0xE4, "sfondo");
AssertGrey(image.GetPixel(135 - 25, 240), 0x9A, "disco");
AssertGrey(image.GetPixel(135 + 2, 240), 0xE4, "segno di riproduzione");
}
[TestMethod]
@@ -121,4 +205,39 @@ public sealed class ThumbnailStoreTests
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mp4")));
}
private static void AssertGrey((byte R, byte G, byte B, byte A) pixel, int level, string what) =>
Assert.IsTrue(Math.Abs(pixel.R - level) <= 4 && Math.Abs(pixel.G - level) <= 4 && Math.Abs(pixel.B - level) <= 4, $"{what}: {pixel}");
/// <summary>A 24-bit BI_RGB BMP, rows bottom up, the way VideoImage.ToBmp writes it.</summary>
private static byte[] Bmp24(RgbaImage image)
{
var stride = ((image.Width * 3) + 3) & ~3;
var size = 54 + (stride * image.Height);
var bmp = new byte[size];
var span = bmp.AsSpan();
span[0] = (byte)'B';
span[1] = (byte)'M';
BinaryPrimitives.WriteInt32LittleEndian(span[2..], size);
BinaryPrimitives.WriteInt32LittleEndian(span[10..], 54);
BinaryPrimitives.WriteInt32LittleEndian(span[14..], 40);
BinaryPrimitives.WriteInt32LittleEndian(span[18..], image.Width);
BinaryPrimitives.WriteInt32LittleEndian(span[22..], image.Height);
BinaryPrimitives.WriteInt16LittleEndian(span[26..], 1);
BinaryPrimitives.WriteInt16LittleEndian(span[28..], 24);
BinaryPrimitives.WriteInt32LittleEndian(span[34..], stride * image.Height);
for (var y = 0; y < image.Height; y++)
{
var source = image.GetRow(y);
var target = span.Slice(54 + ((image.Height - 1 - y) * stride), image.Width * 3);
for (var x = 0; x < image.Width; x++)
{
target[x * 3] = source[(x * 4) + 2];
target[(x * 3) + 1] = source[(x * 4) + 1];
target[(x * 3) + 2] = source[x * 4];
}
}
return bmp;
}
}