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