diff --git a/docs/decisioni.md b/docs/decisioni.md index bef0d74..bb4eff6 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -422,3 +422,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» | | 2026-11-18 | Insieme fisso di immagini di riferimento per i codec di casa in `tests/Febe.Tests/Imaging/Riferimenti` (57 casi, circa 2,2 MB, descritti in `LEGGIMI.md`): per ogni caso un file d'ingresso (PNG, GIF e BMP costruiti a mano dalle specifiche; PNG, JPEG base e WebP codificati da SkiaSharp; JPEG con un `APP1` EXIF di orientamento inserito a mano) e `.atteso.png`, la lettura di SkiaSharp 4.153.1 in RGBA a 8 bit non premoltiplicata, raddrizzata. Generato una volta sola, con il permesso di Alberto, da un programma usa e getta fuori dal repository; contenuto solo sintetico. Le immagini attese sono PNG RGBA a 8 bit senza interlacciamento, filtro 0, un solo `IDAT`, scritti a mano e non dal codificatore di SkiaSharp, così le legge il lettore PNG di casa (passo 2 di C1); fino ad allora `ReferenceSetTests` controlla solo la struttura (firme, misure, CRC dei blocchi, nessun file in più o in meno). JPEG progressivo, intervalli di ripristino e CMYK/Adobe non hanno riferimento: li proveranno codificatori di prova nostri dalla T.81 (allegati F e G) con controlli sui coefficienti. Estensioni delle immagini `binary` in `.gitattributes`, `elenco.txt` con `eol=lf` | SkiaSharp esce da Febe (C1): serve un termine di confronto prima di toglierlo, e dopo non si potrà più generarlo. Un riferimento che solo SkiaSharp sapesse leggere sarebbe inutile proprio quando serve | | 2026-11-18 | Base dei codec d'immagine di casa in `src/Febe.Core/Codecs/Images` (spazio dei nomi `Febe.Core.Codecs.Images`, accanto a `Codecs/Containers` del ramo `funzione/decoder-h264`): `RgbaImage` (RGBA a 8 bit non premoltiplicata, array suo o preso dal pool e reso con `Dispose`), `ImageLimits` (predefiniti 65535 pixel per lato, 100 milioni di pixel come `ImageDecoding.MaxDecodedPixels`, 512 MiB di memoria di lavoro, 16 MiB di metadati decompressi), `ImageDecodeException` con `ImageLimitException` e `ImageFormatNotSupportedException`, `ImageFormatSniffer`, la facciata `ImageDecoder`; lettore e scrittore PNG, lettori GIF e BMP dalle specifiche, CRC-32 e LZW scritti in casa, zlib di `System.IO.Compression`. Scelte di lettura: i campioni a 16 bit tengono il byte alto e le maschere BMP sotto gli 8 bit si scalano con arrotondamento (così i 37 riferimenti PNG, GIF e BMP coincidono byte per byte); nessuna gestione del colore (profilo ICC, gamma); un blocco PNG ausiliario con il CRC sbagliato si salta, uno critico ferma la lettura; un PNG senza `IEND` dopo dati completi si accetta, uno tagliato prima no; un GIF tagliato o con dati LZW rotti dà ciò che si è letto, il resto trasparente; del GIF solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo, più il numero dei fotogrammi; nel BMP l'alfa viene solo da una maschera alfa di `BI_BITFIELDS`/`BI_ALPHABITFIELDS`, i pixel saltati da RLE restano trasparenti, `BI_PNG` passa al lettore PNG, `BI_JPEG` e 64 bit non si leggono. `Identify` legge misura, fotogrammi e metadati senza applicare i limiti di misura; `Decode` li applica prima di allocare. Lo scrittore PNG scrive RGB o RGBA a 8 bit (RGB in automatico se tutto è opaco), per ogni riga il filtro con la minima somma dei valori assoluti (specifica PNG §12.8), `IDAT` da 64 KiB e, a richiesta, `eXIf`, `iCCP` e l'XMP in un `iTXt` | C1: SkiaSharp esce da Febe e niente componenti esterni (decisione di Alberto del 18 novembre 2026). Lettori tolleranti dove lo sono i browser (GIF, metadati), severi dove un'immagine letta a metà passerebbe per buona (PNG, BMP); limiti controllati prima di ogni allocazione, perché pochi byte di un file possono chiedere gigabyte | +| 2026-11-18 | Lettore e scrittore JPEG di casa (`JpegDecoder`, `JpegEncoder`), scritti dalla T.81: il lettore fa sequenziale di base ed esteso, progressivo, senza perdita, con Huffman e con codifica aritmetica, a 8 e 12 bit (senza perdita da 2 a 16), qualunque campionamento, ripristino, DNL; IDCT esatta in virgola mobile e crominanza con il filtro triangolare dove il rapporto è 2; colori secondo JFIF, Adobe APP14 (CMYK e YCCK invertiti come li scrive Adobe) e identificatori `R`, `G`, `B`; tabelle dell'allegato K quando manca `DHT` (Motion JPEG); dati troncati dentro una scansione = file danneggiato, EOI mancante e byte dopo EOI accettati; gerarchici e JPEG a 2 componenti rifiutati come formato non letto. L'orientamento EXIF va in `ImageMetadata.Orientation` e non si applica ai pixel. Lo scrittore fa solo il sequenziale di base (qualità 1–100 sulle tabelle dell'allegato K, 4:2:0 e 4:4:4, grigio, ripristino) con EXIF, ICC a pezzi, XMP e commenti. Progressivo, aritmetico, 12 bit e senza perdita si provano con un codificatore di prova (`tests/Febe.Tests/Imaging/JpegTestEncoder.cs`) confrontando i coefficienti con la codifica di base; contro SkiaSharp la tolleranza è PSNR ≥ 40 dB per canale e ≤ 0,1% di pixel con scarto oltre 16 | Tappa C1, passo 3: niente componenti esterni (decisione del 18 novembre 2026). Due lettori JPEG corretti differiscono per gli arrotondamenti, quindi contro il riferimento serve una soglia; il nostro sta fra 59 e 67 dB. La codifica aritmetica è verificata solo con il nostro codificatore e le tabelle della specifica: nessun file di riferimento esterno | diff --git a/src/Febe.Core/Codecs/Images/ExifOrientation.cs b/src/Febe.Core/Codecs/Images/ExifOrientation.cs new file mode 100644 index 0000000..762d145 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ExifOrientation.cs @@ -0,0 +1,79 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.Images; + +/// Reads the Orientation tag (0x0112) of the first IFD of an EXIF block (a TIFF structure). +internal static class ExifOrientation +{ + private const ushort OrientationTag = 0x0112; + + /// + /// The orientation 1-8 of (starting with «II*\0» or «MM\0*»), or 1 when the block has no + /// such tag, an invalid value or is damaged. + /// + public static int Read(ReadOnlySpan tiff) + { + if (tiff.Length < 8) + { + return 1; + } + + bool little; + if (tiff[0] == (byte)'I' && tiff[1] == (byte)'I') + { + little = true; + } + else if (tiff[0] == (byte)'M' && tiff[1] == (byte)'M') + { + little = false; + } + else + { + return 1; + } + + if (U16(tiff[2..], little) != 42) + { + return 1; + } + + var ifd = U32(tiff[4..], little); + if (ifd > (uint)(tiff.Length - 2)) + { + return 1; + } + + var entries = U16(tiff[(int)ifd..], little); + for (var i = 0; i < entries; i++) + { + var entry = (long)ifd + 2 + (12L * i); + if (entry + 12 > tiff.Length) + { + break; + } + + var e = tiff.Slice((int)entry, 12); + if (U16(e, little) != OrientationTag) + { + continue; + } + + var type = U16(e[2..], little); + var value = type switch + { + 3 => U16(e[8..], little), + 4 => U32(e[8..], little), + _ => 0u, + }; + return value is >= 1 and <= 8 ? (int)value : 1; + } + + return 1; + } + + private static ushort U16(ReadOnlySpan b, bool little) => + little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b); + + private static uint U32(ReadOnlySpan b, bool little) => + little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b); +} diff --git a/src/Febe.Core/Codecs/Images/ImageDecoder.cs b/src/Febe.Core/Codecs/Images/ImageDecoder.cs index b61486b..302d9f8 100644 --- a/src/Febe.Core/Codecs/Images/ImageDecoder.cs +++ b/src/Febe.Core/Codecs/Images/ImageDecoder.cs @@ -7,7 +7,7 @@ namespace Febe.Core.Codecs.Images; public static class ImageDecoder { /// Whether Febe has a decoder for . - public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Gif or ImageFormat.Bmp; + public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp; /// Size, frames and metadata of an image, without decoding the pixels. /// The format is not known or has no decoder yet. @@ -16,6 +16,7 @@ public static class ImageDecoder ImageFormatSniffer.Detect(data.Span) switch { ImageFormat.Png => PngDecoder.Identify(data, limits), + ImageFormat.Jpeg => JpegDecoder.Identify(data, limits), ImageFormat.Gif => GifDecoder.Identify(data, limits), ImageFormat.Bmp => BmpDecoder.Identify(data, limits), var other => throw NotSupported(other), @@ -29,6 +30,7 @@ public static class ImageDecoder ImageFormatSniffer.Detect(data.Span) switch { ImageFormat.Png => PngDecoder.Decode(data, limits, pooled), + ImageFormat.Jpeg => JpegDecoder.Decode(data, limits, pooled), ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled), ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled), var other => throw NotSupported(other), diff --git a/src/Febe.Core/Codecs/Images/ImageMetadata.cs b/src/Febe.Core/Codecs/Images/ImageMetadata.cs index 2236cdb..6098830 100644 --- a/src/Febe.Core/Codecs/Images/ImageMetadata.cs +++ b/src/Febe.Core/Codecs/Images/ImageMetadata.cs @@ -1,7 +1,7 @@ namespace Febe.Core.Codecs.Images; -/// A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment). -/// The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF comment. +/// A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment; JPEG COM). +/// The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF or JPEG comment. /// The text. /// The language tag of an iTXt chunk, empty otherwise. /// The translated keyword of an iTXt chunk, empty otherwise. @@ -16,13 +16,19 @@ public sealed class ImageMetadata /// The EXIF block as a TIFF structure (starts with «II*\0» or «MM\0*»), or null. public byte[]? Exif { get; init; } + /// + /// The EXIF orientation, 1-8 (T.81 has none of its own: it is the Orientation tag of ); 1 when the + /// image has no EXIF block, no such tag or an invalid value. The decoders never apply it to the pixels. + /// + public int Orientation { get; init; } = 1; + /// The ICC colour profile, decompressed, or null. public byte[]? IccProfile { get; init; } /// The name of the ICC profile as the file gives it, or null. public string? IccProfileName { get; init; } - /// The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG), or null. + /// The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG, the APP1 segment of a JPEG), or null. public string? Xmp { get; init; } /// The texts, in file order (the XMP packet is in , not here). diff --git a/src/Febe.Core/Codecs/Images/JpegArithmetic.cs b/src/Febe.Core/Codecs/Images/JpegArithmetic.cs new file mode 100644 index 0000000..ac03559 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegArithmetic.cs @@ -0,0 +1,202 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// The probability estimation state machine of the T.81 arithmetic coder (Table D.2), shared by the decoder and the +/// test encoder. A context is one byte: bit 7 the sense of the MPS, bits 0-6 the index in the table. +/// +internal static class JpegArithmeticTable +{ + /// Index of the fixed estimate (Qe = 0x5A1D, never adapted) used for the signs of AC coefficients. + public const byte FixedState = 113; + + /// Qe of each index; entry 113 is the fixed estimate. + public static ReadOnlySpan Qe => + [ + 0x5A1D, 0x2586, 0x1114, 0x080B, 0x03D8, 0x01DA, 0x00E5, 0x006F, 0x0036, 0x001A, 0x000D, 0x0006, 0x0003, 0x0001, + 0x5A7F, 0x3F25, 0x2CF2, 0x207C, 0x17B9, 0x1182, 0x0CEF, 0x09A1, 0x072F, 0x055C, 0x0406, 0x0303, 0x0240, 0x01B1, + 0x0144, 0x00F5, 0x00B7, 0x008A, 0x0068, 0x004E, 0x003B, 0x002C, 0x5AE1, 0x484C, 0x3A0D, 0x2EF1, 0x261F, 0x1F33, + 0x19A8, 0x1518, 0x1177, 0x0E74, 0x0BFB, 0x09F8, 0x0861, 0x0706, 0x05CD, 0x04DE, 0x040F, 0x0363, 0x02D4, 0x025C, + 0x01F8, 0x01A4, 0x0160, 0x0125, 0x00F6, 0x00CB, 0x00AB, 0x008F, 0x5B12, 0x4D04, 0x412C, 0x37D8, 0x2FE8, 0x293C, + 0x2379, 0x1EDF, 0x1AA9, 0x174E, 0x1424, 0x119C, 0x0F6B, 0x0D51, 0x0BB6, 0x0A40, 0x5832, 0x4D1C, 0x438E, 0x3BDD, + 0x34EE, 0x2EAE, 0x299A, 0x2516, 0x5570, 0x4CA9, 0x44D9, 0x3E22, 0x3824, 0x32B4, 0x2E17, 0x56A8, 0x4F46, 0x47E5, + 0x41CF, 0x3C3D, 0x375E, 0x5231, 0x4C0F, 0x4639, 0x415E, 0x5627, 0x50E7, 0x4B85, 0x5597, 0x504F, 0x5A10, 0x5522, + 0x59EB, 0x5A1D, + ]; + + /// Next_Index_LPS of each index. + public static ReadOnlySpan NextLps => + [ + 1, 14, 16, 18, 20, 23, 25, 28, 30, 33, 35, 9, 10, 12, 15, 36, 38, 39, 40, 42, 43, 45, 46, 48, 49, 51, 52, 54, 56, + 57, 59, 60, 62, 63, 32, 33, 37, 64, 65, 67, 68, 69, 70, 72, 73, 74, 75, 77, 78, 79, 48, 50, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 61, 61, 65, 80, 81, 82, 83, 84, 86, 87, 87, 72, 72, 74, 74, 75, 77, 77, 80, 88, 89, 90, 91, 92, 93, + 86, 88, 95, 96, 97, 99, 99, 93, 95, 101, 102, 103, 104, 99, 105, 106, 107, 103, 105, 108, 109, 110, 111, 110, 112, + 112, 113, + ]; + + /// Next_Index_MPS of each index. + public static ReadOnlySpan NextMps => + [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 9, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 32, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 48, 81, 82, 83, 84, 85, 86, 87, 71, 89, + 90, 91, 92, 93, 94, 86, 96, 97, 98, 99, 100, 93, 102, 103, 104, 99, 106, 107, 103, 109, 107, 111, 109, 111, 113, + ]; + + /// Switch_MPS of each index: 1 where an LPS inverts the sense of the MPS. + public static bool Switches(int index) => index is 0 or 14 or 36 or 64 or 80 or 88 or 95 or 105 or 110 or 112; + + /// The state of a context after coding its LPS with renormalization (T.81 D.1.5.4). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte AfterLps(byte state) + { + var index = state & 0x7F; + var mps = state & 0x80; + if (Switches(index)) + { + mps ^= 0x80; + } + + return (byte)(mps | NextLps[index]); + } + + /// The state of a context after coding its MPS with renormalization (T.81 D.1.5.3). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte AfterMps(byte state) => (byte)((state & 0x80) | NextMps[state & 0x7F]); +} + +/// +/// The arithmetic decoder of T.81 D.2, with the register layout of Table D.5: C is 32 bits, Cx its high half; bytes +/// enter the high byte of C-low. At a marker or at the end of the data it supplies zero bytes, as D.1.8 requires. +/// +internal ref struct JpegArithmeticDecoder +{ + private readonly ReadOnlySpan _data; + private int _position; + private uint _c; + private int _a; + private int _ct; + + public JpegArithmeticDecoder(ReadOnlySpan data, int position) + { + _data = data; + _position = position; + Initialize(); + } + + /// Position of the next byte not yet read. + public readonly int Position => _position; + + /// Initdec (Figure D.22) at , for a restart interval. + public void Restart(int position) + { + _position = position; + Initialize(); + } + + /// Decode(S) of Figure D.16: one binary decision of context , updated in place. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Decode(ref byte state) + { + var s = state; + int qe = JpegArithmeticTable.Qe[s & 0x7F]; + var mps = s >> 7; + _a -= qe; + int decision; + if ((int)(_c >> 16) < _a) + { + if (_a >= 0x8000) + { + return mps; + } + + // Cond_MPS_exchange (Figure D.18). + if (_a < qe) + { + decision = 1 - mps; + state = JpegArithmeticTable.AfterLps(s); + } + else + { + decision = mps; + state = JpegArithmeticTable.AfterMps(s); + } + } + else + { + // Cond_LPS_exchange (Figure D.17). + _c -= (uint)_a << 16; + if (_a < qe) + { + decision = mps; + state = JpegArithmeticTable.AfterMps(s); + } + else + { + decision = 1 - mps; + state = JpegArithmeticTable.AfterLps(s); + } + + _a = qe; + } + + // Renorm_d (Figure D.19). + do + { + if (_ct == 0) + { + ByteIn(); + _ct = 8; + } + + _a <<= 1; + _c <<= 1; + _ct--; + } + while (_a < 0x8000); + + return decision; + } + + /// A decision with the fixed estimate of probability one half (signs of AC coefficients). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int DecodeFixed() + { + var state = JpegArithmeticTable.FixedState; + return Decode(ref state); + } + + private void Initialize() + { + _c = 0; + ByteIn(); + _c <<= 8; + ByteIn(); + _c <<= 8; + _ct = 0; + _a = 0x10000; + } + + /// Byte_in of Figure D.20: a stuffed 0xFF 0x00 is one 0xFF; at a marker nothing is consumed. + private void ByteIn() + { + uint value = 0; + if (_position < _data.Length) + { + var b = _data[_position]; + if (b != 0xFF) + { + value = b; + _position++; + } + else if (_position + 1 < _data.Length && _data[_position + 1] == 0) + { + value = 0xFF; + _position += 2; + } + } + + _c += value << 8; + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegDct.cs b/src/Febe.Core/Codecs/Images/JpegDct.cs new file mode 100644 index 0000000..05463a8 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegDct.cs @@ -0,0 +1,150 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// The 8×8 discrete cosine transforms of T.81 (A.3.3), separable, in single precision. Each one-dimensional pass +/// splits the eight points into an even half (a four-point transform on coefficients 0, 2, 4, 6) and an odd half +/// (coefficients 1, 3, 5, 7), which is the textbook factorisation of the defining sums: accurate to well under one +/// level, which is what the "accurate" integer IDCT of other decoders gives too. +/// +internal static class JpegDct +{ + private const float C1 = 0.98078528040323044913f; // cos(1π/16) + private const float C2 = 0.92387953251128675613f; // cos(2π/16) + private const float C3 = 0.83146961230254523708f; // cos(3π/16) + private const float C4 = 0.70710678118654752440f; // cos(4π/16) + private const float C5 = 0.55557023301960222474f; // cos(5π/16) + private const float C6 = 0.38268343236508977173f; // cos(6π/16) + private const float C7 = 0.19509032201612826785f; // cos(7π/16) + + /// + /// Dequantizes a block (natural order) and writes its 8×8 samples to , row after row + /// bytes apart. With 12 the samples are 12-bit and are + /// reduced to 8 bits through (4096 entries); with 8 they are written as they are. + /// + public static void Inverse(ReadOnlySpan block, ReadOnlySpan quantization, Span output, int stride, int precision, ReadOnlySpan to8Bit) + { + Span work = stackalloc float[64]; + for (var c = 0; c < 8; c++) + { + if (block[8 + c] == 0 && block[16 + c] == 0 && block[24 + c] == 0 && block[32 + c] == 0 + && block[40 + c] == 0 && block[48 + c] == 0 && block[56 + c] == 0) + { + var dc = block[c] * quantization[c] * C4; + for (var r = 0; r < 8; r++) + { + work[(r * 8) + c] = dc; + } + + continue; + } + + float x0 = block[c] * quantization[c]; + float x1 = block[8 + c] * quantization[8 + c]; + float x2 = block[16 + c] * quantization[16 + c]; + float x3 = block[24 + c] * quantization[24 + c]; + float x4 = block[32 + c] * quantization[32 + c]; + float x5 = block[40 + c] * quantization[40 + c]; + float x6 = block[48 + c] * quantization[48 + c]; + float x7 = block[56 + c] * quantization[56 + c]; + Inverse1D(x0, x1, x2, x3, x4, x5, x6, x7, work, c, 8); + } + + // The column pass left every value doubled, the row pass doubles again: a quarter brings them back. + var shift = precision == 12 ? 2048.5f : 128.5f; + var max = precision == 12 ? 4095 : 255; + Span row = stackalloc float[8]; + for (var r = 0; r < 8; r++) + { + var w = work.Slice(r * 8, 8); + Inverse1D(w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], row, 0, 1); + var o = output.Slice(r * stride, 8); + for (var c = 0; c < 8; c++) + { + var value = (int)((row[c] * 0.25f) + shift); + if ((uint)value > (uint)max) + { + value = value < 0 ? 0 : max; + } + + o[c] = precision == 12 ? to8Bit[value] : (byte)value; + } + } + } + + /// + /// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order, + /// not yet quantized. + /// + public static void Forward(ReadOnlySpan samples, Span coefficients) + { + Span work = stackalloc float[64]; + for (var r = 0; r < 8; r++) + { + var s = samples.Slice(r * 8, 8); + Forward1D(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], work, r * 8, 1); + } + + for (var c = 0; c < 8; c++) + { + Forward1D(work[c], work[8 + c], work[16 + c], work[24 + c], work[32 + c], work[40 + c], work[48 + c], work[56 + c], coefficients, c, 8); + } + + for (var i = 0; i < 64; i++) + { + coefficients[i] *= 0.25f; + } + } + + /// Eight points of x[n] = Σ C(k) X[k] cos((2n+1)kπ/16), C(0) = 1/√2, C(k) = 1: twice the T.81 inverse. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Inverse1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span output, int start, int step) + { + var t0 = C4 * (x0 + x4); + var t1 = C4 * (x0 - x4); + var t2 = (C2 * x2) + (C6 * x6); + var t3 = (C6 * x2) - (C2 * x6); + var e0 = t0 + t2; + var e3 = t0 - t2; + var e1 = t1 + t3; + var e2 = t1 - t3; + + var o0 = (C1 * x1) + (C3 * x3) + (C5 * x5) + (C7 * x7); + var o1 = (C3 * x1) - (C7 * x3) - (C1 * x5) - (C5 * x7); + var o2 = (C5 * x1) - (C1 * x3) + (C7 * x5) + (C3 * x7); + var o3 = (C7 * x1) - (C5 * x3) + (C3 * x5) - (C1 * x7); + + output[start] = e0 + o0; + output[start + step] = e1 + o1; + output[start + (2 * step)] = e2 + o2; + output[start + (3 * step)] = e3 + o3; + output[start + (4 * step)] = e3 - o3; + output[start + (5 * step)] = e2 - o2; + output[start + (6 * step)] = e1 - o1; + output[start + (7 * step)] = e0 - o0; + } + + /// Eight points of X[k] = C(k) Σ x[n] cos((2n+1)kπ/16): twice the T.81 forward transform. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Forward1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span output, int start, int step) + { + var s0 = x0 + x7; + var s1 = x1 + x6; + var s2 = x2 + x5; + var s3 = x3 + x4; + var d0 = x0 - x7; + var d1 = x1 - x6; + var d2 = x2 - x5; + var d3 = x3 - x4; + + output[start] = C4 * (s0 + s1 + s2 + s3); + output[start + (4 * step)] = C4 * (s0 - s1 - s2 + s3); + output[start + (2 * step)] = (C2 * (s0 - s3)) + (C6 * (s1 - s2)); + output[start + (6 * step)] = (C6 * (s0 - s3)) - (C2 * (s1 - s2)); + output[start + step] = (C1 * d0) + (C3 * d1) + (C5 * d2) + (C7 * d3); + output[start + (3 * step)] = (C3 * d0) - (C7 * d1) - (C1 * d2) - (C5 * d3); + output[start + (5 * step)] = (C5 * d0) - (C1 * d1) + (C7 * d2) + (C3 * d3); + output[start + (7 * step)] = (C7 * d0) - (C5 * d1) + (C3 * d2) - (C1 * d3); + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegDecoder.cs b/src/Febe.Core/Codecs/Images/JpegDecoder.cs new file mode 100644 index 0000000..8ada0d5 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegDecoder.cs @@ -0,0 +1,95 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// Reads JPEG files (ITU-T T.81): baseline and extended sequential DCT, progressive DCT (spectral selection and +/// successive approximation), lossless, each with Huffman or arithmetic coding, 8 and 12 bits (lossless 2-16), any +/// sampling factors, restart intervals and DNL. Grey, YCbCr (JFIF), RGB, and with an Adobe APP14 segment CMYK and +/// YCCK, all converted to straight RGBA8 (alpha 255). The IDCT is accurate (single precision), chroma is upsampled +/// with the triangular filter where the ratio is 2 and replicated otherwise. Metadata: EXIF (with its orientation, +/// reported and not applied), the ICC profile from its APP2 chunks, XMP, comments. +/// +/// +/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged +/// (), as is a Huffman code the table does not have; a missing EOI after complete +/// scans, bytes after EOI and stray restart markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused +/// with . +/// +public static class JpegDecoder +{ + /// Whether the bytes start like a JPEG file (SOI and the start of a marker). + public static bool IsJpeg(ReadOnlySpan data) => data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF; + + /// Size and metadata of a JPEG, without decoding the pixels. + /// The file is damaged or not a JPEG. + public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) + { + var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Identify, readMetadata: true); + file.Run(); + return file.ToInfo(); + } + + /// Decodes a JPEG to straight RGBA8. + /// The file is damaged, truncated or not a JPEG. + /// The file uses the hierarchical process. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) + { + using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: false); + file.Run(); + return file.Render(pooled); + } + + /// Decodes a JPEG to straight RGBA8 and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false) + { + using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: true); + file.Run(); + var image = file.Render(pooled); + info = file.ToInfo(); + return image; + } + + /// + /// The quantized DCT coefficients of every block of a DCT-based JPEG, as they stand after the last scan, with the + /// frame parameters: what tests compare between encodings of the same image (sequential, progressive, restart). + /// + internal static JpegCoefficients DecodeCoefficients(ReadOnlyMemory data, ImageLimits? limits = null) + { + var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Coefficients, readMetadata: false); + file.Run(); + return file.ToCoefficients(); + } +} + +/// The coefficients of one component, natural order inside each block, blocks row after row. +/// Component identifier. +/// Horizontal sampling factor. +/// Vertical sampling factor. +/// Blocks that cover the component's samples horizontally. +/// Blocks that cover the component's samples vertically. +/// Blocks per row in (the MCU grid, at least ). +/// The quantization table the component used, natural order. +/// 64 coefficients per block. +internal sealed record JpegComponentCoefficients(int Id, int H, int V, int BlocksWide, int BlocksHigh, int Stride, ushort[] Quantization, short[] Coefficients) +{ + /// The DQT table the component refers to. + public int QuantizationTable { get; init; } + + /// Rows of blocks in . + public int StoredRows => Coefficients.Length / 64 / Stride; + + /// The 64 coefficients of block (, ). + public ReadOnlySpan Block(int x, int y) => Coefficients.AsSpan(((y * Stride) + x) * 64, 64); +} + +/// What returns. +internal sealed record JpegCoefficients( + int FrameMarker, + int Precision, + int Width, + int Height, + int RestartInterval, + int AdobeTransform, + bool Jfif, + int ScanCount, + IReadOnlyList Components); diff --git a/src/Febe.Core/Codecs/Images/JpegEncoder.cs b/src/Febe.Core/Codecs/Images/JpegEncoder.cs new file mode 100644 index 0000000..20d9648 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegEncoder.cs @@ -0,0 +1,796 @@ +using System.Buffers.Binary; +using System.Numerics; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// Chroma sampling of a colour JPEG. +public enum JpegSubsampling +{ + /// Chroma at half width and half height (H = V = 2 for luma): the usual choice for photos. + Ratio420, + + /// Chroma at full resolution. + Ratio444, +} + +/// How writes a file. +public sealed record JpegEncoderOptions +{ + /// The options used when a caller passes none. + public static JpegEncoderOptions Default { get; } = new(); + + /// Quality 1-100: the Annex K tables scaled (50 keeps them as they are). + public int Quality { get; init; } = 85; + + /// Chroma sampling of a colour image. + public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Ratio420; + + /// One component (luma) instead of three. + public bool Grayscale { get; init; } + + /// MCUs per restart interval (DRI and RSTn markers), 0 for none. + public int RestartInterval { get; init; } + + /// + /// EXIF to write in an APP1 segment: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by «Exif\0\0». + /// + public byte[]? Exif { get; init; } + + /// ICC profile to write in APP2 «ICC_PROFILE» chunks. + public byte[]? IccProfile { get; init; } + + /// XMP packet to write in an APP1 segment (at most one segment: no extended XMP). + public string? Xmp { get; init; } + + /// Comments to write in COM segments, UTF-8. + public IReadOnlyList Comments { get; init; } = []; +} + +/// +/// Writes baseline JPEG files (T.81 sequential DCT, Huffman, 8 bits): JFIF YCbCr with 4:2:0 or 4:4:4 chroma, or grey; +/// quantization from the Annex K tables scaled for the quality, the Annex K Huffman tables, optional restart +/// intervals, EXIF, ICC profile, XMP and comments. Alpha is dropped (JPEG has none): the colour under it is encoded. +/// The image is encoded one row of MCUs at a time, so memory is the output plus a strip of 16 rows. +/// +public static class JpegEncoder +{ + /// Encodes an image to a JPEG file. + public static byte[] Encode(RgbaImage image, JpegEncoderOptions? options = null) + { + var output = new JpegOutput(); + Write(image, options ?? JpegEncoderOptions.Default, output); + return output.ToArray(); + } + + /// Encodes an image to a JPEG file written to . + public static void Encode(RgbaImage image, Stream output, JpegEncoderOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + var buffer = new JpegOutput(); + Write(image, options ?? JpegEncoderOptions.Default, buffer); + buffer.WriteTo(output); + } + + /// + /// The quantized coefficients the encoder would write for , with its frame layout: what tests + /// compare with the decoder and with other entropy codings of the same image. + /// + internal static JpegCoefficients Transform(RgbaImage image, JpegEncoderOptions? options = null) + { + options ??= JpegEncoderOptions.Default; + var frame = new FrameLayout(image, options); + var components = new JpegComponentCoefficients[frame.Count]; + for (var i = 0; i < frame.Count; i++) + { + var c = frame.Components[i]; + components[i] = new JpegComponentCoefficients(c.Id, c.H, c.V, c.BlocksWide, c.BlocksHigh, c.Stride, frame.Quantization[c.Table], new short[c.Stride * c.Rows * 64]) + { + QuantizationTable = c.Table, + }; + } + + var strip = new Strip(frame); + for (var my = 0; my < frame.McusHigh; my++) + { + strip.Load(image, my); + for (var i = 0; i < frame.Count; i++) + { + var c = frame.Components[i]; + for (var v = 0; v < c.V; v++) + { + for (var bx = 0; bx < c.Stride; bx++) + { + var by = (my * c.V) + v; + strip.Quantize(i, bx, v, components[i].Coefficients.AsSpan(((by * c.Stride) + bx) * 64, 64)); + } + } + } + } + + return new JpegCoefficients(0xC0, 8, image.Width, image.Height, options.RestartInterval, -1, true, 1, components); + } + + /// + /// Quantized coefficients of arbitrary component planes (tests: CMYK, 12-bit, odd sampling factors). Each plane has + /// the component's own size, ceil(width × H / Hmax) × ceil(height × V / Vmax); edges are repeated to fill the blocks. + /// + internal static JpegCoefficients TransformPlanes( + int width, + int height, + int precision, + IReadOnlyList<(int Id, int H, int V, int Table, int[] Samples)> planes, + IReadOnlyList quantization, + int frameMarker) + { + var maxH = 0; + var maxV = 0; + foreach (var p in planes) + { + maxH = Math.Max(maxH, p.H); + maxV = Math.Max(maxV, p.V); + } + + var mcusWide = (width + (8 * maxH) - 1) / (8 * maxH); + var mcusHigh = (height + (8 * maxV) - 1) / (8 * maxV); + var shift = 1 << (precision - 1); + var result = new JpegComponentCoefficients[planes.Count]; + Span samples = stackalloc float[64]; + Span dct = stackalloc float[64]; + for (var i = 0; i < planes.Count; i++) + { + var p = planes[i]; + var cw = ((width * p.H) + maxH - 1) / maxH; + var ch = ((height * p.V) + maxV - 1) / maxV; + var blocksWide = (cw + 7) / 8; + var blocksHigh = (ch + 7) / 8; + var stride = planes.Count == 1 ? blocksWide : mcusWide * p.H; + var rows = planes.Count == 1 ? blocksHigh : mcusHigh * p.V; + var table = quantization[p.Table]; + var coefficients = new short[stride * rows * 64]; + for (var by = 0; by < rows; by++) + { + for (var bx = 0; bx < stride; bx++) + { + for (var y = 0; y < 8; y++) + { + var sy = Math.Min((by * 8) + y, ch - 1); + for (var x = 0; x < 8; x++) + { + var sx = Math.Min((bx * 8) + x, cw - 1); + samples[(y * 8) + x] = p.Samples[(sy * cw) + sx] - shift; + } + } + + JpegDct.Forward(samples, dct); + var block = coefficients.AsSpan(((by * stride) + bx) * 64, 64); + for (var k = 0; k < 64; k++) + { + block[k] = Round(dct[k] / table[k]); + } + } + } + + result[i] = new JpegComponentCoefficients(p.Id, p.H, p.V, blocksWide, blocksHigh, stride, table, coefficients) { QuantizationTable = p.Table }; + } + + return new JpegCoefficients(frameMarker, precision, width, height, 0, -1, false, 1, result); + } + + private static short Round(float value) => (short)Math.Clamp(MathF.Round(value, MidpointRounding.AwayFromZero), short.MinValue, short.MaxValue); + + private static void Write(RgbaImage image, JpegEncoderOptions options, JpegOutput output) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Width, 65535, nameof(image)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Height, 65535, nameof(image)); + ArgumentOutOfRangeException.ThrowIfNegative(options.RestartInterval, nameof(options)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(options.RestartInterval, 65535, nameof(options)); + var frame = new FrameLayout(image, options); + + output.Marker(0xD8); + JpegSegments.WriteJfif(output); + JpegSegments.WriteMetadata(output, options.Exif, options.Xmp, options.IccProfile, options.Comments); + JpegSegments.WriteQuantization(output, frame.Quantization); + var sof = new List<(int Id, int H, int V, int Table)>(); + foreach (var c in frame.Components) + { + sof.Add((c.Id, c.H, c.V, c.Table)); + } + + JpegSegments.WriteFrame(output, 0xC0, 8, image.Width, image.Height, sof); + JpegSegments.WriteHuffman(output, 0, 0, JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues); + JpegSegments.WriteHuffman(output, 1, 0, JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues); + if (!options.Grayscale) + { + JpegSegments.WriteHuffman(output, 0, 1, JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues); + JpegSegments.WriteHuffman(output, 1, 1, JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues); + } + + if (options.RestartInterval > 0) + { + JpegSegments.WriteRestartInterval(output, options.RestartInterval); + } + + var scan = new List<(int Id, int Dc, int Ac)>(); + foreach (var c in frame.Components) + { + scan.Add((c.Id, c.Table, c.Table)); + } + + JpegSegments.WriteScan(output, scan, 0, 63, 0, 0); + + var dc = new[] { StandardTables.LuminanceDc, StandardTables.ChrominanceDc }; + var ac = new[] { StandardTables.LuminanceAc, StandardTables.ChrominanceAc }; + var writer = new JpegBitWriter(output); + var predictors = new int[frame.Count]; + var strip = new Strip(frame); + Span block = stackalloc short[64]; + var mcu = 0; + var restart = 0; + for (var my = 0; my < frame.McusHigh; my++) + { + strip.Load(image, my); + for (var mx = 0; mx < frame.McusWide; mx++, mcu++) + { + if (options.RestartInterval > 0 && mcu > 0 && mcu % options.RestartInterval == 0) + { + writer.Flush(); + output.Marker(0xD0 + (restart++ & 7)); + Array.Clear(predictors); + } + + for (var i = 0; i < frame.Count; i++) + { + var c = frame.Components[i]; + for (var v = 0; v < c.V; v++) + { + for (var h = 0; h < c.H; h++) + { + strip.Quantize(i, (mx * c.H) + h, v, block); + EncodeBlock(writer, block, ref predictors[i], dc[c.Table], ac[c.Table]); + } + } + } + } + } + + writer.Flush(); + output.Marker(0xD9); + } + + /// One block, baseline: DC difference (F.1.2.1) and run-length coded AC (F.1.2.2). + internal static void EncodeBlock(JpegBitWriter writer, ReadOnlySpan block, ref int predictor, JpegHuffmanTable dc, JpegHuffmanTable ac) + { + var zigzag = JpegTables.ZigZag; + var difference = block[0] - predictor; + predictor = block[0]; + writer.WriteValue(dc, 0, difference); + var run = 0; + for (var k = 1; k < 64; k++) + { + int value = block[zigzag[k]]; + if (value == 0) + { + run++; + continue; + } + + while (run > 15) + { + writer.WriteSymbol(ac, 0xF0); + run -= 16; + } + + writer.WriteValue(ac, run, value); + run = 0; + } + + if (run > 0) + { + writer.WriteSymbol(ac, 0x00); + } + } + + /// The Annex K Huffman tables, built once. + internal static class StandardTables + { + public static readonly JpegHuffmanTable LuminanceDc = JpegHuffmanTable.Build(JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues); + public static readonly JpegHuffmanTable ChrominanceDc = JpegHuffmanTable.Build(JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues); + public static readonly JpegHuffmanTable LuminanceAc = JpegHuffmanTable.Build(JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues); + public static readonly JpegHuffmanTable ChrominanceAc = JpegHuffmanTable.Build(JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues); + } + + /// Components, sampling factors and quantization of the frame the encoder writes. + private sealed class FrameLayout + { + public FrameLayout(RgbaImage image, JpegEncoderOptions options) + { + var quality = options.Quality; + ArgumentOutOfRangeException.ThrowIfLessThan(quality, 1, nameof(options)); + ArgumentOutOfRangeException.ThrowIfGreaterThan(quality, 100, nameof(options)); + Width = image.Width; + Height = image.Height; + Quantization = options.Grayscale + ? [JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, quality)] + : [JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, quality), JpegTables.ScaledQuantization(JpegTables.ChrominanceQuantization, quality)]; + var luma = options.Grayscale || options.Subsampling == JpegSubsampling.Ratio444 ? 1 : 2; + MaxH = luma; + MaxV = luma; + McusWide = (Width + (8 * luma) - 1) / (8 * luma); + McusHigh = (Height + (8 * luma) - 1) / (8 * luma); + Components = options.Grayscale + ? [new LayoutComponent(1, 1, 1, 0, this)] + : [new LayoutComponent(1, luma, luma, 0, this), new LayoutComponent(2, 1, 1, 1, this), new LayoutComponent(3, 1, 1, 1, this)]; + } + + public int Width { get; } + + public int Height { get; } + + public int MaxH { get; } + + public int MaxV { get; } + + public int McusWide { get; } + + public int McusHigh { get; } + + public ushort[][] Quantization { get; } + + public LayoutComponent[] Components { get; } + + public int Count => Components.Length; + } + + private sealed class LayoutComponent + { + public LayoutComponent(int id, int h, int v, int table, FrameLayout frame) + { + Id = id; + H = h; + V = v; + Table = table; + Width = ((frame.Width * h) + frame.MaxH - 1) / frame.MaxH; + Height = ((frame.Height * v) + frame.MaxV - 1) / frame.MaxV; + BlocksWide = (Width + 7) / 8; + BlocksHigh = (Height + 7) / 8; + Stride = frame.McusWide * h; + Rows = frame.McusHigh * v; + } + + public int Id { get; } + + public int H { get; } + + public int V { get; } + + public int Table { get; } + + public int Width { get; } + + public int Height { get; } + + public int BlocksWide { get; } + + public int BlocksHigh { get; } + + /// Blocks per row of the MCU grid. + public int Stride { get; } + + /// Rows of blocks of the MCU grid. + public int Rows { get; } + } + + /// + /// One row of MCUs as component samples: RGB to YCbCr (T.871), chroma averaged over 2×2 pixels for 4:2:0, edges + /// repeated beyond the image; then the forward DCT and quantization of a block on request. + /// + private sealed class Strip + { + // RGB to YCbCr in 16-bit fixed point; each row of weights sums to 0 or 65536, so grey stays grey. + private const int YR = 19595; + private const int YG = 38470; + private const int YB = 7471; + private const int CbR = 11059; + private const int CbG = 21709; + private const int CrG = 27439; + private const int CrB = 5329; + private const int Half = 32768; + + private readonly FrameLayout _frame; + private readonly byte[][] _planes; + private readonly int[] _strides; + private readonly float[][] _reciprocals; + + public Strip(FrameLayout frame) + { + _frame = frame; + _planes = new byte[frame.Count][]; + _strides = new int[frame.Count]; + _reciprocals = new float[frame.Count][]; + for (var i = 0; i < frame.Count; i++) + { + var c = frame.Components[i]; + _strides[i] = c.Stride * 8; + _planes[i] = new byte[_strides[i] * c.V * 8]; + var table = frame.Quantization[c.Table]; + _reciprocals[i] = new float[64]; + for (var k = 0; k < 64; k++) + { + _reciprocals[i][k] = 1f / table[k]; + } + } + } + + public void Load(RgbaImage image, int mcuRow) + { + var lastX = image.Width - 1; + var lastY = image.Height - 1; + var luma = _frame.Components[0]; + var lumaRows = luma.V * 8; + var lumaStride = _strides[0]; + var top = mcuRow * lumaRows; + for (var y = 0; y < lumaRows; y++) + { + var source = image.GetRow(Math.Min(top + y, lastY)); + var plane = _planes[0].AsSpan(y * lumaStride, lumaStride); + for (var x = 0; x < lumaStride; x++) + { + var o = Math.Min(x, lastX) * 4; + plane[x] = (byte)(((YR * source[o]) + (YG * source[o + 1]) + (YB * source[o + 2]) + Half) >> 16); + } + } + + if (_frame.Count == 1) + { + return; + } + + var factor = _frame.MaxH; // 1 for 4:4:4, 2 for 4:2:0 + var chromaStride = _strides[1]; + var chromaTop = mcuRow * 8; + for (var y = 0; y < 8; y++) + { + var cb = _planes[1].AsSpan(y * chromaStride, chromaStride); + var cr = _planes[2].AsSpan(y * chromaStride, chromaStride); + for (var x = 0; x < chromaStride; x++) + { + long sumCb = 0; + long sumCr = 0; + for (var dy = 0; dy < factor; dy++) + { + var source = image.GetRow(Math.Min(((chromaTop + y) * factor) + dy, lastY)); + for (var dx = 0; dx < factor; dx++) + { + var o = Math.Min((x * factor) + dx, lastX) * 4; + int r = source[o]; + int g = source[o + 1]; + int b = source[o + 2]; + sumCb += (-CbR * r) - (CbG * g) + (Half * b); + sumCr += (Half * r) - (CrG * g) - (CrB * b); + } + } + + var count = factor * factor; + var shift = 16 + BitOperations.Log2((uint)count); + var round = 1L << (shift - 1); + cb[x] = (byte)Math.Clamp(((sumCb + round) >> shift) + 128, 0, 255); + cr[x] = (byte)Math.Clamp(((sumCr + round) >> shift) + 128, 0, 255); + } + } + } + + /// Block (, row of the strip) of component , quantized. + public void Quantize(int i, int bx, int v, Span block) + { + Span samples = stackalloc float[64]; + Span coefficients = stackalloc float[64]; + var stride = _strides[i]; + var plane = _planes[i]; + var start = (v * 8 * stride) + (bx * 8); + for (var y = 0; y < 8; y++) + { + var row = plane.AsSpan(start + (y * stride), 8); + for (var x = 0; x < 8; x++) + { + samples[(y * 8) + x] = row[x] - 128; + } + } + + JpegDct.Forward(samples, coefficients); + var reciprocal = _reciprocals[i]; + for (var k = 0; k < 64; k++) + { + var q = coefficients[k] * reciprocal[k]; + var rounded = (int)(q + (q >= 0 ? 0.5f : -0.5f)); + + // Baseline Huffman tables have AC categories up to 10 and DC differences up to 11. + block[k] = (short)Math.Clamp(rounded, -1023, 1023); + } + } + } +} + +/// A growing byte buffer for the encoders. +internal sealed class JpegOutput +{ + private byte[] _buffer = new byte[64 * 1024]; + private int _length; + + public int Length => _length; + + public void Add(byte value) + { + if (_length == _buffer.Length) + { + Array.Resize(ref _buffer, _buffer.Length * 2); + } + + _buffer[_length++] = value; + } + + public void Add(ReadOnlySpan values) + { + if (_length + values.Length > _buffer.Length) + { + Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + values.Length)); + } + + values.CopyTo(_buffer.AsSpan(_length)); + _length += values.Length; + } + + public void Marker(int marker) + { + Add(0xFF); + Add((byte)marker); + } + + /// Drops bytes from the end (the trailing zeros an arithmetic coder may leave out). + public void Truncate(int length) => _length = length; + + public byte this[int index] => _buffer[index]; + + public byte[] ToArray() => _buffer.AsSpan(0, _length).ToArray(); + + public void WriteTo(Stream stream) => stream.Write(_buffer, 0, _length); +} + +/// Writes Huffman codes and extra bits of an entropy-coded segment, stuffing a zero after each 0xFF. +internal sealed class JpegBitWriter +{ + private readonly JpegOutput _output; + private ulong _bits; + private int _count; + + public JpegBitWriter(JpegOutput output) + { + _output = output; + } + + public void WriteBits(int value, int count) + { + if (count == 0) + { + return; + } + + _bits = (_bits << count) | ((uint)value & ((1u << count) - 1)); + _count += count; + while (_count >= 8) + { + var b = (byte)(_bits >> (_count - 8)); + _output.Add(b); + if (b == 0xFF) + { + _output.Add(0); + } + + _count -= 8; + } + + _bits &= (1UL << _count) - 1; + } + + public void WriteSymbol(JpegHuffmanTable table, int symbol) + { + var size = table.Sizes[symbol]; + if (size == 0) + { + throw new InvalidOperationException($"The Huffman table has no code for symbol 0x{symbol:X2}."); + } + + WriteBits(table.Codes[symbol], size); + } + + /// Symbol (run << 4 | category) and the low bits of (F.1.2.1, F.1.2.2). + public void WriteValue(JpegHuffmanTable table, int run, int value) + { + var magnitude = Math.Abs(value); + var category = magnitude == 0 ? 0 : BitOperations.Log2((uint)magnitude) + 1; + WriteSymbol(table, (run << 4) | category); + if (category > 0 && category < 16) + { + WriteBits(value < 0 ? value - 1 : value, category); + } + } + + /// Pads the last byte with one bits (F.1.2.3). + public void Flush() + { + if (_count > 0) + { + WriteBits((1 << (8 - _count)) - 1, 8 - _count); + } + } +} + +/// Marker segments of T.81 Annex B and of JFIF, EXIF, XMP and ICC, for the encoders. +internal static class JpegSegments +{ + private const int MaxPayload = 65533; + private const int IccChunk = 65519; + + public static void WriteSegment(JpegOutput output, int marker, ReadOnlySpan payload) + { + if (payload.Length > MaxPayload) + { + throw new ArgumentException($"A JPEG segment holds at most {MaxPayload} bytes, not {payload.Length}.", nameof(payload)); + } + + output.Marker(marker); + output.Add((byte)((payload.Length + 2) >> 8)); + output.Add((byte)(payload.Length + 2)); + output.Add(payload); + } + + public static void WriteJfif(JpegOutput output) => + WriteSegment(output, 0xE0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]); + + public static void WriteMetadata(JpegOutput output, byte[]? exif, string? xmp, byte[]? icc, IReadOnlyList? comments) + { + if (exif is not null) + { + ReadOnlySpan tiff = exif; + if (tiff.StartsWith("Exif\0\0"u8)) + { + tiff = tiff[6..]; + } + + if (!tiff.StartsWith("II*\0"u8) && !tiff.StartsWith("MM\0*"u8)) + { + throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif)); + } + + if (tiff.Length + 6 > MaxPayload) + { + throw new ArgumentException($"EXIF of {tiff.Length} bytes does not fit one APP1 segment.", nameof(exif)); + } + + var payload = new byte[tiff.Length + 6]; + "Exif\0\0"u8.CopyTo(payload); + tiff.CopyTo(payload.AsSpan(6)); + WriteSegment(output, 0xE1, payload); + } + + if (xmp is not null) + { + var packet = Encoding.UTF8.GetBytes(xmp); + var ns = JpegFile.XmpNamespace; + if (packet.Length + ns.Length > MaxPayload) + { + throw new ArgumentException($"XMP of {packet.Length} bytes does not fit one APP1 segment (extended XMP is not written).", nameof(xmp)); + } + + var payload = new byte[ns.Length + packet.Length]; + ns.CopyTo(payload); + packet.CopyTo(payload, ns.Length); + WriteSegment(output, 0xE1, payload); + } + + if (icc is not null) + { + var chunks = Math.Max(1, (icc.Length + IccChunk - 1) / IccChunk); + if (chunks > 255) + { + throw new ArgumentException($"An ICC profile of {icc.Length} bytes needs more than 255 APP2 chunks.", nameof(icc)); + } + + for (var i = 0; i < chunks; i++) + { + var part = icc.AsSpan(i * IccChunk, Math.Min(IccChunk, icc.Length - (i * IccChunk))); + var payload = new byte[14 + part.Length]; + "ICC_PROFILE\0"u8.CopyTo(payload); + payload[12] = (byte)(i + 1); + payload[13] = (byte)chunks; + part.CopyTo(payload.AsSpan(14)); + WriteSegment(output, 0xE2, payload); + } + } + + if (comments is not null) + { + foreach (var comment in comments) + { + WriteSegment(output, 0xFE, Encoding.UTF8.GetBytes(comment)); + } + } + } + + /// One DQT segment with every table (8-bit entries when all fit, 16-bit otherwise), zig-zag order. + public static void WriteQuantization(JpegOutput output, IReadOnlyList tables) + { + var payload = new List(); + var zigzag = JpegTables.ZigZag; + for (var id = 0; id < tables.Count; id++) + { + var table = tables[id]; + var wide = false; + foreach (var q in table) + { + wide |= q > 255; + } + + payload.Add((byte)((wide ? 0x10 : 0) | id)); + for (var k = 0; k < 64; k++) + { + var q = table[zigzag[k]]; + if (wide) + { + payload.Add((byte)(q >> 8)); + } + + payload.Add((byte)q); + } + } + + WriteSegment(output, 0xDB, payload.ToArray()); + } + + public static void WriteFrame(JpegOutput output, int marker, int precision, int width, int height, IReadOnlyList<(int Id, int H, int V, int Table)> components) + { + var payload = new byte[6 + (3 * components.Count)]; + payload[0] = (byte)precision; + BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(1), (ushort)height); + BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(3), (ushort)width); + payload[5] = (byte)components.Count; + for (var i = 0; i < components.Count; i++) + { + var c = components[i]; + payload[6 + (3 * i)] = (byte)c.Id; + payload[7 + (3 * i)] = (byte)((c.H << 4) | c.V); + payload[8 + (3 * i)] = (byte)c.Table; + } + + WriteSegment(output, marker, payload); + } + + public static void WriteHuffman(JpegOutput output, int tableClass, int id, ReadOnlySpan counts, ReadOnlySpan values) + { + var payload = new byte[17 + values.Length]; + payload[0] = (byte)((tableClass << 4) | id); + counts.CopyTo(payload.AsSpan(1)); + values.CopyTo(payload.AsSpan(17)); + WriteSegment(output, 0xC4, payload); + } + + public static void WriteRestartInterval(JpegOutput output, int interval) => + WriteSegment(output, 0xDD, [(byte)(interval >> 8), (byte)interval]); + + public static void WriteScan(JpegOutput output, IReadOnlyList<(int Id, int Dc, int Ac)> components, int ss, int se, int ah, int al) + { + var payload = new byte[4 + (2 * components.Count)]; + payload[0] = (byte)components.Count; + for (var i = 0; i < components.Count; i++) + { + payload[1 + (2 * i)] = (byte)components[i].Id; + payload[2 + (2 * i)] = (byte)((components[i].Dc << 4) | components[i].Ac); + } + + payload[^3] = (byte)ss; + payload[^2] = (byte)se; + payload[^1] = (byte)((ah << 4) | al); + WriteSegment(output, 0xDA, payload); + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs new file mode 100644 index 0000000..a2dd77f --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs @@ -0,0 +1,338 @@ +namespace Febe.Core.Codecs.Images; + +/// Arithmetic-coded scans: sequential (T.81 F.2.4), progressive (G.1.3, G.2) and lossless (H.1.2.3). +internal sealed partial class JpegFile +{ + private const int DcStatistics = 64; + private const int AcStatistics = 256; + private const int LosslessStatistics = 158; + + private int DecodeArithmeticScan(Scan scan, int start) + { + var decoder = new JpegArithmeticDecoder(Data, start); + var pass = PassOf(Progressive, scan); + var (perRow, total) = McuLayout(scan); + var single = scan.Components.Length == 1; + var zigzag = JpegTables.ZigZag; + ReadOnlySpan to8 = Precision == 12 ? Twelve.ToEight : []; + var temp = new short[64]; + var dcStatistics = new byte[4 * DcStatistics]; + var acStatistics = new byte[4 * AcStatistics]; + + for (var mcu = 0; mcu < total; mcu++) + { + if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0) + { + decoder.Restart(SkipRestartMarker(decoder.Position)); + Array.Clear(dcStatistics); + Array.Clear(acStatistics); + foreach (var c in scan.Components) + { + c.DcPredictor = 0; + c.DcContext = 0; + } + } + + var mx = mcu % perRow; + var my = mcu / perRow; + foreach (var c in scan.Components) + { + var wide = single ? 1 : c.H; + var high = single ? 1 : c.V; + var dc = dcStatistics.AsSpan(c.DcTable * DcStatistics, DcStatistics); + var ac = acStatistics.AsSpan(c.AcTable * AcStatistics, AcStatistics); + for (var v = 0; v < high; v++) + { + for (var h = 0; h < wide; h++) + { + var bx = single ? mx : (mx * c.H) + h; + var by = single ? my : (my * c.V) + v; + Span block; + if (c.Coefficients is { } coefficients) + { + block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64); + } + else + { + block = temp; + block.Clear(); + } + + switch (pass) + { + case BlockPass.Sequential: + c.DcPredictor += DecodeDifference(ref decoder, dc, ref c.DcContext, 20, _dcL[c.DcTable], _dcU[c.DcTable]); + block[0] = (short)c.DcPredictor; + DecodeAcArithmetic(ref decoder, ac, _acK[c.AcTable], 1, 63, 0, block, zigzag); + if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh) + { + JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8); + } + + break; + case BlockPass.DcFirst: + c.DcPredictor += DecodeDifference(ref decoder, dc, ref c.DcContext, 20, _dcL[c.DcTable], _dcU[c.DcTable]); + block[0] = (short)(c.DcPredictor << scan.Al); + break; + case BlockPass.DcRefine: + if (decoder.DecodeFixed() != 0) + { + block[0] |= (short)(1 << scan.Al); + } + + break; + case BlockPass.AcFirst: + DecodeAcArithmetic(ref decoder, ac, _acK[c.AcTable], scan.Ss, scan.Se, scan.Al, block, zigzag); + break; + default: + DecodeAcRefineArithmetic(ref decoder, ac, scan, block, zigzag); + break; + } + } + } + } + } + + return FindNextMarker(decoder.Position); + } + + /// + /// The five classes of a difference for conditioning (T.81 F.1.4.4.1.2): 0 zero, 1 small positive, 2 small + /// negative, 3 large positive, 4 large negative. + /// + private static int Classify(int difference, int low, int high) + { + var magnitude = Math.Abs(difference); + var lowerBound = low == 0 ? 0 : 1 << (low - 1); + if (magnitude <= lowerBound) + { + return 0; + } + + var negative = difference < 0 ? 1 : 0; + return magnitude <= 1 << high ? 1 + negative : 3 + negative; + } + + /// + /// Decode_DC_DIFF with Decode_V (T.81 F.2.4.1, F.2.4.3): one difference of the DC model whose first four bins + /// start at , magnitude bins from . The context of the next + /// difference is set from this one. + /// + private static int DecodeDifference(ref JpegArithmeticDecoder decoder, Span statistics, ref int context, int x1, int low, int high) + { + var s0 = context; + var difference = DecodeValue(ref decoder, statistics, s0, x1); + context = Classify(difference, low, high) * 4; + return difference; + } + + private static int DecodeValue(ref JpegArithmeticDecoder decoder, Span statistics, int s0, int x1) + { + if (decoder.Decode(ref statistics[s0]) == 0) + { + return 0; + } + + var sign = decoder.Decode(ref statistics[s0 + 1]); + var s = s0 + 2 + sign; + var magnitude = 0; + if (decoder.Decode(ref statistics[s]) != 0) + { + var bound = 1; + s = x1; + while (decoder.Decode(ref statistics[s]) != 0) + { + bound <<= 1; + if (bound == 0x8000) + { + throw BadValue(); + } + + s++; + } + + magnitude = DecodeMagnitudeBits(ref decoder, statistics, s + 14, bound); + } + + var value = magnitude + 1; + return sign != 0 ? -value : value; + } + + /// Decode the bits below the leading one of Sz (Figure F.9 reversed), all with bin . + private static int DecodeMagnitudeBits(ref JpegArithmeticDecoder decoder, Span statistics, int s, int bound) + { + var magnitude = bound; + for (var bit = bound >> 1; bit != 0; bit >>= 1) + { + if (decoder.Decode(ref statistics[s]) != 0) + { + magnitude |= bit; + } + } + + return magnitude; + } + + /// AC coefficients of a sequential block or of the first scan of a band (Figure F.5, Table F.5). + private static void DecodeAcArithmetic(ref JpegArithmeticDecoder decoder, Span statistics, int kx, int ss, int se, int al, Span block, ReadOnlySpan zigzag) + { + for (var k = ss; k <= se; k++) + { + var se3 = 3 * (k - 1); + if (decoder.Decode(ref statistics[se3]) != 0) + { + return; + } + + while (decoder.Decode(ref statistics[se3 + 1]) == 0) + { + se3 += 3; + k++; + if (k > se) + { + throw BadValue(); + } + } + + var sign = decoder.DecodeFixed(); + var s = se3 + 2; + var magnitude = 0; + if (decoder.Decode(ref statistics[s]) != 0) + { + var bound = 1; + if (decoder.Decode(ref statistics[s]) != 0) + { + bound = 2; + s = k <= kx ? 189 : 217; + while (decoder.Decode(ref statistics[s]) != 0) + { + bound <<= 1; + if (bound == 0x8000) + { + throw BadValue(); + } + + s++; + } + } + + magnitude = DecodeMagnitudeBits(ref decoder, statistics, s + 14, bound); + } + + var value = magnitude + 1; + block[zigzag[k]] = (short)((sign != 0 ? -value : value) * (1 << al)); + } + } + + /// A later scan of successive approximation of a band (Figures G.10, G.11; Table G.2). + private static void DecodeAcRefineArithmetic(ref JpegArithmeticDecoder decoder, Span statistics, in Scan scan, Span block, ReadOnlySpan zigzag) + { + var plus = 1 << scan.Al; + var minus = -1 << scan.Al; + + // EOBx: one past the last coefficient made nonzero by the earlier scans. + var endOfBand = scan.Se; + while (endOfBand > 0 && block[zigzag[endOfBand]] == 0) + { + endOfBand--; + } + + for (var k = scan.Ss; k <= scan.Se; k++) + { + var se3 = 3 * (k - 1); + if (k > endOfBand && decoder.Decode(ref statistics[se3]) != 0) + { + return; + } + + while (true) + { + ref var coefficient = ref block[zigzag[k]]; + if (coefficient != 0) + { + if (decoder.Decode(ref statistics[se3 + 2]) != 0 && (coefficient & plus) == 0) + { + coefficient = (short)(coefficient >= 0 ? coefficient + plus : coefficient + minus); + } + + break; + } + + if (decoder.Decode(ref statistics[se3 + 1]) != 0) + { + coefficient = (short)(decoder.DecodeFixed() != 0 ? minus : plus); + break; + } + + se3 += 3; + k++; + if (k > scan.Se) + { + throw BadValue(); + } + } + } + } + + private int DecodeLosslessArithmeticScan(Scan scan, int start) + { + var decoder = new JpegArithmeticDecoder(Data, start); + var statistics = new byte[4 * LosslessStatistics]; + var predictor = new LosslessPredictor(this, scan); + var (perRow, total) = McuLayout(scan); + var single = scan.Components.Length == 1; + + // The class of the difference coded for every sample (T.81 H.1.2.3.1), for the contexts of its neighbours. + var classes = new byte[scan.Components.Length][]; + for (var i = 0; i < scan.Components.Length; i++) + { + var c = scan.Components[i]; + classes[i] = new byte[c.PlaneStride * c.PaddedUnitsHigh]; + } + + for (var mcu = 0; mcu < total; mcu++) + { + var mx = mcu % perRow; + var my = mcu / perRow; + if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0) + { + decoder.Restart(SkipRestartMarker(decoder.Position)); + Array.Clear(statistics); + predictor.Restart(my); + } + + for (var ci = 0; ci < scan.Components.Length; ci++) + { + var c = scan.Components[ci]; + var wide = single ? 1 : c.H; + var high = single ? 1 : c.V; + var stats = statistics.AsSpan(c.DcTable * LosslessStatistics, LosslessStatistics); + int low = _dcL[c.DcTable]; + int up = _dcU[c.DcTable]; + var cls = classes[ci]; + for (var v = 0; v < high; v++) + { + for (var h = 0; h < wide; h++) + { + var x = single ? mx : (mx * c.H) + h; + var y = single ? my : (my * c.V) + v; + var i = (y * c.PlaneStride) + x; + + // 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 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.Finish(); + return FindNextMarker(decoder.Position); + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs new file mode 100644 index 0000000..263a240 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs @@ -0,0 +1,459 @@ +namespace Febe.Core.Codecs.Images; + +/// Huffman-coded scans: sequential (T.81 F.2), progressive (G.2) and lossless (H.2). +internal sealed partial class JpegFile +{ + private enum BlockPass + { + Sequential, + DcFirst, + DcRefine, + AcFirst, + AcRefine, + } + + private static BlockPass PassOf(bool progressive, in Scan scan) => + !progressive ? BlockPass.Sequential + : scan.Ss == 0 ? (scan.Ah == 0 ? BlockPass.DcFirst : BlockPass.DcRefine) + : scan.Ah == 0 ? BlockPass.AcFirst : BlockPass.AcRefine; + + private int DecodeHuffmanScan(Scan scan, int start) + { + var data = Data; + var reader = new JpegBitReader(data, start); + var pass = PassOf(Progressive, scan); + var (perRow, total) = McuLayout(scan); + var single = scan.Components.Length == 1; + var zigzag = JpegTables.ZigZag; + ReadOnlySpan to8 = Precision == 12 ? Twelve.ToEight : []; + var temp = new short[64]; + var dcTables = new JpegHuffmanTable?[scan.Components.Length]; + var acTables = new JpegHuffmanTable?[scan.Components.Length]; + for (var i = 0; i < scan.Components.Length; i++) + { + var c = scan.Components[i]; + if (pass is BlockPass.Sequential or BlockPass.DcFirst) + { + dcTables[i] = DcTable(c.DcTable); + } + + if (pass is BlockPass.Sequential or BlockPass.AcFirst or BlockPass.AcRefine) + { + acTables[i] = AcTable(c.AcTable); + } + } + + var eobRun = 0; + for (var mcu = 0; mcu < total; mcu++) + { + if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0) + { + if (reader.UsedPadding) + { + throw InterruptedScan(); + } + + reader.Seek(SkipRestartMarker(reader.Position)); + foreach (var c in scan.Components) + { + c.DcPredictor = 0; + } + + eobRun = 0; + } + + var mx = mcu % perRow; + var my = mcu / perRow; + for (var ci = 0; ci < scan.Components.Length; ci++) + { + var c = scan.Components[ci]; + var wide = single ? 1 : c.H; + var high = single ? 1 : c.V; + for (var v = 0; v < high; v++) + { + for (var h = 0; h < wide; h++) + { + var bx = single ? mx : (mx * c.H) + h; + var by = single ? my : (my * c.V) + v; + Span block; + if (c.Coefficients is { } coefficients) + { + block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64); + } + else + { + block = temp; + block.Clear(); + } + + switch (pass) + { + case BlockPass.Sequential: + DecodeSequential(ref reader, dcTables[ci]!, acTables[ci]!, ref c.DcPredictor, block, zigzag); + if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh) + { + JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8); + } + + break; + case BlockPass.DcFirst: + { + var s = reader.DecodeHuffman(dcTables[ci]!); + if (s > 16) + { + throw BadValue(); + } + + c.DcPredictor += reader.ReceiveExtend(s); + block[0] = (short)(c.DcPredictor << scan.Al); + break; + } + + case BlockPass.DcRefine: + if (reader.ReadBit() != 0) + { + block[0] |= (short)(1 << scan.Al); + } + + break; + case BlockPass.AcFirst: + DecodeAcFirst(ref reader, acTables[ci]!, scan, ref eobRun, block, zigzag); + break; + default: + DecodeAcRefine(ref reader, acTables[ci]!, scan, ref eobRun, block, zigzag); + break; + } + } + } + } + } + + if (reader.UsedPadding) + { + throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo blocco.") : InterruptedScan(); + } + + return FindNextMarker(reader.Position); + } + + private static ImageDecodeException InterruptedScan() => + new("JPEG danneggiato: i dati compressi di una scansione si interrompono prima dell'ultimo blocco."); + + private static ImageDecodeException BadValue() => new("JPEG danneggiato: valore compresso non valido."); + + private static void DecodeSequential(ref JpegBitReader reader, JpegHuffmanTable dc, JpegHuffmanTable ac, ref int predictor, Span block, ReadOnlySpan zigzag) + { + var s = reader.DecodeHuffman(dc); + if (s > 16) + { + throw BadValue(); + } + + predictor += reader.ReceiveExtend(s); + block[0] = (short)predictor; + for (var k = 1; k < 64; k++) + { + var rs = reader.DecodeHuffman(ac); + var run = rs >> 4; + s = rs & 15; + if (s == 0) + { + if (run != 15) + { + break; + } + + k += 15; + continue; + } + + k += run; + if (k > 63) + { + throw BadValue(); + } + + block[zigzag[k]] = (short)reader.ReceiveExtend(s); + } + } + + private static void DecodeAcFirst(ref JpegBitReader reader, JpegHuffmanTable ac, in Scan scan, ref int eobRun, Span block, ReadOnlySpan zigzag) + { + if (eobRun > 0) + { + eobRun--; + return; + } + + for (var k = scan.Ss; k <= scan.Se; k++) + { + var rs = reader.DecodeHuffman(ac); + var run = rs >> 4; + var s = rs & 15; + if (s == 0) + { + if (run < 15) + { + eobRun = (1 << run) - 1; + if (run > 0) + { + eobRun += reader.ReadBits(run); + } + + break; + } + + k += 15; + continue; + } + + k += run; + if (k > scan.Se) + { + throw BadValue(); + } + + block[zigzag[k]] = (short)(reader.ReceiveExtend(s) * (1 << scan.Al)); + } + } + + private static void DecodeAcRefine(ref JpegBitReader reader, JpegHuffmanTable ac, in Scan scan, ref int eobRun, Span block, ReadOnlySpan zigzag) + { + var plus = 1 << scan.Al; + var minus = -1 << scan.Al; + var k = scan.Ss; + if (eobRun == 0) + { + for (; k <= scan.Se; k++) + { + var rs = reader.DecodeHuffman(ac); + var run = rs >> 4; + var s = rs & 15; + var value = 0; + if (s != 0) + { + if (s != 1) + { + throw BadValue(); + } + + value = reader.ReadBit() != 0 ? plus : minus; + } + else if (run != 15) + { + eobRun = 1 << run; + if (run > 0) + { + eobRun += reader.ReadBits(run); + } + + break; + } + + // Skip `run` coefficients that are still zero, refining the nonzero ones met on the way, then place the + // new coefficient (none for ZRL) on the next zero. + for (; k <= scan.Se; k++) + { + ref var coefficient = ref block[zigzag[k]]; + if (coefficient != 0) + { + Refine(ref reader, ref coefficient, plus, minus); + } + else + { + if (run == 0) + { + if (value != 0) + { + coefficient = (short)value; + } + + break; + } + + run--; + } + } + } + } + + if (eobRun > 0) + { + // Inside an end-of-band run: only the coefficients that are already nonzero get a correction bit. + for (; k <= scan.Se; k++) + { + ref var coefficient = ref block[zigzag[k]]; + if (coefficient != 0) + { + Refine(ref reader, ref coefficient, plus, minus); + } + } + + eobRun--; + } + } + + private static void Refine(ref JpegBitReader reader, ref short coefficient, int plus, int minus) + { + if (reader.ReadBit() != 0 && (coefficient & plus) == 0) + { + coefficient = (short)(coefficient >= 0 ? coefficient + plus : coefficient + minus); + } + } + + private int DecodeLosslessHuffmanScan(Scan scan, int start) + { + var reader = new JpegBitReader(Data, start); + var tables = new JpegHuffmanTable[scan.Components.Length]; + for (var i = 0; i < tables.Length; i++) + { + tables[i] = DcTable(scan.Components[i].DcTable); + } + + var predictor = new LosslessPredictor(this, scan); + var (perRow, total) = McuLayout(scan); + var single = scan.Components.Length == 1; + for (var mcu = 0; mcu < total; mcu++) + { + var mx = mcu % perRow; + var my = mcu / perRow; + if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0) + { + if (reader.UsedPadding) + { + throw InterruptedScan(); + } + + reader.Seek(SkipRestartMarker(reader.Position)); + predictor.Restart(my); + } + + for (var ci = 0; ci < scan.Components.Length; ci++) + { + var c = scan.Components[ci]; + var wide = single ? 1 : c.H; + var high = single ? 1 : c.V; + for (var v = 0; v < high; v++) + { + for (var h = 0; h < wide; h++) + { + var x = single ? mx : (mx * c.H) + h; + var y = single ? my : (my * c.V) + v; + var s = reader.DecodeHuffman(tables[ci]); + int difference = s switch + { + 0 => 0, + 16 => 32768, + > 16 => throw BadValue(), + _ => reader.ReceiveExtend(s), + }; + predictor.Store(c, x, y, difference); + } + } + } + } + + if (reader.UsedPadding) + { + throw reader.ReachedEnd ? new ImageDecodeException("JPEG troncato: i dati compressi finiscono prima dell'ultimo campione.") : InterruptedScan(); + } + + predictor.Finish(); + return FindNextMarker(reader.Position); + } + + /// The predictors of T.81 H.1.2.1 and the samples they reconstruct. + private sealed class LosslessPredictor + { + private readonly JpegFile _file; + private readonly Scan _scan; + private readonly int[] _firstRow; + private readonly int _initial; + private readonly bool _single; + + public LosslessPredictor(JpegFile file, Scan scan) + { + _file = file; + _scan = scan; + _firstRow = new int[scan.Components.Length]; + _initial = 1 << (file.Precision - scan.Al - 1); + _single = scan.Components.Length == 1; + } + + /// A restart interval starts at MCU row : its first line predicts like the first line of the scan. + public void Restart(int mcuRow) + { + for (var i = 0; i < _scan.Components.Length; i++) + { + _firstRow[i] = _single ? mcuRow : mcuRow * _scan.Components[i].V; + } + } + + /// 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)]; + + public int Predict(JpegComponent c, int x, int y) + { + var samples = c.Samples!; + var stride = c.PlaneStride; + var i = (y * stride) + x; + if (IsFirstLine(c, y)) + { + return x == 0 ? _initial : samples[i - 1]; + } + + if (x == 0) + { + return samples[i - stride]; + } + + int a = samples[i - 1]; + int b = samples[i - stride]; + int cc = samples[i - stride - 1]; + return _scan.Ss switch + { + 1 => a, + 2 => b, + 3 => cc, + 4 => a + b - cc, + 5 => a + ((b - cc) >> 1), + 6 => b + ((a - cc) >> 1), + _ => (a + b) >> 1, + }; + } + + public void Store(JpegComponent c, int x, int y, int difference) + { + var predicted = Predict(c, x, y); + c.Samples![(y * c.PlaneStride) + x] = (ushort)((predicted + difference) & 0xFFFF); + } + + /// Undoes the point transform and writes the 8-bit planes. + public void Finish() => _file.FinishLossless(_scan); + } + + private void FinishLossless(in Scan scan) + { + if (_mode != Mode.Pixels) + { + return; + } + + var max = (1 << Precision) - 1; + var shift = scan.Al; + foreach (var c in scan.Components) + { + var samples = c.Samples!; + var plane = c.Plane!; + for (var y = 0; y < c.Height; y++) + { + var row = y * c.PlaneStride; + for (var x = 0; x < c.Width; x++) + { + var value = Math.Min(samples[row + x] << shift, max); + plane[row + x] = Precision == 8 ? (byte)value : (byte)(((value * 255L) + (max >> 1)) / max); + } + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Render.cs b/src/Febe.Core/Codecs/Images/JpegFile.Render.cs new file mode 100644 index 0000000..ff30494 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.Render.cs @@ -0,0 +1,311 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// From the component planes to RGBA: upsampling of the chroma and colour conversion. +internal sealed partial class JpegFile +{ + /// The colour space of the components, as decoders choose it (JFIF, Adobe APP14, component identifiers). + internal enum ColorModel + { + Grey, + YCbCr, + Rgb, + Cmyk, + Ycck, + } + + internal ColorModel Colors + { + get + { + if (Components.Length == 1) + { + return ColorModel.Grey; + } + + if (Components.Length == 4) + { + return _adobeTransform == 2 ? ColorModel.Ycck : ColorModel.Cmyk; + } + + if (_jfif) + { + return ColorModel.YCbCr; + } + + if (_adobeTransform >= 0) + { + return _adobeTransform == 0 ? ColorModel.Rgb : ColorModel.YCbCr; + } + + return Components[0].Id == 'R' && Components[1].Id == 'G' && Components[2].Id == 'B' ? ColorModel.Rgb : ColorModel.YCbCr; + } + } + + public RgbaImage Render(bool pooled) + { + var image = RgbaImage.Create(Width, Height, _limits, pooled); + var buffers = new byte[Components.Length][]; + try + { + for (var i = 0; i < buffers.Length; i++) + { + buffers[i] = ArrayPool.Shared.Rent(Width + 1); + } + + var model = Colors; + for (var y = 0; y < Height; y++) + { + var output = image.GetRow(y); + var c0 = UpsampleRow(Components[0], y, buffers[0]); + switch (model) + { + case ColorModel.Grey: + WriteGrey(c0, output); + break; + case ColorModel.YCbCr: + WriteYCbCr(c0, UpsampleRow(Components[1], y, buffers[1]), UpsampleRow(Components[2], y, buffers[2]), output); + break; + case ColorModel.Rgb: + WriteRgb(c0, UpsampleRow(Components[1], y, buffers[1]), UpsampleRow(Components[2], y, buffers[2]), output); + break; + default: + WriteCmyk( + c0, + UpsampleRow(Components[1], y, buffers[1]), + UpsampleRow(Components[2], y, buffers[2]), + UpsampleRow(Components[3], y, buffers[3]), + output, + model == ColorModel.Ycck); + break; + } + } + } + catch + { + image.Dispose(); + throw; + } + finally + { + foreach (var buffer in buffers) + { + if (buffer is not null) + { + ArrayPool.Shared.Return(buffer); + } + } + } + + return image; + } + + /// + /// Row of the image for component , samples. A ratio + /// of 2 to the largest sampling factor uses the triangular ("fancy") filter of the JFIF siting: each output sample + /// weighs 3/4 the nearest input sample and 1/4 the next one, the edges repeating; other ratios repeat samples. + /// + private ReadOnlySpan UpsampleRow(JpegComponent c, int y, byte[] buffer) + { + var plane = c.Plane!; + var stride = c.PlaneStride; + var width = Width; + if (c.H == MaxH && c.V == MaxV) + { + return plane.AsSpan(y * stride, width); + } + + var output = buffer.AsSpan(0, width); + var lastX = c.Width - 1; + var lastY = c.Height - 1; + var integral = MaxH % c.H == 0 && MaxV % c.V == 0; + var hr = MaxH / c.H; + var vr = MaxV / c.V; + if (!integral || hr > 2 || vr > 2) + { + var sy = Math.Min((int)((long)y * c.V / MaxV), lastY); + var row = plane.AsSpan(sy * stride, c.Width); + for (var x = 0; x < width; x++) + { + output[x] = row[Math.Min((int)((long)x * c.H / MaxH), lastX)]; + } + + return output; + } + + if (vr == 1) + { + // hr == 2. + var row = plane.AsSpan(y * stride, c.Width); + for (var i = 0; i <= lastX; i++) + { + var three = row[i] * 3; + var o = 2 * i; + output[o] = (byte)((three + row[Math.Max(i - 1, 0)] + 1) >> 2); + if (o + 1 < width) + { + output[o + 1] = (byte)((three + row[Math.Min(i + 1, lastX)] + 2) >> 2); + } + } + + return output; + } + + var cy = y >> 1; + var farY = (y & 1) == 0 ? Math.Max(cy - 1, 0) : Math.Min(cy + 1, lastY); + var near = plane.AsSpan(cy * stride, c.Width); + var far = plane.AsSpan(farY * stride, c.Width); + if (hr == 1) + { + var bias = (y & 1) == 0 ? 1 : 2; + for (var x = 0; x < width; x++) + { + output[x] = (byte)(((near[x] * 3) + far[x] + bias) >> 2); + } + + return output; + } + + // h2v2: column sums first, then the horizontal triangle (rounding 8 and 7 alternate). + var previous = (near[0] * 3) + far[0]; + var current = previous; + for (var i = 0; i <= lastX; i++) + { + var next = i < lastX ? (near[i + 1] * 3) + far[i + 1] : current; + var o = 2 * i; + output[o] = (byte)(((current * 3) + previous + 8) >> 4); + if (o + 1 < width) + { + output[o + 1] = (byte)(((current * 3) + next + 7) >> 4); + } + + previous = current; + current = next; + } + + return output; + } + + private static void WriteGrey(ReadOnlySpan grey, Span output) + { + for (var x = 0; x < grey.Length; x++) + { + var o = x * 4; + var g = grey[x]; + output[o] = g; + output[o + 1] = g; + output[o + 2] = g; + output[o + 3] = 255; + } + } + + private static void WriteRgb(ReadOnlySpan r, ReadOnlySpan g, ReadOnlySpan b, Span output) + { + for (var x = 0; x < r.Length; x++) + { + var o = x * 4; + output[o] = r[x]; + output[o + 1] = g[x]; + output[o + 2] = b[x]; + output[o + 3] = 255; + } + } + + private static void WriteYCbCr(ReadOnlySpan luma, ReadOnlySpan cb, ReadOnlySpan cr, Span output) + { + var tables = YCbCrTables.Instance; + for (var x = 0; x < luma.Length; x++) + { + var o = x * 4; + int y = luma[x]; + int blue = cb[x]; + int red = cr[x]; + output[o] = Clamp(y + tables.CrToR[red]); + output[o + 1] = Clamp(y + ((tables.CbToG[blue] + tables.CrToG[red]) >> 16)); + output[o + 2] = Clamp(y + tables.CbToB[blue]); + output[o + 3] = 255; + } + } + + /// + /// CMYK as Adobe writes it (inverted: 255 is no ink) to RGB, R = C × K / 255 and so on; YCCK first gives the + /// inverted C, M, Y from its YCbCr part (T.81 has no colour spaces: this is the Adobe convention). + /// + private static void WriteCmyk(ReadOnlySpan c0, ReadOnlySpan c1, ReadOnlySpan c2, ReadOnlySpan k, Span output, bool ycck) + { + var tables = YCbCrTables.Instance; + for (var x = 0; x < c0.Length; x++) + { + int c; + int m; + int yellow; + if (ycck) + { + int y = c0[x]; + int blue = c1[x]; + int red = c2[x]; + c = 255 - Clamp(y + tables.CrToR[red]); + m = 255 - Clamp(y + ((tables.CbToG[blue] + tables.CrToG[red]) >> 16)); + yellow = 255 - Clamp(y + tables.CbToB[blue]); + } + else + { + c = c0[x]; + m = c1[x]; + yellow = c2[x]; + } + + int key = k[x]; + var o = x * 4; + output[o] = MulDiv255(c, key); + output[o + 1] = MulDiv255(m, key); + output[o + 2] = MulDiv255(yellow, key); + output[o + 3] = 255; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte MulDiv255(int a, int b) + { + var t = (a * b) + 128; + return (byte)((t + (t >> 8)) >> 8); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte Clamp(int value) => (uint)value <= 255 ? (byte)value : value < 0 ? (byte)0 : (byte)255; + + /// + /// YCbCr to RGB of JFIF (ITU-T T.871): R = Y + 1.402 (Cr − 128), G = Y − 0.344136 (Cb − 128) − 0.714136 (Cr − 128), + /// B = Y + 1.772 (Cb − 128), in 16-bit fixed point with rounding. + /// + internal sealed class YCbCrTables + { + public static readonly YCbCrTables Instance = new(); + + private YCbCrTables() + { + const int one = 1 << 16; + const int half = 1 << 15; + for (var i = 0; i < 256; i++) + { + var x = i - 128; + CrToR[i] = ((Fix(1.402) * x) + half) >> 16; + CbToB[i] = ((Fix(1.772) * x) + half) >> 16; + CrToG[i] = -Fix(0.714136) * x; + CbToG[i] = (-Fix(0.344136) * x) + half; + } + + static int Fix(double value) => (int)((value * one) + 0.5); + } + + public int[] CrToR { get; } = new int[256]; + + public int[] CbToB { get; } = new int[256]; + + public int[] CrToG { get; } = new int[256]; + + public int[] CbToG { get; } = new int[256]; + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs new file mode 100644 index 0000000..1323744 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.cs @@ -0,0 +1,1008 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// One component of a JPEG frame and what the decoder keeps of it. +internal sealed class JpegComponent +{ + public int Id; + public int Index; + public int H; + public int V; + public int QuantizationTable; + + /// Samples of the component: ceil(X × H / Hmax) × ceil(Y × V / Vmax). + public int Width; + public int Height; + + /// Data units (blocks, or samples in lossless) that cover the samples: what a non-interleaved scan codes. + public int UnitsWide; + public int UnitsHigh; + + /// Data units of the MCU grid of an interleaved scan (equal to the above in a one-component frame). + public int PaddedUnitsWide; + public int PaddedUnitsHigh; + + /// Coefficients, 64 per block of the padded grid, natural order; null when not kept. + public short[]? Coefficients; + + /// 8-bit samples, per row, covering the padded grid. + public byte[]? Plane; + public int PlaneStride; + + /// Lossless samples before the point transform is undone, same layout as . + public ushort[]? Samples; + + /// The quantization table latched at the component's first scan, natural order. + public ushort[]? Quantization; + + public bool Coded; + + // Scan state. + public int DcPredictor; + public int DcContext; + public int DcTable; + public int AcTable; +} + +/// +/// The marker-level reader of a JPEG file and its decoded state. One instance per call; the arrays it rents from the +/// pool go back in . +/// +internal sealed partial class JpegFile : IDisposable +{ + private const int MaxComponentsInScan = 4; + private const int MaxBlocksInMcu = 10; + + private readonly ReadOnlyMemory _memory; + private readonly ImageLimits _limits; + private readonly Mode _mode; + private readonly bool _readMetadata; + + private readonly ushort[]?[] _quantization = new ushort[4][]; + private readonly JpegHuffmanTable?[] _dcTables = new JpegHuffmanTable[4]; + private readonly JpegHuffmanTable?[] _acTables = new JpegHuffmanTable[4]; + private readonly byte[] _dcL = new byte[4]; + private readonly byte[] _dcU = [1, 1, 1, 1]; + private readonly byte[] _acK = [5, 5, 5, 5]; + + private int _restartInterval; + private bool _jfif; + private int _adobeTransform = -1; + private int _metadataBudget; + private byte[]? _exif; + private string? _xmp; + private List<(int Sequence, int Count, byte[] Data)>? _iccChunks; + private List? _texts; + + private bool _allocated; + private bool _pooledArrays; + private int _scanCount; + private int _sosEnd; + + public JpegFile(ReadOnlyMemory data, ImageLimits limits, Mode mode, bool readMetadata) + { + _memory = data; + _limits = limits; + _mode = mode; + _readMetadata = readMetadata; + _metadataBudget = limits.MaxMetadataBytes; + } + + internal enum Mode + { + /// Stop at the first scan: frame and metadata only. + Identify, + + /// Decode to samples. + Pixels, + + /// Decode and keep every coefficient (tests). + Coefficients, + } + + public int FrameMarker { get; private set; } + + public bool Progressive { get; private set; } + + public bool Arithmetic { get; private set; } + + public bool Lossless { get; private set; } + + public int Precision { get; private set; } + + public int Width { get; private set; } + + public int Height { get; private set; } + + public JpegComponent[] Components { get; private set; } = []; + + public int MaxH { get; private set; } + + public int MaxV { get; private set; } + + /// MCUs per row and rows of MCUs of an interleaved scan. + public int McusWide { get; private set; } + + public int McusHigh { get; private set; } + + private ReadOnlySpan Data => _memory.Span; + + public void Run() + { + var data = Data; + if (!JpegDecoder.IsJpeg(data)) + { + throw new ImageDecodeException("Non è un file JPEG."); + } + + var pos = 2; + var sawEoi = false; + while (true) + { + // Bytes that are not a marker between segments are skipped, as decoders have always done. + while (pos < data.Length && data[pos] != 0xFF) + { + pos++; + } + + while (pos < data.Length && data[pos] == 0xFF) + { + pos++; + } + + if (pos >= data.Length) + { + break; + } + + int marker = data[pos++]; + if (marker == 0x00 || marker == 0x01 || marker is >= 0xD0 and <= 0xD7) + { + continue; + } + + if (marker == 0xD9) + { + sawEoi = true; + break; + } + + if (marker == 0xD8) + { + throw new ImageDecodeException("JPEG danneggiato: due marcatori di inizio."); + } + + if (data.Length - pos < 2) + { + throw Truncated(); + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(data[pos..]); + if (length < 2 || length > data.Length - pos) + { + throw Truncated(); + } + + var payload = data.Slice(pos + 2, length - 2); + var end = pos + length; + switch (marker) + { + case 0xC0 or 0xC1 or 0xC2 or 0xC3 or 0xC9 or 0xCA or 0xCB: + ReadFrame(marker, payload); + break; + case 0xC5 or 0xC6 or 0xC7 or 0xCD or 0xCE or 0xCF or 0xDE or 0xDF: + throw new ImageFormatNotSupportedException("Febe non legge i JPEG gerarchici (T.81, allegato J)."); + case 0xC4: + ReadHuffmanTables(payload); + break; + case 0xCC: + ReadArithmeticConditioning(payload); + break; + case 0xDB: + ReadQuantizationTables(payload); + break; + case 0xDD: + if (payload.Length < 2) + { + throw new ImageDecodeException("JPEG danneggiato: segmento DRI troppo corto."); + } + + _restartInterval = BinaryPrimitives.ReadUInt16BigEndian(payload); + break; + case 0xDC: + ReadDnl(payload); + break; + case >= 0xE0 and <= 0xEF: + ReadApplication(marker, payload); + break; + case 0xFE: + if (_readMetadata) + { + ReadComment(payload); + } + + break; + case 0xDA: + if (Components.Length == 0) + { + throw new ImageDecodeException("JPEG danneggiato: una scansione prima del fotogramma."); + } + + _sosEnd = end; + if (Height == 0) + { + FindDnl(end); + } + + if (_mode == Mode.Identify) + { + return; + } + + pos = DecodeScan(payload, end); + _scanCount++; + continue; + default: + // JPGn, reserved markers: skipped by their length. + break; + } + + pos = end; + } + + if (Components.Length == 0) + { + throw new ImageDecodeException(sawEoi ? "JPEG senza fotogramma." : "JPEG troncato prima del fotogramma."); + } + + if (_mode == Mode.Identify) + { + if (Height == 0) + { + throw new ImageDecodeException("JPEG senza altezza: manca il segmento DNL."); + } + + return; + } + + if (_scanCount == 0) + { + throw new ImageDecodeException("JPEG senza dati d'immagine."); + } + + foreach (var component in Components) + { + if (!component.Coded) + { + throw new ImageDecodeException("JPEG incompleto: una componente non ha dati."); + } + } + + if (Progressive && _mode == Mode.Pixels) + { + foreach (var component in Components) + { + TransformAll(component); + } + } + } + + public ImageInfo ToInfo() + { + var icc = AssembleIcc(); + var metadata = _exif is null && icc is null && _xmp is null && _texts is null + ? ImageMetadata.Empty + : new ImageMetadata + { + Exif = _exif, + Orientation = _exif is null ? 1 : ExifOrientation.Read(_exif), + IccProfile = icc, + Xmp = _xmp, + Texts = _texts ?? [], + }; + return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata); + } + + public JpegCoefficients ToCoefficients() + { + if (Lossless) + { + throw new ImageFormatNotSupportedException("Un JPEG senza perdita non ha coefficienti."); + } + + var components = new List(Components.Length); + foreach (var c in Components) + { + components.Add(new JpegComponentCoefficients(c.Id, c.H, c.V, c.UnitsWide, c.UnitsHigh, c.PaddedUnitsWide, c.Quantization ?? new ushort[64], c.Coefficients!) { QuantizationTable = c.QuantizationTable }); + } + + return new JpegCoefficients(FrameMarker, Precision, Width, Height, _restartInterval, _adobeTransform, _jfif, _scanCount, components); + } + + public void Dispose() + { + if (!_pooledArrays) + { + return; + } + + foreach (var c in Components) + { + if (c.Plane is { } plane) + { + ArrayPool.Shared.Return(plane); + c.Plane = null; + } + + if (c.Coefficients is { } coefficients) + { + ArrayPool.Shared.Return(coefficients); + c.Coefficients = null; + } + + if (c.Samples is { } samples) + { + ArrayPool.Shared.Return(samples); + c.Samples = null; + } + } + } + + private static ImageDecodeException Truncated() => new("JPEG troncato: un segmento finisce oltre la fine del file."); + + private void ReadFrame(int marker, ReadOnlySpan p) + { + if (Components.Length != 0) + { + throw new ImageDecodeException("JPEG danneggiato: più di un fotogramma."); + } + + if (p.Length < 6) + { + throw new ImageDecodeException("JPEG danneggiato: intestazione del fotogramma troppo corta."); + } + + FrameMarker = marker; + Progressive = marker is 0xC2 or 0xCA; + Arithmetic = marker >= 0xC8; + Lossless = marker is 0xC3 or 0xCB; + Precision = p[0]; + Height = BinaryPrimitives.ReadUInt16BigEndian(p[1..]); + Width = BinaryPrimitives.ReadUInt16BigEndian(p[3..]); + int count = p[5]; + if (Lossless ? Precision is < 2 or > 16 : Precision is not (8 or 12)) + { + throw new ImageFormatNotSupportedException($"Febe non legge i JPEG con campioni di {Precision} bit."); + } + + if (Width == 0) + { + throw new ImageDecodeException("JPEG danneggiato: larghezza zero."); + } + + if (count == 0 || p.Length < 6 + (3 * count)) + { + throw new ImageDecodeException("JPEG danneggiato: componenti del fotogramma mancanti."); + } + + if (count is 2 or > 4) + { + throw new ImageFormatNotSupportedException($"Febe non legge i JPEG con {count} componenti."); + } + + var components = new JpegComponent[count]; + for (var i = 0; i < count; i++) + { + var c = p.Slice(6 + (3 * i), 3); + var component = new JpegComponent { Id = c[0], Index = i, H = c[1] >> 4, V = c[1] & 15, QuantizationTable = c[2] }; + if (component.H is < 1 or > 4 || component.V is < 1 or > 4 || (component.QuantizationTable > 3 && !Lossless)) + { + throw new ImageDecodeException("JPEG danneggiato: fattori di campionamento o tabella di quantizzazione non validi."); + } + + for (var j = 0; j < i; j++) + { + if (components[j].Id == component.Id) + { + throw new ImageDecodeException("JPEG danneggiato: due componenti con lo stesso identificativo."); + } + } + + components[i] = component; + MaxH = Math.Max(MaxH, component.H); + MaxV = Math.Max(MaxV, component.V); + } + + Components = components; + if (Height != 0) + { + ComputeGeometry(); + } + } + + private void ComputeGeometry() + { + var unit = Lossless ? 1 : 8; + McusWide = Ceil(Width, unit * MaxH); + McusHigh = Ceil(Height, unit * MaxV); + foreach (var c in Components) + { + c.Width = Ceil(Width * c.H, MaxH); + c.Height = Ceil(Height * c.V, MaxV); + c.UnitsWide = Ceil(c.Width, unit); + c.UnitsHigh = Ceil(c.Height, unit); + if (Components.Length == 1) + { + c.PaddedUnitsWide = c.UnitsWide; + c.PaddedUnitsHigh = c.UnitsHigh; + } + else + { + c.PaddedUnitsWide = McusWide * c.H; + c.PaddedUnitsHigh = McusHigh * c.V; + } + } + } + + private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor; + + private void ReadDnl(ReadOnlySpan p) + { + if (p.Length < 2) + { + throw new ImageDecodeException("JPEG danneggiato: segmento DNL troppo corto."); + } + + if (Height == 0 && Components.Length > 0) + { + Height = BinaryPrimitives.ReadUInt16BigEndian(p); + if (Height == 0) + { + throw new ImageDecodeException("JPEG danneggiato: altezza zero nel segmento DNL."); + } + + ComputeGeometry(); + } + } + + /// A frame of height 0 gives it in a DNL segment right after the first scan (T.81 B.2.5). + private void FindDnl(int scanStart) + { + var data = Data; + var pos = FindNextMarker(scanStart); + if (pos + 6 <= data.Length && data[pos + 1] == 0xDC) + { + ReadDnl(data.Slice(pos + 4, 2)); + } + + if (Height == 0) + { + throw new ImageDecodeException("JPEG senza altezza: manca il segmento DNL."); + } + } + + private void ReadQuantizationTables(ReadOnlySpan p) + { + var zigzag = JpegTables.ZigZag; + while (p.Length > 0) + { + var precision = p[0] >> 4; + var id = p[0] & 15; + var size = precision == 0 ? 64 : 128; + if (id > 3 || precision > 1 || p.Length < 1 + size) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di quantizzazione non valida."); + } + + var table = new ushort[64]; + for (var k = 0; k < 64; k++) + { + table[zigzag[k]] = precision == 0 ? p[1 + k] : BinaryPrimitives.ReadUInt16BigEndian(p[(1 + (2 * k))..]); + } + + _quantization[id] = table; + p = p[(1 + size)..]; + } + } + + private void ReadHuffmanTables(ReadOnlySpan p) + { + while (p.Length > 0) + { + if (p.Length < 17) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman troncata."); + } + + var tableClass = p[0] >> 4; + var id = p[0] & 15; + if (tableClass > 1 || id > 3) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman non valida."); + } + + var counts = p.Slice(1, 16); + var total = 0; + foreach (var count in counts) + { + total += count; + } + + if (p.Length < 17 + total) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman troncata."); + } + + var table = JpegHuffmanTable.Build(counts, p.Slice(17, total)); + (tableClass == 0 ? _dcTables : _acTables)[id] = table; + p = p[(17 + total)..]; + } + } + + private void ReadArithmeticConditioning(ReadOnlySpan p) + { + for (; p.Length >= 2; p = p[2..]) + { + var tableClass = p[0] >> 4; + var id = p[0] & 15; + var value = p[1]; + if (id > 3) + { + throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico non valido."); + } + + if (tableClass == 0) + { + var low = value & 15; + var high = value >> 4; + if (low > high) + { + throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico con L maggiore di U."); + } + + _dcL[id] = (byte)low; + _dcU[id] = (byte)high; + } + else + { + if (value is < 1 or > 63) + { + throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico Kx non valido."); + } + + _acK[id] = value; + } + } + } + + private void ReadApplication(int marker, ReadOnlySpan p) + { + // JFIF and Adobe decide the colour space, so they are read even without metadata. + if (marker == 0xE0 && p.Length >= 5 && p[..5].SequenceEqual("JFIF\0"u8)) + { + _jfif = true; + return; + } + + if (marker == 0xEE && p.Length >= 12 && p[..5].SequenceEqual("Adobe"u8)) + { + _adobeTransform = p[11]; + return; + } + + if (!_readMetadata) + { + return; + } + + // Damaged or oversized metadata is skipped: it must never stop an image from being shown. + if (marker == 0xE1) + { + if (_exif is null && p.Length > 6 && p[..4].SequenceEqual("Exif"u8) && p[4] == 0) + { + var tiff = p[6..]; + if (Spend(tiff.Length)) + { + _exif = tiff.ToArray(); + } + } + else if (_xmp is null && p.StartsWith(XmpNamespace)) + { + var packet = p[XmpNamespace.Length..]; + if (Spend(packet.Length)) + { + _xmp = Encoding.UTF8.GetString(packet); + } + } + } + else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8)) + { + int sequence = p[12]; + int count = p[13]; + var chunk = p[14..]; + if (sequence >= 1 && sequence <= count && Spend(chunk.Length)) + { + (_iccChunks ??= []).Add((sequence, count, chunk.ToArray())); + } + } + } + + /// The namespace that starts an XMP APP1 segment, with its terminating zero. + internal static ReadOnlySpan XmpNamespace => "http://ns.adobe.com/xap/1.0/\0"u8; + + private void ReadComment(ReadOnlySpan p) + { + if (!Spend(p.Length)) + { + return; + } + + string text; + try + { + text = new UTF8Encoding(false, true).GetString(p); + } + catch (DecoderFallbackException) + { + text = Encoding.Latin1.GetString(p); + } + + (_texts ??= []).Add(new ImageText(string.Empty, text.TrimEnd('\0'))); + } + + private bool Spend(int bytes) + { + if (bytes > _metadataBudget) + { + return false; + } + + _metadataBudget -= bytes; + return true; + } + + /// The ICC profile from its APP2 chunks, or null when a chunk is missing or they disagree. + private byte[]? AssembleIcc() + { + if (_iccChunks is null) + { + return null; + } + + var count = _iccChunks[0].Count; + var parts = new byte[count][]; + foreach (var (sequence, chunkCount, chunk) in _iccChunks) + { + if (chunkCount != count || parts[sequence - 1] is not null) + { + return null; + } + + parts[sequence - 1] = chunk; + } + + var total = 0; + foreach (var part in parts) + { + if (part is null) + { + return null; + } + + total += part.Length; + } + + var profile = new byte[total]; + var offset = 0; + foreach (var part in parts) + { + part.CopyTo(profile, offset); + offset += part.Length; + } + + return profile; + } + + /// The position of the next marker that is not a restart marker, or the end of the data. + private int FindNextMarker(int pos) + { + var data = Data; + while (pos + 1 < data.Length) + { + if (data[pos] == 0xFF) + { + var next = data[pos + 1]; + if (next == 0xFF) + { + pos++; + continue; + } + + if (next != 0 && next is not (>= 0xD0 and <= 0xD7)) + { + return pos; + } + + pos += 2; + continue; + } + + pos++; + } + + return data.Length; + } + + /// + /// After a restart interval: the position just after the next RSTn marker, skipping any stray bytes before it; or + /// the position of a marker that is not RSTn (it ends the scan), or the end of the data. + /// + private int SkipRestartMarker(int pos) + { + var data = Data; + while (pos + 1 < data.Length) + { + if (data[pos] == 0xFF) + { + var next = data[pos + 1]; + if (next is >= 0xD0 and <= 0xD7) + { + return pos + 2; + } + + if (next != 0 && next != 0xFF) + { + return pos; + } + } + + pos++; + } + + return data.Length; + } + + private void Allocate() + { + _limits.CheckSize(Width, Height); + var keepCoefficients = Progressive || _mode == Mode.Coefficients; + long bytes = 0; + foreach (var c in Components) + { + var unit = Lossless ? 1 : 8; + long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit; + bytes += samples; + if (keepCoefficients && !Lossless) + { + bytes += samples * 2; + } + + if (Lossless) + { + // The samples before the point transform, and for arithmetic coding the class of every difference. + bytes += samples * (Arithmetic ? 3 : 2); + } + } + + _limits.CheckWorkingBytes(bytes); + _pooledArrays = _mode == Mode.Pixels; + foreach (var c in Components) + { + var unit = Lossless ? 1 : 8; + c.PlaneStride = c.PaddedUnitsWide * unit; + var samples = c.PlaneStride * c.PaddedUnitsHigh * unit; + if (_mode == Mode.Pixels) + { + c.Plane = ArrayPool.Shared.Rent(samples); + } + + if (Lossless) + { + c.Samples = _pooledArrays ? ArrayPool.Shared.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.AsSpan(0, length).Clear(); + } + else + { + c.Coefficients = new short[length]; + } + } + } + + _allocated = true; + } + + /// A scan: its components in order and its spectral and approximation parameters. + private readonly record struct Scan(JpegComponent[] Components, int Ss, int Se, int Ah, int Al); + + private int DecodeScan(ReadOnlySpan p, int start) + { + if (!_allocated) + { + Allocate(); + } + + var scan = ReadScanHeader(p); + foreach (var c in scan.Components) + { + if (!c.Coded) + { + c.Coded = true; + if (!Lossless) + { + c.Quantization = (ushort[])(_quantization[c.QuantizationTable] + ?? throw new ImageDecodeException("JPEG danneggiato: manca una tabella di quantizzazione.")).Clone(); + } + } + + c.DcPredictor = 0; + c.DcContext = 0; + } + + if (Lossless) + { + return Arithmetic ? DecodeLosslessArithmeticScan(scan, start) : DecodeLosslessHuffmanScan(scan, start); + } + + return Arithmetic ? DecodeArithmeticScan(scan, start) : DecodeHuffmanScan(scan, start); + } + + private Scan ReadScanHeader(ReadOnlySpan p) + { + if (p.Length < 1) + { + throw new ImageDecodeException("JPEG danneggiato: intestazione di scansione vuota."); + } + + int count = p[0]; + if (count is < 1 or > MaxComponentsInScan || p.Length < 4 + (2 * count)) + { + throw new ImageDecodeException("JPEG danneggiato: intestazione di scansione non valida."); + } + + var components = new JpegComponent[count]; + var blocks = 0; + for (var i = 0; i < count; i++) + { + int id = p[1 + (2 * i)]; + var tables = p[2 + (2 * i)]; + JpegComponent? found = null; + foreach (var c in Components) + { + if (c.Id == id) + { + found = c; + } + } + + if (found is null || Array.IndexOf(components, found, 0, i) >= 0) + { + throw new ImageDecodeException("JPEG danneggiato: la scansione nomina una componente che non c'è."); + } + + found.DcTable = tables >> 4; + found.AcTable = tables & 15; + if (found.DcTable > 3 || found.AcTable > 3) + { + throw new ImageDecodeException("JPEG danneggiato: tabella d'entropia non valida."); + } + + components[i] = found; + blocks += found.H * found.V; + } + + if (count > 1 && blocks > MaxBlocksInMcu) + { + throw new ImageDecodeException("JPEG danneggiato: troppi blocchi in un MCU."); + } + + var tail = p.Slice(1 + (2 * count), 3); + int ss = tail[0]; + int se = tail[1]; + var ah = tail[2] >> 4; + var al = tail[2] & 15; + if (Lossless) + { + if (ss is < 1 or > 7 || al >= Precision) + { + throw new ImageDecodeException("JPEG danneggiato: predittore o trasformazione di punto non validi."); + } + } + else if (Progressive) + { + var valid = se <= 63 && ss <= se && al <= 13 && ah <= 13 && (ss == 0 ? se == 0 : count == 1 && ss >= 1); + if (!valid) + { + throw new ImageDecodeException("JPEG danneggiato: parametri della scansione progressiva non validi."); + } + } + else + { + ss = 0; + se = 63; + ah = 0; + al = 0; + } + + return new Scan(components, ss, se, ah, al); + } + + /// The MCUs of a scan: one block (or sample) each when it has one component, the MCU grid otherwise. + private (int PerRow, int Total) McuLayout(in Scan scan) + { + if (scan.Components.Length == 1) + { + var c = scan.Components[0]; + return (c.UnitsWide, c.UnitsWide * c.UnitsHigh); + } + + return (McusWide, McusWide * McusHigh); + } + + private JpegHuffmanTable DcTable(int id) => + _dcTables[id] ?? (id < 2 ? DefaultTables.Dc[id] : throw new ImageDecodeException("JPEG danneggiato: manca una tabella di Huffman.")); + + private JpegHuffmanTable AcTable(int id) => + _acTables[id] ?? (id < 2 ? DefaultTables.Ac[id] : throw new ImageDecodeException("JPEG danneggiato: manca una tabella di Huffman.")); + + /// + /// The Annex K tables, used when a Huffman scan refers to table 0 or 1 that the file never defines (motion JPEG + /// frames leave them out). + /// + private static class DefaultTables + { + public static readonly JpegHuffmanTable[] Dc = + [ + JpegHuffmanTable.Build(JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues), + JpegHuffmanTable.Build(JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues), + ]; + + public static readonly JpegHuffmanTable[] Ac = + [ + JpegHuffmanTable.Build(JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues), + JpegHuffmanTable.Build(JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues), + ]; + } + + /// The IDCT of every visible block of a component whose coefficients were kept. + private void TransformAll(JpegComponent c) + { + var to8 = Precision == 12 ? Twelve.ToEight : default; + var coefficients = c.Coefficients!; + var plane = c.Plane!; + for (var by = 0; by < c.UnitsHigh; by++) + { + for (var bx = 0; bx < c.UnitsWide; bx++) + { + var block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64); + JpegDct.Inverse(block, c.Quantization, plane.AsSpan((by * 8 * c.PlaneStride) + (bx * 8)), c.PlaneStride, Precision, to8); + } + } + } + + /// 12-bit samples to 8 bits, rounded. + private static class Twelve + { + public static readonly byte[] ToEight = Build(); + + private static byte[] Build() + { + var table = new byte[4096]; + for (var i = 0; i < table.Length; i++) + { + table[i] = (byte)(((i * 255) + 2047) / 4095); + } + + return table; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegHuffman.cs b/src/Febe.Core/Codecs/Images/JpegHuffman.cs new file mode 100644 index 0000000..8bbecb9 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegHuffman.cs @@ -0,0 +1,275 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// A Huffman table of T.81 (Annex C): the canonical codes built from the counts per length, with a lookup of the +/// first bits for decoding and the code of every symbol for encoding. +/// +internal sealed class JpegHuffmanTable +{ + /// Bits looked up at once; longer codes take the slow path of T.81 F.2.2.3. + public const int LookupBits = 9; + + private JpegHuffmanTable(byte[] counts, byte[] values) + { + Counts = counts; + Values = values; + } + + /// Codes of each length 1-16. + public byte[] Counts { get; } + + /// The symbols, in code order. + public byte[] Values { get; } + + /// For each value of the next bits: (length << 8) | symbol, or 0. + public ushort[] Lookup { get; } = new ushort[1 << LookupBits]; + + /// Largest code of each length (index 1-16), -1 when there is none. + public int[] MaxCode { get; } = new int[17]; + + /// For each length, the index in of its first code minus that code. + public int[] ValueOffset { get; } = new int[17]; + + /// The code of each symbol (encoding). + public ushort[] Codes { get; } = new ushort[256]; + + /// The length of the code of each symbol, 0 when the table has no code for it (encoding). + public byte[] Sizes { get; } = new byte[256]; + + /// Builds a table from the 16 counts and the symbols of a DHT segment. + /// The counts describe more codes than fit, or do not match the symbols. + public static JpegHuffmanTable Build(ReadOnlySpan counts, ReadOnlySpan values) + { + if (counts.Length != 16) + { + throw new ImageDecodeException("Tabella di Huffman JPEG non valida."); + } + + var total = 0; + foreach (var count in counts) + { + total += count; + } + + if (total > 256 || total != values.Length) + { + throw new ImageDecodeException("Tabella di Huffman JPEG non valida: troppi simboli."); + } + + var table = new JpegHuffmanTable(counts.ToArray(), values.ToArray()); + var code = 0; + var k = 0; + for (var length = 1; length <= 16; length++) + { + int count = counts[length - 1]; + table.ValueOffset[length] = k - code; + for (var i = 0; i < count; i++, k++, code++) + { + var symbol = values[k]; + if (table.Sizes[symbol] == 0) + { + table.Codes[symbol] = (ushort)code; + table.Sizes[symbol] = (byte)length; + } + + if (length <= LookupBits) + { + var shift = LookupBits - length; + var first = code << shift; + var entry = (ushort)((length << 8) | symbol); + table.Lookup.AsSpan(first, 1 << shift).Fill(entry); + } + } + + 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; + } + + return table; + } +} + +/// +/// Reads the bits of an entropy-coded segment (T.81 F.2.2.5): undoes the 0xFF 0x00 stuffing and stops at the first +/// marker or at the end of the data, after which it gives zero bits and counts them, so that a scan that needed bits +/// it did not have can be told apart from one that ended on its last byte. +/// +internal ref struct JpegBitReader +{ + private readonly ReadOnlySpan _data; + private int _position; + private ulong _bits; + private int _count; + private int _padBits; + + public JpegBitReader(ReadOnlySpan data, int position) + { + _data = data; + _position = position; + } + + /// Position of the next byte not yet read. + public readonly int Position => _position; + + /// Whether the reader ran out of data (not at a marker). + public bool ReachedEnd { get; private set; } + + /// Whether a decoded symbol used bits past the end of the segment. + public readonly bool UsedPadding => _padBits > _count; + + /// Drops the bits of the current byte and those buffered, for a restart marker or the end of a scan. + public void Reset() + { + _bits = 0; + _count = 0; + _padBits = 0; + ReachedEnd = false; + } + + /// Moves to , with no buffered bits. + public void Seek(int position) + { + Reset(); + _position = position; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ReadBit() + { + if (_count < 1) + { + Fill(); + } + + var bit = (int)(_bits >> 63); + _bits <<= 1; + _count--; + return bit; + } + + /// The next bits (0-16) as an unsigned number. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ReadBits(int n) + { + if (n == 0) + { + return 0; + } + + if (_count < n) + { + Fill(); + } + + var value = (int)(_bits >> (64 - n)); + _bits <<= n; + _count -= n; + return value; + } + + /// RECEIVE and EXTEND of T.81 F.2.2.1: bits as a signed value of category s. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ReceiveExtend(int s) + { + if (s == 0) + { + return 0; + } + + var value = ReadBits(s); + return value < 1 << (s - 1) ? value - (1 << s) + 1 : value; + } + + /// Decodes one symbol with . + /// The bits are no code of the table. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int DecodeHuffman(JpegHuffmanTable table) + { + if (_count < 16) + { + Fill(); + } + + var entry = table.Lookup[(int)(_bits >> (64 - JpegHuffmanTable.LookupBits))]; + if (entry != 0) + { + var length = entry >> 8; + _bits <<= length; + _count -= length; + return entry & 0xFF; + } + + return DecodeSlow(table); + } + + private int DecodeSlow(JpegHuffmanTable table) + { + for (var length = JpegHuffmanTable.LookupBits + 1; length <= 16; length++) + { + var code = (int)(_bits >> (64 - length)); + if (code <= table.MaxCode[length]) + { + _bits <<= length; + _count -= length; + return table.Values[table.ValueOffset[length] + code]; + } + } + + throw new ImageDecodeException("JPEG danneggiato: un codice di Huffman non esiste nella tabella."); + } + + private void Fill() + { + while (_count <= 56) + { + int value; + if (_padBits > 0) + { + value = 0; + _padBits += 8; + } + else if (_position >= _data.Length) + { + ReachedEnd = true; + value = 0; + _padBits = 8; + } + else + { + value = _data[_position]; + if (value == 0xFF) + { + if (_position + 1 < _data.Length && _data[_position + 1] == 0) + { + _position += 2; + } + else + { + // A marker (or the end of the data right after 0xFF): no more bits in this segment. + if (_position + 1 >= _data.Length) + { + ReachedEnd = true; + } + + value = 0; + _padBits = 8; + } + } + else + { + _position++; + } + } + + _bits |= (ulong)value << (56 - _count); + _count += 8; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegTables.cs b/src/Febe.Core/Codecs/Images/JpegTables.cs new file mode 100644 index 0000000..f8597b5 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegTables.cs @@ -0,0 +1,136 @@ +namespace Febe.Core.Codecs.Images; + +/// Fixed tables of ITU-T T.81: the zig-zag order and the example tables of Annex K. +internal static class JpegTables +{ + /// Coefficients in a block. + public const int BlockSize = 64; + + /// + /// For each position of the zig-zag sequence (T.81 Figure A.6), the index of the coefficient in natural (row-major) + /// order. Built by walking the anti-diagonals, so it cannot be mistyped. + /// + public static readonly byte[] ZigZag = BuildZigZag(); + + /// T.81 Table K.1, luminance quantization, natural order. + public static ReadOnlySpan LuminanceQuantization => + [ + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, + 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, + 72, 92, 95, 98, 112, 100, 103, 99, + ]; + + /// T.81 Table K.2, chrominance quantization, natural order. + public static ReadOnlySpan ChrominanceQuantization => + [ + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + ]; + + /// T.81 Table K.3 as code counts per length 1-16. + public static ReadOnlySpan LuminanceDcCounts => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; + + /// T.81 Table K.3 symbols. + public static ReadOnlySpan LuminanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + + /// T.81 Table K.4 as code counts per length 1-16. + public static ReadOnlySpan ChrominanceDcCounts => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; + + /// T.81 Table K.4 symbols. + public static ReadOnlySpan ChrominanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + + /// T.81 Table K.5 as code counts per length 1-16. + public static ReadOnlySpan LuminanceAcCounts => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D]; + + /// T.81 Table K.5 symbols (run/size), in code order. + public static ReadOnlySpan LuminanceAcValues => + [ + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, + 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, + 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, + 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, + 0xF9, 0xFA, + ]; + + /// T.81 Table K.6 as code counts per length 1-16. + public static ReadOnlySpan ChrominanceAcCounts => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; + + /// T.81 Table K.6 symbols (run/size), in code order. + public static ReadOnlySpan ChrominanceAcValues => + [ + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, + 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, + 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, + 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, + 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, + 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, + 0xF9, 0xFA, + ]; + + /// + /// An Annex K quantization table scaled for a quality of 1-100: 50 keeps the table, higher divides it, lower + /// multiplies it (scale 5000/q below 50, 200 - 2q above), each entry rounded and kept within 1-255 so the table + /// fits a baseline (8-bit) DQT. Natural order. + /// + public static ushort[] ScaledQuantization(ReadOnlySpan table, int quality) + { + quality = Math.Clamp(quality, 1, 100); + var scale = quality < 50 ? 5000 / quality : 200 - (quality * 2); + var result = new ushort[BlockSize]; + for (var i = 0; i < BlockSize; i++) + { + result[i] = (ushort)Math.Clamp(((table[i] * scale) + 50) / 100, 1, 255); + } + + return result; + } + + private static byte[] BuildZigZag() + { + var order = new byte[BlockSize]; + var k = 0; + for (var diagonal = 0; diagonal < 15; diagonal++) + { + var low = Math.Max(0, diagonal - 7); + var high = Math.Min(diagonal, 7); + if ((diagonal & 1) == 1) + { + // Odd diagonals go down-left: the row grows. + for (var row = low; row <= high; row++) + { + order[k++] = (byte)((row * 8) + (diagonal - row)); + } + } + else + { + for (var row = high; row >= low; row--) + { + order[k++] = (byte)((row * 8) + (diagonal - row)); + } + } + } + + return order; + } +} diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs index a288bda..4333493 100644 --- a/src/Febe.Core/Codecs/Images/PngDecoder.cs +++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs @@ -100,7 +100,7 @@ public static class PngDecoder ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha, Exif is null && Icc is null && Xmp is null && Texts is null ? ImageMetadata.Empty - : new ImageMetadata { Exif = 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 ?? [] }); } private static PngFile Parse(ReadOnlyMemory memory, ImageLimits limits, bool readMetadata) diff --git a/tests/Febe.Tests/Imaging/ImageFuzzTests.cs b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs index e36ba13..9f6cd5e 100644 --- a/tests/Febe.Tests/Imaging/ImageFuzzTests.cs +++ b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs @@ -18,6 +18,7 @@ public sealed class ImageFuzzTests [ReferenceFormat.Png], [ReferenceFormat.Gif], [ReferenceFormat.Bmp], + [ReferenceFormat.Jpeg], ]; [TestMethod] diff --git a/tests/Febe.Tests/Imaging/ImageQuality.cs b/tests/Febe.Tests/Imaging/ImageQuality.cs new file mode 100644 index 0000000..9c14b81 --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageQuality.cs @@ -0,0 +1,106 @@ +using System.Globalization; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// How close a lossy decode is to its reference: PSNR per channel and the share of pixels far off. +/// PSNR of the red channel, dB (infinity when identical). +/// PSNR of the green channel, dB. +/// PSNR of the blue channel, dB. +/// PSNR of the alpha channel, dB. +/// Share (0-1) of pixels with some channel off by more than . +/// Largest difference of any channel. +internal sealed record ImageQualityResult(double PsnrRed, double PsnrGreen, double PsnrBlue, double PsnrAlpha, double FarOff, int MaxDifference) +{ + /// The smallest PSNR of the colour channels. + public double MinPsnr => Math.Min(PsnrRed, Math.Min(PsnrGreen, PsnrBlue)); + + public override string ToString() => string.Create( + CultureInfo.InvariantCulture, + $"PSNR R {PsnrRed:F2} G {PsnrGreen:F2} B {PsnrBlue:F2} A {PsnrAlpha:F2} dB, oltre {ImageQuality.FarThreshold}: {FarOff * 100:F3}%, scarto massimo {MaxDifference}"); +} + +/// Measures and orientation helpers for comparing decoded images. +internal static class ImageQuality +{ + /// A pixel counts as far off when one of its channels differs by more than this. + public const int FarThreshold = 16; + + /// Lossy decodes must reach this PSNR on every colour channel (SPECIFICA §14.1, proposal of C1). + public const double MinimumPsnr = 40; + + /// Lossy decodes may have at most this share of pixels far off. + public const double MaximumFarOff = 0.001; + + public static ImageQualityResult Compare(RgbaImage expected, RgbaImage actual) + { + Assert.AreEqual((expected.Width, expected.Height), (actual.Width, actual.Height), "misura diversa"); + var e = expected.Pixels; + var a = actual.Pixels; + Span squares = stackalloc double[4]; + var far = 0; + var max = 0; + for (var i = 0; i < e.Length; i += 4) + { + var isFar = false; + for (var ch = 0; ch < 4; ch++) + { + var d = Math.Abs(e[i + ch] - a[i + ch]); + squares[ch] += d * d; + max = Math.Max(max, d); + isFar |= d > FarThreshold; + } + + if (isFar) + { + far++; + } + } + + var pixels = e.Length / 4; + return new ImageQualityResult(Psnr(squares[0], pixels), Psnr(squares[1], pixels), Psnr(squares[2], pixels), Psnr(squares[3], pixels), (double)far / pixels, max); + } + + /// Asserts the thresholds of a lossy decode. + public static void AssertClose(ImageQualityResult result, string what) + { + Assert.IsGreaterThanOrEqualTo(MinimumPsnr, result.MinPsnr, $"{what}: {result}"); + Assert.IsLessThanOrEqualTo(MaximumFarOff, result.FarOff, $"{what}: {result}"); + } + + private static double Psnr(double squares, int pixels) => + squares == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255.0 / (squares / pixels)); + + /// + /// The image as it should be shown for EXIF orientation (1-8): mirrored, rotated + /// or transposed from the stored pixels. + /// + public static RgbaImage Orient(RgbaImage stored, int orientation) + { + var w = stored.Width; + var h = stored.Height; + var swap = orientation >= 5; + var result = new RgbaImage(swap ? h : w, swap ? w : h); + for (var dy = 0; dy < result.Height; dy++) + { + var row = result.GetRow(dy); + for (var dx = 0; dx < result.Width; dx++) + { + var (sx, sy) = orientation switch + { + 2 => (w - 1 - dx, dy), + 3 => (w - 1 - dx, h - 1 - dy), + 4 => (dx, h - 1 - dy), + 5 => (dy, dx), + 6 => (dy, h - 1 - dx), + 7 => (w - 1 - dy, h - 1 - dx), + 8 => (w - 1 - dy, dx), + _ => (dx, dy), + }; + stored.GetRow(sy).Slice(sx * 4, 4).CopyTo(row[(dx * 4)..]); + } + } + + return result; + } +} diff --git a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs index 61e6cd7..565b0a3 100644 --- a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs +++ b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs @@ -85,11 +85,11 @@ public sealed class ImagingBaseTests [TestMethod] public void TheFacadeSaysWhichFormatsItCannotReadYet() { - var jpeg = ReferenceImages.Of(ReferenceFormat.Jpeg).First().ReadInput(); - var error = Assert.ThrowsExactly(() => ImageDecoder.Decode(jpeg)); - Assert.Contains("JPEG", error.Message); + var webp = ReferenceImages.Of(ReferenceFormat.WebP).First().ReadInput(); + var error = Assert.ThrowsExactly(() => ImageDecoder.Decode(webp)); + Assert.Contains("WEBP", error.Message); Assert.ThrowsExactly(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi"))); - Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp)); - Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Jpeg) || ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown)); + Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg)); + Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.WebP) || ImageDecoder.CanDecode(ImageFormat.Unknown)); } } diff --git a/tests/Febe.Tests/Imaging/JpegCodingTests.cs b/tests/Febe.Tests/Imaging/JpegCodingTests.cs new file mode 100644 index 0000000..e5f7385 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegCodingTests.cs @@ -0,0 +1,549 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The decoding processes the reference set has no file for, checked at coefficient level: the same quantized +/// coefficients are written by the baseline encoder and by the test encoder in every other way (progressive with +/// spectral selection and successive approximation, restart intervals, separate scans, DNL, arithmetic coding, +/// 12 bits, odd sampling factors), and the decoder must read back exactly those coefficients. Lossless files are +/// checked sample by sample; CMYK and YCCK through the colours. +/// +[TestClass] +public sealed class JpegCodingTests +{ + public TestContext TestContext { get; set; } = null!; + + /// Images and encoder settings the cross-checks run on. + public static IEnumerable Sources => + [ + ["gradiente-420", 61, 37, JpegSubsampling.Ratio420, false], + ["gradiente-444", 45, 29, JpegSubsampling.Ratio444, false], + ["grigio", 33, 50, JpegSubsampling.Ratio420, true], + ["riferimento-420", 0, 0, JpegSubsampling.Ratio420, false], + ]; + + private static RgbaImage SourceImage(int width, int height) + { + if (width == 0) + { + // A real-looking picture with edges: the PNG of the reference set. + return PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput()); + } + + return TestImages.Gradient(width, height, width * height); + } + + private static JpegEncoderOptions Settings(JpegSubsampling subsampling, bool grey, int quality = 90) => + new() { Quality = quality, Subsampling = subsampling, Grayscale = grey }; + + [TestMethod] + [DynamicData(nameof(Sources))] + public void TheBaselineFileHoldsExactlyTheEncodersCoefficients(string name, int width, int height, JpegSubsampling subsampling, bool grey) + { + using var image = SourceImage(width, height); + var settings = Settings(subsampling, grey); + var expected = JpegEncoder.Transform(image, settings); + var file = JpegEncoder.Encode(image, settings); + var actual = JpegDecoder.DecodeCoefficients(file); + Assert.AreEqual(0xC0, actual.FrameMarker, name); + AssertSameCoefficients(expected, actual, name); + } + + [TestMethod] + [DynamicData(nameof(Sources))] + public void EveryOtherCodingOfTheSameCoefficientsDecodesToThem(string name, int width, int height, JpegSubsampling subsampling, bool grey) + { + using var image = SourceImage(width, height); + var settings = Settings(subsampling, grey); + var coefficients = JpegEncoder.Transform(image, settings); + using var baseline = JpegDecoder.Decode(JpegEncoder.Encode(image, settings)); + var count = coefficients.Components.Count; + + var variants = new (string What, JpegTestOptions Options, int Marker)[] + { + ("sequenziale esteso", new JpegTestOptions(), 0xC1), + ("scansioni separate", new JpegTestOptions { SeparateScans = true }, 0xC1), + ("ripristino ogni 3", new JpegTestOptions { RestartInterval = 3 }, 0xC1), + ("altezza in DNL", new JpegTestOptions { HeightInDnl = true }, 0xC1), + ("progressivo", new JpegTestOptions { Progressive = true }, 0xC2), + ("progressivo con ripristino", new JpegTestOptions { Progressive = true, RestartInterval = 2 }, 0xC2), + ("solo selezione spettrale", new JpegTestOptions { Progressive = true, Script = SpectralOnly(count) }, 0xC2), + ("approssimazioni fini", new JpegTestOptions { Progressive = true, Script = ManyApproximations(count) }, 0xC2), + ("aritmetico", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic }, 0xC9), + ("aritmetico con ripristino", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 5 }, 0xC9), + ("aritmetico condizionato", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, DcConditioning = (2, 4), AcConditioning = 12 }, 0xC9), + ("aritmetico progressivo", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true }, 0xCA), + ("aritmetico progressivo fine", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true, Script = ManyApproximations(count), RestartInterval = 4 }, 0xCA), + }; + + foreach (var (what, options, marker) in variants) + { + var file = JpegTestEncoder.Write(coefficients, options); + var decoded = JpegDecoder.DecodeCoefficients(file); + Assert.AreEqual(marker, decoded.FrameMarker, $"{name}, {what}"); + AssertSameCoefficients(coefficients, decoded, $"{name}, {what}"); + + // The same coefficients make the same pixels, whatever the coding. + using var pixels = JpegDecoder.Decode(file); + ImageAssert.AreEqual(baseline, pixels, $"{name}, {what}"); + TestContext.WriteLine($"{name}, {what}: {file.Length} byte"); + } + } + + [TestMethod] + public void TheProductionEncodersRestartIntervalsChangeNoCoefficient() + { + using var image = TestImages.Gradient(83, 51, 5); + foreach (var interval in new[] { 1, 2, 7, 100 }) + { + var settings = new JpegEncoderOptions { Quality = 80, RestartInterval = interval }; + var file = JpegEncoder.Encode(image, settings); + var decoded = JpegDecoder.DecodeCoefficients(file); + Assert.AreEqual(interval, decoded.RestartInterval); + AssertSameCoefficients(JpegEncoder.Transform(image, settings), decoded, $"intervallo {interval}"); + var markers = CountRestartMarkers(file); + var mcus = ((83 + 15) / 16) * ((51 + 15) / 16); + Assert.AreEqual((mcus - 1) / interval, markers, $"intervallo {interval}"); + } + } + + public static IEnumerable TwelveBitCases => + [ + [JpegTestCoding.Huffman, false], + [JpegTestCoding.Huffman, true], + [JpegTestCoding.Arithmetic, false], + [JpegTestCoding.Arithmetic, true], + ]; + + [TestMethod] + [DynamicData(nameof(TwelveBitCases))] + public void TwelveBitFilesDecodeToTheirCoefficientsAndCloseToTheirSamples(JpegTestCoding coding, bool progressive) + { + const int width = 43; + const int height = 27; + var random = new Random(12); + var grey = new int[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + grey[(y * width) + x] = Math.Clamp((x * 4095 / (width - 1)) + random.Next(-20, 21), 0, 4095); + } + } + + // Fine 16-bit quantization: 12-bit coefficients need categories up to 15 (DC) and 14 (AC). + var table = Enumerable.Repeat((ushort)2, 64).ToArray(); + table[0] = 1; + var coefficients = JpegEncoder.TransformPlanes(width, height, 12, [(1, 1, 1, 0, grey)], [table], 0xC1); + var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = coding, Progressive = progressive, RestartInterval = 4 }); + var decoded = JpegDecoder.DecodeCoefficients(file); + Assert.AreEqual(12, decoded.Precision); + AssertSameCoefficients(coefficients, decoded, $"{coding}, progressivo {progressive}"); + + using var image = JpegDecoder.Decode(file); + var worst = 0; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var expected = ((grey[(y * width) + x] * 255) + 2047) / 4095; + worst = Math.Max(worst, Math.Abs(image.GetPixel(x, y).R - expected)); + } + } + + Assert.IsLessThanOrEqualTo(1, worst, "a 12 bit con quantizzazione fine l'errore resta sotto un livello di 8 bit"); + } + + public static IEnumerable SamplingCases => + [ + ["4:2:2", 2, 1], + ["4:4:0", 1, 2], + ["4:1:1", 4, 1], + ["4:1:0", 4, 2], + ["3×1 (rapporto non intero con 2×1)", 3, 1], + ]; + + [TestMethod] + [DynamicData(nameof(SamplingCases))] + public void AnySamplingFactorsDecode(string name, int lumaH, int lumaV) + { + using var image = TestImages.Gradient(57, 41, 9); + var (yPlane, cbPlane, crPlane) = YCbCrPlanes(image); + const int width = 57; + const int height = 41; + var chromaH = name.StartsWith('3') ? 2 : 1; + var planes = new List<(int Id, int H, int V, int Table, int[] Samples)> + { + (1, lumaH, lumaV, 0, yPlane), + (2, chromaH, 1, 1, Downsample(cbPlane, width, height, lumaH, lumaV, chromaH, 1)), + (3, chromaH, 1, 1, Downsample(crPlane, width, height, lumaH, lumaV, chromaH, 1)), + }; + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + var coefficients = JpegEncoder.TransformPlanes(width, height, 8, planes, [fine, fine], 0xC1); + foreach (var options in new[] { new JpegTestOptions(), new JpegTestOptions { Progressive = true, RestartInterval = 3 }, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic } }) + { + var file = JpegTestEncoder.Write(coefficients, options); + AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), name); + using var decoded = JpegDecoder.Decode(file); + var quality = ImageQuality.Compare(Opaque(image), decoded); + TestContext.WriteLine($"{name}: {quality}"); + + // The chroma of a smooth gradient survives subsampling well; the luma is lossless but for rounding. + Assert.IsGreaterThanOrEqualTo(30, quality.MinPsnr, $"{name}: {quality}"); + } + } + + [TestMethod] + public void AdobeCmykAndYcckBecomeRgb() + { + using var image = TestImages.Gradient(40, 24, 3); + const int width = 40; + const int height = 24; + var c = new int[width * height]; + var m = new int[width * height]; + var yellow = new int[width * height]; + var k = new int[width * height]; + for (var i = 0; i < c.Length; i++) + { + var p = image.Pixels.Slice(i * 4, 4); + + // Adobe's inverted CMYK: stored values are 255 minus the ink, so R = C × K / 255 with K = the brightest. + var key = Math.Max(p[0], Math.Max(p[1], Math.Max(p[2], (byte)1))); + k[i] = key; + c[i] = Math.Min(255, ((p[0] * 255) + (key / 2)) / key); + m[i] = Math.Min(255, ((p[1] * 255) + (key / 2)) / key); + yellow[i] = Math.Min(255, ((p[2] * 255) + (key / 2)) / key); + } + + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, c), (2, 1, 1, 0, m), (3, 1, 1, 0, yellow), (4, 1, 1, 0, k)], [fine], 0xC1); + var cmykFile = JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 }); + using var fromCmyk = JpegDecoder.Decode(cmykFile); + var cmykQuality = ImageQuality.Compare(Opaque(image), fromCmyk); + TestContext.WriteLine($"CMYK: {cmykQuality}"); + Assert.IsGreaterThanOrEqualTo(40, cmykQuality.MinPsnr, cmykQuality.ToString()); + + // YCCK: the inverted C, M, Y as RGB (255 − stored), to YCbCr; K as it is. + var yy = new int[c.Length]; + var cb = new int[c.Length]; + var cr = new int[c.Length]; + for (var i = 0; i < c.Length; i++) + { + (yy[i], cb[i], cr[i]) = ToYCbCr(255 - c[i], 255 - m[i], 255 - yellow[i]); + } + + var ycck = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, yy), (2, 1, 1, 0, cb), (3, 1, 1, 0, cr), (4, 1, 1, 0, k)], [fine], 0xC1); + var ycckFile = JpegTestEncoder.Write(ycck, new JpegTestOptions { Jfif = false, AdobeTransform = 2, Progressive = true }); + using var fromYcck = JpegDecoder.Decode(ycckFile); + var ycckQuality = ImageQuality.Compare(Opaque(image), fromYcck); + TestContext.WriteLine($"YCCK: {ycckQuality}"); + Assert.IsGreaterThanOrEqualTo(38, ycckQuality.MinPsnr, ycckQuality.ToString()); + } + + [TestMethod] + public void ThreeComponentsAreRgbWithAdobeTransformZeroOrRgbIdentifiers() + { + using var image = TestImages.Gradient(24, 16, 4); + var (r, g, b) = Channels(image); + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + foreach (var (ids, adobe) in new[] { ((1, 2, 3), 0), (('R', 'G', 'B'), -1) }) + { + var coefficients = JpegEncoder.TransformPlanes(24, 16, 8, [(ids.Item1, 1, 1, 0, r), (ids.Item2, 1, 1, 0, g), (ids.Item3, 1, 1, 0, b)], [fine], 0xC1); + using var decoded = JpegDecoder.Decode(JpegTestEncoder.Write(coefficients, new JpegTestOptions { Jfif = false, AdobeTransform = adobe })); + var quality = ImageQuality.Compare(Opaque(image), decoded); + Assert.IsGreaterThanOrEqualTo(45, quality.MinPsnr, quality.ToString()); + } + } + + public static IEnumerable LosslessCases() + { + foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic }) + { + for (var predictor = 1; predictor <= 7; predictor++) + { + yield return [coding, 8, predictor, 0, 1, 0]; + } + + yield return [coding, 8, 4, 2, 3, 0]; + yield return [coding, 12, 7, 0, 1, 5]; + yield return [coding, 16, 4, 0, 3, 0]; + yield return [coding, 16, 6, 3, 1, 9]; + yield return [coding, 2, 1, 0, 1, 0]; + yield return [coding, 8, 5, 0, 3, 4]; + } + } + + [TestMethod] + [DynamicData(nameof(LosslessCases))] + public void LosslessFilesGiveBackTheirSamples(JpegTestCoding coding, int precision, int predictor, int pointTransform, int components, int restart) + { + const int width = 23; + const int height = 14; + var random = new Random((precision * 100) + predictor); + var max = (1 << precision) - 1; + var planes = new List<(int Id, int H, int V, int[] Samples)>(); + for (var c = 0; c < components; c++) + { + var samples = new int[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + // A ramp with noise, plus a hard step: large and small differences both occur. + var value = ((x + (2 * y) + (c * 7)) * max / (width + (2 * height) + 14)) + random.Next(-3, 4) + (x > 15 ? max / 3 : 0); + samples[(y * width) + x] = Math.Clamp(value, 0, max); + } + } + + planes.Add(((byte)"RGB"[c % 3] + (c / 3), 1, 1, samples)); + } + + var options = new JpegTestOptions { Coding = coding, Jfif = false, RestartInterval = restart, DcConditioning = restart == 9 ? (1, 3) : (0, 1) }; + var file = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options); + using var image = JpegDecoder.Decode(file); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var pixel = image.GetPixel(x, y); + for (var c = 0; c < 3; c++) + { + var sample = planes[components == 1 ? 0 : c].Samples[(y * width) + x]; + var restored = (sample >> pointTransform) << pointTransform; + var expected = precision == 8 ? restored : (int)(((restored * 255L) + (max >> 1)) / max); + var actual = c == 0 ? pixel.R : c == 1 ? pixel.G : pixel.B; + Assert.AreEqual(expected, actual, $"({x}, {y}) canale {c}"); + } + } + } + + if (components == 3) + { + // The same samples as three separate scans. + var separate = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options with { SeparateScans = true }); + using var again = JpegDecoder.Decode(separate); + ImageAssert.AreEqual(image, again, "scansioni separate"); + } + } + + [TestMethod] + public void LosslessWithSamplingFactorsAndInterleavedMcus() + { + // Grey with factors 2×2 (one component: MCU of one sample) and two components... no: three, with a 2×1 luma. + const int width = 19; + const int height = 11; + var random = new Random(4); + var luma = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray(); + var chroma = Enumerable.Range(0, 10 * height).Select(_ => 128).ToArray(); + var planes = new List<(int Id, int H, int V, int[] Samples)> { (1, 2, 1, luma), (2, 1, 1, chroma), (3, 1, 1, chroma) }; + foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic }) + { + var file = JpegTestEncoder.WriteLossless(width, height, 8, planes, 1, 0, new JpegTestOptions { Coding = coding, RestartInterval = 10 }); + using var image = JpegDecoder.Decode(file); + + // Neutral chroma: every pixel is grey with the luma sample. + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var expected = luma[(y * width) + x]; + Assert.AreEqual(((byte)expected, (byte)expected, (byte)expected), (image.GetPixel(x, y).R, image.GetPixel(x, y).G, image.GetPixel(x, y).B), $"{coding} ({x}, {y})"); + } + } + } + } + + [TestMethod] + public void TheArithmeticCoderRoundTripsLongRandomDecisions() + { + // Many blocks of random coefficients exercise carries, stacked 0xFF bytes and every state of Table D.2. + var random = new Random(31); + const int width = 64; + const int height = 64; + var samples = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray(); + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + var coefficients = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, samples)], [fine], 0xC9); + foreach (var progressive in new[] { false, true }) + { + var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = progressive }); + AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), $"progressivo {progressive}"); + } + } + + [TestMethod] + public void TheArithmeticTablesHaveOneEntryPerState() + { + Assert.AreEqual(114, JpegArithmeticTable.Qe.Length); + Assert.AreEqual(114, JpegArithmeticTable.NextLps.Length); + Assert.AreEqual(114, JpegArithmeticTable.NextMps.Length); + for (var i = 0; i < 113; i++) + { + Assert.IsLessThan(113, (int)JpegArithmeticTable.NextLps[i], $"stato {i}"); + Assert.IsLessThan(113, (int)JpegArithmeticTable.NextMps[i], $"stato {i}"); + } + + // A few rows of T.81 Table D.2, checked by hand against the Recommendation. + Assert.AreEqual((0x5A1D, 1, 1, true), (JpegArithmeticTable.Qe[0], (int)JpegArithmeticTable.NextLps[0], (int)JpegArithmeticTable.NextMps[0], JpegArithmeticTable.Switches(0))); + Assert.AreEqual((0x0001, 12, 13, false), (JpegArithmeticTable.Qe[13], (int)JpegArithmeticTable.NextLps[13], (int)JpegArithmeticTable.NextMps[13], JpegArithmeticTable.Switches(13))); + Assert.AreEqual((0x002C, 33, 9, false), (JpegArithmeticTable.Qe[35], (int)JpegArithmeticTable.NextLps[35], (int)JpegArithmeticTable.NextMps[35], JpegArithmeticTable.Switches(35))); + Assert.AreEqual((0x2516, 86, 71, false), (JpegArithmeticTable.Qe[87], (int)JpegArithmeticTable.NextLps[87], (int)JpegArithmeticTable.NextMps[87], JpegArithmeticTable.Switches(87))); + Assert.AreEqual((0x59EB, 112, 111, true), (JpegArithmeticTable.Qe[112], (int)JpegArithmeticTable.NextLps[112], (int)JpegArithmeticTable.NextMps[112], JpegArithmeticTable.Switches(112))); + } + + internal static void AssertSameCoefficients(JpegCoefficients expected, JpegCoefficients actual, string what) + { + Assert.AreEqual((expected.Width, expected.Height, expected.Precision), (actual.Width, actual.Height, actual.Precision), what); + Assert.HasCount(expected.Components.Count, actual.Components, what); + for (var i = 0; i < expected.Components.Count; i++) + { + var e = expected.Components[i]; + var a = actual.Components[i]; + Assert.AreEqual((e.Id, e.H, e.V, e.BlocksWide, e.BlocksHigh), (a.Id, a.H, a.V, a.BlocksWide, a.BlocksHigh), $"{what}, componente {i}"); + CollectionAssert.AreEqual(e.Quantization, a.Quantization, $"{what}, quantizzazione {i}"); + for (var by = 0; by < e.BlocksHigh; by++) + { + for (var bx = 0; bx < e.BlocksWide; bx++) + { + var eb = e.Block(bx, by); + var ab = a.Block(bx, by); + if (!eb.SequenceEqual(ab)) + { + var k = 0; + while (eb[k] == ab[k]) + { + k++; + } + + Assert.Fail($"{what}: componente {i}, blocco ({bx}, {by}), coefficiente {k}: atteso {eb[k]}, letto {ab[k]}."); + } + } + } + } + } + + private static int CountRestartMarkers(byte[] file) + { + var count = 0; + for (var i = 0; i + 1 < file.Length; i++) + { + if (file[i] == 0xFF && file[i + 1] is >= 0xD0 and <= 0xD7) + { + count++; + } + } + + return count; + } + + private static IReadOnlyList SpectralOnly(int count) + { + var all = Enumerable.Range(0, count).ToArray(); + var scans = new List { new(all, 0, 0, 0, 0) }; + foreach (var c in all) + { + scans.Add(new([c], 1, 1, 0, 0)); + scans.Add(new([c], 2, 9, 0, 0)); + scans.Add(new([c], 10, 63, 0, 0)); + } + + return scans; + } + + private static IReadOnlyList ManyApproximations(int count) + { + var all = Enumerable.Range(0, count).ToArray(); + var scans = new List { new(all, 0, 0, 0, 4) }; + for (var al = 3; al >= 0; al--) + { + scans.Add(new(all, 0, 0, al + 1, al)); + } + + foreach (var c in all) + { + scans.Add(new([c], 1, 63, 0, 5)); + for (var al = 4; al >= 0; al--) + { + scans.Add(new([c], 1, 63, al + 1, al)); + } + } + + return scans; + } + + private static RgbaImage Opaque(RgbaImage image) + { + var copy = new RgbaImage(image.Width, image.Height, image.ToArray()); + var pixels = copy.Pixels; + for (var i = 3; i < pixels.Length; i += 4) + { + pixels[i] = 255; + } + + return copy; + } + + private static (int[] R, int[] G, int[] B) Channels(RgbaImage image) + { + var n = image.Width * image.Height; + var r = new int[n]; + var g = new int[n]; + var b = new int[n]; + for (var i = 0; i < n; i++) + { + r[i] = image.Pixels[i * 4]; + g[i] = image.Pixels[(i * 4) + 1]; + b[i] = image.Pixels[(i * 4) + 2]; + } + + return (r, g, b); + } + + private static (int Y, int Cb, int Cr) ToYCbCr(int r, int g, int b) => + ( + Math.Clamp((int)Math.Round((0.299 * r) + (0.587 * g) + (0.114 * b)), 0, 255), + Math.Clamp((int)Math.Round((-0.168736 * r) - (0.331264 * g) + (0.5 * b) + 128), 0, 255), + Math.Clamp((int)Math.Round((0.5 * r) - (0.418688 * g) - (0.081312 * b) + 128), 0, 255)); + + private static (int[] Y, int[] Cb, int[] Cr) YCbCrPlanes(RgbaImage image) + { + var (r, g, b) = Channels(image); + var y = new int[r.Length]; + var cb = new int[r.Length]; + var cr = new int[r.Length]; + for (var i = 0; i < r.Length; i++) + { + (y[i], cb[i], cr[i]) = ToYCbCr(r[i], g[i], b[i]); + } + + return (y, cb, cr); + } + + /// A full-resolution plane averaged down to a component with factors (h, v) of a frame with maxima (maxH, maxV). + private static int[] Downsample(int[] plane, int width, int height, int maxH, int maxV, int h, int v) + { + var cw = ((width * h) + maxH - 1) / maxH; + var ch = ((height * v) + maxV - 1) / maxV; + var result = new int[cw * ch]; + for (var y = 0; y < ch; y++) + { + for (var x = 0; x < cw; x++) + { + var sum = 0; + var count = 0; + for (var sy = y * maxV / v; sy < Math.Min(height, (y + 1) * maxV / v); sy++) + { + for (var sx = x * maxH / h; sx < Math.Min(width, (x + 1) * maxH / h); sx++) + { + sum += plane[(sy * width) + sx]; + count++; + } + } + + result[(y * cw) + x] = count == 0 ? 128 : (sum + (count / 2)) / count; + } + } + + return result; + } +} diff --git a/tests/Febe.Tests/Imaging/JpegEncoderTests.cs b/tests/Febe.Tests/Imaging/JpegEncoderTests.cs new file mode 100644 index 0000000..d9d60d7 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegEncoderTests.cs @@ -0,0 +1,275 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The in-house baseline JPEG encoder: the files it writes read back close to the source with our decoder, quality +/// moves size and fidelity the right way, metadata (EXIF, ICC in chunks, XMP, comments) survives the round trip, and +/// what cannot be written is refused. +/// +[TestClass] +public sealed class JpegEncoderTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheAnnexKTablesAreComplete() + { + Assert.AreEqual(12, Sum(JpegTables.LuminanceDcCounts)); + Assert.AreEqual(12, Sum(JpegTables.ChrominanceDcCounts)); + Assert.AreEqual(162, Sum(JpegTables.LuminanceAcCounts)); + Assert.AreEqual(162, Sum(JpegTables.ChrominanceAcCounts)); + Assert.HasCount(162, JpegTables.LuminanceAcValues); + Assert.HasCount(162, JpegTables.ChrominanceAcValues); + + // Every (run, size) pair with size 1..10, plus EOB and ZRL: the full AC alphabet. + var expected = new HashSet { 0x00, 0xF0 }; + for (var run = 0; run < 16; run++) + { + for (var size = 1; size <= 10; size++) + { + expected.Add((byte)((run << 4) | size)); + } + } + + Assert.IsTrue(expected.SetEquals(JpegTables.LuminanceAcValues.ToArray())); + Assert.IsTrue(expected.SetEquals(JpegTables.ChrominanceAcValues.ToArray())); + + // Zig-zag is a permutation that starts 0, 1, 8, 16, 9, 2 and ends at 63. + var zigzag = JpegTables.ZigZag.ToArray(); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), zigzag.Select(v => (int)v).ToArray()); + CollectionAssert.AreEqual(new[] { 0, 1, 8, 16, 9, 2 }, zigzag.Take(6).Select(v => (int)v).ToArray()); + Assert.AreEqual(63, (int)zigzag[63]); + } + + [TestMethod] + public void QualityScalesTheStandardTables() + { + var at50 = JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 50); + CollectionAssert.AreEqual(JpegTables.LuminanceQuantization.ToArray().Select(v => (int)v).ToArray(), at50.Select(v => (int)v).ToArray()); + Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 100).All(v => v == 1)); + Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.ChrominanceQuantization, 1).All(v => v == 255)); + + // 16 at q50 becomes (16 × 20 + 50) / 100 = 3 at q90. + Assert.AreEqual(3, (int)JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 90)[0]); + } + + public static IEnumerable RoundTrips => + [ + [JpegSubsampling.Ratio420, false, 90, 38.0], + [JpegSubsampling.Ratio444, false, 90, 40.0], + [JpegSubsampling.Ratio444, false, 100, 48.0], + [JpegSubsampling.Ratio420, true, 85, 40.0], + ]; + + [TestMethod] + [DynamicData(nameof(RoundTrips))] + public void EncodedImagesReadBackCloseToTheSource(JpegSubsampling subsampling, bool grey, int quality, double minimum) + { + using var source = Opaque(TestImages.Gradient(97, 61, 21), grey); + var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = subsampling, Grayscale = grey }); + Assert.IsTrue(JpegDecoder.IsJpeg(file)); + using var decoded = JpegDecoder.Decode(file, out var info); + Assert.AreEqual((97, 61, false, ImageFormat.Jpeg), (info.Width, info.Height, info.HasAlpha, info.Format)); + var result = ImageQuality.Compare(source, decoded); + TestContext.WriteLine($"{subsampling}, grigio {grey}, q{quality}: {file.Length} byte, {result}"); + Assert.IsGreaterThanOrEqualTo(minimum, result.MinPsnr, result.ToString()); + Assert.AreEqual(0.0, result.FarOff, result.ToString()); + } + + [TestMethod] + public void HigherQualityMeansLargerFilesAndCloserPixels() + { + using var source = Opaque(PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput()), false); + var lastSize = 0; + var lastPsnr = 0.0; + foreach (var quality in new[] { 10, 30, 50, 75, 90, 100 }) + { + // 4:4:4: the image is pixel-level noise in blue, which 4:2:0 cannot keep at any quality. + var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = JpegSubsampling.Ratio444 }); + using var decoded = JpegDecoder.Decode(file); + var result = ImageQuality.Compare(source, decoded); + TestContext.WriteLine($"q{quality}: {file.Length} byte, {result}"); + Assert.IsGreaterThan(lastSize, file.Length, $"q{quality}"); + Assert.IsGreaterThan(lastPsnr, result.MinPsnr, $"q{quality}"); + lastSize = file.Length; + lastPsnr = result.MinPsnr; + } + } + + [TestMethod] + public void TheReferenceImagesSurviveReEncoding() + { + foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg)) + { + using var original = JpegDecoder.Decode(reference.ReadInput()); + var file = JpegEncoder.Encode(original, new JpegEncoderOptions { Quality = 100, Subsampling = JpegSubsampling.Ratio444 }); + using var again = JpegDecoder.Decode(file); + var result = ImageQuality.Compare(original, again); + TestContext.WriteLine($"{reference.Name}: {result}"); + ImageQuality.AssertClose(result, reference.Name); + } + } + + [TestMethod] + public void TinyAndOddSizesWork() + { + foreach (var (width, height) in new[] { (1, 1), (1, 17), (17, 1), (8, 8), (9, 9), (15, 16), (16, 15), (33, 7) }) + { + using var source = Opaque(TestImages.Gradient(width, height, width + height), false); + foreach (var subsampling in new[] { JpegSubsampling.Ratio420, JpegSubsampling.Ratio444 }) + { + var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = 100, Subsampling = subsampling }); + using var decoded = JpegDecoder.Decode(file); + Assert.AreEqual((width, height), (decoded.Width, decoded.Height)); + var result = ImageQuality.Compare(source, decoded); + if (subsampling == JpegSubsampling.Ratio444) + { + Assert.IsLessThanOrEqualTo(8, result.MaxDifference, $"{width}×{height} {subsampling}: {result}"); + } + else + { + // The source has per-pixel noise: averaged chroma loses some of it. + Assert.IsGreaterThanOrEqualTo(25, result.MinPsnr, $"{width}×{height} {subsampling}: {result}"); + } + } + } + } + + [TestMethod] + public void RestartIntervalsDoNotChangeThePixels() + { + using var source = Opaque(TestImages.Gradient(70, 45, 8), false); + using var plain = JpegDecoder.Decode(JpegEncoder.Encode(source)); + foreach (var interval in new[] { 1, 3, 65535 }) + { + using var restarted = JpegDecoder.Decode(JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = interval })); + ImageAssert.AreEqual(plain, restarted, $"intervallo {interval}"); + } + } + + [TestMethod] + public void TheStreamOverloadWritesTheSameBytes() + { + using var source = TestImages.Gradient(20, 20, 1); + using var stream = new MemoryStream(); + JpegEncoder.Encode(source, stream); + CollectionAssert.AreEqual(JpegEncoder.Encode(source), stream.ToArray()); + } + + [TestMethod] + public void MetadataSurvivesTheRoundTrip() + { + using var source = TestImages.Gradient(30, 20, 2); + var exif = Tiff(orientation: 6); + var random = new Random(66); + var icc = new byte[150_000]; + random.NextBytes(icc); + "acsp"u8.CopyTo(icc.AsSpan(36)); + const string xmp = ""; + var options = new JpegEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp, Comments = ["primo commento", "secondo, con àccenti"] }; + var file = JpegEncoder.Encode(source, options); + + // 150 000 bytes need three APP2 chunks of at most 65 519. + Assert.AreEqual(3, CountSegments(file, 0xE2)); + + var info = JpegDecoder.Identify(file); + CollectionAssert.AreEqual(exif, info.Metadata.Exif); + Assert.AreEqual(6, info.Metadata.Orientation); + CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); + Assert.AreEqual(xmp, info.Metadata.Xmp); + CollectionAssert.AreEqual(new[] { "primo commento", "secondo, con àccenti" }, info.Metadata.Texts.Select(t => t.Text).ToArray()); + + // The orientation is reported, not applied: the pixels keep their stored layout. + using var decoded = JpegDecoder.Decode(file); + Assert.AreEqual((30, 20), (decoded.Width, decoded.Height)); + Assert.IsGreaterThan(30, ImageQuality.Compare(Opaque(source, false), decoded).MinPsnr); + + // Without metadata only JFIF is written. + var bare = JpegDecoder.Identify(JpegEncoder.Encode(source)); + Assert.IsNull(bare.Metadata.Exif); + Assert.IsNull(bare.Metadata.IccProfile); + Assert.IsNull(bare.Metadata.Xmp); + Assert.IsEmpty(bare.Metadata.Texts); + Assert.AreEqual(1, bare.Metadata.Orientation); + } + + [TestMethod] + public void WhatCannotBeWrittenIsRefused() + { + using var source = TestImages.Gradient(8, 8, 1); + foreach (var quality in new[] { 0, -5, 101 }) + { + Assert.ThrowsExactly(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality }), $"qualità {quality}"); + } + + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = -1 })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = 65536 })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = "non TIFF"u8.ToArray() })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = Tiff(1, padding: 70_000) })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Xmp = new string('x', 70_000) })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { IccProfile = new byte[256 * 65519] })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Comments = [new string('c', 70_000)] })); + } + + private static byte[] Tiff(int orientation, int padding = 0) + { + // Little-endian TIFF header, IFD0 at 8 with one entry: Orientation (0x0112), SHORT, count 1. + var tiff = new byte[8 + 2 + 12 + 4 + padding]; + "II*\0"u8.CopyTo(tiff); + tiff[4] = 8; + tiff[8] = 1; + tiff[10] = 0x12; + tiff[11] = 0x01; + tiff[12] = 3; + tiff[14] = 1; + tiff[18] = (byte)orientation; + return tiff; + } + + private static int CountSegments(byte[] file, int marker) + { + var count = 0; + var pos = 2; + while (pos + 4 <= file.Length && file[pos] == 0xFF && file[pos + 1] != 0xDA) + { + if (file[pos + 1] == marker) + { + count++; + } + + pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]); + } + + return count; + } + + private static int Sum(ReadOnlySpan counts) + { + var sum = 0; + foreach (var c in counts) + { + sum += c; + } + + return sum; + } + + /// The image with alpha 255 (JPEG has none) and, for grey, R = G = B. + private static RgbaImage Opaque(RgbaImage image, bool grey) + { + var pixels = image.ToArray(); + for (var i = 0; i < pixels.Length; i += 4) + { + if (grey) + { + var y = (byte)(((pixels[i] * 299) + (pixels[i + 1] * 587) + (pixels[i + 2] * 114) + 500) / 1000); + pixels[i] = pixels[i + 1] = pixels[i + 2] = y; + } + + pixels[i + 3] = 255; + } + + return new RgbaImage(image.Width, image.Height, pixels); + } +} diff --git a/tests/Febe.Tests/Imaging/JpegMalformedTests.cs b/tests/Febe.Tests/Imaging/JpegMalformedTests.cs new file mode 100644 index 0000000..0129997 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegMalformedTests.cs @@ -0,0 +1,353 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI, +/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way. +/// +[TestClass] +public sealed class JpegMalformedTests +{ + private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 }; + + private static byte[] Baseline(int width = 37, int height = 21, int restart = 0) => + JpegEncoder.Encode(TestImages.Gradient(width, height, 3), new JpegEncoderOptions { Quality = 80, RestartInterval = restart }); + + [TestMethod] + public void ABaselineFileCutInsideItsScanIsDamaged() + { + foreach (var restart in new[] { 0, 2 }) + { + var file = Baseline(restart: restart); + // Identify needs the headers up to the frame, not the scan. + var sof = SegmentOffset(file, 0xC0); + var frameEnd = sof + 2 + ((file[sof + 2] << 8) | file[sof + 3]); + using var whole = JpegDecoder.Decode(file); + for (var length = 0; length < file.Length - 2; length++) + { + var cut = file[..length]; + Assert.Throws(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte"); + if (length < frameEnd) + { + Assert.Throws(() => JpegDecoder.Identify(cut), $"Identify, {length} byte"); + } + } + + // Only the EOI missing: complete scans are accepted. + using var withoutEoi = JpegDecoder.Decode(file[..^2]); + ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}"); + } + } + + [TestMethod] + public void BytesAfterTheEndAreIgnored() + { + var file = Baseline(); + using var whole = JpegDecoder.Decode(file); + var random = new Random(5); + var tail = new byte[300]; + random.NextBytes(tail); + byte[] longer = [.. file, .. tail]; + using var withTail = JpegDecoder.Decode(longer); + ImageAssert.AreEqual(whole, withTail, "byte dopo EOI"); + } + + [TestMethod] + public void FillBytesAndGarbageBetweenSegmentsAreSkipped() + { + var file = Baseline(); + using var whole = JpegDecoder.Decode(file); + var dqt = SegmentOffset(file, 0xDB); + + // T.81 B.1.1.2: any marker may be preceded by fill bytes 0xFF. + byte[] padded = [.. file[..dqt], 0xFF, 0xFF, 0xFF, .. file[dqt..]]; + using var filled = JpegDecoder.Decode(padded); + ImageAssert.AreEqual(whole, filled, "byte di riempimento"); + } + + [TestMethod] + public void WithoutDhtTheAnnexKTablesAreUsed() + { + // Motion JPEG frames omit DHT and rely on the tables of Annex K, which are the ones our encoder writes. + var file = Baseline(); + using var whole = JpegDecoder.Decode(file); + var stripped = RemoveSegments(file, 0xC4); + Assert.IsLessThan(file.Length, stripped.Length); + using var decoded = JpegDecoder.Decode(stripped); + ImageAssert.AreEqual(whole, decoded, "senza DHT"); + } + + [TestMethod] + public void HierarchicalAndTwoComponentFilesAreNotSupported() + { + var file = Baseline(); + foreach (var marker in new byte[] { 0xC5, 0xC6, 0xC7, 0xCD, 0xCE, 0xCF }) + { + var changed = file.ToArray(); + changed[SegmentOffset(file, 0xC0) + 1] = marker; + Assert.ThrowsExactly(() => JpegDecoder.Decode(changed), $"SOF 0x{marker:X2}"); + } + + var fine = Enumerable.Repeat((ushort)1, 64).ToArray(); + var samples = new int[16 * 16]; + var two = JpegEncoder.TransformPlanes(16, 16, 8, [(1, 1, 1, 0, samples), (2, 1, 1, 0, samples)], [fine], 0xC1); + var twoFile = JpegTestEncoder.Write(two, new JpegTestOptions()); + Assert.ThrowsExactly(() => JpegDecoder.Decode(twoFile)); + } + + [TestMethod] + public void DamagedHeadersAreRefused() + { + var file = Baseline(); + var sof = SegmentOffset(file, 0xC0); + var sos = SegmentOffset(file, 0xDA); + + // Width 0. + var zeroWidth = file.ToArray(); + zeroWidth[sof + 7] = 0; + zeroWidth[sof + 8] = 0; + AssertDamaged(zeroWidth, "larghezza 0"); + + // Height 0 and no DNL segment after the first scan. + var zeroHeight = file.ToArray(); + zeroHeight[sof + 5] = 0; + zeroHeight[sof + 6] = 0; + AssertDamaged(zeroHeight, "altezza 0 senza DNL"); + + // Precision 7. + var precision = file.ToArray(); + precision[sof + 4] = 7; + Assert.Throws(() => JpegDecoder.Decode(precision), "precisione 7"); + + // Sampling factor 0 and 5. + foreach (var factor in new byte[] { 0x01, 0x10, 0x51, 0x15 }) + { + var sampling = file.ToArray(); + sampling[sof + 11] = factor; + AssertDamaged(sampling, $"campionamento 0x{factor:X2}"); + } + + // A scan naming a component the frame does not have. + var unknown = file.ToArray(); + unknown[sos + 5] = 99; + AssertDamaged(unknown, "componente sconosciuto"); + + // A scan referring to a Huffman table that was never defined (slot 3). + var table = file.ToArray(); + table[sos + 6] = 0x33; + AssertDamaged(table, "tabella di Huffman assente"); + + // 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). + var dht = SegmentOffset(file, 0xC4); + var badTable = file.ToArray(); + badTable[dht + 5] = 3; + AssertDamaged(badTable, "tabella di Huffman impossibile"); + + // A segment length that runs past the end. + var longSegment = file.ToArray(); + longSegment[sof + 2] = 0xFF; + AssertDamaged(longSegment, "segmento oltre la fine"); + + // No SOI, no frame, no scan. + AssertDamaged(file[2..], "senza SOI"); + AssertDamaged([0xFF, 0xD8, 0xFF, 0xD9], "solo SOI ed EOI"); + AssertDamaged(file[..sos], "senza scansioni"); + } + + [TestMethod] + public void TheLimitsAreEnforcedBeforeDecoding() + { + var file = Baseline(200, 150); + Assert.ThrowsExactly(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 })); + Assert.ThrowsExactly(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 })); + Assert.ThrowsExactly(() => JpegDecoder.Decode(file, new ImageLimits { MaxWorkingBytes = 40_000 })); + + // A header claiming 65535 × 65535 is refused at once, not after allocating. + var huge = file.ToArray(); + var sof = SegmentOffset(file, 0xC0); + huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF; + Assert.ThrowsExactly(() => JpegDecoder.Decode(huge, Small)); + } + + [TestMethod] + public void AnIccProfileWithAMissingChunkIsDropped() + { + var icc = new byte[140_000]; + new Random(8).NextBytes(icc); + var file = JpegEncoder.Encode(TestImages.Gradient(10, 10, 1), new JpegEncoderOptions { IccProfile = icc }); + CollectionAssert.AreEqual(icc, JpegDecoder.Identify(file).Metadata.IccProfile); + + // Remove the second of three APP2 chunks. + var second = SegmentOffsets(file, 0xE2)[1]; + var length = (file[second + 2] << 8) | file[second + 3]; + byte[] missing = [.. file[..second], .. file[(second + 2 + length)..]]; + Assert.IsNull(JpegDecoder.Identify(missing).Metadata.IccProfile); + using var image = JpegDecoder.Decode(missing); + Assert.AreEqual(10, image.Width); + } + + [TestMethod] + public void OtherFormatsAreNotJpeg() + { + var png = ReferenceImages.Of(ReferenceFormat.Png).First().ReadInput(); + Assert.IsFalse(JpegDecoder.IsJpeg(png)); + Assert.IsFalse(JpegDecoder.IsJpeg([0xFF, 0xD8])); + Assert.Throws(() => JpegDecoder.Decode(png)); + } + + [TestMethod] + public void ChangedBytesInEveryCodingNeverBreakTheDecoder() + { + using var image = TestImages.Gradient(45, 30, 6); + var coefficients = JpegEncoder.Transform(image, new JpegEncoderOptions { Quality = 75 }); + var lossless = new List<(int Id, int H, int V, int[] Samples)> + { + (1, 2, 2, Enumerable.Range(0, 45 * 30).Select(i => i % 251).ToArray()), + (2, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 13).ToArray()), + (3, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 7).ToArray()), + }; + var files = new (string Name, byte[] File)[] + { + ("progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Progressive = true, RestartInterval = 3 })), + ("aritmetico", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 4 })), + ("aritmetico progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true })), + ("DNL", JpegTestEncoder.Write(coefficients, new JpegTestOptions { HeightInDnl = true })), + ("senza perdita", JpegTestEncoder.WriteLossless(45, 30, 8, lossless, 4, 0, new JpegTestOptions { RestartInterval = 7 })), + ("senza perdita aritmetico", JpegTestEncoder.WriteLossless(45, 30, 12, lossless, 7, 1, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic })), + }; + + var random = new Random(2026); + foreach (var (name, file) in files) + { + using (JpegDecoder.Decode(file, Small)) + { + } + + for (var i = 0; i < 150; i++) + { + var mutated = Mutate(file, random); + TryDecode(mutated, $"{name}, modifica {i}"); + } + + // Every cut of the file, as the network would leave it. + for (var length = 0; length < file.Length; length += 1 + (file.Length / 200)) + { + TryDecode(file[..length], $"{name}, {length} byte"); + } + } + } + + private static void TryDecode(byte[] bytes, string what) + { + try + { + using var decoded = JpegDecoder.Decode(bytes, Small); + Assert.IsGreaterThan(0, decoded.Width, what); + } + catch (ImageDecodeException) + { + } + catch (Exception ex) + { + Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); + } + + try + { + JpegDecoder.Identify(bytes, Small); + } + catch (ImageDecodeException) + { + } + catch (Exception ex) + { + Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); + } + } + + private static byte[] Mutate(byte[] original, Random random) + { + var bytes = original.ToArray(); + switch (random.Next(3)) + { + case 0: + for (var k = random.Next(1, 9); k > 0; k--) + { + bytes[random.Next(2, bytes.Length)] = (byte)random.Next(256); + } + + return bytes; + + case 1: + // Headers: the first segments hold the tables and the frame. + bytes[random.Next(2, Math.Min(bytes.Length, 700))] = (byte)(random.Next(3) switch { 0 => 0, 1 => 0xFF, _ => random.Next(256) }); + return bytes; + + default: + var start = random.Next(2, bytes.Length); + var length = Math.Min(bytes.Length - start, random.Next(1, 64)); + for (var k = 0; k < length; k++) + { + bytes[start + k] ^= 0x5A; + } + + return bytes; + } + } + + private static void AssertDamaged(byte[] file, string what) + { + var error = Assert.Throws(() => JpegDecoder.Decode(file), what); + Assert.IsNotInstanceOfType(error, what); + Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what); + } + + /// Offset of the first marker segment of type (the 0xFF byte). + private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0]; + + private static List SegmentOffsets(byte[] file, int marker) + { + var found = new List(); + var pos = 2; + while (pos + 4 <= file.Length && file[pos] == 0xFF) + { + if (file[pos + 1] == marker) + { + found.Add(pos); + } + + if (file[pos + 1] == 0xDA) + { + break; + } + + pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]); + } + + return found; + } + + private static byte[] RemoveSegments(byte[] file, int marker) + { + var result = new List(file.Length); + result.AddRange(file.AsSpan(0, 2)); + var pos = 2; + while (file[pos + 1] != 0xDA) + { + var length = 2 + ((file[pos + 2] << 8) | file[pos + 3]); + if (file[pos + 1] != marker) + { + result.AddRange(file.AsSpan(pos, length)); + } + + pos += length; + } + + result.AddRange(file.AsSpan(pos)); + return [.. result]; + } +} diff --git a/tests/Febe.Tests/Imaging/JpegReferenceTests.cs b/tests/Febe.Tests/Imaging/JpegReferenceTests.cs new file mode 100644 index 0000000..35e1158 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegReferenceTests.cs @@ -0,0 +1,56 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The in-house JPEG decoder against the SkiaSharp (libjpeg-turbo) reads of the reference set. JPEG is lossy and two +/// correct decoders differ by the rounding of their IDCT and upsampling, so the comparison has thresholds instead of +/// equality: every colour channel at least dB and at most +/// of the pixels off by more than . +/// +[TestClass] +public sealed class JpegReferenceTests +{ + public TestContext TestContext { get; set; } = null!; + + public static IEnumerable JpegCases => ReferenceImages.NamesOf(ReferenceFormat.Jpeg); + + [TestMethod] + [DynamicData(nameof(JpegCases))] + public void TheJpegDecoderIsCloseToTheReference(string name) + { + var reference = ReferenceImages.Get(name); + var input = reference.ReadInput(); + using var stored = JpegDecoder.Decode(input, out var info); + Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (stored.Width, stored.Height), name); + Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, name); + Assert.IsTrue(stored.IsOpaque(), name); + + using var shown = ImageQuality.Orient(stored, info.Metadata.Orientation); + using var expected = PngDecoder.Decode(reference.ReadExpectedPng()); + var result = ImageQuality.Compare(expected, shown); + TestContext.WriteLine($"{name}: {result}"); + ImageQuality.AssertClose(result, name); + } + + [TestMethod] + public void TheFacadeReadsJpegAndIdentifyAgreesWithDecode() + { + foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg)) + { + var input = reference.ReadInput(); + using var viaFacade = ImageDecoder.Decode(input); + using var direct = JpegDecoder.Decode(input, pooled: true); + ImageAssert.AreEqual(direct, viaFacade, reference.Name); + + var info = ImageDecoder.Identify(input); + Assert.AreEqual((ImageFormat.Jpeg, reference.StoredWidth, reference.StoredHeight, 1, false), (info.Format, info.Width, info.Height, info.FrameCount, info.HasAlpha), reference.Name); + Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, reference.Name); + if (reference.Orientation != 1) + { + Assert.IsNotNull(info.Metadata.Exif, reference.Name); + Assert.IsTrue(info.Metadata.Exif.AsSpan().StartsWith("II*\0"u8) || info.Metadata.Exif.AsSpan().StartsWith("MM\0*"u8), reference.Name); + } + } + } +} diff --git a/tests/Febe.Tests/Imaging/JpegTestEncoder.cs b/tests/Febe.Tests/Imaging/JpegTestEncoder.cs new file mode 100644 index 0000000..73c8f9e --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegTestEncoder.cs @@ -0,0 +1,1186 @@ +using System.Numerics; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// Entropy coding of the test encoder. +public enum JpegTestCoding +{ + Huffman, + Arithmetic, +} + +/// One scan of a progressive script: components (frame indices), band and approximation. +internal sealed record JpegTestScan(int[] Components, int Ss, int Se, int Ah, int Al); + +/// What the test encoder writes around the coefficients it is given. +internal sealed record JpegTestOptions +{ + public JpegTestCoding Coding { get; init; } = JpegTestCoding.Huffman; + + public bool Progressive { get; init; } + + /// The progressive script; null for . + public IReadOnlyList? Script { get; init; } + + /// Sequential only: one scan per component instead of one interleaved scan. + public bool SeparateScans { get; init; } + + public int RestartInterval { get; init; } + + /// Write height 0 in the frame and give it in a DNL segment after the first scan. + public bool HeightInDnl { get; init; } + + public bool Jfif { get; init; } = true; + + /// Adobe APP14 transform to write (0 none/RGB/CMYK, 1 YCbCr, 2 YCCK), or -1 for no segment. + public int AdobeTransform { get; init; } = -1; + + /// Arithmetic DC conditioning (L, U) and AC conditioning Kx, written in DAC when not the defaults. + public (int L, int U) DcConditioning { get; init; } = (0, 1); + + public int AcConditioning { get; init; } = 5; +} + +/// +/// A JPEG writer for the tests only, from quantized coefficients (, +/// ): extended sequential and progressive DCT (T.81 Annex G: spectral +/// selection and successive approximation, EOB runs, correction bits), Huffman with tables built from the symbol counts +/// of each scan (Annex K.2) or arithmetic coding (Annex D, F.1.4, G.1.3), restart intervals, DNL, Adobe APP14; and +/// lossless (Annex H) from samples. It exists to make files the reference set lacks; the tests then check that the +/// decoder gets back exactly the coefficients (or samples) that went in. +/// +internal static class JpegTestEncoder +{ + private const int DcStatistics = 64; + private const int AcStatistics = 256; + private const int LosslessStatistics = 158; + + /// A script like the usual ones: DC first with Al 1, AC bands with Al 2 then 1, refinements down to 0. + public static IReadOnlyList DefaultScript(int componentCount) + { + var all = Enumerable.Range(0, componentCount).ToArray(); + var scans = new List { new(all, 0, 0, 0, 1) }; + for (var c = 0; c < componentCount; c++) + { + scans.Add(new([c], 1, 5, 0, 2)); + scans.Add(new([c], 6, 63, 0, 2)); + } + + for (var c = componentCount - 1; c >= 0; c--) + { + scans.Add(new([c], 1, 63, 2, 1)); + } + + scans.Add(new(all, 0, 0, 1, 0)); + for (var c = 0; c < componentCount; c++) + { + scans.Add(new([c], 1, 63, 1, 0)); + } + + return scans; + } + + /// Writes a DCT-based file holding exactly 's coefficients. + public static byte[] Write(JpegCoefficients image, JpegTestOptions options) + { + var output = new JpegOutput(); + output.Marker(0xD8); + WriteHeaders(output, options); + var tables = new List(); + foreach (var c in image.Components) + { + while (tables.Count <= c.QuantizationTable) + { + tables.Add(new ushort[64]); + } + + tables[c.QuantizationTable] = c.Quantization; + } + + JpegSegments.WriteQuantization(output, tables); + var marker = (options.Coding, options.Progressive) switch + { + (JpegTestCoding.Huffman, false) => 0xC1, + (JpegTestCoding.Huffman, true) => 0xC2, + (JpegTestCoding.Arithmetic, false) => 0xC9, + _ => 0xCA, + }; + JpegSegments.WriteFrame(output, marker, image.Precision, image.Width, options.HeightInDnl ? 0 : image.Height, image.Components.Select(c => (c.Id, c.H, c.V, c.QuantizationTable)).ToList()); + if (options.RestartInterval > 0) + { + JpegSegments.WriteRestartInterval(output, options.RestartInterval); + } + + if (options.Coding == JpegTestCoding.Arithmetic) + { + WriteConditioning(output, options, image.Components.Count); + } + + var all = Enumerable.Range(0, image.Components.Count).ToArray(); + IReadOnlyList script = options.Progressive + ? options.Script ?? DefaultScript(image.Components.Count) + : options.SeparateScans ? all.Select(c => new JpegTestScan([c], 0, 63, 0, 0)).ToList() : [new JpegTestScan(all, 0, 63, 0, 0)]; + var layout = new Layout(image.Width, image.Height, image.Components.Select(c => (c.H, c.V)).ToList(), 8); + var first = true; + foreach (var scan in script) + { + if (options.Coding == JpegTestCoding.Huffman) + { + WriteHuffmanScan(output, image, layout, scan, options); + } + else + { + WriteArithmeticScan(output, image, layout, scan, options); + } + + if (first && options.HeightInDnl) + { + JpegSegments.WriteSegment(output, 0xDC, [(byte)(image.Height >> 8), (byte)image.Height]); + } + + first = false; + } + + output.Marker(0xD9); + return output.ToArray(); + } + + /// + /// Writes a lossless file (SOF3 or SOF11) of the given samples: one plane per component at its own size, values + /// below 2^precision; 1-7, point transform . + /// + public static byte[] WriteLossless( + int width, + int height, + int precision, + IReadOnlyList<(int Id, int H, int V, int[] Samples)> planes, + int predictor, + int pointTransform, + JpegTestOptions options) + { + var output = new JpegOutput(); + output.Marker(0xD8); + WriteHeaders(output, options); + JpegSegments.WriteFrame(output, options.Coding == JpegTestCoding.Huffman ? 0xC3 : 0xCB, precision, width, height, planes.Select(p => (p.Id, p.H, p.V, 0)).ToList()); + if (options.RestartInterval > 0) + { + JpegSegments.WriteRestartInterval(output, options.RestartInterval); + } + + if (options.Coding == JpegTestCoding.Arithmetic) + { + WriteConditioning(output, options, planes.Count); + } + + var layout = new Layout(width, height, planes.Select(p => (p.H, p.V)).ToList(), 1); + var all = Enumerable.Range(0, planes.Count).ToArray(); + var scans = options.SeparateScans ? all.Select(c => new[] { c }).ToList() : [all]; + foreach (var components in scans) + { + var model = new LosslessModel(layout, planes, components, precision, predictor, pointTransform); + if (options.Coding == JpegTestCoding.Huffman) + { + var counter = new CountingSink(); + model.EncodeHuffman(counter, options.RestartInterval); + var tables = counter.BuildTables(output, components.Length); + JpegSegments.WriteScan(output, components.Select((c, j) => (planes[c].Id, j, 0)).ToList(), predictor, 0, 0, pointTransform); + var writer = new WritingSink(output, tables); + model.EncodeHuffman(writer, options.RestartInterval); + writer.Finish(); + } + else + { + JpegSegments.WriteScan(output, components.Select((c, j) => (planes[c].Id, j, 0)).ToList(), predictor, 0, 0, pointTransform); + var encoder = new ArithmeticEncoder(output); + model.EncodeArithmetic(encoder, options); + encoder.Flush(); + } + } + + output.Marker(0xD9); + return output.ToArray(); + } + + private static void WriteHeaders(JpegOutput output, JpegTestOptions options) + { + if (options.Jfif) + { + JpegSegments.WriteJfif(output); + } + + if (options.AdobeTransform >= 0) + { + JpegSegments.WriteSegment(output, 0xEE, [(byte)'A', (byte)'d', (byte)'o', (byte)'b', (byte)'e', 0, 100, 0, 0, 0, 0, (byte)options.AdobeTransform]); + } + } + + private static void WriteConditioning(JpegOutput output, JpegTestOptions options, int tables) + { + if (options.DcConditioning == (0, 1) && options.AcConditioning == 5) + { + return; + } + + var payload = new List(); + for (var t = 0; t < Math.Min(tables, 4); t++) + { + payload.Add((byte)t); + payload.Add((byte)((options.DcConditioning.U << 4) | options.DcConditioning.L)); + payload.Add((byte)(0x10 | t)); + payload.Add((byte)options.AcConditioning); + } + + JpegSegments.WriteSegment(output, 0xCC, payload.ToArray()); + } + + /// MCU geometry, the same rules as the decoder (T.81 A.2). + private sealed class Layout + { + public Layout(int width, int height, IReadOnlyList<(int H, int V)> sampling, int unit) + { + var maxH = sampling.Max(s => s.H); + var maxV = sampling.Max(s => s.V); + McusWide = (width + (unit * maxH) - 1) / (unit * maxH); + McusHigh = (height + (unit * maxV) - 1) / (unit * maxV); + Sampling = sampling; + Wide = new int[sampling.Count]; + High = new int[sampling.Count]; + Stride = new int[sampling.Count]; + for (var i = 0; i < sampling.Count; i++) + { + var cw = ((width * sampling[i].H) + maxH - 1) / maxH; + var ch = ((height * sampling[i].V) + maxV - 1) / maxV; + Wide[i] = (cw + unit - 1) / unit; + High[i] = (ch + unit - 1) / unit; + Stride[i] = sampling.Count == 1 ? Wide[i] : McusWide * sampling[i].H; + } + } + + public int McusWide { get; } + + public int McusHigh { get; } + + public IReadOnlyList<(int H, int V)> Sampling { get; } + + /// Units covering each component (a non-interleaved scan). + public int[] Wide { get; } + + public int[] High { get; } + + /// Units per row of each component's storage. + public int[] Stride { get; } + + /// Calls (position in scan, component, x, y) for every data unit, and () between intervals. + public void Walk(int[] components, int restartInterval, Action unit, Action restart) + { + var single = components.Length == 1; + var perRow = single ? Wide[components[0]] : McusWide; + var total = single ? Wide[components[0]] * High[components[0]] : McusWide * McusHigh; + for (var mcu = 0; mcu < total; mcu++) + { + if (restartInterval > 0 && mcu > 0 && mcu % restartInterval == 0) + { + restart(); + } + + var mx = mcu % perRow; + var my = mcu / perRow; + for (var j = 0; j < components.Length; j++) + { + var c = components[j]; + var (h, v) = single ? (1, 1) : Sampling[c]; + for (var yy = 0; yy < v; yy++) + { + for (var xx = 0; xx < h; xx++) + { + unit(j, c, single ? mx : (mx * h) + xx, single ? my : (my * v) + yy); + } + } + } + } + } + } + + /// Receives Huffman symbols (tables 0-3 DC, 4-7 AC) and raw bits. + private interface ISink + { + void Symbol(int table, int symbol); + + void Bits(int value, int count); + + void Restart(); + } + + private sealed class CountingSink : ISink + { + private readonly long[][] _counts = Enumerable.Range(0, 8).Select(_ => new long[256]).ToArray(); + + public void Symbol(int table, int symbol) => _counts[table][symbol]++; + + public void Bits(int value, int count) + { + } + + public void Restart() + { + } + + /// Optimal tables for the counted symbols (T.81 K.2), written as DHT segments. + public JpegHuffmanTable?[] BuildTables(JpegOutput output, int count) + { + var tables = new JpegHuffmanTable?[8]; + for (var t = 0; t < 8; t++) + { + if (_counts[t].All(c => c == 0)) + { + continue; + } + + var (counts, values) = OptimalTable(_counts[t]); + tables[t] = JpegHuffmanTable.Build(counts, values); + JpegSegments.WriteHuffman(output, t >= 4 ? 1 : 0, t & 3, counts, values); + } + + return tables; + } + } + + private sealed class WritingSink : ISink + { + private readonly JpegOutput _output; + private readonly JpegHuffmanTable?[] _tables; + private readonly JpegBitWriter _writer; + private int _restart; + + public WritingSink(JpegOutput output, JpegHuffmanTable?[] tables) + { + _output = output; + _tables = tables; + _writer = new JpegBitWriter(output); + } + + public void Symbol(int table, int symbol) => _writer.WriteSymbol(_tables[table]!, symbol); + + public void Bits(int value, int count) + { + if (count > 0) + { + _writer.WriteBits(value, count); + } + } + + public void Restart() + { + _writer.Flush(); + _output.Marker(0xD0 + (_restart++ & 7)); + } + + public void Finish() => _writer.Flush(); + } + + /// Code lengths from symbol counts (Figures K.1-K.3), limited to 16 bits, no all-ones code. + private static (byte[] Counts, byte[] Values) OptimalTable(long[] frequencies) + { + var freq = new long[257]; + Array.Copy(frequencies, freq, 256); + freq[256] = 1; + var codeSize = new int[257]; + var others = Enumerable.Repeat(-1, 257).ToArray(); + while (true) + { + var v1 = -1; + var v2 = -1; + for (var i = 0; i <= 256; i++) + { + if (freq[i] > 0 && (v1 < 0 || freq[i] <= freq[v1])) + { + v1 = i; + } + } + + for (var i = 0; i <= 256; i++) + { + if (freq[i] > 0 && i != v1 && (v2 < 0 || freq[i] <= freq[v2])) + { + v2 = i; + } + } + + if (v2 < 0) + { + break; + } + + freq[v1] += freq[v2]; + freq[v2] = 0; + codeSize[v1]++; + while (others[v1] >= 0) + { + v1 = others[v1]; + codeSize[v1]++; + } + + others[v1] = v2; + codeSize[v2]++; + while (others[v2] >= 0) + { + v2 = others[v2]; + codeSize[v2]++; + } + } + + var bits = new int[33]; + for (var i = 0; i <= 256; i++) + { + if (codeSize[i] > 0) + { + bits[codeSize[i]]++; + } + } + + for (var i = 32; i > 16; i--) + { + while (bits[i] > 0) + { + var j = i - 2; + while (bits[j] == 0) + { + j--; + } + + bits[i] -= 2; + bits[i - 1]++; + bits[j + 1] += 2; + bits[j]--; + } + } + + var longest = 16; + while (bits[longest] == 0) + { + longest--; + } + + bits[longest]--; + var values = new List(); + for (var size = 1; size <= 32; size++) + { + for (var s = 0; s < 256; s++) + { + if (codeSize[s] == size) + { + values.Add((byte)s); + } + } + } + + return (bits.Skip(1).Take(16).Select(b => (byte)b).ToArray(), values.ToArray()); + } + + private static int Category(int value) => value == 0 ? 0 : BitOperations.Log2((uint)Math.Abs(value)) + 1; + + private static void Value(ISink sink, int table, int run, int value) + { + var category = Category(value); + sink.Symbol(table, (run << 4) | category); + sink.Bits(value < 0 ? value - 1 : value, category); + } + + /// Point transform of an AC coefficient: the magnitude shifted, the sign kept (G.1.2.3). + private static int Shifted(int coefficient, int al) => coefficient >= 0 ? coefficient >> al : -(-coefficient >> al); + + private static void WriteHuffmanScan(JpegOutput output, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) + { + var counter = new CountingSink(); + EncodeHuffmanScan(counter, image, layout, scan, options); + var tables = counter.BuildTables(output, scan.Components.Length); + JpegSegments.WriteScan(output, scan.Components.Select((c, j) => (image.Components[c].Id, j, j)).ToList(), scan.Ss, scan.Se, scan.Ah, scan.Al); + var writer = new WritingSink(output, tables); + EncodeHuffmanScan(writer, image, layout, scan, options); + writer.Finish(); + } + + private static void EncodeHuffmanScan(ISink sink, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) + { + var zigzag = JpegTables.ZigZag; + var predictors = new int[scan.Components.Length]; + var eobRun = 0; + var pendingBits = new List(); + var progressive = options.Progressive; + var refineAc = progressive && scan.Ss > 0 && scan.Ah > 0; + + void EmitEobRun() + { + if (eobRun > 0) + { + var bits = BitOperations.Log2((uint)eobRun); + sink.Symbol(4, bits << 4); + sink.Bits(eobRun, bits); + eobRun = 0; + } + + foreach (var bit in pendingBits) + { + sink.Bits(bit, 1); + } + + pendingBits.Clear(); + } + + layout.Walk( + scan.Components, + options.RestartInterval, + (j, c, x, y) => + { + var component = image.Components[c]; + var block = component.Block(x, y); + if (!progressive) + { + var difference = block[0] - predictors[j]; + predictors[j] = block[0]; + Value(sink, j, 0, difference); + var run = 0; + for (var k = 1; k < 64; k++) + { + int value = block[zigzag[k]]; + if (value == 0) + { + run++; + continue; + } + + for (; run > 15; run -= 16) + { + sink.Symbol(4 + j, 0xF0); + } + + Value(sink, 4 + j, run, value); + run = 0; + } + + if (run > 0) + { + sink.Symbol(4 + j, 0x00); + } + } + else if (scan.Ss == 0 && scan.Ah == 0) + { + var dc = block[0] >> scan.Al; + Value(sink, j, 0, dc - predictors[j]); + predictors[j] = dc; + } + else if (scan.Ss == 0) + { + sink.Bits((block[0] >> scan.Al) & 1, 1); + } + else if (!refineAc) + { + var run = 0; + for (var k = scan.Ss; k <= scan.Se; k++) + { + var value = Shifted(block[zigzag[k]], scan.Al); + if (value == 0) + { + run++; + continue; + } + + EmitEobRun(); + for (; run > 15; run -= 16) + { + sink.Symbol(4, 0xF0); + } + + Value(sink, 4, run, value); + run = 0; + } + + if (run > 0 && ++eobRun == 0x7FFF) + { + EmitEobRun(); + } + } + else + { + var end = scan.Ss - 1; + for (var k = scan.Ss; k <= scan.Se; k++) + { + if (Math.Abs(block[zigzag[k]]) >> scan.Al == 1) + { + end = k; + } + } + + var run = 0; + var corrections = new List(); + for (var k = scan.Ss; k <= scan.Se; k++) + { + var coefficient = block[zigzag[k]]; + var magnitude = Math.Abs(coefficient) >> scan.Al; + if (magnitude == 0) + { + run++; + continue; + } + + while (run > 15 && k <= end) + { + EmitEobRun(); + sink.Symbol(4, 0xF0); + run -= 16; + foreach (var bit in corrections) + { + sink.Bits(bit, 1); + } + + corrections.Clear(); + } + + if (magnitude > 1) + { + corrections.Add(magnitude & 1); + continue; + } + + EmitEobRun(); + sink.Symbol(4, (run << 4) | 1); + sink.Bits(coefficient < 0 ? 0 : 1, 1); + foreach (var bit in corrections) + { + sink.Bits(bit, 1); + } + + corrections.Clear(); + run = 0; + } + + if (run > 0 || corrections.Count > 0) + { + eobRun++; + pendingBits.AddRange(corrections); + if (eobRun == 0x7FFF || pendingBits.Count > 900) + { + EmitEobRun(); + } + } + } + }, + () => + { + EmitEobRun(); + sink.Restart(); + Array.Clear(predictors); + }); + EmitEobRun(); + } + + /// The QM coder of T.81 D.1 (Initenc, Code_0/Code_1, Renorm_e, Byte_out with carry, Flush). + private sealed class ArithmeticEncoder + { + private readonly JpegOutput _output; + private long _c; + private int _a; + private int _ct; + private int _buffer; + private int _stack; + private int _start; + private int _restart; + + public ArithmeticEncoder(JpegOutput output) + { + _output = output; + Initialize(); + } + + public void Encode(ref byte state, int bit) + { + var s = state; + int qe = JpegArithmeticTable.Qe[s & 0x7F]; + var mps = s >> 7; + _a -= qe; + if (bit != mps) + { + if (_a >= qe) + { + _c += _a; + _a = qe; + } + + state = JpegArithmeticTable.AfterLps(s); + } + else + { + if (_a >= 0x8000) + { + return; + } + + if (_a < qe) + { + _c += _a; + _a = qe; + } + + state = JpegArithmeticTable.AfterMps(s); + } + + do + { + _a <<= 1; + _c <<= 1; + _ct--; + if (_ct == 0) + { + ByteOut(); + _ct = 8; + } + } + while (_a < 0x8000); + } + + public void EncodeFixed(int bit) + { + var state = JpegArithmeticTable.FixedState; + Encode(ref state, bit); + } + + public void Flush() + { + var t = (_c + _a - 1) & 0xFFFF0000L; + if (t < _c) + { + t += 0x8000; + } + + _c = t << _ct; + ByteOut(); + _c <<= 8; + ByteOut(); + EmitBuffer(); + for (; _stack > 0; _stack--) + { + _output.Add(0xFF); + _output.Add(0); + } + + // Discard_final_zeros: the decoder supplies zeros at the marker anyway; stuffed zeros stay. + while (_output.Length > _start && _output[_output.Length - 1] == 0 && (_output.Length - 1 == _start || _output[_output.Length - 2] != 0xFF)) + { + _output.Truncate(_output.Length - 1); + } + } + + public void Restart() + { + Flush(); + _output.Marker(0xD0 + (_restart++ & 7)); + Initialize(); + } + + private void Initialize() + { + _c = 0; + _a = 0x10000; + _ct = 11; + _buffer = -1; + _stack = 0; + _start = _output.Length; + } + + private void ByteOut() + { + var t = _c >> 19; + if (t > 0xFF) + { + _buffer++; + EmitBuffer(); + for (; _stack > 0; _stack--) + { + _output.Add(0); + } + + _buffer = (int)(t & 0xFF); + } + else if (t == 0xFF) + { + _stack++; + } + else + { + EmitBuffer(); + for (; _stack > 0; _stack--) + { + _output.Add(0xFF); + _output.Add(0); + } + + _buffer = (int)t; + } + + _c &= 0x7FFFF; + } + + private void EmitBuffer() + { + if (_buffer >= 0) + { + _output.Add((byte)_buffer); + if (_buffer == 0xFF) + { + _output.Add(0); + } + } + + _buffer = -1; + } + } + + private static int Classify(int difference, int low, int high) + { + var magnitude = Math.Abs(difference); + if (magnitude <= (low == 0 ? 0 : 1 << (low - 1))) + { + return 0; + } + + var negative = difference < 0 ? 1 : 0; + return magnitude <= 1 << high ? 1 + negative : 3 + negative; + } + + /// Encode_V of a DC-model value (Figures F.4, F.6-F.9; Tables F.4, H.3). + private static void EncodeValue(ArithmeticEncoder encoder, byte[] statistics, int offset, int s0, int x1, int value) + { + if (value == 0) + { + encoder.Encode(ref statistics[offset + s0], 0); + return; + } + + encoder.Encode(ref statistics[offset + s0], 1); + var sign = value < 0 ? 1 : 0; + encoder.Encode(ref statistics[offset + s0 + 1], sign); + var s = s0 + 2 + sign; + var sz = Math.Abs(value) - 1; + if (sz == 0) + { + encoder.Encode(ref statistics[offset + s], 0); + return; + } + + encoder.Encode(ref statistics[offset + s], 1); + var m = 1; + s = x1; + while (sz >= m << 1) + { + encoder.Encode(ref statistics[offset + s], 1); + m <<= 1; + s++; + } + + encoder.Encode(ref statistics[offset + s], 0); + for (var bit = m >> 1; bit != 0; bit >>= 1) + { + encoder.Encode(ref statistics[offset + s + 14], (sz & bit) != 0 ? 1 : 0); + } + } + + private static void EncodeAc(ArithmeticEncoder encoder, byte[] statistics, int offset, int kx, int ss, int se, int al, ReadOnlySpan block) + { + var zigzag = JpegTables.ZigZag; + var last = ss - 1; + for (var k = ss; k <= se; k++) + { + if (Shifted(block[zigzag[k]], al) != 0) + { + last = k; + } + } + + for (var k = ss; k <= se; k++) + { + var se3 = 3 * (k - 1); + if (k > last) + { + encoder.Encode(ref statistics[offset + se3], 1); + return; + } + + encoder.Encode(ref statistics[offset + se3], 0); + while (Shifted(block[zigzag[k]], al) == 0) + { + encoder.Encode(ref statistics[offset + se3 + 1], 0); + se3 += 3; + k++; + } + + encoder.Encode(ref statistics[offset + se3 + 1], 1); + var value = Shifted(block[zigzag[k]], al); + encoder.EncodeFixed(value < 0 ? 1 : 0); + var s = se3 + 2; + var sz = Math.Abs(value) - 1; + if (sz == 0) + { + encoder.Encode(ref statistics[offset + s], 0); + continue; + } + + encoder.Encode(ref statistics[offset + s], 1); + var m = 1; + if (sz < 2) + { + encoder.Encode(ref statistics[offset + s], 0); + } + else + { + encoder.Encode(ref statistics[offset + s], 1); + m = 2; + s = k <= kx ? 189 : 217; + while (sz >= m << 1) + { + encoder.Encode(ref statistics[offset + s], 1); + m <<= 1; + s++; + } + + encoder.Encode(ref statistics[offset + s], 0); + } + + for (var bit = m >> 1; bit != 0; bit >>= 1) + { + encoder.Encode(ref statistics[offset + s + 14], (sz & bit) != 0 ? 1 : 0); + } + } + } + + private static void EncodeAcRefine(ArithmeticEncoder encoder, byte[] statistics, int offset, int ss, int se, int al, ReadOnlySpan block) + { + var zigzag = JpegTables.ZigZag; + var endOfBand = 0; + for (var k = 1; k <= se; k++) + { + if (Math.Abs(block[zigzag[k]]) >> (al + 1) != 0) + { + endOfBand = k; + } + } + + var last = ss - 1; + for (var k = ss; k <= se; k++) + { + if (Math.Abs(block[zigzag[k]]) >> al != 0) + { + last = k; + } + } + + for (var k = ss; k <= se; k++) + { + var se3 = 3 * (k - 1); + if (k > endOfBand) + { + if (k > last) + { + encoder.Encode(ref statistics[offset + se3], 1); + return; + } + + encoder.Encode(ref statistics[offset + se3], 0); + } + + while (true) + { + var coefficient = block[zigzag[k]]; + var magnitude = Math.Abs(coefficient) >> al; + if (magnitude > 1) + { + encoder.Encode(ref statistics[offset + se3 + 2], magnitude & 1); + break; + } + + if (magnitude == 1) + { + encoder.Encode(ref statistics[offset + se3 + 1], 1); + encoder.EncodeFixed(coefficient < 0 ? 1 : 0); + break; + } + + encoder.Encode(ref statistics[offset + se3 + 1], 0); + se3 += 3; + k++; + } + } + } + + private static void WriteArithmeticScan(JpegOutput output, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) + { + JpegSegments.WriteScan(output, scan.Components.Select((c, j) => (image.Components[c].Id, j, j)).ToList(), scan.Ss, scan.Se, scan.Ah, scan.Al); + var encoder = new ArithmeticEncoder(output); + var dc = new byte[4 * DcStatistics]; + var ac = new byte[4 * AcStatistics]; + var predictors = new int[scan.Components.Length]; + var contexts = new int[scan.Components.Length]; + var (low, high) = options.DcConditioning; + var kx = options.AcConditioning; + layout.Walk( + scan.Components, + options.RestartInterval, + (j, c, x, y) => + { + var block = image.Components[c].Block(x, y); + if (!options.Progressive || (scan.Ss == 0 && scan.Ah == 0)) + { + var value = options.Progressive ? block[0] >> scan.Al : block[0]; + var difference = value - predictors[j]; + predictors[j] = value; + EncodeValue(encoder, dc, j * DcStatistics, contexts[j], 20, difference); + contexts[j] = Classify(difference, low, high) * 4; + if (!options.Progressive) + { + EncodeAc(encoder, ac, j * AcStatistics, kx, 1, 63, 0, block); + } + } + else if (scan.Ss == 0) + { + encoder.EncodeFixed((block[0] >> scan.Al) & 1); + } + else if (scan.Ah == 0) + { + EncodeAc(encoder, ac, 0, kx, scan.Ss, scan.Se, scan.Al, block); + } + else + { + EncodeAcRefine(encoder, ac, 0, scan.Ss, scan.Se, scan.Al, block); + } + }, + () => + { + encoder.Restart(); + Array.Clear(dc); + Array.Clear(ac); + Array.Clear(predictors); + Array.Clear(contexts); + }); + encoder.Flush(); + } + + /// Predictions and differences of a lossless scan (H.1.2), the inverse of the decoder. + private sealed class LosslessModel + { + private readonly Layout _layout; + private readonly IReadOnlyList<(int Id, int H, int V, int[] Samples)> _planes; + private readonly int[] _components; + private readonly int _precision; + private readonly int _predictor; + private readonly int _pt; + private readonly int[] _widths; + private readonly int[] _heights; + + public LosslessModel(Layout layout, IReadOnlyList<(int Id, int H, int V, int[] Samples)> planes, int[] components, int precision, int predictor, int pt) + { + _layout = layout; + _planes = planes; + _components = components; + _precision = precision; + _predictor = predictor; + _pt = pt; + _widths = layout.Wide; + _heights = layout.High; + } + + /// The sample (x, y) of component c after the point transform, edges repeated beyond the plane. + private int Sample(int c, int x, int y) => + _planes[c].Samples[(Math.Min(y, _heights[c] - 1) * _widths[c]) + Math.Min(x, _widths[c] - 1)] >> _pt; + + private int Predict(int c, int x, int y, int firstRow) + { + if (y == firstRow) + { + return x == 0 ? 1 << (_precision - _pt - 1) : Sample(c, x - 1, y); + } + + if (x == 0) + { + return Sample(c, x, y - 1); + } + + var a = Sample(c, x - 1, y); + var b = Sample(c, x, y - 1); + var cc = Sample(c, x - 1, y - 1); + return _predictor switch + { + 1 => a, + 2 => b, + 3 => cc, + 4 => a + b - cc, + 5 => a + ((b - cc) >> 1), + 6 => b + ((a - cc) >> 1), + _ => (a + b) >> 1, + }; + } + + /// The difference modulo 2^16, as a value in -32767..32768. + private static int Difference(int sample, int prediction) + { + var d = (sample - prediction) & 0xFFFF; + return d > 32768 ? d - 65536 : d; + } + + private IEnumerable<(int J, int C, int X, int Y, int FirstRow)> Units(int restartInterval, Action restart) + { + // The walk is recorded first, restart points as J = -1; the first line of an interval is the first sample + // row of its first MCU row. + var list = new List<(int J, int C, int X, int Y)>(); + _layout.Walk(_components, restartInterval, (j, c, x, y) => list.Add((j, c, x, y)), () => list.Add((-1, 0, 0, 0))); + var single = _components.Length == 1; + var perRow = single ? _layout.Wide[_components[0]] : _layout.McusWide; + var unitsPerMcu = single ? 1 : _components.Sum(c => _layout.Sampling[c].H * _layout.Sampling[c].V); + var units = 0; + var firstMcuRow = 0; + foreach (var (j, c, x, y) in list) + { + if (j < 0) + { + restart(); + firstMcuRow = units / unitsPerMcu / perRow; + continue; + } + + units++; + yield return (j, c, x, y, firstMcuRow * (single ? 1 : _layout.Sampling[c].V)); + } + } + public void EncodeHuffman(ISink sink, int restartInterval) + { + foreach (var (j, c, x, y, firstRow) in Units(restartInterval, sink.Restart)) + { + var difference = Difference(Sample(c, x, y), Predict(c, x, y, firstRow)); + var category = difference == 32768 ? 16 : Category(difference); + sink.Symbol(j, category); + if (category < 16) + { + sink.Bits(difference < 0 ? difference - 1 : difference, category); + } + } + } + + public void EncodeArithmetic(ArithmeticEncoder encoder, JpegTestOptions options) + { + var statistics = new byte[4 * LosslessStatistics]; + var classes = new Dictionary<(int C, int X, int Y), int>(); + var (low, high) = options.DcConditioning; + foreach (var (j, c, x, y, firstRow) in Units(options.RestartInterval, () => + { + encoder.Restart(); + Array.Clear(statistics); + })) + { + var classA = x == 0 ? 0 : classes[(c, x - 1, y)]; + var classB = y == firstRow ? 0 : classes[(c, x, y - 1)]; + var difference = Difference(Sample(c, x, y), Predict(c, x, y, firstRow)); + EncodeValue(encoder, statistics, j * LosslessStatistics, (20 * classB) + (4 * classA), classB >= 3 ? 129 : 100, difference); + classes[(c, x, y)] = Classify(difference, low, high); + } + } + } +} diff --git a/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs b/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs index 995cde6..6ec9156 100644 --- a/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs +++ b/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs @@ -64,6 +64,12 @@ public sealed class ReferenceDecodeTests continue; } + if (reference.Format == ReferenceFormat.Jpeg) + { + // Lossy: JpegReferenceTests compares it with thresholds, and with the EXIF orientation applied. + continue; + } + using var image = ImageDecoder.Decode(input); using var expectedImage = PngDecoder.Decode(reference.ReadExpectedPng()); ImageAssert.AreEqual(expectedImage, image, reference.Name); diff --git a/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md b/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md index 8e7fef7..66d4702 100644 --- a/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md +++ b/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md @@ -66,8 +66,10 @@ Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up, fotogramma l'immagine attesa è trasparente (0, 0, 0, 0). - Alfa non premoltiplicata: per i PNG il colore sotto un'alfa 0 resta quello del file. - JPEG e WebP con perdita: l'immagine attesa è la lettura di libjpeg-turbo e libwebp dentro SkiaSharp (IDCT, - ricampionamento della crominanza, conversione dei colori). Il nostro lettore potrà differire di poco: la tolleranza - la fissano le prove di quei lettori. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte. + ricampionamento della crominanza, conversione dei colori). Il nostro lettore può differire di poco: per JPEG la + tolleranza è almeno 40 dB di PSNR per canale e al più lo 0,1% dei pixel con uno scarto oltre 16 (il lettore di casa + sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). PNG, GIF, BMP e WebP senza perdita devono coincidere + byte per byte. ## Che cosa qui non c'è @@ -91,7 +93,12 @@ lettore ricava prima della trasformata inversa, poi i pixel di un'immagine sempl attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo. - `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato, - esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per JPEG e - WebP dice che non li legge ancora. + esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e per WebP + dice che non lo legge ancora; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal + passo 3), che applica anche l'orientamento EXIF riportato dal lettore. +- `Imaging/JpegCodingTests.cs`, `JpegEncoderTests.cs`, `JpegMalformedTests.cs` (dal passo 3): i casi qui assenti + (progressivo, ripristino, codifica aritmetica, 12 bit, senza perdita, CMYK e YCCK, campionamenti insoliti) scritti + dal codificatore di prova `JpegTestEncoder.cs` e confrontati coefficiente per coefficiente con la codifica di base + delle stesse immagini; il codificatore di casa; i file danneggiati. - `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini come binarie e tiene `elenco.txt` con le righe Unix.