using System.Buffers.Binary; using Febe.Core.Codecs.Images; using Febe.Core.Library; using ImagingTestImages = Febe.Tests.Imaging.TestImages; namespace Febe.Tests.Library; /// /// 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. /// [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); } } /// A big-endian TIFF with only the Orientation tag. 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; } /// A stream over bytes that counts what was read. 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; } } }