diff --git a/docs/decisioni.md b/docs/decisioni.md index ed3a59d..213f8b5 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -432,3 +432,14 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Impronte percettive già salvate: restano confrontabili, nessun ricalcolo. Misurato prima di togliere Skia su 393 campioni (scene a 7 misure fino a 4000×3000 e 3024×4032 in JPEG q92 e q70, PNG, WebP q80, più i 57 file di riferimento): 390 impronte identiche, 3 a distanza 2, soglia dei doppioni 6 | Stesso algoritmo (luma su bianco con pesi BT.601, media per area a 32×32 in double, DCT 8×8, mediana); cambia solo il lettore | | 2026-11-18 | Un PNG o un JPEG troncato ora non dà miniatura né impronta (il file si importa lo stesso, con SHA-256, nome e date) | SkiaSharp teneva l'immagine a metà («IncompleteInput»); i lettori di casa la rifiutano, come per gli altri file rovinati, e una miniatura a metà non è la foto | | 2026-11-18 | `Febe.ico` ridisegnata dal disegnatore di casa e rigenerata; `tools/Febe.SitoDiProva` ora fa riferimento a `Febe.Core` per disegnare e codificare le foto finte | Le stesse forme del marchio (appendice C), con un rasterizzatore diverso: la prova dell'icona le confronta con il disegno. Il sito di prova non aveva altro modo di fare JPEG senza Skia | +| 2026-11-18 | Tabelle di Huffman JPEG: il controllo «i codici non stanno nella loro lunghezza» si fa per ogni lunghezza prima di scrivere le voci (`code + count <= 1 << length`) | Fatto dopo, una tabella con troppi codici corti (per esempio tre di lunghezza 1) scriveva oltre la tabella di ricerca e dava `ArgumentOutOfRangeException` invece di `ImageDecodeException`: un JPEG rovinato faceva fallire importazione e ricostruzione di quel file invece di lasciarlo senza miniatura (revisione di C1) | +| 2026-11-18 | Scansioni JPEG di Huffman (sequenziali, progressive, senza perdita): il troncamento si controlla a ogni riga di MCU, non solo ai marcatori di ripristino e alla fine | Oltre la fine il lettore dà bit zero, che sono codici validi delle tabelle dell'allegato K: un file tagliato dopo le intestazioni che dichiara 8192×8192 veniva decodificato fino all'ultimo MCU (6,7 s in Debug) per poi fallire comunque; ora si ferma alla prima riga (circa 0,1 s, quasi tutto per riservare i piani). Il risultato non cambia: i bit di riempimento usati restano usati fino al ripristino successivo | +| 2026-11-18 | IDCT ridotta JPEG a 1/2 e 1/4 calcolata direttamente dai coefficienti (`JpegDct.InverseReduced`): la media di due punti vicini dell'inversa a 8 punti è un'inversa a 4 punti dei coefficienti ripiegati (Yk = Xk cos(kπ/16) − X(8−k) sin(kπ/16), X4 sparisce), e a 1/4 restano X0, X1, X3, X5, X7 | Prima ogni blocco era trasformato intero e poi mediato: il decodificare ridotto risparmiava memoria ma non lavoro. Stesso risultato entro un livello (prova contro la definizione di T.81 in doppia precisione). Misurato in Release su questa macchina, il migliore di 5, scena 4000×3000 JPEG q90: miniatura da 126 a 59 ms, decodifica ad almeno 960 pixel da 114 a 45 ms; impronta (1/8, solo DC) invariata, 27-28 ms | +| 2026-11-18 | VP8: con `loop_filter_level` del fotogramma a 0 il filtro di blocco è spento per tutto il fotogramma, qualunque cosa dicano segmenti e differenze | Così fanno libvpx, libwebp e il decodificatore di riferimento di RFC 6386; prima un WebP con segmenti a forza assoluta o differenze positive veniva filtrato e usciva diverso | +| 2026-11-18 | VP8L: si costruiscono solo i gruppi di codici prefisso che l'immagine dei meta codici nomina, rinumerati in fila; i codici degli altri si leggono e si controllano (`Vp8LHuffman.IsValid`) senza costruire tabelle | Un solo pixel di valore 65535 chiedeva 65.536 gruppi: un file di circa 160 KB faceva costruire circa 335 MB di tabelle. Come libwebp | +| 2026-11-18 | BMP con intestazione OS/2 1.x (12 byte): altezza letta senza segno, immagine sempre dal basso | `bcHeight` è una WORD senza segno: letta con segno, le altezze da 32768 a 65535 diventavano negative, cioè capovolte e della misura sbagliata | +| 2026-11-18 | Array di lavoro dei codec (`ImageBuffers`): dal pool condiviso fino a 16 MiB, array normali sopra (immagini decodificate, piani e coefficienti JPEG, piani VP8, ARGB VP8L, alfa WebP, indici GIF, tabelle dello scrittore VP8L) | Il pool condiviso arrotonda alla potenza di due e tiene gli array fino a 1 GiB dopo la restituzione finché non passa una raccolta completa: un'immagine di 100 megapixel lasciava 512 MiB per ogni decodifica parallela (nella prova della revisione, quattro decodifiche parallele lasciavano 2 GiB tenuti per almeno 15 s; non rifatta qui). Sopra la soglia il raccoglitore li libera subito | +| 2026-11-18 | `ImageConverter`: il profilo ICC si copia solo se descrive dati RGB (byte 16-19 «RGB »); un profilo CMYK, in grigi o illeggibile si lascia e lo si dice in `NotCarried`. Un sorgente con più di 8 bit per campione (`ImageInfo.BitsPerSample`: PNG a 16 bit, JPEG a 12 bit o senza perdita, BMP con maschere larghe) dà `Lossy` vero e una riga in `NotCarried`; i blocchi di colore PNG gAMA, cHRM e sRGB (`ImageMetadata.ColorChunks`) non si scrivono e lo si dice | I pixel scritti sono sempre RGB a 8 bit: un profilo CMYK o GRAY su pixel RGB fa sbagliare i colori ai programmi che li gestiscono e in un PNG viola la regola di iCCP. La decisione sulle esportazioni chiede di copiare tutto il possibile e di avvisare di ogni perdita | +| 2026-11-18 | Impronta percettiva e misure di una foto da una sola lettura e una sola decodifica (`PerceptualHash.ComputeWithSize`, usata da importazione, ricostruzione, copia dell'importazione e analisi); `ImageDecoding.ReadSize(Stream)` legge prima 256 KiB per JPEG, GIF e BMP e il resto solo se le intestazioni non ci stanno; PNG e WebP sempre interi | Senza SkiaSharp `ReadSize` leggeva tutto il file solo per le misure, subito dopo l'impronta che lo leggeva di nuovo: ogni foto entrava in memoria due volte, e i file oltre 64 MiB dell'analisi («troppo grandi da tenere in memoria») due volte interi. Se la foto non si decodifica le misure vengono ancora dalle intestazioni, come prima | +| 2026-11-18 | Correzione della riga sulle immagini di riferimento: l'insieme è di 116 file per 2.003.752 byte (circa 2,0 MB), non «circa 2,2 MB» | Somma di `git ls-tree -l` sul ramo `funzione/codec-immagini`; la riga resta com'era perché le righe si aggiungono soltanto | +| 2026-11-18 | `Febe.exe` pubblicato senza SkiaSharp (`dotnet publish` come `installer/costruisci.sh`, un file solo e compresso): 85.583.840 byte, circa 86 MB come prima | Misurato di nuovo per `docs/windows.md`; la libreria nativa di Skia, compressa nel file solo, pesava poco | diff --git a/docs/windows.md b/docs/windows.md index 201ba67..aa298d1 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -46,8 +46,9 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i dove si vuole e si apre, senza installazione. Anche la versione portabile tiene i dati in `%LOCALAPPDATA%\Febe` e la libreria in `Immagini\Febe`, finché non scegli altre cartelle. -`Febe.exe` è un file solo (circa 86 MB): contiene il runtime .NET, l'interfaccia e le librerie native (SQLite, -WebView2Loader). Le immagini le leggono, le scrivono e le disegnano codec di Febe scritti in C#. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. +`Febe.exe` è un file solo (circa 86 MB, misurato di nuovo senza SkiaSharp): contiene il runtime .NET, l'interfaccia +e le librerie native (SQLite, WebView2Loader). Le immagini le leggono, le scrivono e le disegnano codec di Febe scritti +in C#. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. ## Il primo collegamento a Instagram @@ -224,8 +225,9 @@ installer/costruisci.sh 0.2.0 # oppure una versione esplicita ``` Il risultato è in `out/`: `Febe-Setup-.exe` e `Febe--portabile.zip`, ognuno sotto i 100 MB -(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB). Lo script -controlla che la pubblicazione abbia prodotto un solo file e che nulla superi il limite. Lo script NSIS è +(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB; senza +SkiaSharp, il 18 novembre 2026, Febe.exe 85,6 MB). Lo script controlla che la pubblicazione abbia prodotto un solo +file e che nulla superi il limite. Lo script NSIS è `installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`). L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con diff --git a/src/Febe.Core/Codecs/Images/BmpDecoder.cs b/src/Febe.Core/Codecs/Images/BmpDecoder.cs index d1be22b..64243dd 100644 --- a/src/Febe.Core/Codecs/Images/BmpDecoder.cs +++ b/src/Febe.Core/Codecs/Images/BmpDecoder.cs @@ -34,7 +34,11 @@ public static class BmpDecoder return png with { Format = ImageFormat.Bmp }; } - return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty); + var widest = Math.Max(Math.Max(BitOperations.PopCount(header.RedMask), BitOperations.PopCount(header.GreenMask)), Math.Max(BitOperations.PopCount(header.BlueMask), BitOperations.PopCount(header.AlphaMask))); + return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty) + { + BitsPerSample = Math.Max(8, widest), + }; } /// Decodes a BMP to straight RGBA8, top row first. @@ -143,7 +147,8 @@ public static class BmpDecoder if (infoSize == 12) { width = BinaryPrimitives.ReadUInt16LittleEndian(info[4..]); - height = BinaryPrimitives.ReadInt16LittleEndian(info[6..]); + // bcHeight is an unsigned WORD and core bitmaps are always bottom-up (the sign test below keeps them so). + height = BinaryPrimitives.ReadUInt16LittleEndian(info[6..]); planes = BinaryPrimitives.ReadUInt16LittleEndian(info[8..]); header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[10..]); header.Compression = BiRgb; diff --git a/src/Febe.Core/Codecs/Images/GifDecoder.cs b/src/Febe.Core/Codecs/Images/GifDecoder.cs index 709b848..f383eec 100644 --- a/src/Febe.Core/Codecs/Images/GifDecoder.cs +++ b/src/Febe.Core/Codecs/Images/GifDecoder.cs @@ -294,7 +294,7 @@ public static class GifDecoder var frameBytes = (long)frameWidth * frameHeight; limits.CheckWorkingBytes(frameBytes); - var indices = ArrayPool.Shared.Rent((int)frameBytes); + var indices = ImageBuffers.Rent((int)frameBytes); try { var decoded = DecodeLzw(data, file.FrameDataStart, file.FrameCodeSize, indices.AsSpan(0, (int)frameBytes)); @@ -361,7 +361,7 @@ public static class GifDecoder } finally { - ArrayPool.Shared.Return(indices); + ImageBuffers.Return(indices); } } diff --git a/src/Febe.Core/Codecs/Images/ImageBuffers.cs b/src/Febe.Core/Codecs/Images/ImageBuffers.cs new file mode 100644 index 0000000..50ab380 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageBuffers.cs @@ -0,0 +1,44 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// Working arrays of the codecs: from up to , plain arrays +/// above it. +/// +/// +/// The shared pool rounds every request up to a power of two and keeps arrays up to 1 GiB in its per-thread and +/// per-core slots after they are given back, until a full collection trims them: a 100-megapixel picture (400 MB) +/// would leave a 512 MiB array behind for each decoder that ran in parallel. Picture-sized arrays above the threshold +/// are therefore allocated and left to the collector, which frees them at once; the copy they save is small next to +/// the decoding itself. +/// +internal static class ImageBuffers +{ + /// Largest array, in bytes, taken from the shared pool (a power of two, so a pooled array never exceeds it). + public const int PooledBytes = 16 * 1024 * 1024; + + /// An array of at least elements, contents undefined. + public static T[] Rent(int length) + { + if ((long)length * Unsafe.SizeOf() <= PooledBytes) + { + return ArrayPool.Shared.Rent(length); + } + + return GC.AllocateUninitializedArray(length); + } + + /// Gives back an array from ; those above the threshold are left to the collector. + public static void Return(T[] array) + { + if ((long)array.Length * Unsafe.SizeOf() <= PooledBytes) + { + ArrayPool.Shared.Return(array); + } + } + + /// Whether of came from the shared pool. + public static bool IsPooled(T[] array) => (long)array.Length * Unsafe.SizeOf() <= PooledBytes; +} diff --git a/src/Febe.Core/Codecs/Images/ImageConverter.cs b/src/Febe.Core/Codecs/Images/ImageConverter.cs index 89d71b0..a0c7f6a 100644 --- a/src/Febe.Core/Codecs/Images/ImageConverter.cs +++ b/src/Febe.Core/Codecs/Images/ImageConverter.cs @@ -27,7 +27,10 @@ public sealed record ImageConversionOptions /// The format written. /// Width as stored (the orientation is not applied: the tag is copied). /// Height as stored. -/// Whether pixels may differ from the source's (a JPEG target). +/// +/// Whether pixels may differ from the source's: a JPEG target, or a source with more than 8 bits per sample (the +/// decoders keep 8). +/// /// The metadata written. /// What of the source's metadata the target could not take, in Italian, for the interface. public sealed record ImageConversionResult( @@ -42,12 +45,15 @@ public sealed record ImageConversionResult( /// /// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is -/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP losslessly, JPEG at -/// the quality of the options. The EXIF block (dates, camera, the orientation tag), the ICC profile and the XMP -/// packet are copied as they are; the pixels stay as stored, not turned by the orientation, which the copied tag -/// still describes. Texts go where the target can hold them: PNG text chunks, JPEG comments; WebP has none, and -/// what cannot be carried is listed in . Animations keep their first -/// frame only, and say so. +/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP without further loss, +/// JPEG at the quality of the options. The pixels written are always 8-bit RGB(A): a source with more bits per +/// sample (16-bit PNG, 12-bit or lossless JPEG) loses that precision, which the result reports as lossy. The EXIF +/// block (dates, camera, the orientation tag) and the XMP packet are copied as they are, the ICC profile only when it +/// describes RGB data (a CMYK or grey profile would no longer fit the RGB pixels); the pixels stay as stored, not +/// turned by the orientation, which the copied tag still describes. Texts go where the target can hold them: PNG +/// text chunks, JPEG comments; WebP has none. The PNG colour chunks (gAMA, cHRM, sRGB) are not written. Whatever +/// cannot be carried is listed in . Animations keep their first frame +/// only, and say so. /// public static class ImageConverter { @@ -72,9 +78,34 @@ public static class ImageConverter notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}"); } + var lossy = target == ImageFormat.Jpeg; + if (info.BitsPerSample > 8) + { + notCarried.Add($"la profondità di {info.BitsPerSample} bit per campione (i pixel sono scritti a 8 bit)"); + lossy = true; + } + var metadata = info.Metadata; var exif = metadata.Exif; var icc = metadata.IccProfile; + var iccName = metadata.IccProfileName; + if (icc is not null && IccColorSpace(icc) != "RGB ") + { + notCarried.Add(IccColorSpace(icc) switch + { + "CMYK" => "il profilo colore CMYK (i pixel sono stati convertiti in RGB)", + "GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)", + _ => "il profilo colore (non descrive pixel RGB)", + }); + icc = null; + iccName = null; + } + + foreach (var chunk in metadata.ColorChunks) + { + notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)"); + } + var xmp = metadata.Xmp; var texts = metadata.Texts; byte[] data; @@ -85,7 +116,7 @@ public static class ImageConverter { Exif = exif, IccProfile = icc, - IccProfileName = ValidIccName(metadata.IccProfileName) ?? PngEncoderOptions.Default.IccProfileName, + IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName, Xmp = xmp, Texts = PngTexts(texts, notCarried), }); @@ -147,11 +178,34 @@ public static class ImageConverter Exif = exif, Orientation = metadata.Orientation, IccProfile = icc, - IccProfileName = metadata.IccProfileName, + IccProfileName = icc is null ? null : iccName, Xmp = xmp, Texts = target == ImageFormat.WebP ? [] : texts, }; - return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, target == ImageFormat.Jpeg, written, notCarried); + return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried); + } + + /// The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null. + internal static string? IccColorSpace(ReadOnlySpan profile) + { + if (profile.Length < 20) + { + return null; + } + + Span name = stackalloc char[4]; + for (var i = 0; i < 4; i++) + { + var b = profile[16 + i]; + if (b is < 32 or > 126) + { + return null; + } + + name[i] = (char)b; + } + + return new string(name); } /// Bytes of payload in one JPEG marker segment (65535 less the two of the length). diff --git a/src/Febe.Core/Codecs/Images/ImageMetadata.cs b/src/Febe.Core/Codecs/Images/ImageMetadata.cs index 6098830..571c1a0 100644 --- a/src/Febe.Core/Codecs/Images/ImageMetadata.cs +++ b/src/Febe.Core/Codecs/Images/ImageMetadata.cs @@ -33,6 +33,12 @@ public sealed class ImageMetadata /// The texts, in file order (the XMP packet is in , not here). public IReadOnlyList Texts { get; init; } = []; + + /// + /// The PNG chunks that describe the colour of the pixels (gAMA, cHRM, sRGB) the file has, in file order. They are + /// not applied to the pixels and no encoder writes them, so a conversion says they are left behind. + /// + public IReadOnlyList ColorChunks { get; init; } = []; } /// What a file says about its image, read without decoding the pixels. @@ -42,4 +48,11 @@ public sealed class ImageMetadata /// Frames of an animation (GIF images, APNG frames); 1 for a still image. /// Whether the format of the pixels can carry transparency (not whether any pixel is transparent). /// The metadata. -public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata); +public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata) +{ + /// + /// Bits of one sample as the file stores them (PNG bit depth, JPEG precision, BMP mask width; 8 for palettes and + /// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision. + /// + public int BitsPerSample { get; init; } = 8; +} diff --git a/src/Febe.Core/Codecs/Images/JpegDct.cs b/src/Febe.Core/Codecs/Images/JpegDct.cs index 8e670e2..1dc7847 100644 --- a/src/Febe.Core/Codecs/Images/JpegDct.cs +++ b/src/Febe.Core/Codecs/Images/JpegDct.cs @@ -75,10 +75,17 @@ internal static class JpegDct /// /// Like , but writes the block reduced by 2^ (1 to 3) in each - /// direction: every output sample is the rounded mean of a square of the full block's samples. At an eighth that - /// mean is the DC term alone (S00 / 8 plus the level shift: the AC basis functions sum to zero over the block), so - /// no transform is computed. + /// direction: every output sample is the mean of a square of the full block's samples (before rounding and + /// clamping), computed directly from the coefficients without the full transform. /// + /// + /// Averaging two neighbours of the eight-point inverse x[n] = Σ C(k) X[k] cos((2n+1)kπ/16) gives + /// Σ C(k) X[k] cos(kπ/16) cos((2m+1)kπ/8). Coefficient 4 drops out (cos((2m+1)π/2) = 0) and coefficient 8 − k + /// folds onto k with weight −sin(kπ/16), so the half-size block is a four-point inverse of + /// Y0 = C(0) X0, Yk = Xk cos(kπ/16) − X(8−k) sin(kπ/16). Averaging pairs of that once more leaves + /// Y0 ± ((C2 + C6) Y1 + (C6 − C2) Y3) / 2, and at an eighth only the DC term remains (S00 / 8 plus the level + /// shift: the AC basis functions sum to zero over the block). + /// public static void InverseReduced(ReadOnlySpan block, ReadOnlySpan quantization, Span output, int stride, int precision, ReadOnlySpan to8Bit, int shift) { var max = precision == 12 ? 4095 : 255; @@ -91,32 +98,88 @@ internal static class JpegDct return; } - Span full = stackalloc byte[64]; - Inverse(block, quantization, full, 8, precision, to8Bit); var n = 8 >> shift; - var side = 1 << shift; - var area = side * side; - var half = area >> 1; - for (var y = 0; y < n; y++) + Span column = stackalloc float[8]; + Span work = stackalloc float[32]; + Span reduced = stackalloc float[4]; + for (var c = 0; c < 8; c++) { - var o = output.Slice(y * stride, n); - for (var x = 0; x < n; x++) + if (block[8 + c] == 0 && block[24 + c] == 0 && block[40 + c] == 0 && block[56 + c] == 0 + && (shift == 2 || (block[16 + c] == 0 && block[48 + c] == 0))) { - var sum = 0; - for (var dy = 0; dy < side; dy++) + // Only the coefficients that reach the reduced samples are tested (rows 4, and 2 and 6 at a quarter, drop out). + var dc = block[c] * quantization[c] * C4; + for (var r = 0; r < n; r++) { - var row = full.Slice((((y * side) + dy) * 8) + (x * side), side); - for (var dx = 0; dx < side; dx++) - { - sum += row[dx]; - } + work[(r * 8) + c] = dc; } - o[x] = (byte)((sum + half) / area); + continue; + } + + for (var r = 0; r < 8; r++) + { + column[r] = block[(r * 8) + c] * quantization[(r * 8) + c]; + } + + Reduce1D(column, reduced, shift); + for (var r = 0; r < n; r++) + { + work[(r * 8) + c] = reduced[r]; + } + } + + // Each pass doubles the T.81 values, as in Inverse: a quarter brings them back. + var levelShift = precision == 12 ? 2048.5f : 128.5f; + for (var r = 0; r < n; r++) + { + Reduce1D(work.Slice(r * 8, 8), reduced, shift); + var o = output.Slice(r * stride, n); + for (var c = 0; c < n; c++) + { + var value = (int)((reduced[c] * 0.25f) + levelShift); + if ((uint)value > (uint)max) + { + value = value < 0 ? 0 : max; + } + + o[c] = precision == 12 ? to8Bit[value] : (byte)value; } } } + /// + /// The means of 2^ neighbouring points (shift 1 or 2) of the eight-point inverse of + /// (twice the T.81 inverse, like ): four or two values. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Reduce1D(ReadOnlySpan x, Span output, int shift) + { + var y0 = C4 * x[0]; + var y1 = (C1 * x[1]) - (C7 * x[7]); + var y3 = (C3 * x[3]) - (C5 * x[5]); + if (shift == 2) + { + var d = (HalfC2PlusC6 * y1) + (HalfC6MinusC2 * y3); + output[0] = y0 + d; + output[1] = y0 - d; + return; + } + + var y2 = (C2 * x[2]) - (C6 * x[6]); + var e0 = y0 + (C4 * y2); + var e1 = y0 - (C4 * y2); + var o0 = (C2 * y1) + (C6 * y3); + var o1 = (C6 * y1) - (C2 * y3); + output[0] = e0 + o0; + output[1] = e1 + o1; + output[2] = e1 - o1; + output[3] = e0 - o0; + } + + private const float HalfC2PlusC6 = (C2 + C6) / 2; + private const float HalfC6MinusC2 = (C6 - C2) / 2; + /// /// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order, /// not yet quantized. diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs index 96a7934..71886b7 100644 --- a/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs +++ b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs @@ -321,12 +321,12 @@ internal sealed partial class JpegFile // At the start of a line the left difference counts as zero, on the first line of the scan or // of a restart interval the one above does. var classA = x == 0 ? 0 : cls[i - 1]; - var classB = predictor.IsFirstLine(c, y) ? 0 : cls[i - c.PlaneStride]; + var classB = predictor.IsFirstLine(ci, y) ? 0 : cls[i - c.PlaneStride]; var s0 = (20 * classB) + (4 * classA); var x1 = classB >= 3 ? 129 : 100; var difference = DecodeValue(ref decoder, stats, s0, x1); cls[i] = (byte)Classify(difference, low, up); - predictor.Store(c, x, y, difference); + predictor.Store(ci, c, x, y, difference); } } } diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs index dfacbb1..0d1b27b 100644 --- a/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs +++ b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs @@ -46,6 +46,14 @@ internal sealed partial class JpegFile var eobRun = 0; for (var mcu = 0; mcu < total; mcu++) { + // Past the end the reader gives zero bits, which are valid codes: without this check a file cut after + // its headers would be decoded to the last MCU before failing. Padding once used stays used until a + // restart, so failing at the first MCU row that needed it changes only when the error comes. + if (mcu > 0 && mcu % perRow == 0 && reader.UsedPadding) + { + throw Truncated(reader.ReachedEnd, "blocco"); + } + if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0) { if (reader.UsedPadding) @@ -130,12 +138,16 @@ internal sealed partial class JpegFile if (reader.UsedPadding) { - throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo blocco.") : InterruptedScan(); + throw Truncated(reader.ReachedEnd, "blocco"); } return FindNextMarker(reader.Position); } + /// The error for a scan that needed bits it did not have: cut short () or interrupted by a marker. + private static ImageDecodeException Truncated(bool reachedEnd, string unit) => + reachedEnd ? new ImageDecodeException($"JPEG troncato: i dati compressi finiscono prima dell'ultimo {unit}.") : InterruptedScan(); + private static ImageDecodeException InterruptedScan() => new("JPEG danneggiato: i dati compressi di una scansione si interrompono prima dell'ultimo blocco."); @@ -317,6 +329,12 @@ internal sealed partial class JpegFile { var mx = mcu % perRow; var my = mcu / perRow; + if (mx == 0 && mcu > 0 && reader.UsedPadding) + { + // As in DecodeHuffmanScan: fail at the first MCU row that ran out of data, not after the last one. + throw Truncated(reader.ReachedEnd, "campione"); + } + if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0) { if (reader.UsedPadding) @@ -347,7 +365,7 @@ internal sealed partial class JpegFile > 16 => throw BadValue(), _ => reader.ReceiveExtend(s), }; - predictor.Store(c, x, y, difference); + predictor.Store(ci, c, x, y, difference); } } } @@ -355,7 +373,7 @@ internal sealed partial class JpegFile if (reader.UsedPadding) { - throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo campione.") : InterruptedScan(); + throw Truncated(reader.ReachedEnd, "campione"); } predictor.Finish(); @@ -389,15 +407,16 @@ internal sealed partial class JpegFile } } - /// Whether (x, y) of component is on the first line of the scan or restart interval. - public bool IsFirstLine(JpegComponent c, int y) => y == _firstRow[Array.IndexOf(_scan.Components, c)]; + /// Whether row of scan component is the first line of the scan or restart interval. + public bool IsFirstLine(int ci, int y) => y == _firstRow[ci]; - public int Predict(JpegComponent c, int x, int y) + /// The prediction for (x, y) of , the scan's component . + public int Predict(int ci, JpegComponent c, int x, int y) { var samples = c.Samples!; var stride = c.PlaneStride; var i = (y * stride) + x; - if (IsFirstLine(c, y)) + if (y == _firstRow[ci]) { return x == 0 ? _initial : samples[i - 1]; } @@ -422,9 +441,9 @@ internal sealed partial class JpegFile }; } - public void Store(JpegComponent c, int x, int y, int difference) + public void Store(int ci, JpegComponent c, int x, int y, int difference) { - var predicted = Predict(c, x, y); + var predicted = Predict(ci, c, x, y); c.Samples![(y * c.PlaneStride) + x] = (ushort)((predicted + difference) & 0xFFFF); } diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs index 1d5f73e..3f6e51d 100644 --- a/src/Febe.Core/Codecs/Images/JpegFile.cs +++ b/src/Febe.Core/Codecs/Images/JpegFile.cs @@ -323,7 +323,7 @@ internal sealed partial class JpegFile : IDisposable Xmp = _xmp, Texts = _texts ?? [], }; - return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata); + return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision }; } public JpegCoefficients ToCoefficients() @@ -353,19 +353,19 @@ internal sealed partial class JpegFile : IDisposable { if (c.Plane is { } plane) { - ArrayPool.Shared.Return(plane); + ImageBuffers.Return(plane); c.Plane = null; } if (c.Coefficients is { } coefficients) { - ArrayPool.Shared.Return(coefficients); + ImageBuffers.Return(coefficients); c.Coefficients = null; } if (c.Samples is { } samples) { - ArrayPool.Shared.Return(samples); + ImageBuffers.Return(samples); c.Samples = null; } } @@ -822,19 +822,19 @@ internal sealed partial class JpegFile : IDisposable var samples = c.PlaneStride * c.PaddedUnitsHigh * unit; if (_mode == Mode.Pixels) { - c.Plane = ArrayPool.Shared.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit); + c.Plane = ImageBuffers.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit); } if (Lossless) { - c.Samples = _pooledArrays ? ArrayPool.Shared.Rent(samples) : new ushort[samples]; + c.Samples = _pooledArrays ? ImageBuffers.Rent(samples) : new ushort[samples]; } else if (keepCoefficients) { var length = c.PaddedUnitsWide * c.PaddedUnitsHigh * 64; if (_pooledArrays) { - c.Coefficients = ArrayPool.Shared.Rent(length); + c.Coefficients = ImageBuffers.Rent(length); c.Coefficients.AsSpan(0, length).Clear(); } else diff --git a/src/Febe.Core/Codecs/Images/JpegHuffman.cs b/src/Febe.Core/Codecs/Images/JpegHuffman.cs index 8bbecb9..5e21bf4 100644 --- a/src/Febe.Core/Codecs/Images/JpegHuffman.cs +++ b/src/Febe.Core/Codecs/Images/JpegHuffman.cs @@ -64,6 +64,12 @@ internal sealed class JpegHuffmanTable for (var length = 1; length <= 16; length++) { int count = counts[length - 1]; + if (code + count > 1 << length) + { + // Checked before any entry is written: an oversubscribed length would otherwise index past the lookup. + throw new ImageDecodeException("Tabella di Huffman JPEG non valida: i codici non stanno nella loro lunghezza."); + } + table.ValueOffset[length] = k - code; for (var i = 0; i < count; i++, k++, code++) { @@ -84,11 +90,6 @@ internal sealed class JpegHuffmanTable } table.MaxCode[length] = count == 0 ? -1 : code - 1; - if (code > 1 << length) - { - throw new ImageDecodeException("Tabella di Huffman JPEG non valida: i codici non stanno nella loro lunghezza."); - } - code <<= 1; } diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs index 4333493..7a92baa 100644 --- a/src/Febe.Core/Codecs/Images/PngDecoder.cs +++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs @@ -87,6 +87,7 @@ public static class PngDecoder public string? IccName; public string? Xmp; public List? Texts; + public List? ColorChunks; public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 }; @@ -98,9 +99,21 @@ public static class PngDecoder Height, FrameCount, ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha, - Exif is null && Icc is null && Xmp is null && Texts is null + Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null ? ImageMetadata.Empty - : new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, IccProfileName = IccName, Xmp = Xmp, Texts = Texts ?? [] }); + : new ImageMetadata + { + Exif = Exif, + Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), + IccProfile = Icc, + IccProfileName = IccName, + Xmp = Xmp, + Texts = Texts ?? [], + ColorChunks = ColorChunks ?? [], + }) + { + BitsPerSample = ColorType == 3 ? 8 : BitDepth, + }; } private static PngFile Parse(ReadOnlyMemory memory, ImageLimits limits, bool readMetadata) @@ -226,6 +239,14 @@ public static class PngDecoder break; + case "gAMA" or "cHRM" or "sRGB": + if (readMetadata && !(file.ColorChunks ??= []).Contains(name)) + { + file.ColorChunks.Add(name); + } + + break; + case "tEXt" or "zTXt" or "iTXt" or "iCCP" or "eXIf": if (readMetadata) { diff --git a/src/Febe.Core/Codecs/Images/RgbaImage.cs b/src/Febe.Core/Codecs/Images/RgbaImage.cs index 3dc2903..a64aa6a 100644 --- a/src/Febe.Core/Codecs/Images/RgbaImage.cs +++ b/src/Febe.Core/Codecs/Images/RgbaImage.cs @@ -7,9 +7,10 @@ namespace Febe.Core.Codecs.Images; /// (8 bits each, alpha not premultiplied: the colour under an alpha of 0 is kept as the file had it). /// /// -/// The pixels live either in an array of exactly the right size () or in an array -/// rented from (), which gives back; a pooled -/// image must not be used after that. Disposing an image that owns its array does nothing, so callers can always +/// The pixels live either in an array of exactly the right size () or in a rented +/// array (: from up to 16 MiB, a plain array above, so that very +/// large pictures are not kept by the pool), which gives back; a rented image must not be used +/// after that. Disposing an image that owns its array does nothing, so callers can always /// dispose. /// public sealed class RgbaImage : IDisposable @@ -46,13 +47,13 @@ public sealed class RgbaImage : IDisposable } /// - /// A new image whose pixels come from the shared array pool, every pixel (0, 0, 0, 0). Give it back with - /// . + /// A new image whose pixels are rented (the shared array pool up to 16 MiB), every pixel (0, 0, 0, 0). Give it + /// back with . /// public static RgbaImage Rent(int width, int height) { var length = CheckedLength(width, height); - var buffer = ArrayPool.Shared.Rent(length); + var buffer = ImageBuffers.Rent(length); buffer.AsSpan(0, length).Clear(); return new RgbaImage(width, height, buffer, pooled: true); } @@ -76,7 +77,7 @@ public sealed class RgbaImage : IDisposable /// Bytes of the whole image. public int Length { get; } - /// Whether the pixels come from the array pool. + /// Whether the pixels were rented with (and must not be used after ). public bool IsPooled => _pooled; /// All the pixels, row after row. @@ -118,13 +119,13 @@ public sealed class RgbaImage : IDisposable /// A copy of the pixels in an array of exactly bytes. public byte[] ToArray() => Pixels.ToArray(); - /// Gives a pooled array back to the pool; the image cannot be used afterwards. + /// Gives a rented array back; the image cannot be used afterwards. public void Dispose() { if (_pooled && _buffer is { } buffer) { _buffer = null; - ArrayPool.Shared.Return(buffer); + ImageBuffers.Return(buffer); } } diff --git a/src/Febe.Core/Codecs/Images/Vp8Decoder.cs b/src/Febe.Core/Codecs/Images/Vp8Decoder.cs index 34f764b..c64d967 100644 --- a/src/Febe.Core/Codecs/Images/Vp8Decoder.cs +++ b/src/Febe.Core/Codecs/Images/Vp8Decoder.cs @@ -200,14 +200,13 @@ internal sealed class Vp8Decoder ParseHeader(ref header); SetUpPartitions(_start + 10 + firstSize, _length - 10 - firstSize); - var pool = ArrayPool.Shared; - _y = pool.Rent((int)lumaBytes); - _u = pool.Rent((int)(lumaBytes / 4)); - _v = pool.Rent((int)(lumaBytes / 4)); - _mbSegment = pool.Rent(_mbWidth * _mbHeight); - _mbFlags = pool.Rent(_mbWidth * _mbHeight); - _intraTop = pool.Rent(_mbWidth * 4); - _nzTop = pool.Rent(_mbWidth * 9); + _y = ImageBuffers.Rent((int)lumaBytes); + _u = ImageBuffers.Rent((int)(lumaBytes / 4)); + _v = ImageBuffers.Rent((int)(lumaBytes / 4)); + _mbSegment = ImageBuffers.Rent(_mbWidth * _mbHeight); + _mbFlags = ImageBuffers.Rent(_mbWidth * _mbHeight); + _intraTop = ImageBuffers.Rent(_mbWidth * 4); + _nzTop = ImageBuffers.Rent(_mbWidth * 9); _intraTop.AsSpan(0, _mbWidth * 4).Fill(Vp8Tables.BDc); _nzTop.AsSpan(0, _mbWidth * 9).Clear(); @@ -237,17 +236,19 @@ internal sealed class Vp8Decoder } } - Vp8LoopFilter.Apply(this); + if (_filterLevel > 0) + { + Vp8LoopFilter.Apply(this); + } } private void Release() { - var pool = ArrayPool.Shared; foreach (var array in new[] { _y, _u, _v, _mbSegment, _mbFlags, _intraTop, _nzTop }) { if (array.Length > 0) { - pool.Return(array); + ImageBuffers.Return(array); } } @@ -358,6 +359,14 @@ internal sealed class Vp8Decoder private void ComputeFilterParams() { + if (_filterLevel == 0) + { + // A frame loop_filter_level of 0 turns the filter off for the whole frame, whatever the segment levels and + // the deltas would give (as libvpx, libwebp and the RFC 6386 reference decoder do). + Array.Clear(_filterParams); + return; + } + for (var s = 0; s < 4; s++) { var baseLevel = !_segmentation ? _filterLevel : _absoluteDeltas ? _segmentFilter[s] : _filterLevel + _segmentFilter[s]; diff --git a/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs b/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs index ded00d7..f1117eb 100644 --- a/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs +++ b/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs @@ -103,7 +103,7 @@ internal sealed class Vp8LDecoder } finally { - ArrayPool.Shared.Return(argb); + ImageBuffers.Return(argb); } } @@ -125,7 +125,7 @@ internal sealed class Vp8LDecoder } finally { - ArrayPool.Shared.Return(argb); + ImageBuffers.Return(argb); } } @@ -194,7 +194,7 @@ internal sealed class Vp8LDecoder CheckStream(); } - var argb = ArrayPool.Shared.Rent((int)pixelCount); + var argb = ImageBuffers.Rent((int)pixelCount); try { DecodeSpatial(xsize, height, argb, allowMeta: true); @@ -222,7 +222,7 @@ internal sealed class Vp8LDecoder } catch { - ArrayPool.Shared.Return(argb); + ImageBuffers.Return(argb); throw; } } @@ -253,6 +253,8 @@ internal sealed class Vp8LDecoder uint[]? meta = null; var metaWidth = 0; var groupCount = 1; + var codedGroups = 1; + int[]? remap = null; if (allowMeta && _br.ReadBits(1) == 1) { metaBits = _br.ReadBits(3) + 2; @@ -266,7 +268,24 @@ internal sealed class Vp8LDecoder max = Math.Max(max, g); } - groupCount = max + 1; + // The stream holds the codes of groups 0 to max, but the meta image may name only a few of them (one + // pixel of value 65535 asks for 65,536 groups): only the groups it names are built, renumbered densely; + // the codes of the others are read and checked, then dropped, as libwebp does. + codedGroups = max + 1; + Charge(codedGroups * 4L); + remap = new int[codedGroups]; + remap.AsSpan().Fill(-1); + groupCount = 0; + for (var i = 0; i < meta.Length; i++) + { + ref var dense = ref remap[(int)meta[i]]; + if (dense < 0) + { + dense = groupCount++; + } + + meta[i] = (uint)dense; + } } CheckStream(); @@ -274,13 +293,17 @@ internal sealed class Vp8LDecoder var groups = new Vp8LHuffman[groupCount * 5]; Span alphabets = [256 + NumLengthCodes + cacheSize, 256, 256, 256, NumDistanceCodes]; var lengths = new byte[alphabets[0]]; - for (var g = 0; g < groupCount; g++) + for (var g = 0; g < codedGroups; g++) { + var dense = remap is null ? g : remap[g]; for (var k = 0; k < 5; k++) { - var code = ReadCode(alphabets[k], lengths); - Charge(code.TableSize * 4L); - groups[(g * 5) + k] = code; + var code = ReadCode(alphabets[k], lengths, build: dense >= 0); + if (code is not null) + { + Charge(code.TableSize * 4L); + groups[(dense * 5) + k] = code; + } } CheckStream(); @@ -289,7 +312,8 @@ internal sealed class Vp8LDecoder DecodePixels(width, height, output, groups, meta, metaBits, metaWidth, cacheBits); } - private Vp8LHuffman ReadCode(int alphabet, byte[] buffer) + /// Reads one prefix code; with false it is only checked, and null comes back. + private Vp8LHuffman? ReadCode(int alphabet, byte[] buffer, bool build = true) { var lengths = buffer.AsSpan(0, alphabet); lengths.Clear(); @@ -379,6 +403,11 @@ internal sealed class Vp8LDecoder throw Truncated(); } + if (!build) + { + return Vp8LHuffman.IsValid(lengths) ? null : throw Damaged(); + } + return Vp8LHuffman.Build(lengths) ?? throw Damaged(); } diff --git a/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs b/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs index 0e7d501..1ee3fb2 100644 --- a/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs +++ b/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs @@ -101,6 +101,32 @@ internal sealed class Vp8LHuffman /// Entries of the decoding tables, for the memory budget. public int TableSize => _table.Length; + /// + /// Whether would accept , without building any table: for the codes + /// of groups that no pixel uses. + /// + public static bool IsValid(ReadOnlySpan lengths) + { + var space = 1 << MaxCodeLength; + var used = 0; + foreach (var len in lengths) + { + if (len > MaxCodeLength) + { + return false; + } + + if (len > 0) + { + used++; + space -= 1 << (MaxCodeLength - len); + } + } + + // One symbol is a code of zero bits; more must fill the code space exactly (Kraft). + return used == 1 || (used > 1 && space == 0); + } + /// /// The code given by the code lengths of each symbol (0 = not used), or null when the lengths are not a complete /// prefix code (or use no symbol at all). A single used symbol is a code of zero bits. diff --git a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs index cf04c23..7e67ca8 100644 --- a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs +++ b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs @@ -274,9 +274,8 @@ internal static class Vp8LEncoder private static void WriteCoded(Vp8LBitWriter writer, uint[] pixels, int width, int height, Vp8LEncoderSettings settings, bool mainImage) { var count = width * height; - var pool = ArrayPool.Shared; - var lengths = pool.Rent(count); - var distances = pool.Rent(count); + var lengths = ImageBuffers.Rent(count); + var distances = ImageBuffers.Rent(count); try { var tokens = settings.Lz77 ? FindMatches(pixels, width, count, settings.ChainLength, lengths, distances) : Literals(count, lengths); @@ -399,8 +398,8 @@ internal static class Vp8LEncoder } finally { - pool.Return(lengths); - pool.Return(distances); + ImageBuffers.Return(lengths); + ImageBuffers.Return(distances); } } @@ -415,7 +414,7 @@ internal static class Vp8LEncoder private static int FindMatches(uint[] pixels, int width, int count, int chainLength, int[] lengths, int[] distances) { var head = ArrayPool.Shared.Rent(1 << HashBits); - var previous = ArrayPool.Shared.Rent(count); + var previous = ImageBuffers.Rent(count); try { head.AsSpan(0, 1 << HashBits).Fill(-1); @@ -475,7 +474,7 @@ internal static class Vp8LEncoder finally { ArrayPool.Shared.Return(head); - ArrayPool.Shared.Return(previous); + ImageBuffers.Return(previous); } } diff --git a/src/Febe.Core/Codecs/Images/WebPDecoder.cs b/src/Febe.Core/Codecs/Images/WebPDecoder.cs index 74eb291..b96bdc6 100644 --- a/src/Febe.Core/Codecs/Images/WebPDecoder.cs +++ b/src/Febe.Core/Codecs/Images/WebPDecoder.cs @@ -429,7 +429,7 @@ internal static class WebPAlpha var count = width * height; limits.CheckWorkingBytes(count); - var alpha = ArrayPool.Shared.Rent(count); + var alpha = ImageBuffers.Rent(count); try { var plane = alpha.AsSpan(0, count); @@ -456,7 +456,7 @@ internal static class WebPAlpha } finally { - ArrayPool.Shared.Return(alpha); + ImageBuffers.Return(alpha); } } diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index 4914a82..1afca4d 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -85,8 +85,9 @@ internal static class ContentAnalysis { try { - var size = ImageDecoding.ReadSize(bytes); - return (size?.Width, size?.Height, PerceptualHash.Compute(new MemoryStream(bytes, writable: false))); + // The bytes are already in memory: one decode of them gives hash and size, with no copy. + var (hash, size) = PerceptualHash.ComputeWithSize(bytes); + return (size?.Width, size?.Height, hash); } catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException) { @@ -94,22 +95,28 @@ internal static class ContentAnalysis } } - /// The same for a photo too large to keep in memory, opened twice. + /// + /// The same for a photo over , which the analysis does not keep for the copy: it is read once + /// more, whole (up to ; the codecs need the bytes in memory), and decoded + /// once for both hash and size. + /// private static (int? Width, int? Height, ulong? Hash) Decode(Func open) { try { - int? width = null, height = null; + byte[]? data; using (var stream = open()) { - if (ImageDecoding.ReadSize(stream) is { } size) - { - (width, height) = size; - } + data = ImageDecoding.ReadAll(stream); } - using var again = open(); - return (width, height, PerceptualHash.Compute(again)); + if (data is null) + { + return (null, null, null); + } + + var (hash, size) = PerceptualHash.ComputeWithSize(data); + return (size?.Width, size?.Height, hash); } catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException) { diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 0bae0c3..762e1c7 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -517,11 +517,11 @@ public sealed class ImportCopier(ImportEnvironment env) { try { - hash = PerceptualHash.ComputeFromFile(saved.FullPath); - await using var stream = File.OpenRead(saved.FullPath); - if (ImageDecoding.ReadSize(stream) is { } size) + // One read of the file gives both the perceptual hash and the size as shown. + (hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath); + if (size is { } shown) { - (width, height) = size; + (width, height) = shown; } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs index 6be35a5..8453f19 100644 --- a/src/Febe.Core/Library/ImageDecoding.cs +++ b/src/Febe.Core/Library/ImageDecoding.cs @@ -32,8 +32,15 @@ internal static class ImageDecoding } /// Like , from bytes already in memory. - public static RgbaImage? DecodeUpright(ReadOnlyMemory data, int? minLongSide = null) + public static RgbaImage? DecodeUpright(ReadOnlyMemory data, int? minLongSide = null) => DecodeUpright(data, minLongSide, out _); + + /// + /// Like , and also gives what + /// would (the full size as shown, even when the picture comes back reduced or not at all), from the same bytes. + /// + public static RgbaImage? DecodeUpright(ReadOnlyMemory data, int? minLongSide, out (int Width, int Height)? shownSize) { + shownSize = null; if (data.IsEmpty) { return null; @@ -46,6 +53,7 @@ internal static class ImageDecoding stored = minLongSide is { } min && min > 0 ? ImageDecoder.DecodeAtLeast(data, min, out info, Limits, pooled: true) : ImageDecoder.Decode(data, out info, Limits, pooled: true); + shownSize = ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation); var upright = ImageOrientation.Apply(stored, info.Metadata.Orientation, pooled: true); if (!ReferenceEquals(upright, stored)) { @@ -57,6 +65,8 @@ internal static class ImageDecoding } catch (ImageDecodeException) { + // A damaged, truncated or too large picture can still tell its size from its headers. + shownSize ??= ReadSize(data); return null; } finally @@ -65,11 +75,57 @@ internal static class ImageDecoding } } + /// + /// Bytes read first by for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is + /// at most 64 KiB) fit; when they do not (large ICC profiles) the rest of the file is read as well. PNG and WebP + /// are always read whole. + /// + internal const int HeaderBytes = 256 * 1024; + /// Dimensions of an image as displayed (orientation applied), without decoding the pixels. public static (int Width, int Height)? ReadSize(Stream stream) { ArgumentNullException.ThrowIfNull(stream); - return ReadAll(stream) is { } data ? ReadSize(data) : null; + if (!stream.CanSeek) + { + return ReadAll(stream) is { } all ? ReadSize(all) : null; + } + + var remaining = stream.Length - stream.Position; + if (remaining <= 0 || remaining > MaxFileBytes) + { + return null; + } + + if (remaining <= HeaderBytes) + { + return ReadSize(ReadAll(stream)); + } + + var data = new byte[HeaderBytes]; + stream.ReadExactly(data); + if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp)) + { + // PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs + // past the data: neither can be identified from a prefix. + Array.Resize(ref data, (int)remaining); + stream.ReadExactly(data.AsSpan(HeaderBytes)); + return ReadSize(data); + } + + try + { + var info = ImageDecoder.Identify(data, Limits); + return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation); + } + catch (ImageDecodeException) + { + // The headers go on past the prefix (or the file is damaged): read the rest and look again. + } + + Array.Resize(ref data, (int)remaining); + stream.ReadExactly(data.AsSpan(HeaderBytes)); + return ReadSize(data); } /// Like , from bytes already in memory. @@ -91,7 +147,8 @@ internal static class ImageDecoding } } - private static byte[]? ReadAll(Stream stream) + /// The rest of , or null when it is empty or over . + internal static byte[]? ReadAll(Stream stream) { if (stream.CanSeek) { diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index 08f8f58..cc883d0 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -278,11 +278,11 @@ public sealed class LibraryIngest( { try { - hash = PerceptualHash.ComputeFromFile(saved.FullPath); - await using var stream = File.OpenRead(saved.FullPath); - if (ImageDecoding.ReadSize(stream) is { } size) + // One read of the file gives both the perceptual hash and the size as shown. + (hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath); + if (size is { } shown) { - (width, height) = size; + (width, height) = shown; } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index 1b59398..484dd97 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -445,13 +445,11 @@ public sealed class LibraryRebuilder( { if (!isVideo) { - phash = PerceptualHash.ComputeFromFile(path); - await using (var stream = File.OpenRead(path)) + // One read of the file gives both the perceptual hash and the size as shown. + (phash, var size) = PerceptualHash.ComputeWithSizeFromFile(path); + if (size is { } shown) { - if (ImageDecoding.ReadSize(stream) is { } size) - { - (width, height) = size; - } + (width, height) = shown; } } } diff --git a/src/Febe.Core/Library/PerceptualHash.cs b/src/Febe.Core/Library/PerceptualHash.cs index cbf7ee6..bb2892a 100644 --- a/src/Febe.Core/Library/PerceptualHash.cs +++ b/src/Febe.Core/Library/PerceptualHash.cs @@ -64,6 +64,28 @@ public static class PerceptualHash return Compute(stream); } + /// + /// Hash and size as shown of an encoded image from one decode of the same bytes; each null when it cannot be had + /// (a damaged file may still give its size). + /// + internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory encodedImage) + { + using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size); + return (image is null ? null : Compute(image), size); + } + + /// Like for a file, read once. + internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path) + { + byte[]? data; + using (var stream = File.OpenRead(path)) + { + data = ImageDecoding.ReadAll(stream); + } + + return data is null ? (null, null) : ComputeWithSize(data); + } + /// Hash of a decoded image (any size), upright as it is shown. internal static ulong Compute(RgbaImage image) { diff --git a/tests/Febe.Tests/Imaging/BmpDecoderTests.cs b/tests/Febe.Tests/Imaging/BmpDecoderTests.cs index 7829d36..aaf7bea 100644 --- a/tests/Febe.Tests/Imaging/BmpDecoderTests.cs +++ b/tests/Febe.Tests/Imaging/BmpDecoderTests.cs @@ -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() { diff --git a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs index b73f8c1..17ec59b 100644 --- a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs +++ b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs @@ -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 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 } /// Bytes standing in for an ICC profile (the codecs carry it without reading it). - private static byte[] Profile(int length) + /// A stand-in ICC profile: arbitrary bytes with the data colour space of its header (bytes 16-19) set. + 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; } + + /// A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI. + 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)]; + } } diff --git a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs index dc93dac..61e94a4 100644 --- a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs +++ b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs @@ -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(() => 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(1000); + Assert.AreEqual(1024, small.Length); + Assert.IsTrue(ImageBuffers.IsPooled(small)); + ImageBuffers.Return(small); + + var limit = ImageBuffers.Rent(ImageBuffers.PooledBytes); + Assert.AreEqual(ImageBuffers.PooledBytes, limit.Length); + Assert.IsTrue(ImageBuffers.IsPooled(limit)); + ImageBuffers.Return(limit); + + var large = ImageBuffers.Rent(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((ImageBuffers.PooledBytes / 2) + 1); + Assert.AreEqual((ImageBuffers.PooledBytes / 2) + 1, shorts.Length); + ImageBuffers.Return(shorts); + var words = ImageBuffers.Rent(1000); + Assert.AreEqual(1024, words.Length); + ImageBuffers.Return(words); } [TestMethod] diff --git a/tests/Febe.Tests/Imaging/JpegMalformedTests.cs b/tests/Febe.Tests/Imaging/JpegMalformedTests.cs index 0129997..f5d948f 100644 --- a/tests/Febe.Tests/Imaging/JpegMalformedTests.cs +++ b/tests/Febe.Tests/Imaging/JpegMalformedTests.cs @@ -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(() => 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(() => 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(() => 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(() => JpegDecoder.Decode(file), what); + StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", what); + } + /// Offset of the first marker segment of type (the 0xFF byte). private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0]; diff --git a/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs b/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs index ca7eb6a..4dbbfbd 100644 --- a/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs +++ b/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs @@ -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() { diff --git a/tests/Febe.Tests/Imaging/WebPContainerTests.cs b/tests/Febe.Tests/Imaging/WebPContainerTests.cs index 57fc1fc..4d462c6 100644 --- a/tests/Febe.Tests/Imaging/WebPContainerTests.cs +++ b/tests/Febe.Tests/Imaging/WebPContainerTests.cs @@ -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 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(() => 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() { diff --git a/tests/Febe.Tests/Library/ImageDecodingTests.cs b/tests/Febe.Tests/Library/ImageDecodingTests.cs new file mode 100644 index 0000000..4e46587 --- /dev/null +++ b/tests/Febe.Tests/Library/ImageDecodingTests.cs @@ -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; + +/// +/// 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; + } + } +}